- Home /
Question by
Voyak · Nov 13, 2018 at 11:10 PM ·
guimouse-dragobject movement
How to rotate UI element with Mouse
Hello Unity Users!
I'm struggling with a problem i cannot seem to find an answer to, despite looking for a few hours now.
Basically i want to have a UI sprite which will have a circle on it and i want to be able to rotate it with mouse drag.
UI canvas is set up for using screen space - overlay. I cannot seem to be able to transfer mouse position on to the rotation of the UI element.
I have this code from another possible solution attached below but it doesnt work as it's using world mouse position i think:
public float rotationSpeed = 8; //This will determine max rotation speed, you can adjust in the inspector
void Update() {
//If you want to prevent rotation, just don't call this method
RotateObject();
}
void RotateObject() {
//Get mouse position
Vector3 mousePos = Input.mousePosition;
//Adjust mouse z position
mousePos.z = Camera.main.transform.position.y - transform.position.y;
//Get a world position for the mouse
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(mousePos);
//Get the angle to rotate and rotate
float angle = -Mathf.Atan2(transform.position.z - mouseWorldPos.z, transform.position.x - mouseWorldPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, angle, 0), rotationSpeed * Time.deltaTime);
}
Please help! Best, Wojtek
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612182105im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I make a Gui mouse interface? 0 Answers
Can I change GUIButton behaviour? 1 Answer
How can i show the texture in the array? 2 Answers
Could I display XML content in Unity GUI interface? 0 Answers