- Home /
The question is answered, right answer was accepted
(Solved) Continuous movement
Hi, I am trying to get my player to move in one direction continuously and then move the opposite direction continuously when I press a button. So far I've been able to get the player to move in one direction continuously, however when I want it to go the other way I have to hold down a button rather than just press it once.
This is what I've got (btw this is for a 2D game)
rigidbody2D.velocity = new Vector2(transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);
bool movementKeyPressed = false;
if (Input.GetKey(KeyCode.RightArrow)|| Input.GetKey(KeyCode.D))
{rigidbody2D.velocity = new Vector2(transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);
movementKeyPressed = true;
}
if (Input.GetKey(KeyCode.LeftArrow)|| Input.GetKey(KeyCode.A))
{
rigidbody2D.velocity = new Vector2(-transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);
movementKeyPressed = true;
}
$$anonymous$$ake sure this line isn't in your update function
rigidbody2D.velocity = new Vector2(transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);
Also, it would help if your code in your post was formatted better.
Accept the answer if it was helpful; don't write "solved" in the title.
Answer by thaiscorpion · Feb 18, 2014 at 12:12 AM
You can try keeping this line:
rigidbody2D.velocity = new Vector2(transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);
But add in a direction variable, that would be '1' if going right and '-1' if going left and multiply it like this:
rigidbody2D.velocity = new Vector2(playerDirection * transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);
Now if you change you input ifs like this:
if (Input.GetKey(KeyCode.RightArrow)|| Input.GetKey(KeyCode.D)){
playerDirection = 1;
movementKeyPressed = true;
}
if (Input.GetKey(KeyCode.LeftArrow)|| Input.GetKey(KeyCode.A)){
playerDirection = -1;
movementKeyPressed = true;
}
This way once you press the button the player will continue to move in that direction until you press another direction button. Hope that helps.
Thanks thaiscorpion, that works; but when creating a variable was I supposed to write
int playerDirection = 1;
Follow this Question
Related Questions
animation 2d platformer 2 Answers
Why do I double jump? This isn't supposed to happen... 2 Answers
2d platformer dash move. 1 Answer
Animating 2D sprite upon movement script help. 2 Answers
Damaging Enemies 1 Answer