I want to create a follower AI like Sparx from Spyro. You can see the mechanics in this video
https://youtu.be/2DicrivJ2xc?t=5
Sparx looks for gems on the ground, flies to them and flies back to Spyro. When flying to them, the gems start to fly to the player too. So Sparx is collecting the gems.
I already created the functionality making the gem fly to the player. Let's say I call this method
StartMovingToPlayer();
Sparx will call this method from the gem in his script.
public class PlayerFollower : Ai
{
private void OnTriggerEnter(Collider col) // something entered the trigger
{
Collectable collectable = col.GetComponent<Collectable>(); // try to get the collectable script
if (collectable != null) // is it a collectable?
collectable.StartMovingToPlayer(); // make it move to the player
}
}
So my question is, how can I make the AI fly to the gem, call the method, fly back and have all the gems in the trigger stored in a queue because when there is more than one gem in the trigger, the AI has to queue it.
So here's an update, I tried to make the follower collecting the gems when having them stored in my list
public class PlayerFollower : Ai { private List collectablesToCollect = new List(); // have all the gems in range stored here private bool isCollecting = false; // is the follower currently collecting gems? private float movementSpeed = 10; // collecting speed
private void Update()
{
if (CollectablesInRange()) // any gems in range?
{
if (!isCollecting) // collecting queued?
MoveToCollectable(); // collect it
}
else
{
// follow the player
}
}
private void OnTriggerEnter(Collider col)
{
Collectable collectable = col.GetComponent<Collectable>(); // get the gem
if (collectable != null) // is the object a gem?
{
if (!collectable.GetMovementState()) // got the gem already collected?
collectablesToCollect.Add(collectable); // add it to the queue
}
}
private void OnTriggerExit(Collider col)
{
Collectable collectable = col.GetComponent<Collectable>();
if (collectable != null)
collectablesToCollect.Remove(collectable); // remove it from the queue
}
private void MoveToCollectable() // start collecting
{
isCollecting = true;
if (CollectablesInRange())
{
Collectable collectable = collectablesToCollect.First(); just look for one gem
Vector3 defaultPosition = transform.position;
transform.position = Vector3.MoveTowards(transform.position, collectable.GetCollectablePosition(), movementSpeed * Time.deltaTime); // move to the gem
collectable.StartMovingToPlayer(); // call the gems movement
transform.position = Vector3.MoveTowards(transform.position, defaultPosition, movementSpeed * Time.deltaTime); // move back to the player
collectablesToCollect.Remove(collectable); // remove it from the queue
isCollecting = false;
if (CollectablesInRange()) // collect again, when the list is not empty
MoveToCollectable();
}
}
private bool CollectablesInRange()
{
return collectablesToCollect.Count > 0; // are there any gems in range?
}
}