learningPixi icon indicating copy to clipboard operation
learningPixi copied to clipboard

Keyboard Movement - buggy logic

Open ova2 opened this issue 7 years ago • 3 comments

Hello,

The code in https://github.com/kittykatattack/learningPixi/blob/master/examples/12_keyboardMovement.html is not quite correct in my opinion. Steps to reproduce:

  1. press the right arrow -> the sprite starts running to the right direction (ok)
  2. keep the right arrow and press the left arrow -> the sprite gets running to the left direction (ok)
  3. release the left arrow -> the sprite keeps running to the left direction (not ok).

The behavior of the step 3) is not correct. The sprite should run to the right because the right arrow is still pressed.

ova2 avatar Dec 16 '17 19:12 ova2

A possible solution,

//assuming the variables for left arrow and right arrow keys to be left and right respectively.

let v1 = 0, v2 = 0, v3 = 0;

left.press = () => {v1 = -5; v3 = -5;}
left.release = () => {v1 = 0;}
right.press = () => {v2 = 5; v3 = 5;}
right.release = () => {v2 = 0;}

//now inside the play(delta) function.

function play(delta) {
    if((v1 + v2 === 0) && v1 != 0 && v2 != 0){cat.vx = v3;}
    else {cat.vx = v1 + v2;}
}

This should bring about the required behavior.

shamanX86 avatar Mar 12 '18 11:03 shamanX86

@ova2 can you please check if my solution working for you??

shamanX86 avatar Mar 15 '18 14:03 shamanX86

How about if pressing left and right at the same time (or up and down at the same time) cancel each other out, causing no movement along that axis? Many games work this way.

keanemind avatar Oct 07 '18 15:10 keanemind