Wie Sie den Ball reibungslos bewegen jedes Mal, wenn ich eine Pfeiltaste klicke. Jedes Mal, wenn ich auf eine Pfeiltaste klicke, wird es klobig und bewegt sich nur alle 1 Sekunde, wenn ich es halte. Ich will es so, wenn ich es lange drücke, bewegt es sich ziemlich schnell und glatt.Smooth Moving Ball mit Pfeiltasten JavaScript
\t var canvas = document.getElementById('game');
\t var ctx = canvas.getContext('2d');
\t var ball = {
\t \t pos: {x: 500,y: 300},
\t \t speed: 5,
\t };
\t var FPS = 30;
window.onload = function() {
\t setInterval(function() {
\t \t gameBack();
\t }, 1000/FPS);
}
// background code
function gameBack() {
\t drawRect(0,0,canvas.width,canvas.height, 'Black');
\t colorCircle(ball.pos.x,ball.pos.y,10, 'white');
}
// Rectangle Code
function drawRect(leftX,topY,width,height, drawColor) {
\t ctx.fillStyle = drawColor;
\t ctx.fillRect(leftX,topY,width,height);
}
//Circle Code
function colorCircle(centerX,centerY,radius, drawColor) {
\t ctx.fillStyle = drawColor;
\t ctx.beginPath();
\t ctx.arc(centerX,centerY,radius,0,Math.PI*2,true);
\t ctx.closePath();
\t ctx.fill();
}
//Game Controls
document.addEventListener('keydown', event => {
if (event.keyCode === 37) { //Left
\t xBall(-5);
} else if (event.keyCode === 39) { //Right
\t xBall(5);
} else if (event.keyCode === 38) { //Up
\t yBall(-5);
} else if (event.keyCode === 40) { //Down
\t yBall(5);
}
});
function yBall(offset) {
\t ball.pos.y += offset;
}
function xBall(offset) {
\t ball.pos.x += offset;
}
<canvas id="game" width=800 height=600></canvas>
Mögliche Duplikat [Body Animation ist nicht glatt] (https://stackoverflow.com/questions/32365542/body-animation-isnt-smooth) – Kaiido