Object Rotation Not Snapping In 2D

I’ve been trying to get my 2D Image To snap to certain points on the Z. Like if its close to 90, say at 85 degrees, lets snap it to 90, else if we are dragging again unsnap… heres my code.

using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragRotate : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler, IPointerDownHandler
{

    public GameObject target;
  
    public event Action<Quaternion> OnAngleChanged;

    Quaternion dragStartRotation;
    Quaternion dragStartInverseRotation;


    private void Awake()
    {
     
        OnAngleChanged += (rotation) => target.transform.localRotation = rotation;
    }


  
    public void OnPointerDown(PointerEventData eventData)
    {
        dragStartRotation = target.transform.localRotation;
        Vector3 worldPoint;
        if (DragWorldPoint(eventData, out worldPoint))
        {
           
            dragStartInverseRotation = Quaternion.Inverse(Quaternion.LookRotation(worldPoint - target.transform.position, Vector3.forward));
        }
        else
        {
            Debug.LogWarning("Couldn't get drag start world point");
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
       
    }
    public void OnEndDrag(PointerEventData eventData)
    {
      
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 worldPoint;
        if (DragWorldPoint(eventData, out worldPoint))
        {
            Quaternion currentDragAngle = Quaternion.LookRotation(worldPoint - target.transform.position, Vector3.forward);
            if (OnAngleChanged != null)
            {
                OnAngleChanged(currentDragAngle * dragStartInverseRotation * dragStartRotation);
            }

            if (target.transform.rotation.z > 85)
            {
                target.transform.rotation = Quaternion.Euler(0, 0, 90);
            }
        }
    }


  
    private bool DragWorldPoint(PointerEventData eventData, out Vector3 worldPoint)
    {
        return RectTransformUtility.ScreenPointToWorldPointInRectangle(
            GetComponent<RectTransform>(),
            eventData.position,
            eventData.pressEventCamera,
            out worldPoint);
    }
}

I only took a very quick look at your code, so there may be more, but first and foremost:
Rotations are stored and internally worked with as Quaternions, meaning target.transform.rotation.z > 85 does not do what you expect it to do.

A good way to get around that is to pick a direction vector (say, Vector3.right), and use Vector3.Angle between that vector and some target vector. For example:

if ( (Vector3.Angle(target.transform.rotation * Vector3.right, Vector3.up) < 5f) {
1 Like