使用透视相机拖动对象



我正在尝试编写一个函数,因此当我按住鼠标时,我可以拖动游戏对象,然后将其锁定到目标中。 我使用的是透视,垂直相机,物理相机检查,焦距35。我也不知道这是否重要,但我正在 Y 轴和 Z 轴上拖动对象。 我使用的代码将对象拖得离相机太近。我该如何解决这个问题?

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;
}

您正在通过减去 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;

这有帮助吗?与任何其他飞机类似。

最新更新