Mike6679
Mike6679

Reputation: 6117

Unity3D How to Prevent "Tilt" when rotating on x and z axis only?

(This is 3d. Screen shot attached for reference.)

I have read so many articles on here or elsewhere on issues similar to mine but nothing solves it. My pistol is pointing forward and I only rotate on the x and z axis (up , down , left, right) but my pistol always ends up tilted to the left or right. I tried solutions like this (Problems limiting object rotation with Mathf.Clamp()) (substituting x for y)but my gun ends up freezing or in in weird positions. I think I'm missing a fundamental concept here.

I should also mention that the rotating left, right , up down on their own does work correctly BUT its when combining them all together is when things go awry. For example: left rotate > then up rotate > then left rotate then I end up in a titled position

You can see in the picture that my controls on the bottom left only allow the user to move the gun up, down left and right --- but somehow the gun ends up tilted, in this screen shot to the right --- I want to prevent tilt to right or left.

public void Update()
         {
             if (mButtonHeld) {
                 switch(mCurBtnName){
                     case "ButtonUp":
                     mPistol.transform.Rotate (PISTOL_INCREMENT, 0, 0); 

                     break;
                     case "ButtonDown":
                        mPistol.transform.Rotate (-PISTOL_INCREMENT, 0, 0); 

                     break;
                     case "ButtonLeft":
                         mPistol.transform.Rotate(0,0,-PISTOL_INCREMENT_LR);    

                     break;
                     case "ButtonRight":
                         mPistol.transform.Rotate(0,0,PISTOL_INCREMENT_LR);
                     break;
                 }
                         //How can I lock y axis here??
             } 
         }

enter image description here

Upvotes: 0

Views: 1882

Answers (1)

Frederic Gaudet
Frederic Gaudet

Reputation: 161

Applying rotations to different axis is not commutative; the order is important and this is probably what is causing you problems. A simple fix is to do something like that:

public void Start()
{
    (...)
    m_VectorPistolInitState = mPistol.transform.rotation;
}

public void Update()
{
    static float azimuth = 0;
    static float elevation = 0;
    if (mButtonHeld) {
        switch(mCurBtnName){
            case "ButtonUp":
                elevation += PISTOL_INCREMENT;
            break;
            case "ButtonDown":
                elevation -= PISTOL_INCREMENT;
            break;
            case "ButtonLeft":
                azimuth -= PISTOL_INCREMENT_LR;
            break;
            case "ButtonRight":
                azimuth += PISTOL_INCREMENT_LR;
            break;
        }

        mPistol.transform.rotation = m_VectorPistolInitState;
        mPistol.transform.Rotate(elevation,0,azimuth);
    } 
}

Upvotes: 1

Related Questions