kittykatattack / learningPixi

A step-by-step introduction to making games and interactive media with the Pixi.js rendering engine.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Keyboard Movement - buggy logic

ova2 opened this issue · 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.

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.

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

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.