【问题标题】:Move Object with mouse depending on its rotation Unity3D根据其旋转Unity3D用鼠标移动对象
【发布时间】:2020-06-15 23:55:48
【问题描述】:

我正在使用下面的脚本通过鼠标移动平滑地移动对象(在 X 和 Z 轴上),它在世界轴上完美运行,我的意思是当对象的旋转为 (0,0,0) 时。

但是我怎样才能使对象在其局部轴上移动(我的意思是当它的 X 旋转为 -20 时,它的 Z 移动应该是渐进的)?

脚本:

private Vector3 screenPoint;
private Vector3 offset;

// Update is called once per frame
void Update () {

    if (Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        screenPoint = Camera.main.WorldToScreenPoint(transform.position);

        offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    if (Input.GetMouseButton(0) && !Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

        Vector3 curPosition = new Vector3((Camera.main.ScreenToWorldPoint(curScreenPoint).x + offset.x), 2, (Camera.main.ScreenToWorldPoint(curScreenPoint).z + offset.z));

        float newX = Mathf.Clamp(curPosition.x, -3f, 3f);
        float newZ = Mathf.Clamp(curPosition.z, -6f, 1.5f);

        transform.position = Vector3.Lerp(transform.position, new Vector3(newX, transform.position.y, newZ), 10 * Time.deltaTime);
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    好的,我找到了答案,很简单:

    • 创建一个空的游戏对象并使其成为移动对象的父对象。
    • 将旋转应用于父级,因此子级没有旋转。
    • 将代码附加到孩子身上,但使用“transform.localposition”而不是“transform.position”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2019-07-10
      • 2013-11-04
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多