Unity3d 使用透视摄影机拖动对象
我正在尝试编写一个函数,这样当我按住鼠标时,我可以拖动游戏对象,然后将其锁定到目标中。 我使用的是透视垂直相机,检查了物理相机,焦距为35。我也不知道这是否重要,但我正在Y轴和Z轴上拖动对象。 我使用的代码将对象拖得离摄影机太近。我怎样才能解决这个问题Unity3d 使用透视摄影机拖动对象,unity3d,Unity3d,我正在尝试编写一个函数,这样当我按住鼠标时,我可以拖动游戏对象,然后将其锁定到目标中。 我使用的是透视垂直相机,检查了物理相机,焦距为35。我也不知道这是否重要,但我正在Y轴和Z轴上拖动对象。 我使用的代码将对象拖得离摄影机太近。我怎样才能解决这个问题 private void OnMouseDrag() { if (IsLatched) { print($"is latched:{IsLatched}"); return; } f
private void OnMouseDrag()
{
if (IsLatched)
{
print($"is latched:{IsLatched}");
return;
}
float distance = -Camera.main.transform.position.z + this.transform.position.z;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
this.transform.position = rayPoint;
print($"{name} transform.position:{transform.position}");
this.gameObject.GetComponent<Rigidbody>().isKinematic = true;
isHeld = true;
}
private void OnMouseDrag()
{
如果(已锁定)
{
打印($“已锁定:{IsLatched}”);
回来
}
float distance=-Camera.main.transform.position.z+this.transform.position.z;
Ray-Ray=Camera.main.screenpointoray(输入.鼠标位置);
Vector3光线点=光线.GetPoint(距离);
this.transform.position=光线点;
打印($“{name}transform.position:{transform.position}”);
this.gameObject.GetComponent().iskinetic=true;
isHeld=真;
}
计算距离的方法是减去z坐标,然后沿单击光线取一个点,并与该距离相等。这将不是同一z坐标上的一个点。如果要保持一个分量不变,我宁愿将光线与XY平面相交
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float Zplane = this.transform.position.z; // example. use any Z from anywhere here.
// find distance along ray.
float distance = (Zplane-ray.origin.z)/ray.direction.z ;
// that is our point
Vector3 point = ray.origin + ray.direction*distance;
// Z will be equal to Zplane, unless considering rounding errors.
// but can remove that error anyway.
point.z = Zplane;
this.transform.position = point;
这有帮助吗?将与任何其他飞机类似。使用物理。光线投射,以便从中获得命中位置。是的,这非常有帮助!因为我使用的是X轴,所以我相应地将Z平面更改为X平面。我将从其他角度尝试这段代码,看看它是否也能正常工作。