Thursday, November 8, 2018

2D Platformer Character 5 - Triggers

This time we will use small but useful script to add simple trap to our level. We are going to make red crystals fall down when player enters particular area. First, lets prepare our object that will fall on unsuspecting player.

Put new sprite of your choice into the scene, add 'Rigidbody 2D' and some kind of 'Collider 2D' to it. Make sure to uncheck 'Simulated' property on Rigidbody, so it wont fall down straight away. You can also change its Tag to 'Kill', so it will kill the player when touched. Next, create empty Game Object, add 'Box Collider 2D' to it and check it's 'Is Trigger' property. Adjust its size and position to encompass area that should trigger our red gem to fall. Feel free to rename our new Game Object to something more appropriate (like 'gem red fall' for example). Add PlayerTrigger.cs script to it
using UnityEngine;
using UnityEngine.Events;
 
public class PlayerTrigger : MonoBehaviour
{
    public UnityEvent onEnter;
 
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
            onEnter.Invoke();
    }
}
And set it up in inspector, so it will turn on 'Simulated' property of our 'gem red' game object. The only thing left to do is to make sure our player object has 'Player' tag assigned, otherwise PlayerTrigger.cs script wont recognize it. Congratulations, you made your first trap. Of course this is just simple example, you can use PlayerTrigger.cs script in many other ways, limited only by your imagination :3

No comments:

Post a Comment