如何使用箭头键在画布中平滑移动对象 [英] How to use arrow keys to move object smoothly in canvas

查看:72
本文介绍了如何使用箭头键在画布中平滑移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个简单的太空游戏,其中一艘船左右移动以躲避小行星。



我学会了从< a href = https://www.youtube.com/watch?v=OFzs4unxVtU rel = nofollow>此视频。



但是运动非常块状。我如何平稳地移动船?



这是我所有的代码:



  // JavaScript文档//////变量////// var canvas = {width:300,height:300}; var score = 0; var player = {x:canvas.width / 2,y:canvas.height-100,speed:20}; //////方向键/////// function move(e){if(e.keyCode = = 37){player.x-= player.speed; } if(e.keyCode == 39){player.x + = player.speed; } update(); } document.onkeydown = move; //////其他函数/////////用于清除画布的函数clearCanvas(){ctx.clearRect(0,0,canvas.width,canvas.height);} / /绘制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();} // updatesetInterval(update,50); function update(){clearCanvas(); ship();}  

 <!doctype html>< ; html>< head>< meta charset = UTF-8>< title>我的游戏< / title> < script src = game-functions.js>< / script> < / head>< body><画布id = ctx width = 300 height = 300 style = border:浅黑色;背景颜色:黑色;< / canvas> < br>< script> //////画布设置////// var ctx = document.getElementById( ctx)。getContext( 2d);< / script>< / body> ;< / html>  

解决方案

这是因为键按下会触发事件,类似于键盘在记事本上的键入方式,因为它会触发一次但稍有延迟,并且会触发更多的计时器。 / p>

按照 @Azamantes 的说明解决此问题,您需要将布尔值设置为 true 快捷键上为$ c>,在快捷键上为 false 。然后,您将使用带有 setTimeout / setInterval 和/或 requestAnimationFrame 的主事件循环。在下面的示例中,为简单起见,我仅使用 setInterval 作为主循环,因为您已经拥有了它,然后我们可以移动 move()进入该主循环:






注意:用于实现 requestAnimationFrame 参见@MarkE对这个问题的评论。



requestAnimationFrame 将默认情况下,刷新尽可能多。换句话说,如果需要控制FPS,则需要添加更多逻辑,这在HTML5游戏中很常见。有关在受控FPS上使用 requestAnimationFrame 的信息,请参见此答案



  // JavaScript文档//////变量/ ////// var canvas = {width:300,height:300}; var score = 0; var player = {x:canvas.width / 2,y:canvas.height-100,speed:3}; var LEFT =错误; var RIGHT = false; ///////方向键///////功能move(){if(LEFT){player.x-= player.speed; } if(RIGHT){player.x + = player.speed; }} document.onkeydown = function(e){if(e.keyCode == 37)LEFT = true; if(e.keyCode == 39)RIGHT = true;} document.onkeyup = function(e){if(e.keyCode == 37)LEFT = false; if(e.keyCode == 39)RIGHT = false;} ///////其他函数/////////清除画布的函数function clearCanvas(){ctx.clearRect(0,0,canvas.width, canvas.height);} //绘制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();} // updatesetInterval(update,10); function update(){clearCanvas();船(); move();}  

 <!doctype html>< ; html>< head>< meta charset = UTF-8>< title>我的游戏< / title> < script src = game-functions.js>< / script> < / head>< body><画布id = ctx width = 300 height = 300 style = border:浅黑色;背景颜色:黑色;< / canvas> < br>< script> //////画布设置////// var ctx = document.getElementById( ctx)。getContext( 2d);< / script>< / body> ;< / html>  


I'm working on making a simple space game where a ship moves left and right to dodge asteroids.

I learned to move my ship left and right from this video.

But the movement is pretty blocky. How do I move the ship smoothly?

Here is all my code:

// 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>

解决方案

This is because keydown triggers events similarity to how you keyboard will type on Notepad, as it it will trigger once have a slight delay and they trigger many more timers.

As @Azamantes stated to solve this you will want to make a boolean that is set to true on keydown and false on keyup. Then you will be using a main event loop with either a setTimeout/setInterval and/or requestAnimationFrame. In the example below I've just used setInterval for the main loop for simplicity since you already have it, we can then move move() into that main loop:


Note: For implementing requestAnimationFrame see @MarkE's comment on this question.

Also requestAnimationFrame will refresh as much as it can by default. In other words you need to add more logic if you need to control the FPS, which can be common in HTML5 games. For using requestAnimationFrame with controlled FPS see this answer.

// JavaScript Document

////// Variables //////
var canvas = {width:300, height:300 };
var score = 0;

var player = {
	x:canvas.width/2,
	y:canvas.height-100,
	speed: 3
};

var LEFT = false; 
var RIGHT = false;


////// Arrow keys //////

function move() {
	
	if(LEFT) { 
		player.x -= player.speed;
	}
	if(RIGHT) {
		player.x += player.speed;	
	}
	
}

document.onkeydown = function(e) {
	if(e.keyCode == 37) LEFT = true;
	if(e.keyCode == 39) RIGHT = true;
}

document.onkeyup = function(e) {
	if(e.keyCode == 37) LEFT = false;
	if(e.keyCode == 39) RIGHT = false;
}


////// 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, 10);

function update() {
	clearCanvas();
	ship();
    move();
}

<!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>

这篇关于如何使用箭头键在画布中平滑移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆