So I am creating a 2d game where basically the player is driving a car and must change lanes to avoid collisions with other cars. I’m using the arrow keys that when you press the left arrow key, you move one lane left, and when you press the right arrow key, you move one lane right. The code I’m currently using is
function Update () {
if (Input.GetKeyDown (KeyCode.LeftArrow)) transform.Translate (Vector2(-1.2,0));
if (Input.GetKeyDown (KeyCode.RightArrow)) transform.Translate (Vector2(1.2,0));
}
this works except that vehicles don’t teleport when they change lanes, they gradually move to the next lane. How would I go about having an object move gradually when a key is pressed?
So it looks like you want the object to move over 1.2 units in either direction when you press the arrows.
Try storing the position that you want to move to (1.2 units away from the cars current position) into a variable, and then each frame, translate the car by a fixed amount until reaching that goal position, and then stop moving!
Do you need example code for this or does that make sense?