- Home /
Rotate 2d image by dragging with mouse
I'm trying to make a 2D image rotate in increments by clicking and dragging. I've successfully managed to get this working on a 3D quad, but trying to translate the code to a UI image fails to yield any results. I'm inches away from ripping my own hair out over this.
The code in question that's working for the 3D quad is as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseRotate : MonoBehaviour {
public int snapdegrees;
private float baseAngle = 0.0f;
void OnMouseDown(){
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos = Input.mousePosition - pos;
baseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;
baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) *Mathf.Rad2Deg;
}
void OnMouseDrag(){
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos = Input.mousePosition - pos;
float ang = Mathf.Atan2(pos.y, pos.x) *Mathf.Rad2Deg - baseAngle;
ang -= (ang % (360.0f/snapdegrees));
transform.rotation = Quaternion.AngleAxis(ang, Vector3.forward);
}
}
when trying to make this work in 2D, the object fails to recognise any clicks, even with a 2D collider on it.
Answer by spilat12 · May 19, 2018 at 06:25 PM
First of all, your script is perfectly fine for 2D, it should work for any 2D object that has a collider on it.
However, if you are using UnityEngine.UI elements, it will not work, because
UnityEngine.UI elements have no transform
OnMouseDown is called only with GUIElements or colliders
From the documentation:
OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
My advice: use the EventTriggers instead. Note the OnBeginDrag, OnEndDrag and OnDrag.
EDIT:
I hope that helps.
Vector3 RotationVector;
public void RotateUIElement()
{
GetComponent<RectTransform>().Rotate(RotationVector);
}
The setup:
Make sure you have an EventSystem in the scene.
What you're suggesting isn't making enough sense, so if you could explain it in a more detailed manner, or even provide a working example, that would help me even more.
Still not making enough sense. if you could share the full contents of your uiRotation script, so i can see how that's set up, and i should be able to successfully get there
Your answer
Follow this Question
Related Questions
How can I add a distance cap to this script? 3 Answers
How do I trigger GUI elements 1 Answer
[Unity UI] Keep Text in Image 0 Answers
Why is the alpha on my UI Image not decreasing properly? 2 Answers
Where is the Editor UI stored? 1 Answer