Ich arbeite daran, ein einfaches Weltraumspiel zu machen, in dem sich ein Schiff nach links und rechts bewegt, um Asteroiden auszuweichen.Wie man mit den Pfeiltasten Objekte in Canvas sanft bewegt
Ich habe gelernt, mein Schiff von this video nach links und rechts zu bewegen.
Aber die Bewegung ist ziemlich blockig. Wie bewege ich das Schiff reibungslos?
Hier ist mein Code:
// JavaScript Document
////// Variables //////
var canvas = {width:300, height:300 };
var score = 0;
var player = {
\t x:canvas.width/2,
\t y:canvas.height-100,
\t speed: 20
};
////// Arrow keys //////
function move(e) {
\t
\t if(e.keyCode == 37) {
\t \t player.x -= player.speed;
\t }
\t if(e.keyCode == 39) {
\t \t player.x += player.speed; \t
\t }
\t
\t update();
\t
}
document.onkeydown = move;
////// other functions //////
//function to clear canvas
function clearCanvas() {
\t ctx.clearRect(0,0,canvas.width,canvas.height);
}
// Draw Player ship.
function ship(x,y) {
\t var x = player.x;
\t var y = player.y;
\t ctx.fillStyle = "#FFFFFF";
\t ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x+15,y+50);
ctx.lineTo(x-15,y+50);
ctx.fill();
}
// update
setInterval (update, 50);
function update() {
\t clearCanvas();
\t ship();
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Game</title>
<script src="game-functions.js"></script>
</head>
<body>
<canvas id="ctx" width="300" height="300" style="border: thin solid black; background-color: black;"></canvas>
<br>
<script>
////// Canvas setup //////
var ctx = document.getElementById("ctx").getContext("2d");
</script>
</body>
</html>
Mögliche Duplikat [Body Animation ist nicht glatt] (http://stackoverflow.com/questions/32365542/body-animation-isnt-smooth) – Kaiido
Im Allgemeinen Ihre Bewegungen wird weicher, wenn Sie kleinere Bewegungen (kleinere 'player.speed') häufiger machen (Zeitintervall 1000/60 = 16,67). Erwägen Sie, etwas über [requestAnimationFrame] (https: //www.paulirish.com/2011/requestanimationframe-for-smart-animating /) das ist eine bessere Timing-Schleife für die Animation. – markE