如何设置对象数组的动画?

时间:2011-12-23 08:37:05

标签: javascript animation html5-canvas

这是我在动画的每次迭代中应用于每个对象的代码:

for(var i=0;i<60;i++){
 var ship = new object();
        ship.size = 10;
        ship.image = getMediaObject('shipImage');
        ship.speed.x = 0;
        ship.speed.y = 0;
        ship.flyingByEllipce = true;
        ship.MoveEllipce(p, cont, 4, 100);
        shipsMove.push(clone(ship));
}
for (var i = 0; i < shipsMove.length / 2; i++) {
    shipsMove[i].speed.x = (p1.info.point.x - shipsMove[i].x) / sens;
    shipsMove[i].speed.y = (p1.info.point.y - shipsMove[i].y) / sens;
    p.pop--;
    currentPop--;
    document.getElementById('population-current').innerHTML = currentPop;
    shipsMove[i].animatable = true;
    shipsMove[i].flyingByEllipce = false;
    shipsMove[i].animate(cont, p1.x + 25, p1.y + 25);
    shipsMove[i].animate(shipGo, p1.x + 25, p1.y + 25);
}

以下是动画本身的代码:

function object() { //flying object
var Ship = this;
this.x = 0;
this.y = 0;
this.speed={ x: 0, y: 0 };
this.size = 20;
this.iter = 0;
this.health = 100;
this.position = 3;
this.print= function (canvas) {
    canvas.ctx.drawImage(this.image, (this.x - this.size), (this.y - this.size), this.size, this.size);
};
this.redraw = function (canvas, beforeX, beforeY, afterX, afterY) {
    var params = {
        fromX: (beforeX - this.size),
        fromY: (beforeY - this.size),
        size: (this.size * 3),
        toX: (afterX - this.size),
        toY: (afterY - this.size)
    }
    canvas.ctx.clearRect(params.fromX - 7, params.fromY - 7, params.size + 2, params.size + 2);
    canvas.ctx.drawImage(getMediaObject('shipImage'), params.toX, params.toY, this.size, this.size);
};
this.animatable = false;
//метод подсчета урона наносимого кораблями
this.battle = function (canv,damage) {
    this.health -= damage;
    if (this.health <= 0)
        canv.ctx.clearRect((this.x - this.size) - 1, (this.y - this.size) - 1, (this.size) + 3, (this.size) + 3);
}
//анимация полета корабля
this.animate = function (canvas, tox, toy) {
    if ((this.x + this.speed.x) >= (tox - this.size) && (this.y + this.speed.y) <= (toy - this.size)) {
        //canvas.ctx.clearRect((Ship.x - Ship.size) - 1, (Ship.y - Ship.size) - 1, (Ship.size) + 3, (Ship.size) + 3);
        this.animatable = false;
    } else if ((this.x + this.speed.x) >= (tox - this.size) && (this.y + this.speed.y) >= (toy - this.size)) {
        //canvas.ctx.clearRect((Ship.x - Ship.size) - 1, (Ship.y - Ship.size) - 1, (Ship.size) + 3, (Ship.size) + 3);
        this.animatable = false;
    }
    this.redraw(canvas, this.x, this.y, (this.x + this.speed.x), (this.y + this.speed.y));
    this.x += this.speed.x;
    this.y += this.speed.y;
    if (this.animatable == true) {
        this.tim = setTimeout(this.animate, 60, canvas, tox, toy);
    } else clearTimeout(this.tim);
};

当我将动画应用于单个对象时,它可以工作,但是当我需要将动画应用于多个对象时,它不会发生,我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:4)

您似乎需要在方法中将Ship替换为this