How to restrict the direction of rotation of a sprite

Hello everyone! I’m creating a script and I’ve been trying to achieve behavior that I would say is pretty simple for way too long.

So if someone can guide me a little it would be great because I’m quite frustrated with it…

I have a basic script that applies a rotation to a sprite (with a collider) according to the position of the mouse, that is, with the mouse I can click and drag a wheel to rotate it, this is working correctly, however what I want to do is to restrict the rotation so that it can only be done counterclockwise and I can’t achieve it…

 public Collider2D wheelCollider;
 private Vector2 screenPosition;
 private float angleOffset;
 private bool wheelPressed;
 private void Update()
 {
     Vector2 inputPosition = Input.touchCount > 1 ? (Vector3) Input.GetTouch(0).position : Input.mousePosition;
     //Mouse events
     if (Input.GetMouseButtonDown(0))
     {
         if (wheelCollider == Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(inputPosition)))
         {
             wheelPressed = true;
             screenPosition = Camera.main.WorldToScreenPoint(wheelCollider.transform.position);
             Vector2 aux = inputPosition - screenPosition;
             angleOffset = (Mathf.Atan2(wheelCollider.transform.right.y, wheelCollider.transform.right.x) - Mathf.Atan2(aux.y, aux.x)) * Mathf.Rad2Deg;
         }
     }
     else if (Input.GetMouseButtonUp(0) && wheelPressed)
     {
         wheelPressed = false;
     }
     //Apply Rotation
     if (wheelPressed)
     {
         Vector2 aux = inputPosition - screenPosition;
         float nextAngle = Mathf.Atan2(aux.y, aux.x) * Mathf.Rad2Deg;
         nextAngle += angleOffset;
         wheelCollider.transform.eulerAngles = new Vector3(0, 0, nextAngle);
     }
 }

9764160--1398642--2024-04-11-13-35-54.gif

using UnityEngine;
public class AntiClockwise : MonoBehaviour
{
    float previousAngle;

    void OnMouseDown()
    {
        previousAngle = GetAngle();
    }
    void OnMouseDrag()
    {
        float angle = GetAngle();
        if (Mathf.DeltaAngle(angle,previousAngle)<0) 
            transform.Rotate(0,0,angle-previousAngle);
        previousAngle=angle;
    }
    float GetAngle()
    {
        Vector2 inputPosition = Input.touchCount > 1 ? (Vector3) Input.GetTouch(0).position : Input.mousePosition;
        Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
        return Vector2.SignedAngle(Vector2.up, inputPosition - screenPosition);
    }
}
2 Likes

Just what I needed and much simpler than my code. Thanks!!! :slight_smile: