Jump to content

Computer keeps drawing square.


OhNoItsATornahdo
 Share

Recommended Posts

So I'm testing out collision and keyboard input right now and my application looks like this:

Capture.PNG.399af00ac7faf0319eef3d2f73cbfa62.PNG

 

When I press and WASD key, I get this:

Capture1.PNG.7df007477ec5c66f7b1257cb338acace.PNG

 

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?

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...