Hello. I want to know if there is a way to rotate the object only when the user click and drag on the gameobject. If the user click and drag anywhere else, the gameobject must not rotate.
Here is my rotating script in C#:
using UnityEngine;
using System.Collections;
public class RotateShelf : MonoBehaviour {
private Camera myCam;
private Vector3 screenPos;
private float angleOffset;
void Start () {
myCam=Camera.main;
}
void Update () {
//This fires only on the frame the button is clicked
if(Input.GetMouseButtonDown(0)) {
screenPos = myCam.WorldToScreenPoint (transform.position);
Vector3 v3 = Input.mousePosition - screenPos;
angleOffset = (Mathf.Atan2(transform.right.y, transform.right.x) - Mathf.Atan2(v3.y, v3.x)) * Mathf.Rad2Deg;
}
//This fires while the button is pressed down
if(Input.GetMouseButton(0)) {
Vector3 v3 = Input.mousePosition - screenPos;
float angle = Mathf.Atan2(v3.y, v3.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0,0,angle+angleOffset);
}
}
}
The object is rotating when I click and drag anywhere in the view. Is there a way to only set it to the gameobject?
you can use the OnMouseDown() function. It gets fired once the player clicks an object.
You can create a new bool that get’s set to true in the OnMouseDown, and get’s set to false once the player releases his mouse button.
Thank you Thank you Thank you!! Omg I spent so much time searching for a script that will do this! I’ve spent so much time, trying to combine scripts I’ve found that didn’t work like I wanted them to work. And nooow finally I found your script! You are my hero, thank you! Your script works perfect .o.