Hello everyone! I am making my runner game, and I got a problem with turns. Look:
if(Input.GetKeyDown(KeyCode.A))
transform.position = new Vector3(Mathf.Lerp(transform.position.x, transform.position.x-5, smooth*Time.time), transform.position.y, transform.position.z);
I want my runner to change his X-position smoothly, so I am using lerp. But the problem is that it doesn’t smoothes my turns:
if smooth = 1, it changes position very fast, like there is no smooth at all;
but if smooth<1, it changes position very fast as well, but it is less that 5.
So how to make a smooth change in position with Lerp?
Lerp functions will return a linearly eased value between the from and to value that you provide. The time/progress parameter needs to be a value between 0 and 1, with 0 resulting in the from value being returned, and a 1 returning the to value, and numbers between returning the progression between the two values.
Your code currently listens for the key-down event of the A key, and then instantly moved the transform position to x-5, since you’re passing in Time.time which will likely be greater than 1.
If you’re wanting to change your players direction gradually, I’d suggest maintaining an x-velocity value and lerping it up to the desired speed given the players current running direction.
float x_velocity = 0;
float MAX_SPEED = 5;
float SMOOTH_DAMPING = 0.1f;
if(Input.GetKey(KeyCode.A))
x_velocity = Mathf.Lerp(x_velocity, -MAX_SPEED, SMOOTH_DAMPING);
else if(Input.GetKey(KeyCode.D))
x_velocity = Mathf.Lerp(x_velocity, MAX_SPEED, SMOOTH_DAMPING);
else
x_velocity = Mathf.Lerp(x_velocity, 0, SMOOTH_DAMPING);
transform.position += new Vector3(x_velocity, 0 0);
Or something along those lines…
Hope that helps.
It is amazing! It is working! fenderrio, thank you very much!
If you use transform.position.x and transform.position.x-5, both those positions will change over time. You have to use a variable for the final position so it doesn’t change.