Home > Mobile >  Clamping a Rotating GameObject
Clamping a Rotating GameObject

Time:10-26

I have tried to clamp a rotation on one of my Gameobjects for over a week now and still have no luck. This is my code so far and what I have tried:

        if ((transform.rotation.eulerAngles.z > 330  ) && (Input.GetKey(KeyCode.RightArrow)))
    {
    
    transform.Rotate(Vector3.forward * speed * Time.deltaTime * -1);
    }

    if ((transform.rotation.eulerAngles.z < 30) && (Input.GetKey(KeyCode.LeftArrow)))
    {
    
    transform.Rotate(Vector3.forward * speed * Time.deltaTime);
    }

Then I went on and tried this:

    if (Input.GetKey(KeyCode.RightArrow))
    {
    
    transform.Rotate(Vector3.forward * speed * Time.deltaTime * -1);
    }

    if (Input.GetKey(KeyCode.LeftArrow))
    {
    
    transform.Rotate(Vector3.forward * speed * Time.deltaTime);
    }
    transform.localEulerAngles = new Vector3( 0 , 0 , Mathf.Clamp(0, -30, 30) );

But I still have no luck. Btw I am using C# This is the type of game that it looks like and I also wish for the player to rotate back to 0 when no key is pressed

This is the type of game that it looks like and I also wish for the player to rotate back to 0 when no key is pressed

CodePudding user response:

Your second code example is much cleaner. The only issue is in your last line:

transform.localEulerAngles = new Vector3( 0 , 0 , Mathf.Clamp(0, -30, 30) ); //this always returns [0,0,0]

I think you mean:

float rotation = 0;
if (Input.GetKey(KeyCode.RightArrow))
{        
   rotation -= 1;
}

if (Input.GetKey(KeyCode.LeftArrow))
{
    rotation  = 1; 
}
float newZAngle = transform.localEulerAngles.Z   (speed*Time.deltaTime*rotation);
transform.localEulerAngles = new Vector3( 0 , 0 , Mathf.Clamp(newZAngle, -30, 30) );

I wrote that without an IDE, so there might be some typos. Also, I haven't used Unity in a while, I'm just going off memory.

Also, I changed rotation using =/-= so that when you hold both arrows it doesn't rotate.

CodePudding user response:

I think the issue has to do with how you are handling your angles. Here is a link to something from 2014 (but should still be relevant in your situation since it appears to be a logical issue). There is also someone who updated a reply from this year. Ill attach a screenshot for the person who specifically discusses how to clamp euler angles (incase you dont want to click the link) enter image description here

  • Related