【问题标题】:Dragging an object using perspective camera使用透视相机拖动对象
【发布时间】:2020-05-14 21:13:59
【问题描述】:

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

【问题讨论】:

  • 使用 Physics.Raycast 获取命中位置。

标签: unity3d


【解决方案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;

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

【讨论】:

  • 是的,它帮助很大!因为我使用的是 X 轴,所以我将 ZPlane 相应地更改为 XPlane。我会从其他角度尝试这段代码,看看它是否也能正常工作。
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 2017-09-21
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
相关资源
最近更新 更多