Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
独立项目符号的相对运动(HTML5/Javascript)_Javascript_Html_Canvas_Cursor - Fatal编程技术网

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

独立项目符号的相对运动(HTML5/Javascript),javascript,html,canvas,cursor,Javascript,Html,Canvas,Cursor,我需要一些关于这个代码的帮助。我制作的atm机游戏是一个自上而下的2d游戏。我的角色已经可以移动并射出子弹了。我面临的问题是使子弹朝着光标的方向射击 我已经这样做了,但问题是,当我射击多个子弹时,所有的子弹都会改变方向,朝向我的光标。我想需要做的是,每一颗子弹都需要指定它的特殊路径,这样当我发射另一颗子弹时,它就不会改变。子弹已经是物体了,所以我不知道我做错了什么 Bullet.prototype.draw = function() { this.drawX += (mouseX - t

我需要一些关于这个代码的帮助。我制作的atm机游戏是一个自上而下的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);
};
正如你所看到的,每个项目符号都遵循这里的规则和逻辑

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


非常感谢。

您在该函数中使用的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点到鼠标点的向量。这将允许子弹跟随该向量无限远(但你知道,实际上不是无限远,希望你一旦超出边界就将其移除)


如果你在寻找一种模拟子弹轨迹的算法,这应该会有所帮助-我遇到的问题是说Dx和Dy是未定义的,你在创建子弹时更改代码以传递x和y坐标?新的项目符号(x,y)而不是新的项目符号()?这个x和y代表什么?
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
    );
}