Breaking 2D Object Sprites into 'pixels'
Midnight T-Rex » Devlog
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 as a non-artsy programmer.
- 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.
- When a breakable object is started, I loop over all pixels on the sprite and instantiate my single-pixel prefab, setting it to the same color as the pixel on the main sprite.
- When I want to break the object (via collision or trigger) I just turn off the main sprite, enable all the instantiated pixels, and run some pseudo-physics to have them look like they're falling to the floor.
Instantiating the pixels:
// 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); } }
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
Midnight T-Rex
A roguelite dinosaur dungeon adventure! Play solo or co-op with a friend.
Status | In development |
Author | Slow Seer |
Genre | Action |
Tags | Co-op, Dinosaurs, Fishing, Halloween, Local Co-Op, Multiplayer, Pixel Art, Roguelike, Roguelite, Top-Down |
Languages | English |
More posts
- Build 1.0.3 - Eggs & Secrets27 days ago
- Build 1.0.2 - Bugs & Bosses28 days ago
- Build 1.0.1 - Boss 2 Balance Tweaks32 days ago
- Playing on the SteamDeck36 days ago
- Launch!38 days ago
Leave a comment
Log in with itch.io to leave a comment.