How to add smooth Player Movement?

Viewed 42

I have added the player movement in the Update() function using the code below:

if (Input.GetKeyDown(KeyCode.LeftArrow))
{
    transform.position += transform.right * (Time.deltaTime * 5);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
    transform.position -= transform.right * (Time.deltaTime * 5);
} 

This works, however, the movement is choppy. The user would have to click on the left arrow multiple times to have the object move left and the same for the right arrow. I want to have the user click on the left arrow while the object keeps moving left until the left arrow is released. How do I go about doing this?

2 Answers

Use Input.GetKey("KeyName") instead of Input.GetKeyDown("KeyName").

According to Unity's documentation, GetKeyDown will return true only when the button is pressed not when you are holding it down. If you want to move the game object continuously when the button is pressed you need to use the GetKey method.

transform.Translate(Vector3.right * Time.smoothdeltatime* 5);
transform.Translate(Vector3.left * Time.smoothdeltatime* 5);
Related