- Home /
How do I make forward and backward speed not affect each other?
I'm new to C# and Unity in general so please excuse me for not knowing most of the terms. I'm having trouble getting my players movement control to work right. My forward speed is faster than my back speed so when I press both keys at once, the character will still move forward only a bit slower. I want to be able to press forward and still have the up and down buttons to work the same but not allow the back button to work until I let go of the forward button... and vice-versa.
public float forwardSpeed = 7;
public float backSpeed = 4;
public float dropSpeed = 4;
public float riseSpeed = 5;
void Update () {
if(Input.GetKey("up")) {
transform.position = transform.position + (transform.up * riseSpeed * Time.deltaTime);
}
if(Input.GetKey("down")) {
transform.position = transform.position - (transform.up * dropSpeed * Time.deltaTime);
}
if(Input.GetKey("left")) {
transform.position = transform.position - (transform.right * backSpeed * Time.deltaTime);
}
if(Input.GetKey("right")) {
transform.position = transform.position + (transform.right * forwardSpeed * Time.deltaTime);
}
}
Answer by Deathcalibur · Jun 18, 2013 at 07:43 PM
One simple solution is to check if "competing" keys are pushed down in your if statements. For example:
if(Input.GetKey("up")) ... //stays the same
if(Input.GetKey("down") && !Input.GetKey("up"))... //! is logically NOT whatever
In this case, up will always have precedence over the down key. It's not the best solution necessarily but something to get you started with. You can do the same with left and right if you need. There are better ways to handle this if you want the first/last key pressed to take precedence.
Your answer
Follow this Question
Related Questions
Javascript coding on how to zoom in using keyboard 1 Answer
same keyboard multiplayer for two cars 0 Answers
Basic Keycontrole doesnt work 2 Answers
Best Practice Multiple Control Methods 1 Answer
Removing Joystick Controls 2 Answers