繁体   English   中英

带有箭头键的平滑移动球javascript

[英]Smooth Moving Ball with Arrow keys javascript

每当我单击箭头键时,如何使球平稳移动。 每次单击箭头键时,它都会变得笨拙,如果按住它,则每1秒移动一次。 我想要它,因此,如果长时间按下它,它会移动得相当快且平稳。

  var canvas = document.getElementById('game'); var ctx = canvas.getContext('2d'); var ball = { pos: {x: 500,y: 300}, speed: 5, }; var FPS = 30; window.onload = function() { setInterval(function() { gameBack(); }, 1000/FPS); } // background code function gameBack() { drawRect(0,0,canvas.width,canvas.height, 'Black'); colorCircle(ball.pos.x,ball.pos.y,10, 'white'); } // Rectangle Code function drawRect(leftX,topY,width,height, drawColor) { ctx.fillStyle = drawColor; ctx.fillRect(leftX,topY,width,height); } //Circle Code function colorCircle(centerX,centerY,radius, drawColor) { ctx.fillStyle = drawColor; ctx.beginPath(); ctx.arc(centerX,centerY,radius,0,Math.PI*2,true); ctx.closePath(); ctx.fill(); } //Game Controls document.addEventListener('keydown', event => { if (event.keyCode === 37) { //Left xBall(-5); } else if (event.keyCode === 39) { //Right xBall(5); } else if (event.keyCode === 38) { //Up yBall(-5); } else if (event.keyCode === 40) { //Down yBall(5); } }); function yBall(offset) { ball.pos.y += offset; } function xBall(offset) { ball.pos.x += offset; } 
 <canvas id="game" width=800 height=600></canvas> 

添加方向向量。 让按键控制方向矢量,并使用方向矢量更新每帧中的位置。 根据更新方向矢量的方式,可以使球增加速度或缓慢停止。

例如:

  var canvas = document.getElementById('game'); var ctx = canvas.getContext('2d'); var ball = { pos: {x: 500,y: 300}, direction: { x: 0, y: 0 }, speed: 5, brake: 0.9, // smaller number stop faster, max 0.99999 }; var FPS = 30; window.onload = function() { setInterval(function() { animate(); gameBack(); }, 1000/FPS); }; function animate() { ball.pos.x += ball.direction.x * ball.speed; ball.pos.y += ball.direction.y * ball.speed; ball.direction.x *= ball.brake; ball.direction.y *= ball.brake; } // background code function gameBack() { drawRect(0,0,canvas.width,canvas.height, 'Black'); colorCircle(ball.pos.x,ball.pos.y,10, 'white'); } // Rectangle Code function drawRect(leftX,topY,width,height, drawColor) { ctx.fillStyle = drawColor; ctx.fillRect(leftX,topY,width,height); } //Circle Code function colorCircle(centerX,centerY,radius, drawColor) { ctx.fillStyle = drawColor; ctx.beginPath(); ctx.arc(centerX,centerY,radius,0,Math.PI*2,true); ctx.closePath(); ctx.fill(); } //Game Controls document.addEventListener('keydown', event => { if (event.keyCode === 37) { //Left xBall(-1); } else if (event.keyCode === 39) { //Right xBall(1); } else if (event.keyCode === 38) { //Up yBall(-1); } else if (event.keyCode === 40) { //Down yBall(1); } }); function yBall(offset) { ball.direction.y += offset; } function xBall(offset) { ball.direction.x += offset; } 
 <canvas id="game" width=800 height=600></canvas> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM