使用透视相机拖动对象

时间:2020-05-14 09:32:59

标签: unity3d

我正在尝试编写一个函数,因此当我按住鼠标时,可以拖动游戏对象,然后将其锁定到目标中。 我使用的是透视相机,其垂直相机已选中“物理相机”,焦距为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;
}

1 个答案:

答案 0 :(得分:1)

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

这可以帮助吗?与任何其他飞机相似。

相关问题