Q: How can I make an entity move to the specified location?
A: Here's an example that moves an NPC character towards its goal using primitive, and yet fully functional obstacle avoidance code.
ENTITY* goal;
action npc_goal() // attach this action to the destination entity
{
goal = my;
}
action goal_tracker() // attach this action to your NPC character
{
while (!goal) {wait (1);} // wait until the goal entity is loaded
VECTOR temp, temp_angle;
var npc_speed = 5;
var covered_dist, i;
while (1)
{
my.skill10 += 6 * time_step; // 6 gives the animation speed
vec_set (temp.x, my.x); // trace 10,000 quants below the npc entity
temp.z -= 10000;
temp.z = -c_trace (my.x, temp.x, IGNORE_ME | IGNORE_PASSABLE | USE_BOX) + 20; // play with 20
temp.x = npc_speed * time_step;
temp.y = 0;
ent_animate(my, "walk", my.skill10, ANM_CYCLE);
covered_dist = c_move (my, temp.x, nullvector, IGNORE_PASSABLE | GLIDE);
if (covered_dist < 0.1) // the npc is stuck?
{
my.pan += 90 - random(180); // then add a random angle to its pan angle
i = 0;
while (i < 10) // walk in the new direction for 10 frames, play with 10
{
c_move (my, temp.x, nullvector, IGNORE_PASSABLE | GLIDE);
ent_animate(my, "walk", my.skill10, ANM_CYCLE);
i++;
wait (1);
}
}
else // the npc can move? Then rotate it towards the goal again!
{
vec_set(temp_angle, goal.x);
vec_sub(temp_angle, my.x);
vec_to_angle(my.pan, temp_angle);
my.tilt = 0;
}
if (vec_dist(goal.x, my.x) < 50) // the npc has found the goal entity?
break; // then get out of the while loop!
wait (1);
}
// the goal was reached here
ent_animate(my, "stand", 0, 0); // switch to "stand"
}