@roaminggamer:
That’s exactly what I’m looking for. [see below]
@Everyone Else:
For the sake of learning, I’m trying to achieve it myself. With torbenratzlaff’s pointers, I’ve come up with this… The only problem is that it always tries to get the lowest angle, so it “wiggles” when the angle between the knatch and the missile goes back and forth. Any suggestions for how to solve this?
For the record, “knatch” is a word I made up to mean object, boid, thingy, or anything else that moves in a game. Boxes are knatches. Pillbugs are knatches. Etc., etc., etc.
[lua]
local deg = math.deg
local rad = math.rad
local atan2 = math.atan2
local sin = math.sin
local cos = math.cos
local function angleBetween(a, b)
return deg(math.atan2(b.y - a.y, b.x - a.x)) + 90
end
local function forcesByAngle(totalForce, angle)
local forces={}
local radians= -rad(angle)
forces.x = cos(radians) * totalForce
forces.y = sin(radians) * totalForce
return forces
end
local function smallestAngleDiff(target, source)
local a = target - source
if (a > 180) then
a = a - 360
elseif (a < -180) then
a = a + 360
end
return a
end
local function clamp(n, l, h)
if n < l then
return l
elseif n > h then
return h
else
return n
end
end
local knatch = display.newCircle(0, 0, 20)
knatch.x, knatch.y = 128, 384
knatch.xSpeed = 3; knatch.ySpeed = 0
local missile = display.newRect(0, 0, 60, 10)
missile.x, missile.y = 512, 512
missile.xSpeed, missile.ySpeed = 0, 0
missile.firingSpeed = 6
missile.maxTurningAngle = 4
local function onRuntime(event)
knatch:translate(knatch.xSpeed, knatch.ySpeed)
missile:translate(missile.xSpeed, missile.ySpeed)
local angle = math.abs(clamp(angleBetween(missile, knatch) + 90, missile.rotation - missile.maxTurningAngle, missile.rotation + missile.maxTurningAngle))%360
missile.rotation = angle
local forces = forcesByAngle(missile.firingSpeed, math.abs(angle))
missile.xSpeed, missile.ySpeed = -forces.x, forces.y
if knatch.x > display.contentWidth then
knatch.xSpeed = -3
elseif knatch.x < 0 then
knatch.xSpeed = 3
end
end
Runtime:addEventListener(“enterFrame”, onRuntime)
[/lua]