繁体   English   中英

如何正确使用鼠标在一个轴上旋转 2D 对象

[英]How to rotate the 2D object in one axis with the mouse correctly

目标是在按住鼠标按钮的同时旋转磁盘。

以下代码完美地完成了它的工作 - 正是我想要的:

public class Rotator : MonoBehaviour {

    private void OnMouseDrag()
    {

        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        difference.Normalize();
        float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
        
    }

}

除了在不拖动的情况下正常单击时出现的异常磁盘行为:

我怎样才能防止这种旋转跳跃? 我只需要拖动时平滑旋转。

由于您只想在拖动时应用此功能,因此我会这样做

  • OnMouseDown -> 存储初始鼠标偏移和当前旋转
  • OnMouseDrag -> 使用原始和当前鼠标偏移之间的增量来计算从初始旋转 + 增量的旋转

就像是

private Vector2 startDelta;
private Quaternion startRotation;

private void OnMouseDown()
{
    // Store the initial mouse offset
    startDelta = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
    startDelta.Normalize();

    // Store the initial rotation
    startRotation = transform.rotation;
}

private void OnMouseDrag()
{
    // Get the current mouse offset
    Vector2 currentDelta = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
    currentDelta.Normalize();

    // Get the angle difference between the initial and current offset
    var rotation_z = Vector2.SignedAngle(startDelta, currentDelta);

    // From the initial rotation rotate about the calculated difference angle
    transform.rotation = startRotation * Quaternion.Euler(0f, 0f, rotation_z);
}

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM