Hello, I have a problem with OnTriggerEnter2D
.
I’m trying to make afire trap which if the character enters collision of fire trap object, after few seconds delay, it it will activate fire and will cause instant death to my character.
Everything works fine if my character started from the outside of the firetrap collider, then trigger the trap and move towards the collider when the fire activated that will cause death to my character.
However, when i move my character to the trap, which triggering it and stay there wait for few seconds until the fire being activated, the fire trap collision does not detect/recognize my character when I already inside of the collision, thus not causing death to my character.
I’ve tried using OnTriggerStay
instead/making sure my fire trap collider is Triggered/adding RigidBody2D
to firetrap object , but nothing is working.
If you know how to fix this, please help!
Firetrap.cs
public class Firetrap : MonoBehaviour
{
[Header("Firetrap Timer")]
[SerializeField] private float activationDelay;
[SerializeField] private float activeTime;
private Animator firetrapanim;
private SpriteRenderer spriteRend;
private bool traptriggered;
private bool trapactivated;
PlayerCharacterController PlayerCharacterController;
[SerializeField] private GameObject PlayerCharacter;
void Awake()
{
firetrapanim = GetComponent<Animator>();
spriteRend = GetComponent<SpriteRenderer>();
PlayerCharacterController = PlayerCharacter.GetComponent<PlayerCharacterController>();
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
if (!traptriggered)
{
//trigger the firetrap
StartCoroutine(ActivateFiretrap());
}
if (trapactivated)
{
PlayerCharacterController.Death = true;
}
}
}
IEnumerator ActivateFiretrap()
{
//turn red to notify player and trigger the trap
traptriggered = true;
spriteRend.color = Color.red;
//wait for delay, activate trap, turn on animation, return color back to normal
yield return new WaitForSeconds(activationDelay);
spriteRend.color = Color.white;
trapactivated = true;
firetrapanim.SetBool("activated", true);
//wait "activetime" seconds, deactivate trap and reset all variables and animatior
yield return new WaitForSeconds(activeTime);
trapactivated = false;
traptriggered = false;
firetrapanim.SetBool("activated", false);
}
}