Reputation: 121
I'm making a guy in which I have objects to move, each objects has an image attached to it, but I have no idea how I could move them from the center and not the left upper corner.
This is the player:
function Player() {
this.height = 167.5;
this.width = 100;
this.pos_x = 350;
this.pos_y = 425;
this.player_image = new Image();
this.player_image.src = 'img/player_car_img.png';
};
And its method "Move":
Player.prototype.move = function(){
if (37 in keysDown) {
this.pos_x -= 10;
} else if (39 in keysDown) {
this.pos_x += 10;
}
};
Upvotes: 1
Views: 453
Reputation: 9994
I don't know where you're drawing this image, but I would use what you already have and simply draw the image in a different position.
You can draw the image around your position (with Player.pos_x
and Player.pos_y
as a central point, rather than top left) by taking off half the image dimensions from the initial position like so:
Y = Y location - (image height / 2)
X = X location - (image width / 2)
In actual code this would look something like:
var x = Player.pos_x - Player.player_image.width/2;
var y = Player.pos_y - Player.player_image.height/2;
ctx.drawImage(Player.player_image, x, y);
This way your Player.pos_x
and Player.pos_y
remain in the same position, but the image will be drawn "around" that center.
Upvotes: 2