I’m using libgdx with box2d. Write me a util method that calculates the linear velocity…
- User
I’m using libgdx with box2d. Write me a util method that calculates the linear velocity needed to smoothly push a box2d body to a target position without overshooting the target.
Overshooting happens the the velocity returned is greater than needed to reach the target in the next physics timestep.
Also note, you likely need to utilize delta time
This method should be able to handle high velocities. I should be able to call this method every frame like so
Vector2 velocity = PhysicsUtils.velocityToPosition(body, target, maxSpeed); body.setLinearVelocity(velocity);Assume you have access to any information you need. Note these you also have access to, PhysicsSystem.STEP_FREQUENCY (when physics timestep = 1/60f, this = 60f)
- Assistant
Here is a possible implementation of the required util method:
public static Vector2 velocityToPosition(Body body, Vector2 target, float maxSpeed) { Vector2 position = body.getPosition(); Vector2 velocity = body.getLinearVelocity(); float distance = target.dst(position); float time = MathUtils.clamp(distance / maxSpeed, 0f, 1f / PhysicsSystem.STEP_FREQUENCY); Vector2 displacement = target.cpy().sub(position); Vector2 targetVelocity = displacement.cpy().scl(1f / time); Vector2 impulse = targetVelocity.cpy().sub(velocity); impulse.scl(body.getMass()); // Clamp impulse magnitude to avoid overshooting float maxImpulse = body.getMass() * maxSpeed * PhysicsSystem.STEP_FREQUENCY; if (impulse.len2() > maxImpulse * maxImpulse) { impulse.nor().scl(maxImpulse); } impulse.scl(1f / PhysicsSystem.STEP_FREQUENCY); return impulse; }