Hallo Leute,
ich programmiere momentan ein Javascript Spiel mit HTML5 Canvas.
Die Steuerung hackt noch ein bischen. Mir ist das Verhalten des Browsers
nicht ganz klar.
Hier ist ein kleines funktionierender Code(Einfach kopieren, speichern, im Browser öffnen)
Das Problem ist:
Drückt man "oben" dann "rechts" und dann "links" funktioniert das einwandfrei.
Drückt man aber "unten" dann "rechts" und dann "links" gibt es einen kleinen Stopp.
Wieso gibt es diesen kleinen Stop beim move nach oben nicht?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<div>
<canvas id="canvas" width="500" height="500" style="border: 1px solid black">
</canvas>
</div>
<script>
$(document).ready(function(){
game();
function game(){
var self = this;
this.keydown = null;
this.prevkey = null;
this.canvas = document.getElementById("canvas");
this.context = canvas.getContext("2d");
this.x = 0;
this.y = 0;
window.setInterval(function(){
self.inputs();
self.move();
self.draw();
}, 50);
this.inputs = function(){
var self = this;
$("body").keydown(function(e){
if(self.prevkey==null) self.prevkey = e.keyCode;
self.keydown = e.keyCode;
});
$("body").keyup(function(e){
if(self.prevkey === e.keyCode){
self.prevkey = null;
}
else{
self.keydown = self.prevkey;
}
});
};
this.move = function(){
switch(this.keydown){
case 40:
this.y += 2;
break;
case 38:
this.y -= 2;
break;
case 39:
this.x += 2;
break;
case 37:
this.x -= 2;
break;
};
};
this.draw = function(){
this.context.fillStyle = "white";
this.context.fillRect(0,0,500,500);
this.context.fillStyle = "black";
this.context.fillRect(this.x,this.y,50,50);
};
};
});
</script>
</body>
</html>