Destruction of enemies by a jump, as in "Mario" Unity 2D

Hello! In this article I would like to share how to realize the destruction of enemies by leap, as in Mario. I’m still studying myself, so if I have any useful tips or hints, please write to the comments. Well, after numerous views of tutorials and read articles, only two interesting ones were found, and probably the easiest way to implement the options:





First, we write a function that will take the life of the player, and is necessary for both options:



public int health = 3; void Hurt() { health--; if (health <= 0) SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); }
      
      





1 option



We will analyze the first option if the contact point is greater than or equal to a height of 0.6, the player jumps from above and the enemy is destroyed, otherwise the player takes damage.



 void OnCollisionEnter2D(Collision2D collision) { Enemy enemy = collision.collider.GetComponent<Enemy>(); if (enemy != null) { foreach (ContactPoint2D point in collision.contacts) { if (point.normal.y >= 0.6f) { enemy.EnemyHurt(); } else { Hurt(); } } }
      
      





(A fragment of the code that is hung on the player)



 public void EnemyHurt() { Destroy(this.gameObject); }
      
      





(A snippet of code that hangs on the enemy)



Option 2



We add a collider, make it a little higher than the main collider, put a tick “is Trigger” on the object, hang a script, and add this code fragment.



 private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "Player") Destroy(this.gameObject); }
      
      





(A snippet of code that hangs on the enemy)



When the collider touches an object called “Player” the object is destroyed (as a contact mark, you can use tag).



Further in the same object we create one more gameObject and call it DeathZone. Add a collider to it, make it a little bigger, and check the “is Trigger” box.







  private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "DeathZone") { Hurt(); } }
      
      





(A fragment of the code that is hung on the player)



As you can see, unlike the first option, in the second option, the use of colliders was slightly larger, and there was no need to use triggers.





(Second option)



You can also add that the player jumps after the destruction of the enemy. Well, everything seems to be, thank you all for your attention!



All Articles