我试图在游戏更新中创建对象并移动它们。这是我的香蕉对象:
function Banana() {
this.height = 1.96;
this.width = 3.955;
this.pos_x = CENTER - this.width/2;
this.pos_y = -475;
this.banana_image = banana_image;
};
这就是Move方法:
Banana.prototype.move = function(){
if (this.pos_y > 500) {
//this.banana_image.parentElement.removeChild(this.banana_image);
}
this.height += ZOOM_RATE;
this.width += ZOOM_RATE;
this.pos_y += 3;
this.pos_x -= SIDES_RATE;
};
这是游戏更新部分:
Game.update = function() {
this.player.move();
//creating bananas
if (objs.lenght <= 0) {
this.banana = new Banana();
} else {
for (i = 0; i < 10; i++) {
objs.push(new Banana());
}
}
//moving bananas
for (i = 0; i < objs.lenght; i++) {
this.objs[0].move();
}
};
游戏抽奖:
function Game.draw = function() {
this.context.drawImage(road, 0,0, rw, rh);
this.context.drawImage(
this.player.player_image,
this.player.pos_x, this.player.pos_y,
this.player.width, this.player.height);
this.context.drawImage(
this.banana.banana_image,
this.banana.pos_x, this.banana.pos_y,
this.banana.width, this.banana.height);
};
我试图向多人提问,但我无法找到答案。
答案 0 :(得分:1)
假设你想要移动对象10次然后停止。
首先,您需要在Game.draw
的开头添加一行,以便它清除画布,使您始终从头开始绘图:
this.context.clearRect(0,0,500,500); // clear canvas, adjust box size if needed
然后创建一个函数来调用update
和draw
,并将该函数排队再次调用:
var count = 10;
function updateAndDraw() {
Game.update();
Game.draw();
count--;
if (count) requestAnimationFrame(updateAndDraw);
}
// start moving:
requestAnimationFrame(updateAndDraw);
此动作可能会根据您的喜好过快,因此请调整move
方法进行较小的更改,或使用setTimeout
代替requestAnimationFrame
(但这会减少动画流利)。
请注意,您的代码中有一些错误,您需要首先解决这些错误:
lenght
应为length
function Game.draw = function() {
:在function
之前删除Game.draw
。