简体   繁体   English

如何对具有定向速度的射弹施加重力?

[英]How to apply gravity to a projectile that has directional velocity?

I have a bullet that fires at an angle. 我有一颗子弹可以倾斜发射。 I want the bullet to react to a gravitational force. 我希望子弹对重力产生反应。 The following code is in the update function of a bullet. 以下代码位于项目符号的更新功能中。

this.pos.x += Math.cos(this.angle * Math.PI/4) * (this.vel.x);
this.pos.y += Math.sin(this.angle * Math.PI/4) * (this.vel.y);

This means that the bullet has been fired at this.angle which shouldn't change. 这意味着子弹已this.angle此角射击,不应改变。 The velocities should always be angled at this.angle . 速度应始终与this.angle成一定角度。 The question now is: How do I add gravity? 现在的问题是:如何添加重力? Here is what I've tried so far. 到目前为止,这是我尝试过的。

The following code simply curves the bullet (down, but also up). 以下代码仅使项目符号弯曲(向下但也向上)。

this.pos.x += Math.cos(this.angle * Math.PI/4) * (this.vel.x);
this.pos.y += Math.sin(this.angle * Math.PI/4) * (this.vel.y);
this.vel.y += GRAVITY

I've also tried this: 我也尝试过这个:

this.pos.x += Math.cos(this.angle * Math.PI/4) * (this.vel.x);
this.pos.y += Math.sin(this.angle * Math.PI/4) * (this.vel.y);
this.vel.y += Math.sin(this.angle * Math.PI/4) * GRAVITY

The latter is the closest I've gotten to what I want it to do. 后者是我最想要的功能。 However, when this.angle is 0, sin(0) is also 0 . 但是,当this.angle为0时, sin(0) is also 0 This results in strange projectile misbehaviour when the angle is 0. 当角度为0时,这会导致奇怪的射弹异常。

What are the best / conventional workarounds to this? 最佳/常规的解决方法是什么?

Your position equation doesn't depend on the angle. 您的位置方程式与角度无关。 You should only need the angle to initialize the vel.x and vel.y values. 您只需要角度即可初始化vel.x和vel.y值。

You should have a normal speed and do initialize them with 您应该具有正常速度,并使用进行初始化

var bulletSpeed = 100;
this.vel.x = Math.cos(this.angle)*bulletSpeed;
this.vel.y = Math.sin(this.angle)*bulletSpeed;

Then update the values with 然后使用

this.pos.x += this.vel.x;
this.pos.y += this.vel.y;
this.vel.y += GRAVITY

This doesn't use gravity as an acceleration though since there's no time variable from what I can tell 尽管我无法分辨出时间变量,但这并没有使用重力作为加速度

is there some variable for time? 时间会有所变化吗? if so then 如果是的话

this.vel.y += GRAVITY * time

might work 可能有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM