Reputation: 25
I am building a simple game in using HTML5 Canvas/Javascript. However, the game will be passed Javascript functions (js injected into the browser). The code passed will be to move the character ie. "moveRight(); moveRight(); moveUp();". Currently, i have the character moving, however for "moveRight(); moveRight();", the character teleports itself to its new position. I would like the character to moveRight and then take a pause before moving right again.
function right(){
window.setTimeout(function() {
character.x += 30;
}, 2000);
}
How can I accomplish something like this. I tried using a timeout, but it did not help me much.
Thanks,
Upvotes: 1
Views: 165
Reputation: 5434
The best way to approach this would be to use requestAnimationFrame, and use a counter for when the player is able to move.
setInterval won't work for this situation, since you need to acknowledge cases where the player moves the other way around, or when the player cancels the movement.
It's hard to understand your current logic without more code, but below you will find an approach to a grid based movement.
const c = document.getElementById('canvas');
c.width = window.innerWidth;
c.height = window.innerHeight;
const ctx = c.getContext('2d');
// player delay for movement
const playerMovementDelay = 2;
const tileSize = 32;
// player starting position
const myPlayer = {x: 1, y: 1, h: 1, w: 1};
let pkl = 0, pkr = 0, pku = 0, pkd = 0;
let pvelx = 0, pvely = 0;
let movementCountdown = 0;
function render() {
// player logic
movementCountdown -= 0.16;
const deltax = pkr + pkl;
const deltay = pkd + pku;
if (movementCountdown <= 0 && (deltax != 0 || deltay != 0)) {
movementCountdown = playerMovementDelay;
pvelx = deltax;
pvely = deltay;
}
const speed = 1;
myPlayer.x += pvelx * speed;
myPlayer.y -= pvely * speed;
pvelx = pvely = 0;
ctx.clearRect(0, 0, c.width, c.height);
// player render
ctx.fillStyle = '#FFD9B3';
ctx.fillRect(myPlayer.x * tileSize, myPlayer.y * tileSize, myPlayer.w * tileSize, myPlayer.h * tileSize);
window.requestAnimationFrame(render);
}
window.addEventListener('keydown', e => {
if (e.key == 'ArrowRight') {
pkr = 1;
e.preventDefault();
} else if (e.key == 'ArrowLeft') {
pkl = -1;
e.preventDefault();
}
if (e.key == 'ArrowUp') {
pku = 1;
e.preventDefault();
} else if (e.key == 'ArrowDown') {
pkd = -1;
e.preventDefault();
}
});
window.addEventListener('keyup', e => {
if (e.key == 'ArrowRight') {
pkr = 0;
} else if (e.key == 'ArrowLeft') {
pkl = 0;
}
if (e.key == 'ArrowUp') {
pku = 0;
} else if (e.key == 'ArrowDown') {
pkd = 0;
}
});
window.requestAnimationFrame(render);
body, html {
margin: 0;
}
<canvas id="canvas"></canvas>
Upvotes: 2
Reputation: 495
You can use setInterval for the same.
var rightCount = 1;
var moveRight = function () {
rightCount++;
character.x += 30;
}
var move = function () {
setInterval(function () {
if (rightCount < 2) {
moveRight();
}
}, 2000)
}
move();
Upvotes: 0