HTML5 JS-我如何使我的子弹/镜头在一个恒定的方向

HTML5 JS - How do I make my bullets/shots go in a constant direction?

本文关键字:一个 方向 JS- 何使 我的 子弹 HTML5      更新时间:2023-12-13

我已经为项目符号代码苦苦挣扎了一段时间。我知道很可能有一个更简单的解决方案(事实上,我记得我以前做过类似的事情,但我就是记不起来了)。但无论如何;

问题:我的子弹射向四个方向,应该是这样。然而,如果我选择在发射后向不同的方向移动,子弹的方向和位置也会发生变化。

例如,如果我面朝上,发射3发子弹,然后向右移动,子弹会随着我改变方向和速度,相反,我希望它在我朝不同方向移动时继续朝那个方向移动。

这是子弹的代码;

    function Bullet(w, h, s){
        this.x = tank.x;
        this.y = tank.y
        this.width = w;
        this.height = h;
        this.speed = s; 
    }
    //setInterval of firing
    function setFire(){
        tankCanFire = true;
    }
    //Create a new bullet
    function fireBullet(){
        if(tankCanFire){
            tankCanFire = false;
                bullets.push(new Bullet(5, 10, 15));    

                ctx.fillText("Ding", 300, 300);
            }
        }
    //DRAW the Bullets + velocities.
    function drawBullet(){
            ctx.fillText("length = " +bullets.length, 200, 200); 

        if (bullets.length > 0){
            for (var key in bullets)
            {
                    ctx.fillText("DONG", 200, 250);
                    if (tank.up == true) 
                    {               
                    ctx.drawImage(bulletImage, bullets[key].x + 13, bullets[key].y - 8);
                    bullets[key].y -= 15;   
                        if (bullets[key].y < 0) 
                            delete bullets[key];

                    }
                    else if (tank.down == true)
                    {               
                    ctx.drawImage(bulletImage, bullets[key].x + 13, bullets[key].y + 40);
                    bullets[key].y += 15;   
                        if (bullets[key].y > 400)
                            delete bullets[key];
                    }
                    else if (tank.left == true)
                    {               
                    ctx.drawImage(bulletImage, bullets[key].x - 8, bullets[key].y + 13);
                    bullets[key].x -= 15;   
                        if (bullets[key].x < 0)
                            delete bullets[key];
                    }
                    else if (tank.right == true)
                    {               
                    ctx.drawImage(bulletImage, bullets[key].x + 40, bullets[key].y + 13);
                    bullets[key].x += 15;   
                        if (bullets[key].x > 600)
                            delete bullets[key];
                    }               
            }                   
        }           
    }   

在Bullet中,除了x、y、宽度、高度和速度之外,还需要存储特定子弹的前进方向。当前代码在移动子弹时会查看坦克的方向,因此如果你转动坦克,子弹的方向会改变。这也很有趣,但如果你想要传统的子弹,那么在子弹中存储它的方向是有意义的。

最简单的方法是存储,而不是速度,而是速度。类似这样的东西:

function Bullet(w, h, dx, dy){
    this.x = tank.x;
    this.y = tank.y
    this.width = w;
    this.height = h;
    this.dx = dx; // how much x changes at every time step 
    this.dy = dy;
}