gpt4 book ai didi

javascript - 独立项目符号的相对运动 (HTML5/Javascript)

转载 作者:行者123 更新时间:2023-11-28 09:25:53 25 4
gpt4 key购买 nike

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

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

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);
};

正如您所看到的,每个项目符号都遵循此处的规则和逻辑。

另一个问题是子弹的速度不是恒定的。

非常感谢。

最佳答案

看起来您在该函数中使用的 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
);
}

关于javascript - 独立项目符号的相对运动 (HTML5/Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com