简体   繁体   中英

Object in a rotate loop in Unity

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.

Try using

transform.Rotate(new Vector3(0f, 180f, 0f), Space.World);

Well that's pretty obvious.

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.

What you want is probably rather eg

transform.rotation = Quaternion.Euler(0, 180, 0);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM