Reputation: 45
Hello im trying to program the classic pong game. I am trying to implement smooth movement.So when the key has been released it should gradually slow to a stop. I have been following a few tutorials but cant seem to get it straight.
I noticed if you keep hold arrow up for a bit and let it move then hold arrow down it will still move in the up direction for a bit then start moving down. any idea whats this from?
Here is my code:
var canvas;
var canvasContext;
var x = 5,
y = 150;
var velY = 0;
var speed = 50;
var friction = 0.9;
window.onload = function() {
canvas = document.getElementById("gameCanvas");
canvasContext = canvas.getContext("2d");
var fps = 30;
setInterval(function() {
draw();
}, 1000 / fps); // 1000miliseconds = 1 seconds
document.addEventListener("keydown",
function(event) {
var x = event.key;
switch (x) {
case 'ArrowDown':
key_down();
velY *= friction;
y += velY;
break;
case 'ArrowUp':
key_up();
velY *= friction;
y += velY;
break;
}
});
}
function key_up() {
if (velY > -speed)
velY--;
}
function key_down() {
if (velY < speed)
velY++;
}
function draw() {
//canvas background color
colorRect(0, 0, canvas.width, canvas.height, "black");
//left player paddle
colorRect(x, y, 15, 100, "white");
}
function colorRect(leftX, topY, width, height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(leftX, topY, width, height);
}
<canvas id="gameCanvas" width="600" height="400" style="border:1px solid black;"></canvas>
Upvotes: 0
Views: 79
Reputation: 108
The way it is programmed it will slow down its speed before moving in the other direction. If you set the velocity to 0 first, it will start moving directly.
function key_up() {
velY = 0; // Set to zero to stop paddle
if (velY > -speed)
velY--;
}
function key_down() {
velY = 0; // Set to zero to stop paddle
if (velY < speed)
velY++;
}
Upvotes: 1