Home > Back-end >  Rotating Object is Snapping to a Spot not Moving at a constant speed
Rotating Object is Snapping to a Spot not Moving at a constant speed

Time:10-27

I have a script so that when I let go of both of the left and right arrow keys it moves back to 0, but it is snapping to 0. This is my code to check that the statements are true:

        if (!Input.GetKey(KeyCode.RightArrow) && !Input.GetKey(KeyCode.LeftArrow)) {
    if (transform.eulerAngles.z < 0) {
    rotation  = speed * Time.deltaTime;     
    }
    else{
        rotation = 0;
    }
    }

And this is the script that rotates the GameObject:

rotation = Mathf.Clamp(rotation, -30, 30);
    transform.localRotation = Quaternion.Euler(0, 0, rotation);

I want to make it so that it moves at the speed of Float: speed and doesnt snap to that rotation.

CodePudding user response:

Ah I think I got now what you want.

You an achieve that by using Mathf.MoveTowards in order to smoothly move the rotation value towards 0 - regardless whether it is positive or negative - as soon as no button is pressed:

var left = Input.GetKey(KeyCode.LeftArrow);
var right = Input.GetKey(KeyCode.RightArrow);

if (left && !right)
{
    rotation -= speed * Time.deltaTime;
}
else if (right && !left)
{
    rotation  = speed * Time.deltaTime;
}
else
{
    rotation = Mathf.MoveTowards(rotation, 0, speed * Time.deltaTime);
}

rotation = Mathf.Clamp(zRotation, -30, 30);

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

Note: Now if you press both it is the se as if you press no key at all. If you don't want this behavior you could just remove the excluding conditions (!left and !right)

  • Related