OnTriggerEnter2D and OnTriggerExit2D called mutiples time

Viewed 134

I have one Player with RigidBody2D and a pillar with BoxCollider2D.

I check when OnTriggerEnter2D is called ( Player collided with the pillar ) then I try to keep Player position by change his bodyType to Static.

When OnTriggerExit2D is called, Player bodyType will be reverted to Dynamic again.

My problem is: after change player bodyType to Static , OnTriggerExit2D is called immediately. And after reverted to Dynamic, then OnTriggerEnter2D is called immediately. It goes on repeating again and again.

This is my Player and pillar

enter image description here

If you have any suggest please tell me.

Thank you.

2 Answers

From the RigidbodyType2D.Static docs:

Static behaviour stops the Rigidbody2D from reacting to gravity or applied forces including contacts with any other Rigidbody2D.

This type of Rigidbody2D should never repositioned explicitly. It is designed to never move.

A static Rigidbody2D will only collide with a dynamic Rigidbody2D body type. The exception to this is if Rigidbody2D.useFullKinematicContacts is set to true in which case it will also collide with any [[Kinematic]] body types.

When an attached Collider2D is set to trigger, it will always produce a trigger for any Collider2D attached to [[Dynamic]] or [[Kinematic]] body types.

That's why the exit is triggered again, if you want your character to sticks to the wall you should do a different approach.

My solution for this issue is changed to use constraints. The way I approached it was to freeze the X and Y positions as well as the Z rotation whenever OnCollisionEnter() was triggered.

void OnCollisionEnter2D(Collision2D collison){
     if(collison.transform.tag -= "Player"){
             body.constraints = RigidbodyConstraints2D.FreezePositionY | RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
     } 
}

void OnCollisionExit2D(Collision2D collision){
     if(collision.transform.tag == "Player"){
         body.constraints = RigidbodyConstraints2D.None;
     }
 }
Related