- Home /
How to rotate an object using mouse (only z axis, not x and y) in 3D
Hi guys As I already mentioned, is there any way to rotate an object only z axis using mouth in unity 3D?
I've been searching internets but I couldn't find out how to do that...
@Bunny83 @Eric5h5 @robertbu @aldonaletto @whydoidoit @tanoshimi @duck @fafase @clunk47 @Statement @Graham-Dunnett
Answer by Tanoshimi2000 · Aug 05, 2019 at 04:52 PM
Try this:
Vector3 mRot;
Vector3 point = new Vector3();
Event currentEvent = Event.current;
Vector2 mousePos = new Vector2();
// Get the mouse position from Event.
// Note that the y position from Event is inverted.
mousePos.x = currentEvent.mousePosition.x;
mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
// get the current rotation
mRot = myObject.rotation.eulerAngles;
// change the rotation
mRot.z = Mathf.Clamp(point.x, -360, 360); // or point.y
// apply the changes
myObject.rotation.eulerAngles = mRot;
This will make the object rotate when the mouse is rotated. You can play with the mRot.z = line to change the speed at which it rotates relative to the mouse. For example, you might want the top of the screen to be 0, and the bottom of the screen to be 360 so that moving from top to bottom allows you to see the entire object. Or right to left.
*** This is code I just drummed up and partially copied from samples, so I can't guarantee it will work. But it will give you a start.