Learning Unity 2D

by re-creating Mega Man

Not a terrible exciting update. A lot of brainstorming this weekend.

Death

Finally. He can die.

When I thought about how to do this, it was pretty simple: just make a bunch of similarly animated game objects and send them in different directions at different speeds. It’s not an animation really, just particles flying about. Doing that was simple:

private void Die()
{
    CreateDeathParticles(4);
    CreateDeathParticles(8);
}

private void CreateDeathParticles(float speed)
{
    for (var x = -1; x <= 1; x++)
    {
        for (var y = -1; y <= 1; y++)
        {
            if (x == 0 && y == 0)
            {
                continue;
            }
            Instantiate(deathParticle, transform.position, Quaternion.identity)
                .SetMovement(new Vector2(x, y), speed);
        }
    }

But a few immediate problems came up:

  1. How do make Mega Man disappear? Destroy the game object?
  2. How to make sure he can’t shoot any more?
  3. The death keeps triggering. Why?

For 1 and 3, we had to disable stuff. Easily, we can disable the game object’s immediate SpriteRenderer, PlayerInput, and Collider2D. However, while Mega Man disappeared and no longer spammed death particles every time his missing corpse got hit, he could still shoot. This is because the Gun object (and its WeaponController) was a different game object.

So, passing that as a serialized field (after adding a method to it do disable its PlayerInput) allowed me access to turn it off. I used GetComponentInChildren within Awake at first, which is a viable solution, but I switched to a serialized property for… unknown reasons. Just felt better, I guess?

Refactoring Plans

The rest of the weekend has been research and brainstorming refactoring. As the code/game is so far, it’s a mess. Game objects here and there, scripts wherever I put them, absolutely zero persistent state or state management. Just terrible.

So, I think my next goal is to establish the player’s health as a persistent object (likely a singleton), and use an event-based system to take damage and die. Obviously, to do something like this, I need to research more on Unity events and play around with their usage. But, the ultimate goal would be to establish a framework that I can use to:

  • Track lives.
  • Track weapons owned.
  • Restart stages from a certain point when dead.
  • Stage select.
  • … and more.

Too many things to cover at once, so I’ll start simple with the health tracking and move on from there. It’s not about health tracking (we already have that), but how it’s implemented.

Posted in

Leave a comment