Hello everyone,
I'm currently having issues making the arrow keys working correctly while pressing [space] key. Everything is working whle holding [space] key and one of the arrow keys. But if I try to press [space] and hold [up] and [left] at the same time , it will go straigh to the top of the screen as if the [left] key wasn't even pressed (it should move diagonally to the top left corner). This is only happening while pressing [space]. I'd like to use this key for shooting bullets later on.
Is there something wrong in my code? Or is it some kind of bug?
Apologies for my bad english :/ ..
<!DOCTYPE html>
<body>
<canvas id="myCanvas" width="568" height="262">
</canvas>
<script type="text/javascript">
var canvas;
var ctx;
var dx = 0.5;
var dy = 0.5;
var x = 284;
var y = 130;
var WIDTH = 568;
var HEIGHT = 262;
var keys = new Array();
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
window.addEventListener('keydown',doKeyDown,true);
window.addEventListener('keyup',doKeyUp,true);
return setInterval(draw, 1);
}
function draw() {
move();
clear();
ctx.fillStyle = "white";
ctx.strokeStyle = "black";
rect(0,0,WIDTH,HEIGHT);
// player ///
ctx.fillStyle = "purple";
circle(x, y, 20);
}
function doKeyDown(evt)
{
keys[evt.keyCode] = true;
evt.preventDefault(); // Prevents the page to scroll up/down while pressing arrow keys
}
function doKeyUp(evt){
keys[evt.keyCode] = false;
}
function move() {
if (32 in keys && keys[32]){
; // fire bullets
}
if (38 in keys && keys[38]){ //up
y -= dy;
}
if (40 in keys && keys[40]){ //down
y += dy;
}
if (37 in keys && keys[37]){ //left
x -= dx;
}
if (39 in keys && keys[39]){ //right
x += dx;
}
}
init();
</script>
</body>
</html>