OhNoItsATornahdo Posted September 5, 2017 Share 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 Link to comment Share on other sites More sharing options...
Jem Kazama Posted September 5, 2017 Share 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. Taz 1 Quote Link to comment Share on other sites More sharing options...
OhNoItsATornahdo Posted September 6, 2017 Author Share 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 Link to comment Share on other sites More sharing options...
Jem Kazama Posted September 6, 2017 Share 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 Taz 1 Quote Link to comment Share on other sites More sharing options...
Taz Posted September 7, 2017 Share 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); OhNoItsATornahdo 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.