Reputation: 141
I'm very new to programming and I'm trying to create some code that will allow me to move a square around the Canvas by pressing arrow keys. I'm able to get the square to move, but its motion isn't very smooth. I have it moving by increments of 10 pixels at a time, so I understand why it feels kind of jerky, because there isn't any animation between each position of 10-frames-difference, but having it move by smaller increments makes it far too slow. What I've done so far is below:
window.onload = function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
setInterval(gameLoop,50);
window.addEventListener('keydown',whatKey,true);
}
avatarX = 400
avatarY = 300
function gameLoop() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800
canvas.height = 600
ctx.fillRect(avatarX,avatarY,50,50);
}
function whatKey(e) {
switch(e.keyCode) {
case 37:
avatarX = avatarX - 10;
break;
case 39:
avatarX = avatarX + 10;
break;
case 40:
avatarY = avatarY + 10;
break;
case 38:
avatarY = avatarY - 10;
break;
}
}
Every time I press the arrow key right, I would like for the square to move smoothly in that direction at a constant rate. Thanks in advance for any help at all!
Upvotes: 4
Views: 6328
Reputation: 133
Massive shout out to @Loktar for answering this a decade ago. I'm currently making a game using React and this answer is still relevant. Here's my React adaptation for anyone that stumbles across this in the future!
import { useEffect, useState } from "react";
function Player(){
const [x, setX] = useState(0);
const [y, setY] = useState(0);
let keys = [];
let velocity = [0,0];
const maxSpeed = 3;
useEffect(() => {
window.addEventListener("keydown", keyDown);
window.addEventListener("keyup", keyUp );
gameLoop();
return () => {
window.removeEventListener("keydown", keyDown);
window.removeEventListener("keyup", keyUp);
};
}, [])
function keyDown(e){
keys[e.code] = true;
}
function keyUp(e){
keys[e.code] = false;
}
function handleInput(){
if(keys["KeyA"] && velocity[0] > -maxSpeed) velocity[0] -= 0.15;
if(keys["KeyD"] && velocity[0] < maxSpeed) velocity[0] += 0.15;
if(keys["KeyS"] && velocity[1] < maxSpeed) velocity[1] += 0.15;
if(keys["KeyW"] && velocity[1] > -maxSpeed) velocity[1] -= 0.15;
if(!keys["KeyA"] && !keys["KeyD"]){
if((velocity[0] < 0.1 && velocity[0] > 0) || (velocity[0] > -0.1 && velocity[0] < 0)) velocity[0] = 0;
if(velocity[0] < 0) velocity[0] += 0.1;
if(velocity[0] > 0) velocity[0] -= 0.1;
}
if(!keys["KeyW"] && !keys["KeyS"]){
if((velocity[1] < 0.1 && velocity[1] > 0) || (velocity[1] > -0.1 && velocity[1] < 0)) velocity[1] = 0;
if(velocity[1] < 0) velocity[1] += 0.1;
if(velocity[1] > 0) velocity[1] -= 0.1;
}
}
function gameLoop() {
handleInput();
if(velocity[0]) setX(prev => prev + velocity[0])
if(velocity[1]) setY(prev => prev + velocity[1])
requestAnimationFrame(gameLoop);
}
const characterMover = {
transform: `translate(${x}px, ${y}px)`
}
return <div id="player" style={characterMover}></div>
}
export default Player;
I'm still yet to implement sprite animations, and reserve the right to tweak this later, but this is a great base for me to start with!
Upvotes: 1
Reputation: 35309
Added a few things, the first is requestAnimationFrame
for reasons explained here.
I then added a keyup
and keydown
event handler, these will keep track of what keys are currently being pushed by using an array. If the key is true in the array its currently being pushed, if false it isn't. This method also allows you to press and hold multiple keys at once.
I then added velocity variables which increase or decreased based on whats being pressed, and a maxSpeed
variable so you don't go faster than a certain speed. The maxSpeed
variable could be removed and the incrementing and decrementing velX
and velY
could also be removed, you would just need to uncomment the lines I left. It just seemed to go too fast at 10 thats why I added the gradual speed up.
The above will seem jerky, because the frame is scrolling with the up and down arrows since the canvas is a bit bitter, use the full screen link to fully test the movement.
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
window.onload = function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
gameLoop();
}
window.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
window.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
var avatarX = 400,
avatarY = 300,
velX = 0,
velY = 0,
keys = [],
maxSpeed = 10;
function gameLoop() {
whatKey();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;
avatarX += velX;
avatarY += velY;
ctx.fillRect(avatarX, avatarY, 50, 50);
requestAnimationFrame(gameLoop);
}
function whatKey() {
if (keys[37]) {
//velX = -10;
if (velX > -maxSpeed) {
velX -= 0.5;
}
}
if (keys[39]) {
//velX = 10;
if (velX < maxSpeed) {
velX += 0.5;
}
}
if (keys[40]) {
//velY = 10;
if (velY < maxSpeed) {
velY += 0.5;
}
}
if (keys[38]) {
//velY = -10;
if (velY > -maxSpeed) {
velY -= 0.5;
}
}
}
Upvotes: 15