1

我正在尝试用 Javascript 创建一个小型小行星游戏,并且我已经完成了飞船在屏幕上绘制并可以四处飞行的程度。但是,每当我尝试将其旋转一定量时,它只能在 +/- PI/2 之间旋转。我需要它覆盖的范围不只是 180 度,否则船永远不会掉头。我正在尝试使用自定义 2D Vector 类从头开始执行此操作,并且有几个人在看它时不知道该怎么做。

这是我的矢量代码,或者至少是构造函数和旋转函数。

function Vec2D(x, y) {
    var self = this;
    var sqrt = Math.sqrt;
    this.x = x !== null ? Number(x) : 0;
    this.y = y !== null ? Number(y) : 0;
}
Vec2D.prototype.rotate = function (deg) {
    var theta = deg * (Math.PI / 180),
        xTemp = this.x;
    this.x = this.x * Math.cos(theta) - this.y * Math.sin(theta); 
    this.y = xTemp * Math.sin(theta) + this.y * Math.cos(theta);
    return this;
}

这是我的船试图旋转的代码。

function Ship(x_, y_, size_) {
    this.position = new Vec2D(x_, y_);
    this.velocity = new Vec2D(0, 0);
    this.forward = new Vec2D(0, 0);
    //some other things
    this.turningRight = false;
    this.turningLeft = false;
    this.turnAmt = 5;
    //some more things
}
Ship.prototype.update = function () {
   //other update code
   if (this.turningRight) {
        this.forward.rotate(this.turnAmt);
        console.log("right");
   }
   if (this.turningLeft) {
        this.forward.rotate(-1.0 * this.turnAmt);
        console.log("left");
   }
   //end of rotation code in update
}

如有必要,我可以重现更多代码,但据我所知,这是所有相关代码。我试过控制台打印,我试过弄乱旋转矩阵,我什至试过只使用弧度而不是每次都从度数转换(老实说,我真的应该这样做)。

对我的新手 JavaScript 有什么想法吗?

4

0 回答 0