One important aspect to consider is using only one instance of requestAnimationFrame
and avoiding multiple uses of setTimeout
. When these functions begin to run out of sync, it becomes difficult to pause the game smoothly when needed.
Instead of relying on timeouts, utilize a counter in your code.
let fruitCounter = 0
function drawGame() {
// include all drawing logic here
...
// drop a new fruit every 60 frames
fruitCounter++
if(fruitCounter > 60){
fruitCounter = 0
dropNewFruit()
}
// continue requesting frames unless the game is over
if(!gameOver) {
requestAnimationFrame(drawGame)
}
}
Moreover, keyboard events can result in choppy gameplay due to input delays. To address this issue, set a variable upon key press.
window.addEventListener("keydown", function(e){
if(e.keyCode == 37){
moveLeft = 1
}
}
window.addEventListener("keyup", function(e){
if(e.keyCode == 37){
moveLeft = 0
}
}
You can then incorporate this variable into your animation logic.
function drawGame() {
// include all drawing logic here
player.x += moveLeft
// continue requesting frames unless the game is over
if(!gameOver) {
requestAnimationFrame(drawGame)
}
}
These are just a few helpful guidelines that have proven effective in my experience developing JavaScript games.