HTML5-JS:从正面发射子弹

HTML5 - JS: Shoot Bullet From Facing Direction

本文关键字:发射 子弹 HTML5-JS      更新时间:2023-09-26

我正在开发一款自上而下的HTML5射击游戏。我目前正在尝试让子弹从我的角色面对的角度发射。

我的角色始终面向鼠标位置(旋转)。所以,当我发射子弹时,我需要考虑旋转。

我差不多到了,唯一的问题是子弹从我的实际鼠标位置开始,尽管它朝着正确的方向移动。

我相信我的数学在我的速度变量范围内是错误的:

var b = new Rectangle( this.x + (this.width / 2) - 4, this.y + (this.height / 2) - 4, 8, 8);
var velocityInstance = new Vector2(0, 0);
velocityInstance.x = input.mouseX - (this.localX + this.width/2);
velocityInstance.y = input.mouseY - (this.localY + this.height/2);
var bulletInstance = new Bullet(velocityInstance, b, this.bullets.length + 1);
this.bullets.push(bulletInstance);
this.shotBullet = true;

"this"指的是我的播放器。localX/Y是我角色的中心位置(他总是在屏幕的中心,场景在他周围移动)。

如果有人能帮我检查一下,我将不胜感激。谢谢!

------编辑------

这是我的子弹功能:

Bullet = function(vel, rectangle, index){
    this.velocity = vel;
    this.rect = rectangle;
    this.index = index;
    this.Update = function(){
        this.rect.x += this.velocity.x;
        this.rect.y += this.velocity.y;
        //Collisions
        for(var c = 0; c < GameObjects.length; c++){
            if(this.rect.Intersects(GameObjects[c])){
                console.debug("Bullet Hit: " + GameObjects[c].tag);
                //Player.bullets.splice(index, 1);
            }
        }
    };
    this.Draw = function(ctx){
        this.rect.Draw(ctxMap);
    };
};

实际上,为了提高效率,我建议不要使用trig函数。Math.atan2、Math.cos和Math.sin可能会变得昂贵。

您已经拥有(稍微重命名)

var deltaX = input.mouseX - (this.localX + this.width/2);
var deltaY = input.mouseY - (this.localY + this.height/2);

为什么不简单地往这边跳呢?

var magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
var velocityScale = bulletSpeed / magnitude;
velocityInstance.x = deltaX * velocityScale;
velocityInstance.y = deltaY * velocityScale;

它的功能相同,但只使用了一个泰勒级数,而不是3个,因此应该更有效。越快越好,对吧?

想明白了。我需要使用Math.cos和Math.sin:

var targetX = input.mouseX - (this.localX + this.width/2);
var targetY = input.mouseY - (this.localY + this.height/2);
this.rotation = Math.atan2(targetY, targetX);
velocityInstance.x = Math.cos(this.rotation) * bulletSpeed;
velocityInstance.y = Math.sin(this.rotation) * bulletSpeed;

无论如何,感谢社区!帮我理清思路!