【发布时间】:2016-10-01 12:55:42
【问题描述】:
我正在制作一个简单的太空游戏,其中一艘船左右移动以躲避小行星。
我从this video学会了左右移动我的船。
但是这个动作是相当块状的。如何顺利移动船?
这是我所有的代码:
// JavaScript Document
////// Variables //////
var canvas = {width:300, height:300 };
var score = 0;
var player = {
x:canvas.width/2,
y:canvas.height-100,
speed: 20
};
////// Arrow keys //////
function move(e) {
if(e.keyCode == 37) {
player.x -= player.speed;
}
if(e.keyCode == 39) {
player.x += player.speed;
}
update();
}
document.onkeydown = move;
////// other functions //////
//function to clear canvas
function clearCanvas() {
ctx.clearRect(0,0,canvas.width,canvas.height);
}
// Draw Player ship.
function ship(x,y) {
var x = player.x;
var y = player.y;
ctx.fillStyle = "#FFFFFF";
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() {
clearCanvas();
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>
【问题讨论】:
-
一般来说,如果您更频繁地进行较小的动作(较小的 'player.speed')(时间间隔 1000/60=16.67),您的动作会更流畅。考虑了解requestAnimationFrame,这是一个更好的动画时序循环。
标签: javascript html canvas arrow-keys