Jacob Hicks (akutalata)

1 reply · posted

Rotating GameObjects OnMouseDrag

I am so close to getting a fully working prototype of my application working.  I generate a mesh dynamically based on user input, but then I would like them to be able to rotate it in much the same way objects rotate in the Unity GUI (just the free rotation not the plane constricted versions).  I know the OnMouseDrag() method of my class is being called (I put a debug statement in it), but none of the tutorials I have seen online are causing any rotation.  Can someone help me out?  If I need to brush up on my quaternions I can, but it has been a while.  

Once I have the above working I thought it might be neat to have one of the momentum spins where the object continues to rotate if the user releases the mouse while it is still in motion.  But first things first, I need to get it rotating.

  • crew

    I have a few lessons here and there covering some rotation using mouse input like this one: https://cgcookie.com/lesson/rotating-turret

    This is a code snippet I'm using in a current project for rotating a tank's turret:

        void BaseRotation ()
        {
            moveX += Input.GetAxis("Mouse X") * speed;
            baseRotation = Quaternion.Euler(0, moveX, 0);
            turretBase.rotation = Quaternion.Lerp(turretBase.rotation, baseRotation, smooth);
        }
    


    This just works off the Horizonal axis of the mouse, but you could also add in the Y axis as well. So something like this:

        void BaseRotation ()
        {
            moveX += Input.GetAxis("Mouse X") * speed;
            moveY += Input.GetAxis("Mouse Y") * speed;
            baseRotation = Quaternion.Euler(moveY, moveX, 0);
            turretBase.rotation = Quaternion.Lerp(turretBase.rotation, baseRotation, smooth);
        }
    

    So in that code snippet you're moving both along the X and Y axis. The horizontal axis (Mouse X) rotates the object along the Y axis (like turning your head) while the Vertical Axis (Mouse Y) rotates the object along its X axis (looking up and down). Speed and Smooth are float values that just help it move faster/slower. Hope that helps.