movement key press

Hi all,

My question is how do I make a character move in only the direction of the last arrow key input.

So if you press up the character moves upward and then press left without letting go of the up arrow, the character stops moving up and then moves left instead. I have tried and I presume the solution is incredibly simple but it just doesn’t want to reveal itself to me.

Here is the code I currently tried, it works but only in one of the axis, when moving up or down the character will change direction if you press either the left or right keys. However if you start with the left or right keys, then the character doesn’t change when you press the up or down.


		     if(input.left.isPressed()) mx--;
		else if(input.right.isPressed()) mx++;
		else if(input.up.isPressed()) my--;
		else if(input.down.isPressed()) my++;

I have also tried to make it that when you press one of the arrow keys all the other keys are released and that had the same result as this code, one axis it works and the other it does not.

Sorry if it is difficult to understand the question, my brain is fried from trying to figure this out, the quality of the question could be ruined because of that.

Use mx and my. Whenever any key is pressed (as in when it goes down not when it is down) set both mx and my to zero and then set them as appropriate for the key that is pressed.

remove else from all the statements

currently in your current set of if statements, if one key is pressed, the other cant be pressed.

in your current code, left has priority, if you press left and down, left will always execute as its the first if statement. to fix this, you must have a separate if statement for each key press, so do not use

 else if(statement) 

.

new code:


if(input.left.isPressed()) mx--;
if(input.right.isPressed()) mx++;
if(input.up.isPressed()) my--;
if(input.down.isPressed()) my++;

remember, when you have if else statements, it will continue to check each else if until the statement is TRUE, it will not check all if it does not have to.

this is how I had it originally, but this allows players to move in diagonal lines… and that is now what I want… I need it to move in only one direction at a time

So say


if(!input.left.isPressed() && input.up.isPressed()) my--;

Do this for all the angles. Its simple.