我正在製作一個簡單的空間遊戲,其中一艘船左右移動以躲避小行星。如何使用箭頭鍵在畫布中平滑移動對象
我學會了將我的船從this video左右移動。
但是,這個動作很塊。我如何順利移動船?
這裏是我的所有代碼:
// 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>
的可能的複製【正文動畫不流暢(http://stackoverflow.com/questions/32365542/body-animation-isnt-smooth) – Kaiido
一般情況下,你的動作如果更頻繁地進行更小的移動(更小的'player.speed')(時間間隔1000/60 = 16.67),將會更平滑。考慮學習[requestAnimationFrame](https://www.paulirish。com/2011/requestanimationframe-for-smart-animating /)這是一個更好的動畫定時循環。 – markE