[英]How to rotate the 2D object in one axis with the mouse correctly
The goal is to rotate the disk while holding down the mouse button down on it.目标是在按住鼠标按钮的同时旋转磁盘。
The following code does its job perfectly - exactly what I wanted:以下代码完美地完成了它的工作 - 正是我想要的:
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);
}
}
Except for unusual disk behavior on normal click without dragging:除了在不拖动的情况下正常单击时出现的异常磁盘行为:
How can I prevent such rotation jumps?我怎样才能防止这种旋转跳跃? I only need the smooth rotation while dragging.
我只需要拖动时平滑旋转。
Since you only want this to be applied while dragging I would do由于您只想在拖动时应用此功能,因此我会这样做
Something like就像是
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.