Diagonal move not working and issue on left-longPress/right simultaneous
But on double keypress the ship goes crazy!
$(document).bind(\'keydown\', fu
Relying on keyboard events to move an element will make it dependent on the OS key-interval delay. Instead, use the game interval and check the pressed keys stored inside an Object
On keydown keyup
events, if the keyCode returned by event.which
is >=37 && <=40
means arrow keys were used. Store inside a K
(keys) Object a boolean value for key-number property.
Inside a window.requestAnimationFrame
increase or decrease the x
, y
position of your element if a key-number property (inside our K
object) is true
(if(K[37])
).
Moving an element diagonally using simultaneously i.e. the ↑ and → needs a compensation for the diagonal distance: 1 / Math.sqrt(2)
(0.7071..)
const Player = {
el: document.getElementById('player'),
x: 200,
y: 100,
speed: 2,
move() {
this.el.style.transform = `translate(${this.x}px, ${this.y}px)`;
}
};
const K = {
fn(ev) {
const k = ev.which;
if (k >= 37 && k <= 40) {
ev.preventDefault();
K[k] = ev.type === "keydown"; // If is arrow
}
}
};
const update = () => {
let dist = K[38] && (K[37] || K[39]) || K[40] && (K[37] || K[39]) ? 0.707 : 1;
dist *= Player.speed;
if (K[37]) Player.x -= dist;
if (K[38]) Player.y -= dist;
if (K[39]) Player.x += dist;
if (K[40]) Player.y += dist;
Player.move();
}
document.addEventListener('keydown', K.fn);
document.addEventListener('keyup', K.fn);
(function engine() {
update();
window.requestAnimationFrame(engine);
}());
#player{
position: absolute;
left: 0; top: 0;
width: 20px; height: 20px;
background: #000; border-radius: 50%;
}
Click here to focus, and use arrows