kittykatattack / learningPixi

A step-by-step introduction to making games and interactive media with the Pixi.js rendering engine.
4.4k stars 851 forks source link

Keyboard Movement - buggy logic #83

Open ova2 opened 6 years ago

ova2 commented 6 years ago

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.

shamanX86 commented 6 years ago

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 commented 6 years ago

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

keanemind commented 5 years ago

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.