0
votes

My animations enters a state and it's collision with enemy projectiles either defends himself or gets hurt depending on what animation he is currently in. I'm trying to detect collisions with the ONTRIGGERENTER function and boxcollider2D's but it's not having any affect. I want to figure out how to correctly facilitate trigger enters and collisions between these animations.

I've already tried giving my sprite a tag and calling that tag when the ONTRIGGERENTER function is called but it didn't work. I also tried a more complicated way of calling the tag of the collider but that didn't work either. How do you access the trigger when it's an animation?

string DefenceAnimTag = "Defending";
string DestroyEnemTag = "Eliminated";   

//This code is connected to the enemy projectile and trying to  
//sense when it's collided with the player
void OnTriggerEnter(Collider2D col)
{
 if (col.tag == Defending)
 {
    GetComponent<Animator>().SetBool("Elim", true);
 }
 else { //deal damage to the player }
}

//The first method didn't work so I tried a second method.
//Here is an alternative attempt at detecting triggers in
//animations.
void OnCollisionStay2D(Collider2D col)
{
 if (col.gameobject.CompareString("Defending"))
 {
  GetComponent<Animator>().SetBool("Elim", true);
 }
}
//This method didn't work either even though the Animation 
//WOULD be Defending

I expected enemy projectiles to collide with my player when he was defending himself and get defeated. I knew that it was working when the Enemy projectiles transition into their Elim state, where they get defeated by enemy defenses, however they made collisions and then continued unaffected.

1

1 Answers

0
votes

Okay, okay, I figured it out. Because a Gameobject can have many animations to it, you cannot go by the tag that the GameObject in the inspector has. You have to go by the title of the Animations that is currently playing. In order to access the animation currently playing we must use the following code:

AnimatorClipInfo[] m_AnimClipInf;
string m_ClipName;

void Start()
{
//Set up our projectile for possible Elimination
//upon Collision
Getcomponent<Animator>().SetBool("Elim", false);
}

void OnTriggerEnter2D(Collider2D col)
{
 m_AnimClipInf = col.GetComponent<Animator> 
 ().GetCurrentAnimatorClipInfo(0);

 m_ClipName = m_AnimClipInf[0].clip.name;

 if (m_ClipName == "Defending")
 {
 GetComonent<Animator>().SetBool("Elim", true);
 //Projectile gets eliminated
 }

}