Breaking 2D Object Sprites into 'pixels'



One of the most fun parts of any game is smashing anything and everything. 

Here's how I came up with what I think is a satisfying smash visual effect as a non-artsy programmer (game engine: unity).

  1. I created a white single pixel sprite that has the same 16 pixels-per-unit as all other objects, then made a prefab for it. 
  2. When a breakable object is started:
    1. Loop over all pixels on the sprite,
    2. Instantiate a single-pixel prefab for each one,
    3. Set it to the same color as the pixel on the main sprite.
  3. When I want to break the object (via collision or trigger):
    1. Turn off the main sprite,
    2. Enable all the instantiated pixels, 
    3. Run some pseudo-physics to have them look like they're falling to the floor.

Instantiating the pixels (C#):

// Properties / Awake
List<GameObject> _pixels = new ();
SpriteRenderer _spriteRenderer = GetComponent<spriterenderer>();
// Function to build pixels (I called mine from Start)
var spriteRect = _spriteRenderer.sprite.rect;
  
var start = new Vector2Int(
  Mathf.FloorToInt(spriteRect.x), 
  Mathf.FloorToInt(spriteRect.y));
  
var end = new Vector2Int(
  Mathf.CeilToInt(spriteRect.x + spriteRect.width), 
  Mathf.CeilToInt(spriteRect.y + spriteRect.height));
 
// -0.5 To account for the pixel center pivot.
// I chose not to edit the pivot on the pixel so
//   it could be reused in other things like particles.
var spritePivot = spriteRect.position 
  + _spriteRenderer.sprite.pivot 
  + new Vector2(-0.5f, -0.5f);
 
for (int x = start.x; x < end.x; x++)
{
  for (int y = start.y; y < end.y; y++)
  {
    var pixelColor = _spriteRenderer.sprite.texture.GetPixel(x, y);
  
    // Skip non-visible pixels
    if (pixelColor.a == 0) { continue; }
  
    var spritePos = (new Vector2(x, y) - spritePivot) 
      / _spriteRenderer.sprite.pixelsPerUnit;
  
    var pos = transform.position + (Vector3)spritePos;
  
    var pixelGameObject= Instantiate(
      _pixelPrefab, 
      pos, 
      _pixelPrefab.transform.rotation, 
      parent: transform);
  
    pixelGameObject.GetComponent<SpriteRenderer>().color 
      = pixelColor * _spriteRenderer.color;
  
    _pixels.Add(pixelGameObject);
  }
}

Notes:

Obviously this isn't a super efficient approach, but its better than making the art for each broken piece!

Get Midnight T-Rex

Buy Now$3.50 USD or more

Leave a comment

Log in with itch.io to leave a comment.