Home > Blockchain >  Object in a rotate loop in Unity
Object in a rotate loop in Unity

Time:01-05

I was making a function so that my object can turn around. So I made this function:

void Drehen(){
    if(Input.GetAxis("Horizontal") > 0.1){
        transform.Rotate(new Vector3(0f, 0f, 0f));
        vorne = true;
    }

    if(Input.GetAxis("Horizontal") > -0.1){
        transform.Rotate(new Vector3(0f, 180f, 0f));
        vorne = false;
    }

    
}

The function checks the input if the player goes forwards or backwards and rotates him in the direction via transform.Rotate(new Vector3(0f, 180f, 0f));

Now, every time I start the game I am able to go forward but as soon as I go backward it flips every side every frame.

CodePudding user response:

Try using

transform.eulerAngles = new Vector3(0f, 180f, 0f);

CodePudding user response:

Well that's pretty obvious.

  1. Rotate rotates the object from the current rotation about the given amount so

     transform.Rotate(0, 0, 0);
    

    does absolutely nothing at all and in

     transform.Rotate(0, 180, 0);
    

    you rotate it by 180° every frame.

  2. In the second condition you have > -0.1 which is the case all the time while you don't press the negative key.

    It should probably rather be < 0.1f.

What you want is probably rather e.g.

var horizontal = Input.GetAxis("Horizontal");

if(horizontal > 0.1f)
{
    // or localRotation depending on your needs
    transform.rotation = Quaternion.identity;
    vorne = true;
}
else if(horizontal < 0.1f)
{
    transform.rotation = Quaternion.Euler(0f, 180f, 0f);
    vorne = false;
}

Or actually as alternative you could also do

var horizontal = Input.GetAxis("Horizontal");

if(Mathf.Abs(horizontal) > 0.1f)
{
    transform.forward = new Vector3(0, 0, horizontal);
}
  •  Tags:  
  • Related