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?
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.
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.
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.