I just discovered how great Polar Coords and I am trying to get homing missies to work. For some reason my missile will occasionally spaz out and continue in the opposite direction. Any ideas why? I’m still trying to get a better understanding of using angles.
function setup()
parameter.watch("Distance")
targets = {}
target = nil
x = WIDTH/2
y = 0
length = 5
angle = math.deg(math.atan(y/x))
inc = 4
tAngle = 0
for i=1,5 do
table.insert(targets,{x=math.random(1,WIDTH),y=math.random(1,HEIGHT),select = false,alive = true})
end
missleSelect()
end
function draw()
background(255,255,255,255)
for i=1,#targets do
drawtarget(targets[i])
end
drawMissle()
home()
end
function drawtarget(v)
if v.alive then
pushMatrix()
pushStyle()
translate(v.x,v.y)
if v.select then c = color(60, 254, 1, 255)else c= color(255,0,0,255) end
fill(c)
ellipse(0,0,25)
fill(214, 213, 213, 255)
ellipse(0,0,15)
fill(c)
ellipse(0,0,10)
popStyle()
popMatrix()
end
end
function drawMissle()
x = x + length * math.cos(math.rad(angle))
y = y + length * math.sin(math.rad(angle))
pushMatrix()
pushStyle()
translate(x,y)
fill(255, 233, 0, 255)
ellipse(0,0,15)
popStyle()
popMatrix()
end
function missleSelect()
if #targets ~= 0 then
local rnd = math.random(1,#targets)
targets[rnd].select = true
target = rnd
tAngle = math.deg(math.atan2(targets[rnd].y - y,targets[rnd].x - x))
end
end
function home()
if #targets ~= 0 then
tAngle = math.deg(math.atan2(targets[target].y-y,targets[target].x - x))
Distance = (targets[target].y-y) +(targets[target].x - x)
--if angle - tAngle < -180 then angle = angle + 180 end
if angle < tAngle then
angle = angle + inc
else
angle = angle - inc
end
if x< targets[target].x +15 and x > targets[target].x -15 and
y < targets[target].y +15 and y> targets[target].y - 15 then
-- print("hit")
table.remove(targets,target)
missleSelect()
end
end
end