HTML5-JS:从正面发射子弹
HTML5 - JS: Shoot Bullet From Facing Direction
我正在开发一款自上而下的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;
无论如何,感谢社区!帮我理清思路!
相关文章:
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- 多次发射多个可观察器的问题
- socket.io发射三次
- 如何在HTML列表中添加事件's子弹
- 如何收集所有发射回调的所有响应
- 通过socket.io发射给特定的人
- Phonegap iOS-设备准备不发射其他事件做
- dragcenter/dragleave可防止发射落弹
- RX受试者使用上一个值添加新发射
- Javascript事件发射器一次处理多个事件
- WebRTC,socket.io,node.js:无法读取属性'发射'的未定义
- 无法模拟在 node.js 中使用事件发射器刺激的类中的函数
- 试图让Facebook发射器工作
- 为什么不't通过socket.io发射事件火
- MapReduce还是普通查询?(每个贴图有几个发射)
- 向屏幕外发射子弹
- JavaScript游戏;子弹阵列;当我射击时,所有的子弹从玩家所在的地方重新发射
- 使用jQuery/Javascript发射子弹
- 如何让我的目标一颗接一颗发射子弹
- HTML5-JS:从正面发射子弹