【发布时间】:2016-08-03 08:57:53
【问题描述】:
将重力应用到物理世界很容易,您只需要创建一个Vector2 并设置其水平和垂直重力值。如果我想创建一个零重力的自上而下的 2D 游戏,并且只将重力应用于特定的身体,就像箭头的抛射运动一样。当然,如果您一开始就将世界设置为有重力,则很容易进行抛射运动。
float GRAVITY_EARTH = -9.8f;
Vector2 gravity = new Vector2(0, GRAVITY_EARTH);
World world = new World(gravity, true);
Box2d body 类有一个取消或反转重力的方法,但我不想每次都使用它,就像下面的代码示例一样。
body.setGravityScale(0); // set 0 to cancel the gravity, and set -1 to reverse the gravity
但我想要多才多艺,我只想将重力应用于特定的身体。例如,我使用setLinearVelocity 方法将身体移动到特定目的地。现在,如果世界的重力 y 为 -9.8f,它将自动进行抛射运动。
Vector2 initialVelocity = targetPoint.sub(originPoint).nor();
initialVelocity.scl(speed); // to apply constant speed
body.setLinearVelocity(initialVelocity);
我尝试将 y 的初始速度增加到 -9.8 以应用重力。但它没有工作,我错过了什么?
initialVelocity.y += -9.8f;
body.setLinearVelocity(initialVelocity);
// or
body.applyForce(initialVelocity, body.getWorldCenter(), true);
【问题讨论】:
标签: libgdx box2d game-physics