Movement script problem

I wanna code a script that moves a player in specific direction when i press a key once, but i want a movement to be going on until i stop it with a key so im using a GetKeyDown command but i dont know how to execute this all cuz when i use

void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
transform.Translate(Vector2.up);
}
}
It just moves a bit. How do I execute code in if brackets every frame?

Use the keypress to set the direction of movement, then move the player every frame based on that direction.

private Vector2 movementDirection;
private float movementSpeed = 10;

private void Update()
{
    if(Input.GetKeyDown(KeyCode.W))
    {
        movementDirection = Vector2.up;
    }
   
    Move();
}

private void Move()
{
    transform.Translate(movementDirection * movementSpeed * Time.deltaTime);
}

Basically GetKetDown returns true only for the first frame when you hold button. GetKey returns true continuously while holding the button.

Code under GetKeyDown will execute once no matter how long you keep the key pressed.

If you change GetKeyDown for GetKey, your code should work, but the correct way to move a game object that have a rigibody attached is by applying a force or change its velocity. Send me a reply if you need help with it.

He wants to press the button once and have it keep moving until he presses another button, so that change won’t actually solve his problem.

There are several “right” ways to move a game object, manual translation is valid if you don’t need or want physics.

I 'spose you could use a system of bools so when you press the appropriate key, it changes a bool to true. Then, while the bool is true the character will move that direction. Not entirely sure but I think it would work. Assuming 4 directions, you would just have 4 bools and then an appropriate move direction when the specific bool is true and the others false. If you cant figure anything else out maybe give that a shot.

That can definitely work, but then you’ve got a bunch of booleans to check with if statements and turn on and off all the time which can be a pain to manage, especially if the system grows larger.

If you check out my example code above , I do what you’re describing but store the direction as a Vector2 in a single variable, then use that Vector2 to apply the movement in Update.

1 Like

Whatever works for the dude that is asking. Since the original guy hasnt responded i figured I’d throw out an alternative that maybe he would understand. Definitely not optimal, but its easy to understand. Im still relatively new myself to all this.

1 Like