Dang, thought I had commented on the previous post which was very much along these lines, but anyway…
Here’s a link I nabbed from the other post someone was asking about turret shooting “tower defense” style games:
Flash demo: http://paul.sc/shooting-moving-target/
PDF: http://paul.sc/shooting-moving-target/Shooting_Moving_Target.pdf
And I’ve taken the flash code from the PDF and converted it to lua, though please note I’ve only tested it here: http://www.lua.org/cgi-bin/demo and not in an actual program:
[lua]function newBall(x,y,vx,vy)
local ball = {}
ball.x, ball.y = x, y
ball.vx, ball.vy = vx, vy
return ball
end
local p = newBall(10,10,10,10)
local q = newBall(100,100,10,10)
local v = 10
local bulletSpeed = 50
local dx, dy = p.x - q.x, p.y - q.y
local a = p.vx * p.vx + p.vy * p.vy - v * v
local b = 2 * (p.vx * dx + p.vy * dy )
local c = dx * dx + dy * dy
– Check we 're not breaking into complex numbers
local r = b * b - 4 * a * c
if (r < 0) then
– Doesn 't look like this is going to work !
print( " Shit !" )
end
– The time that we will hit the target
if (a < 0) then
a = -1
else
a = 1
end
local t = (a * math.sqrt( r ) - b) / (2 * a)
– Aim for where the target will be after time t
dx = dx + t * p.vx
dy = dy + t * p.vy
local theta = math.atan2 (dy , dx )
– Throw the ball
q.vx = bulletSpeed * math.cos( theta )
q.vy = bulletSpeed * math.sin( theta )[/lua]
Let us know how you get on…
matt. [import]uid: 8271 topic_id: 4798 reply_id: 15419[/import]