Good answer from undef. Linear interpolation will work for animations but for "autonomously moving agents" a better approach might be "steering".
Take a look at the bottom of:
http://2dengine.com/doc_1_3_10/gs_vector.html
Code: Select all
-- move the agent to target point, return true when we arrive
agent.moveto = function(agent, target, dt)
-- find the agent's "step" distance for this frame
local step = agent.speed * dt
-- find the distance to target
local distx, disty = target.x - agent.x, target.y - agent.y
local dist = math.sqrt(distx*distx + disty*disty)
if dist <= step then
-- we have arrived
agent.x = target.x
agent.y = target.y
return true
end
-- get the normalized vector between the target and agent
local nx, ny = distx/dist, disty/dist
-- find the movement vector for this frame
local dx, dy = nx * step, ny * step
-- keep moving
agent.x = agent.x + dx
agent.y = agent.y + dy
return false
end
Ideally, you want to modify the "velocity" of the agent not his position.
Currently when the map loads the enemy starts at the first wp, so the second wp is where they need to head to. Then the third, then back to the first, and onwards... I'm having trouble with returning the initial destination wp and when they reach it, cycling on to the next in the wps table.
Depends on your implementation. You can try something like:
Code: Select all
agent.wps = {{x=100,y=100}, {x=200, y=200}, {x=100,y=200}}
agent.nextwp = 1
agent.x, agent.y = 100, 100 -- agent's "current" position
agent.speed = 100 -- in pixels per second
agent.movetowp = function(agent, dt)
-- no waypoint set?
if agent.nextwp == nil then
return
end
-- move
local target = agent.wps[agent.nextwp]
if agent:moveto(target) then
-- we have arrived!
agent.nextwp = agent.nextwp + 1
-- loop?
if agent.nextwp > #agent.wps then
agent.nextwp = 1
end
end
end
agent.update = function(agent, dt)
agent:movetowp(dt)
end
If you set .nextwp to "nil" the agent will stop moving, otherwise it will cycle through all the waypoints.