【问题标题】:HTML5 - JS: Shoot Bullet From Facing DirectionHTML5 - JS:从正面射击子弹
【发布时间】:2014-03-05 23:45:50
【问题描述】:

我正在开发一款自上而下的 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);
    };

};

【问题讨论】:

  • 如果子弹总是应该来自角色,为什么在计算中提到input.mouseXinput.mouseY?这些值决定了子弹的方向,而不是它的位置。
  • 如果子弹朝着正确的方向移动,那么偏离的不是你的速度——而是你的子弹的初始位置。我认为您将其设置为 (input.mouseX, input.mouseY) 而不是 (this.localX + this.width/2, this.localY + this.height/2),但您没有向我们展示位置代码。
  • 我更新了我的问题。我的首发好像没问题?我正在使用球员位置。
  • this.x和this.localX有区别吗?如果没有,那么是的,初始位置看起来不错,我不得不责怪更高的代码 - 也许是渲染子弹的部分。
  • localX/Y 是我的屏幕中心的位置(screen = 300x300, localX/Y = 150x150),this.x 是我的播放器的位置(即使播放器总是在中心,它仍然会考虑它在地图上的移动)。

标签: javascript html mouse


【解决方案1】:

实际上,我建议不要使用三角函数,只是为了提高效率。 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,所以应该更有效。越快越好,对吧?

【讨论】:

    【解决方案2】:

    想通了。我需要使用 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;
    

    感谢社区!帮助我理解它!

    【讨论】:

    • 你输入的速度比我快。当我看到您的更新弹出时,我只是将其发布为答案。当然, sin 和 cos 会给你一个归一化的向量,你已经添加了子弹速度。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多