【问题标题】:Relative movement for independant bullets (HTML5/Javascript)独立项目符号的相对移动 (HTML5/Javascript)
【发布时间】:2013-01-19 21:59:56
【问题描述】:

我需要一些有关此代码的帮助。我正在制作的游戏是一个自上而下的 2d 游戏。我的角色已经可以移动并发射子弹了。我面临的问题是使子弹朝着光标的方向射击。

我已经完成了,但问题是当我发射多发子弹时,所有子弹都会改变方向以朝向我的光标。我认为需要做的是每颗子弹都需要分配它的特定路径,这样当我发射另一颗子弹时它不会改变。子弹已经是一个物体,所以我不知道我做错了什么。

Bullet.prototype.draw = function() {
    this.drawX += (mouseX - this.drawX) * 0.01 ;
    this.drawY += (mouseY - this.drawY) * 0.01 ;
    ctxbullet.drawImage(imgSprite, this.srcX, this.srcY, 
        this.width, this.height, this.drawX, this.drawY, 10, 8);
};

如您所见,每个 Bullet 都遵循此处的规则和逻辑。

另一个问题是子弹不会以恒定的速度移动。

非常感谢。

【问题讨论】:

标签: javascript html canvas cursor


【解决方案1】:

看起来您在该函数中使用的 mouseX 和 mouseY 属性是在其他地方定义的。这意味着随着该变量在此函数之外更新,您用于更新 drawX 和 drawY 的数字也会发生变化。

您需要做的是在创建时跟踪 mouseX 和 mouseY 的本地副本。我不知道你的其余代码是什么样的,但我会猜一下。

function Bullet(x, y) {
    this.srcX = x;
    this.srcY = y;
    // keep track of original mouse coordinates
    this.mouseX = mouseX;
    this.mouseY = mouseY;
}

Bullet.prototype.draw = function() {
    this.drawX += (this.mouseX - this.drawX) * 0.01;
    this.drawY += (this.mouseY - this.drawY) * 0.01;
    ctxbullet.drawImage(
        imgSprite,
        this.srcX,  this.srcY,
        this.width, this.height,
        this.drawX, this.drawY,
        10, 8
    );
};

这将确保子弹在创建时始终朝着鼠标坐标移动,但您很快就会遇到另一个问题。由于速度与子弹距离这些鼠标坐标的距离有关(这就是您遇到速度不一致的原因),所以子弹会减速到鼠标坐标处停止。

您需要做的是创建一个从 src 点到鼠标点以所需速度的向量。这将允许子弹跟随那个向量直到无穷大(但你知道,实际上并不是无穷大,希望你一旦超出边界就将其移除)。

function Bullet(x, y) {
    var dX = mouseX - x,
        dY = mouseY - y,
        dist = Math.sqrt(dX * dX + dY * dY)
    ;
    // we want our deltas to be proportions of the total distance
    this.dX = dX / dist;
    this.dY = dY / dist;
    this.speed = 5; // arbitrary number
}

Bullet.prototype.draw = function() {
    // I didn't test this, but I think it works
    this.drawX += this.dX * this.speed;
    this.drawY += this.dY * this.speed;
    ctxbullet.drawImage(
        imgSprite,
        this.srcX,  this.srcY,
        this.width, this.height,
        this.drawX, this.drawY,
        10, 8
    );
}

【讨论】:

  • 我遇到的问题是 Dx 和 Dy 未定义
  • 您是否更改了代码以在创建项目符号时传递 x 和 y 坐标? new Bullet(x, y) 而不是 new Bullet()?
  • 这个 x 和 y 代表什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-23
  • 2012-01-21
  • 2019-12-19
  • 1970-01-01
  • 2015-05-17
  • 2011-09-18
相关资源
最近更新 更多