OhNoItsATornahdo Posted September 29, 2017 Share Posted September 29, 2017 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? Quote Link to comment Share on other sites More sharing options...
BobF Posted September 29, 2017 Share Posted September 29, 2017 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. OhNoItsATornahdo and hotfeet 2 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.