NPC AI - Collision Detection & Resuming Behavior
Having some trouble diagnosing why two pieces of code attached to my NPC companion aren't behaving properly... Here's what I want it to do:
Follow the PC (it does that)
When it sees an enemy within range, stop following the PC and move towards the enemy (it does that)
When it collides with the enemy, trigger the attack animation and do damage (not working)
When the enemy dies, go back to following the PC (not working)
Here are the pieces of code I'm using:
private bool chasing;
private Animator anim;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
theEnemy = GameObject.FindGameObjectWithTag("Enemy");
//Is there an enemy in range?
if (Vector3.Distance(theEnemy.transform.position, gameObject.transform.position) <= chaseLength)
{
if (Vector3.Distance(theEnemy.transform.position, gameObject.transform.position) <= triggerLength)
{
chasing = true;
}
else
{
chasing = false;
}
}
if (chasing)
{
transform.position = Vector3.MoveTowards(transform.position, theEnemy.transform.position, moveSpeed * Time.deltaTime);
lastMove = new Vector2(Input.GetAxisRaw("Horizontal"), 0f);
lastMove = new Vector2(0f, Input.GetAxisRaw("Vertical"));
return;
}
My thought here was that this piece would keep repeating if the chasing conditions (within chase length and trigger length) were both true; otherwise it would ignore the "return" command because chasing would be false.
This is my "Follow the PC" script which works up until chasing is engaged:
targetPlayerPos = new Vector3(followPlayer.transform.position.x, followPlayer.transform.position.y, 0);
transform.position = Vector3.Lerp(transform.position, targetPlayerPos, moveSpeed * Time.deltaTime);
lastMove = new Vector2(Input.GetAxisRaw("Horizontal"), 0f);
lastMove = new Vector2(0f, Input.GetAxisRaw("Vertical"));
And finally, this is the method I made for when the companion's BoxCollider2D collides with the enemy: public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
anim.SetBool("Attacking", true);
}
else
{
anim.SetBool("Attacking", false);
}
}
The idea here is that the "Attacking" bool in the animator would be triggered. As of right now, when the companion collides with the enemy, the bool in the animator doesn't change, so obviously something is amiss. I'm guessing because of the "return" command in the above code. Also, when I destroy the enemy with the PC and there are no other enemies around, the companion doesn't pick up its "Follow the Player" instructions...it stays "Chasing" = true. Any ideas?