示例:一门大炮以 60 kpH 的球速发射/
给定:(60 kpH) 距离 = 60 公里, 时间 = 1 小时
Libgdx:游戏世界
// Given that I am using 1/45.0f step time, the rest iteration velocity 6 and position 2
// Given that 60.00012 kilometres per hour = 16.6667 metres per second
float speed = 16.6667f; // 16.6667 metres per second
Vector2 bulletPosition = body.getPosition();
Vector2 targetPosition = new Vector2(touchpoint.x touchpoint.y);
Vector2 targetDirection = targetPosition.cpy().sub(bulletPosition).scl(speed);
问题: 但我的问题是炮弹没有以我想要的速度移动,还有我如何记录 body 速度以便检查速度是否正确。我只是注意到这是错误的,因为炮弹移动得太慢了,想象一下 60 kpH
PS: 假设上图宽5米,高3米
body.setLinearVelocity(targetDirection.scl(deltaTime));
问题 2: 我不知道如何根据给定的速度和步长时间计算力
// Given that F = ma
Vector2 acceleration = ???
float mass = body.getMass();
Vector2 force = ???
body.applyForces(force);
最佳答案
在 Box2d 中,不是直接施加力,而是施加一个冲量,该冲量是施加一段时间的力,这会有效地产生接近瞬时的加速度。计算你的冲动只是一点物理知识。
首先我们定义一些变量,F
是牛顿的力,a
是加速度,I
是冲量(我们想要计算应用于 Box2d),u
是初始速度(米每秒),v
是最终速度,t
是以秒为单位的时间.
使用牛顿定律和我们开始的加速度定义:
现在我们可以计算冲量了:
在你的例子中,u
是 0,因为炮弹最初是静止的,所以它归结为:
就是这样!因此,在您的代码中,您将对炮弹施加等于其质量乘以所需速度的冲量。以下代码还包含如何计算到触摸点的方向。
例如:
float mass = body.getMass();
float targetVelocity = 16.6667f; //For 60kmph simulated
Vector2 targetPosition = new Vector2(touchpoint.x, touchpoint.y);
// Now calculate the impulse magnitude and use it to scale
// a direction (because its 2D movement)
float impulseMag = mass * targetVelocity;
// Point the cannon towards the touch point
Vector2 impulse = new Vector2();
// Point the impulse from the cannon ball to the target
impulse.set(targetPosition).sub(body.getPosition());
// Normalize the direction (to get a constant speed)
impulse.nor();
// Scale by the calculated magnitude
impulse.scl(impulseMag);
// Apply the impulse to the centre so there is no rotation and wake
// the body if it is sleeping
body.applyLinearImpulse(impulse, body.getWorldCentre(), true);
编辑:回应评论:
归一化 vector 是一个单位长度 vector ,这意味着它的大小为 1(无论它处于哪个角度)。视觉解释(来自维基百科):
vector d1
和d2
都是单位 vector ,因此称为归一化。在 Vector2
中,nor
函数通过将 vector 保持在相同的角度但给它一个大小来使 vector 归一化。如下图所示(蓝色为原始 vector ,绿色为归一化后):
对于您的游戏,这样做的要点是无论玩家触摸屏幕离炮弹很近还是很远,炮弹都以相同的速度行进,重要的是与炮弹的角度。
关于java - libgdx box2d body - 如何通过给定的力或速度、距离和时间移动 body ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38230201/