Jump to content

How Would I Move My Player?


OhNoItsATornahdo
 Share

Recommended Posts

So I created a player object:

function Player(x, y, width, height, speed, context) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this.speed = speed;

  this.create = function() {
    context.fillRect(this.x, this.y, this.width, this.height);
  }
}

And I created it in my draw() function:

function draw() {
  var canvas = document.getElementById('mainCanvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    var player = new Player(0, 0, 50, 50, 3, ctx);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    player.create();

    if (upPressed == true) {
      player.y -= player.speed;
    }
    if (downPressed == true) {
      player.y += player.speed;
    }
    if (leftPressed == true) {
      player.x -= player.speed;
    }
    if (rightPressed == true) {
      player.x += player.speed;
    }

    requestAnimationFrame(draw);
  }
}

draw();

But for some reason, my player is still not moving. Is there something I'm missing, or should have done better?

Link to comment
Share on other sites

You're recreating the player at coordinates (0, 0) on every frame. Try creating the player just once somewhere outside of "draw" and then move line "player.create()"  to after the lines that update the player's position (and consider renaming "player.create" to something like "player.draw").

Move the canvas and context declarations outside of draw as well because you don't want to waste CPU cycles doing that for every frame.

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...