Archive for 02/11/2015

Unity – Platforms

Example time.

You have began making a 2D platformer. But how are your platforms? Are they rigid, do they move. More importantly, do they have one way collision in most high class 2D platformers?

Well if your looking for one way collision platforms in Unity, i got some good news for you.

Here we will be looking into setting up such a platform.

There are a few ways to achieve this effect. One would be to use layers but that can lead you into problems. So here we will be usign a delegate system. The idea is that when the player goes from jumping to falling, each platform gets notified and checks whether to become “solid” or not based on whether or not it’s intersecting the player already.

To achieve this desired effect. We need to look into 4 main scripts.

  1. Player
  2. World
  3. Platform
  4. Includes

 

PLAYER.CS

new public static BoxCollider2D collider;

void Awake()
{
    collider = GetComponent<BoxCollider2D>();
void Update()
{
    if(jumping && velocity.y < 0f)
    {
        World.SetPlayerPlatformCollision(true);
    }
    else if(!jumping && Input.GetButtonDown("Jump"))
    {
        World.SetPlayerPlatformCollision(false);
    }
}

The Player script is pretty straight forward, we check for jumping and the velocity. However, the SetPlayerPlatformCollision method that is important. It is this that will tell the platform to toggle.

 

INCLUDES.CS

public class BoolEvent : UnityEvent<bool>{};

The Includes script is used just to contain one thing. The BoolEvent. Which tracks the status of a platform.

 

WORLD.CS

public static BoolEvent OnTogglePlayerPlatformCollision {get; private set;} 

static World()
{ 
    OnTogglePlayerPlatformCollision = newBoolEvent();
}

public static void SetPlayerPlatformCollision(bool collide)
{
    OnTogglePlayerPlatformCollision.Invoke(collide);
}

 

PLATFORM.CS

new BoxCollider2D collider;

void Start()
{
    collider = GetComponent<BoxCollider2D>();
    World.OnTogglePlayerPlatformCollision.AddListener(OnTogglePlayerPlatformCollision);
}

void OnTogglePlayerPlatformCollision(bool collide)
{
    collider.enabled = collide && !collider.bounds.Intersects(Player.collider.bounds);
}

The platform scripts checks wether the player has collided with the platform.

Hopefully this explains how it works, and arguably the best method of implementation.

Regards.