In Box2D, the trajectory of a moving body is affected by
1. gravity (including the gravity scale of the body)
2. linear damping
For starters, set the gravity to (0, 0) and the linear damping to 0 and see if it works.
Also, check out the
following post.
Code: Select all
-- STEP ONE: figure out the velocity required to reach the target
-- vector to target:
local dx = self.target.x - self.position.x
local dy = self.target.y - self.position.y
-- distance to target:
local d = math.sqrt(dx*dx + dy*dy)
assert(d > 0, "target == position")
-- normalized vector to target:
local nx = dx/d
local ny = dy/d
-- velocity required to reach the target:
local vx = nx*desiredLV
local vy = ny*desiredLV
-- minimum time to reach the target:
local dt = d/desiredLV
-- STEP TWO: factor in gravity and linear damping
-- adjust the velocity to compensate for the effects of gravity and linear damping:
-- v = v - g
vx, vy = steering.compG(vx, vy, gx, gy, dt) -- ignore if "gx" and "gy" are 0
vx, vy = steering.compLD(vx, vy, damping, maxLV, dt) -- ignore if "damping" is 0
-- STEP THREE: find the force based on the velocity: F = m*a, a = (fv - iv)/dt, dt = d/desiredLV
-- initial velocity, in this case 0, 0:
local ivx, ivy = 0, 0 -- body:GetLinearVelocity()
-- final velocity:
local fvx, fvy = vx, vy
-- force required to reach the final velocity:
local fx, fy = steering.force(ivx, ivy, fvx, fvy, mass, dt)
where:
Code: Select all
gx, gy: world gravity
damping: linear damping of the body
mass: mass of the body
maxLV: maximum linear velocity (Box2D constant)
desiredLV: desired linear velocity (0 < desired LV <= maxLV)
dt: time interval (> 0) in this case: dt = d/desiredLV
Once you know the force required to direct the body to a given target then you have to convert that to an impulse (from
the Box2D forums):
p = F * s (where p is the change of impulse, F a force and s the time, here dt). That means applyImpulse(10) and 10 seconds applyForce(1) will result in the same velocity for the body
These calculations work assuming that the body is not attached to a joint and doesn't collides with other bodies.