Last Updated on 2021-10-28 by Clay
I recently use Unity to develop when a snake game, I want to delete the head game object when my snake head collides with another snake's body, I need to use OnTriggerEnter2D()
to set the collision determination.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Snake")
{
Destroy(gameObject);
}
}
However, because I need to determine the snakes collision or not, I use Rigidbody2D to my game object, but this make my snake head and body push each other.
Solution
The solution is very easy, just change the Body Type of RigidBody2D to Kinematic.
There are 3 types of Body Type: Dynamic, Kinematic, and Static.
Dynamic
- Dynamic game objects are completely driven by physics engine
- The force, speed, etc. of Dynamic game objects are affected
- The physic engine handles bounces according to the collision requirements of other objects
- It is suitable for game characters and mobile game objects
Kinematic
- Kinematic game objects are completely script-driven, so
MovePosition()
,MoveRotation()
must be processed - Kinematic game objects only process collisions with Dynamic game objects; for example, when bouncing, send the
OnCollisionEnter()
event - It is suitable for making game characters more flexible and customized (this is my requirement)
Static
- There is no real RigidBody component attached, so the physics engine does not work
- No collisions, cannot use
OnTrigger()
andOnCollision()
- It is suitable for game objects that do not want to collide, such as floors and walls
References
- https://needoneapp.medium.com/unity-should-i-choose-kinematic-static-or-dynamic-for-rigidbody-2d-body-type-191ce65fa35f
- https://docs.unity3d.com/Manual/class-Rigidbody2D.html