简体   繁体   中英

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

  • OnMouseDown -> store the initial mouse offset and current rotation
  • OnMouseDrag -> use the delta between the original and current mouse offset to calculate a rotation from the initial rotation + delta

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);
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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