我正在创建一个要在其中移动对象的家伙,每个对象都附有一个图像,但是我不知道如何从中心而不是从左上角移动它们。
这是玩家:
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';
};
及其方法“移动”:
Player.prototype.move = function(){
if (37 in keysDown) {
this.pos_x -= 10;
} else if (39 in keysDown) {
this.pos_x += 10;
}
};
我不知道您要在何处绘制此图像,但是我会使用已经拥有的内容,只是将图像绘制在不同的位置。
您可以通过从初始位置取一半图像尺寸来围绕位置绘制图像(使用Player.pos_x
和Player.pos_y
作为中心点,而不是左上角),如下所示:
Y = Y location - (image height / 2)
X = X location - (image width / 2)
在实际代码中,这看起来像:
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);
这样,您Player.pos_x
和会Player.pos_y
保持在同一位置,但是图像将在该中心“周围”绘制。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句