【问题标题】:How to rotate the position of an object based on mouse position?如何根据鼠标位置旋转对象的位置?
【发布时间】:2018-11-25 17:44:50
【问题描述】:

我目前正在使用此代码将坦克炮塔对象旋转到鼠标位置:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit, range);
Vector3 dir = hit.point - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);

是否有任何方法可以创建旋转,即使光线没有击中任何对象(将鼠标指向没有启动对象的位置)(击中为假)?还有更好的解决方案吗?

谢谢。

【问题讨论】:

    标签: c# unity3d game-engine


    【解决方案1】:

    基本上,我只是获取鼠标在屏幕上的位置,将其与目标对象进行比较,将其转换为度数,然后围绕所需的轴旋转对象(Y 表示 topDown 3D 空间,Z 表示 2D)。

    void RotateTowards()
        {
            var mouse = Input.mousePosition;
            var screenPoint = Camera.main.WorldToScreenPoint(tankTransform.localPosition);
            var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
            var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Euler(0, angle, 0);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多