I'm using libgdx with box2d. Trying to write a util method that calculates the linear…
- User
I'm using libgdx with box2d. Trying to write a util method that calculates the linear velocity needed to smoothly push a box2d body to a target position without overshooting the target and resulting in tiny oscillations for the body.
Overshooting happens the the velocity returned is greater than needed to reach the target when applied to a box2d body
I need the velocity to gradually reduce in relation to the distance between current position and target.
Note, maxSpeed is the maximum desired speed for the returned velocity, there is no minimum however. A returned velocity that is <= maxSpeed does NOT guarantee no overshooting 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);Here's what I came up with but it doesn't work. I want you to explain why this code doesn't handle overshooting, modify or write a new method that fixes this. And explain/compare how your solution works.
public static Vector2 velocityToPosition(Body body, Vector2 targetPosition, float maxSpeed) { Vector2 position = body.getPosition(); Vector2 velocity = body.getLinearVelocity(); // point in target direction Vector2 targetDirection = targetPosition.cpy().sub(position); float distance = targetDirection.len(); // Calculate distance that can be covered in one frame float maxDistance = maxSpeed / PhysicsSystem.STEP_FREQUENCY; if (distance <= maxDistance) { velocity.set(targetDirection); } else { velocity.set(targetDirection.scl(maxSpeed / distance)); } // If passed target position, zero velocity if (velocity.dot(targetDirection) < 0) { velocity.setZero(); } return velocity; }Note: PhysicsSystem.STEP_FREQUENCY (when physics timestep = 1/60f, this = 60f)
- Assistant
The reason the provided code doesn't handle overshooting is because it doesn't consider the time it takes to decelerate the body when it nears its target. You just limit the body's speed to
maxSpeed, but when it is very close to the target position, it is still too fast and can overshoot it.To fix this, you can add a deceleration factor that reduces the body's speed based on the distance remaining to the target position. And also, utilize delta time in calculations.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.