Home > OS >  How to rotate the 2D object in one axis with the mouse correctly
How to rotate the 2D object in one axis with the mouse correctly

Time:11-08

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.

CodePudding user response:

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

enter image description here

  • Related