← All projects

Side project

2D Character Controller

A reusable 2D platformer character controller in Unity, built around the new Input System and a central event system based on the observer pattern.

Type
Side project
Engine
Unity
Pattern
Observer
Play
itch.io

More in the privacy policy.

01

Input management

  • Uses Unity’s new Input System for clean action mapping.
  • Turns raw input into high-level events such as OnMove, OnJump and OnAttack.
private void SubscribeToPlayerEvents()
{
    player.ID.events.OnMove += Walk;
    player.ID.events.OnJump += JumpInput;
    player.ID.events.OnJumpRelease += JumpReleaseInput;
    player.ID.events.OnDash += DashInput;
    player.ID.events.OnLand += GroundTouch;
}

private void UnsubscribeToPlayerEvents()
{
    player.ID.events.OnMove -= Walk;
    player.ID.events.OnJump -= JumpInput;
    player.ID.events.OnJumpRelease -= JumpReleaseInput;
    player.ID.events.OnDash -= DashInput;
    player.ID.events.OnLand -= GroundTouch;
}

02

Movement & physics

  • Walking, running, jumping, wall sliding, wall jumping and dashing.
  • Variable jump height and fall multipliers for a better platformer feel.
  • Cooldowns for the dash and dropping through platforms.
private void Jump(Vector2 direction)
{
    _rb.velocity = new Vector2(_rb.velocity.x, 0);
    _rb.velocity += direction * _jumpForce;
    _extraJump--;
    _jump = false;
}

private void WallSlide()
{
    if (!player.ID.status.CanMove)
        return;

    _rb.velocity = new Vector2(_rb.velocity.x, Mathf.Clamp(_rb.velocity.y, -_wallSlideSpeed, float.MaxValue));
}
private void Dash(int direction)
{
    if (!player.ID.status.CanMove)
        return;

    if (_dashTime <= 0 || player.ID.status.IsOnWall)
    {
        _dash = false;
        _dashTime = _startDashTime;
    }
    else
    {
        _dashTime -= Time.deltaTime;
        if (_direction == 1)
            _rb.velocity = Vector2.right * _dashSpeed;
        else
            _rb.velocity = Vector2.left * _dashSpeed;

        player.ID.events.UseDash?.Invoke();
    }
}

03

Observer pattern via PlayerEvents

  • PlayerEvents defines actions like OnMove, OnJump, OnLand and OnTakeHit.
  • Each gameplay system subscribes in OnEnable and unsubscribes in OnDisable.
  • This keeps the systems independent of each other.
  • Unity
  • C#
  • Input System
  • Observer pattern
UML diagram of the observer pattern
Observer pattern
public struct PlayerEvents
{
    // Input Events
    public Action<Vector2> OnMove;
    public Action OnJump;
    public Action OnJumpRelease;
    public Action OnDash;
    public Action OnAttack;
    public Action OnWeaponSwitch;
    public Action OnInteract;

    // Animation Events
    public Action UseDash;
    public Action OnTakeHit;
    public Action OnDead;

    // Environment Events
    public Action OnLand;
    public Action OnGoThroughPlatform;
}

Interested in working together?