Ok, so I’ve been playing with the code found here:
http://paul.sc/shooting-moving-target/Shooting_Moving_Target.pdf
And I’m having some trouble. Fair enough, my math isn’t brilliant, but I thought this should be producing something a bit more workable.
Would anyone be able to tell me why this is behaving so oddly, please?
Refs:
https://developer.anscamobile.com/forum/2010/12/06/tower-defense-physics
https://developer.anscamobile.com/forum/2011/01/03/physics-question-using-bodyapplyforce-bullet
[lua]-- remove status bar
display.setStatusBar( display.HiddenStatusBar )
function newBall(x,y,vx,vy,c)
local ball = display.newCircle( x,y, 25 )
ball:setFillColor( c.r,c.g,c.b )
ball.x, ball.y = x, y
ball.vx, ball.vy = vx, vy
return ball
end
local p = newBall(200,100,0,2,{r=0,g=0,b=255})
local q = newBall(100,100,0,0,{r=0,g=255,b=0})
local balls = {}
balls[#balls+1] = p
balls[#balls+1] = q
local v = 2
local bulletSpeed = 5
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
local t = 10
if (a < 0) then
t = (-1 * math.sqrt® - b) / (2 * a)
else
t = (1 * math.sqrt® - b) / (2 * a)
print(a,t,r,b)
end
– 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 )
function enterFrame( event )
for i=1, #balls do
local ball = balls[i]
ball.x = ball.x + ball.vx
ball.y = ball.y + ball.vy
end
end
–Runtime:addEventListener( “enterFrame”, enterFrame )
enterFrame()[/lua]
Thanks,
Matt. [import]uid: 8271 topic_id: 4859 reply_id: 304859[/import]