PDA

View Full Version : Dumb Pathfinding (Ignores walls etc)



Pleng
03-22-2008, 11:39 AM
This code will move your entity directly through multiple waypoints, regardless of the path being clear. Example uses are adding floating monsters or graphical effects to your RPGS, or moving platforms which raise through other platforms in side-scrolling games



// let's start at the very beginning!

m_start = 1;

// these are existing waypoints/named objects on the map
// set 'count' to the amount of waypoints in the path
// if the count is too low then the exta waypoints will be ignored
// if the count is too high you will get error messages and the game will
// not work - you have been warned!

m_count = 5;
m_tag = {};
m_tag[1] = "Ele1A";
m_tag[2] = "Ele1B";
m_tag[3] = "Ele1C";
m_tag[4] = "Ele1D";
m_tag[5] = "Ele1E";

m_closenessNeededToTarget = 50; //how close we need to to assume we reached our target
m_speed = 10; //how fast we move
m_curTargetPos = Vector2(0,0);

function SetNewTarget()

if (m_curTargetPos == GetTagManager:GetPosFromName(m_tag[m_start])) then

// go to the next one!

m_start = m_start + 1;

// reset to beginning if we already reached the last one

if (m_start > m_count) then
m_start = 1;
end

m_curTargetPos = GetTagManager:GetPosFromName(m_tag[m_start]);

else
//well, let's go to A then
m_start = m_start + 1;
m_curTargetPos = GetTagManager:GetPosFromName(m_tag[m_start]);
end
LogMsg(m_start);

end

function OnInit() //run upon initialization
this:SetGravityOverride(0);
this:SetDampening(0);
this:SetCollisionMode(C_COLLISION_MODE_PLAYER_ONLY );
SetNewTarget();
end

function OnPostInit() //run during the entity's first logic update
GetWatchManager:Add(this, C_TIME_FOREVER); //always function offscreen
//let's have a function that gets run every logic tick
this:SetRunUpdateEveryFrame(true);
end

//this is run every logic tick
function Update(step)

//remove all movement, no momentum
this:AddForceConstant(this:GetLinearVelocity() *-1);

//move towards target
this:AddForceConstant(this:GetVectorToPosition(m_c urTargetPos)*m_speed);

if (this:GetDistanceFromPosition(m_curTargetPos) < m_closenessNeededToTarget) then
//we reached out target! Set a new one.
SetNewTarget();
end

end


Possible areas for improvement:

Currently you have to set up the waypoints inside the script, as well as the amount of waypoints needed. It would be a lot more elegant if you could list the waypoints and the waypoint count in the entity properties - but I don't know how to do that! Even nicer would be a way for the script to calculate the amount of waypoints itself.

Anyway. I hope it's of use to people.

Many thanks to Seth for setting me in the right direction with this one... I couldn't have done it myself! :D

vulkodlac138
01-15-2010, 05:20 PM
brilliant!