- Home /
Moving Right pressing left
I have my character running on a 2D plane and with the current script he stops moving when both left and right are held down. Any tips on how to have the character continue moving right if right was pressed first even if player presses left at the same time?
if (Input.GetKey("a") ) {
x += -0.5f;
}
if (Input.GetKey("d") ) {
x += 0.5f;
}
Answer by robertbu · Aug 02, 2013 at 11:38 PM
This is a simple problem to state, but I don't see a simple fix. Here is one way:
#pragma strict
var rightFirst = true;
function Update() {
var x = 0.0;
var rightDown = Input.GetKeyDown(KeyCode.D);
var right = Input.GetKey (KeyCode.D);
var leftDown = Input.GetKeyDown(KeyCode.A);
var left = Input.GetKey (KeyCode.A);
if (rightDown && !left ) rightFirst = true;
if (leftDown && !right) rightFirst = false;
if (right && rightFirst ) x -= 0.05f;
if (left && !rightFirst ) x += 0.05f;
if (Input.GetKeyUp(KeyCode.D)) rightFirst = false;
if (Input.GetKeyUp(KeyCode.A)) rightFirst = true;
}
Note if this is some sort of movement code, you want to scale your movement by Time.deltaTime
.
it didn't work for me when I put it into my code but I'm sure others will definitely find this useful. Thanks.
If you want to post more of your code, I'll be glad to help you integrate it. I see one "mistake." When I tested it I changed the amount to add and subtract from 'x'. Your original code at 0.5.
I am not sure if I can because this is from an asset I got and I don't know how all this works.
Your answer
![](https://koobas.hobune.stream/wayback/20220613111439im_/https://answers.unity.com/themes/thub/images/avi.jpg)