- Home /
Detecting left and right being pressed at the same time.
I'm working on a 2D platformer and one of the things I want to implement is zeroing out the player's X velocity if both left and right are being pressed at the same time. Almost everything I've tried in code hasn't worked at all unless both keys are pressed down starting at the same time. What I want to do is, if the player is holding right and then starts pressing left at the same time, they come to a stop.
if (Input.GetKey("left")) {
transform.localScale = Vector2(-1,1);
physics.velocity.x += Input.GetAxis("Horizontal") * physics.maxVelocity.x * 2;
} else if (Input.GetKey("right")) {
transform.localScale = Vector2(1,1);
physics.velocity.x += Input.GetAxis("Horizontal") * physics.maxVelocity.x * 2;
} else {
physics.velocity.x = 0;
}
Also, since it'll probably come up, I'm using GetKey because GetAxis takes some time to come to a stop when I want the character to be able to stop on a dime.
Answer by AlucardJay · May 11, 2012 at 04:40 PM
untested , but try checking for both buttons first , then follow down to each individual button :
if (Input.GetKey("left") && Input.GetKey("right")) {
physics.velocity.x = 0;
} else if (Input.GetKey("left")) {
transform.localScale = Vector2(-1,1);
physics.velocity.x += Input.GetAxis("Horizontal") * physics.maxVelocity.x * 2;
} else if (Input.GetKey("right")) {
transform.localScale = Vector2(1,1);
physics.velocity.x += Input.GetAxis("Horizontal") * physics.maxVelocity.x * 2;
}
I... feel especially dumb right now because that's the one thing I didn't try. I think I kept leaving the check in its own conditional statement rather than part of the whole. This works perfectly though, thanks!
Your answer
Follow this Question
Related Questions
Stopping an object immediately 1 Answer
New Input System 'Started' and 'Performed' actions fire at the same time? 1 Answer
Weird Rigidbody2D.velocity.x problem, float out of control 0 Answers
Is there a way to check agent velocity for NavMeshAgent movement? 5 Answers
Stuttering/jerky movement of kinematic rigidbody 2d moving by velocity in 2D game on iOS 0 Answers