OhNoItsATornahdo 0 Report post Posted September 5, 2017 So I'm testing out collision and keyboard input right now and my application looks like this: When I press and WASD key, I get this: As you can see, it keeps drawing the square over and over. Here is my code: function gameLoop(timeStamp) { var delta = timeStamp - (lastTime || timeStamp); if(aPressed){ player.x -= player.speed * delta; } if(dPressed){ player.x += player.speed * delta; } if(wPressed){ player.y -= player.speed * delta; } if(sPressed){ player.y += player.speed * delta; } window.requestAnimationFrame(gameLoop); lastTime = timeStamp; canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); playerObject = ctx.fillRect(player.x, player.y, player.width, player.height); collisionObject = ctx.fillRect(collisionBox.x, collisionBox.y, collisionBox.width, collisionBox.height); collision(player, collisionBox); } window.requestAnimationFrame(gameLoop); You might wonder 'okay, just take the playerObject and collisionObject out of the loop'. Actually, it isn't that easy. If I did do that, ctx.fillRect would be undefined. If I took took the canvas and ctx code out, the screen won't update. If I took the code from the canvas line to the collisionObject line, nothing would happen. How am I supposed to fix this? Quote Share this post Link to post Share on other sites
Jem Kazama 12 Report post Posted September 5, 2017 You need to clear the screen. It's drawing the square over and over. Think of it like a flip book -- every page it's moved a bit, but the page is blank. 1 Taz reacted to this Quote Share this post Link to post Share on other sites
OhNoItsATornahdo 0 Report post Posted September 6, 2017 5 hours ago, MysticJ said: You need to clear the screen. It's drawing the square over and over. Think of it like a flip book -- every page it's moved a bit, but the page is blank. I know that, I don't know how though. Quote Share this post Link to post Share on other sites
Jem Kazama 12 Report post Posted September 6, 2017 Ah, gotcha. Something like canvasContext.fillStyle = fillColor; canvasContext.fillRect(topLeftX, topLeftY, boxWidth, boxHeight); That you do at the beginning of each loop iteration, where the values are 0, 0, canvas.width, canvas.height 1 Taz reacted to this Quote Share this post Link to post Share on other sites
Taz 43 Report post Posted September 7, 2017 There's also clearRect() if you want transparent instead of using a background color like above: ctx.clearRect(0, 0, canvas.width, canvas.height); 1 OhNoItsATornahdo reacted to this Quote Share this post Link to post Share on other sites