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 effect as a non-artsy programmer (game engine: unity).
- 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:
- Loop over all pixels on the sprite,
- Instantiate a single-pixel prefab for each one,
- Set it to the same color as the pixel on the main sprite.
- When I want to break the object (via collision or trigger):
- Turn off the main sprite,
- Enable all the instantiated pixels,
- 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
Midnight T-Rex
Halloween & dinosaur themed roguelite w/ fishing & co-op. ~ Free to play in-browser! ~
More posts
- Build 1.0.8 - Halloween Special! 👻39 days ago
- Build 1.0.7 - Arcane Studies85 days ago
- Build 1.0.6 - New Upgrades & Bug FixesJul 09, 2024
- Build 1.0.5 - Marigold & VariantsJul 02, 2024
- Build 1.0.4 - EndgameJun 23, 2024
- Build 1.0.3 - Eggs & SecretsApr 18, 2024
- Build 1.0.2 - Bugs & BossesApr 17, 2024
- Build 1.0.1 - Boss 2 Balance TweaksApr 14, 2024
- Playing on the SteamDeckApr 10, 2024
Leave a comment
Log in with itch.io to leave a comment.