I’m working on a space game and am trying to implement an efficient way of predicting whether two ships will move within a specific distance of each other over time. Can anyone recommend a more efficient way of doing this? My vector math is a bit rusty. I could probably make the loop more efficient by not checking every frame over four seconds.
[lua] function ship.intersection(target)
local sx, sy, svx, svy, frames
local tx, ty, tvx, tvy, dx, dy
local hitFrame, hitX, hitY
sx = ship.x
sy = ship.y
svx = ship.vx – x velocity
svy = ship.vy – y velocity
frames = 120
tx = target.x
ty = target.y
tvx = target.vx – x velocity
tvy = target.vy – y velocity
for i = 1, frames do
sx = sx + svx – calculate future positions
sy = sy + svy
tx = tx + tvx
ty = ty + tvy
dx = sx - tx – x distance between ship and target
dy = sy - ty – y distance between ship and target
local d = math.sqrt(dx * dx + dy * dy)
if d < 40 then
hitFrame = i
hitX = tx
hitY = ty
break
end
end
return hitFrame, hitX, hitY
end[/lua] [import]uid: 1560 topic_id: 31761 reply_id: 331761[/import]