I am building a game where you are rotating some GameObjects. When you select the GameObject, a handle will appear. When you press and drag the handle (or GameObject) I would like to rotate only on the Y-axis the depending on the mouse position. I was thinking of using transform.LookAt but I can´t seem to get it correct. The code below is what I have used now, but it only rotates the GameObject depending on the mouse x position. I would like the player to really have control over the rotation. Any ideas?
You might be able to actually track the change in the current drag angle around the object and react accordingly. Something like this:
Vector3 startDragDir;
Vector3 currentDragDir;
Quaternion initialRotation;
float angleFromStart;
void OnMouseDown()
{
startDragDir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
initialRotation = transform.rotation;
}
void OnMouseDrag()
{
currentDragDir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
//gives you the angle in degrees the mouse has rotated around the object since starting to drag
angleFromStart = Vector3.Angle(startDragDir, currentDragDir);
transform.rotation = initialRotation;
transform.Rotate(0.0f, angleFromStart, 0.0f);
}
I haven’t actually tested this code, so it might take some tweaking, but I think this would work. I used this sort of code in an iphone game where you rotate things by dragging your finger around an object.
Hi @MattiasWargren and @justinpatterson
Your script works fine for the object rotation on mouse click-drag.
I’ve been trying to control minimum and maximum rotation angles on both x and y. Consider I can rotate and view an objects top view, but dont wanna see the bottom. Same way I can rotate and see front left and right side views but dont wanna rotate to see backside. How to control and set Minimum(x and Y) and Maximum(x and y) angles in the script.
(Note: I dont wanna rotate camera rather only object rotation)
Please Help