HTML 5导航导弹

时间:2014-02-01 03:58:57

标签: javascript html5 canvas html5-canvas game-physics

这是我的班级

function Missile(drawX, drawY) {
    this.srcX = 0;
    this.srcY = 0;
    this.width = 16;
    this.r = this.width * 0.5;
    this.height = 10;
    this.drawX = drawX;
    this.drawY = drawY;
    this.img = planeHomingMissile;
    this.rotation = -90;
}

Missile.prototype.draw = function () {
    ctxHM.save();
    ctxHM.translate(this.drawX, this.drawY);
    ctxHM.rotate(this.rotation); 
    ctxHM.drawImage(this.img, -this.r, -this.r);
    ctxHM.restore();
} 

这是我的JavaScript逻辑:

function shootHomingMissile() {
    //if(!missileOut) {
        hMissile = new Missile(player1.drawX + 22, player1.drawY + 32);
        missileOut = true;
    //}
}

function updateHomingMissile() {
    if(missileOut) {
        var targetX = 500 - hMissile.drawX;
        var targetY = 50 - hMissile.drawY;
        //The atan2() method returns the arctangent of the quotient of its arguments, as a numeric value between PI and -PI radians.
        //The number returned represents the counterclockwise angle in radians (not degrees) between the positive X axis and the point (x, y)
        var rotations = Math.atan2(targetY, targetX) * 180 / Math.PI;
        hMissile.rotation = rotations;

        var vx = bulletSpd * (90 - Math.abs(rotations)) / 90;
        var vy;
        if (rotations < 0)
            vy = -bulletSpd + Math.abs(vx);
        else
            vy = bulletSpd - Math.abs(vx);

        hMissile.drawX += vx;   
        hMissile.drawY += vy;   
    }
}

function drawHomingMissile() {
    ctxHM.clearRect(0,0,575,800);   

    hMissile.draw();
}

我希望我的导弹(朝上)能够瞄准目标(500,50)并面对目标。

运动似乎有效,但它没有面向目标它只是一直在旋转,但导弹正在向目标发射。

我是初学者,所以我的代码有点乱,请帮帮我:)。

1 个答案:

答案 0 :(得分:1)

您正在将角度从弧度转换为度数,并将其用于需要弧度的rotation()

Missile.prototype.draw

中试试这个
ctxHM.rotate(this.rotation * Math.PI / 180); 

(或简单地保持所有阶段的弧度角度)