Destructible 2D


DOCUMENTATION

Thank you for using Destructible 2D ❤️

If you haven't already, please consider writing a review. They really help me out!



How do I upgrade?

First, make sure you back up your project files.

Next, install the latest version.

If for some reason the latest updates breaks your project (e.g. errors in the console), then try deleting the root folder for this asset, and reinstalling it.

If it still doesn't work then go back to your previous version, and let me know what the errors are, so I can fix it.



Making a Destructible Sprite

To turn a normal sprite into a destructible sprite, you have to:

Step 1 Drag and drop your sprite into the scene.
Step 2 Find the SpriteRenderer component on your GameObject.
Step 3 Open the context menu for it (the ⋮ button).
Step 4 Select "Make Destructible".

Your sprite GameObject will now have the D2dDestructibleSprite component attached with basic settings.



Adding Colliders

A destructible sprite is incompatible with Unity's normal 2D colliders (e.g. PolygonCollider2D).

To add colliders, you must use either the D2dPolygonCollider component, or the D2dEdgeCollider component. This can be done manually, or by pressing the "+ Polygon Collider" or "+Edge Collider" buttons.

NOTED2dEdgeCollider will only work with non-moving GameObjects like the ground. For moving (e.g. physics) objects, you must use the D2dPolygonCollider component.


Stamp/Paint Modes

When you damage or heal sprites, you use a component like D2dTapToStamp or D2dExplosion. These components have various settings for the way they stamp destructible objects in the scene. Stamping is usually done based on a stamp shape texture, and a stamp paint mode.


The Paint Shape Textures

These components have the ColorShape and AlphaShape textures. If you use the default Cut paint mode, then only the AlphaShape will be used, where the opacity/alpha of this texture will be used to cut holes in your destructible objects.



The Paint Setting

These components have the Paint setting, which allows you to control how the stamp shape texture(s) modify any paintable textures.

Cut This blending mode uses only the AlphaShape texture. This will damage sprites by subtracting alpha using alpha from the AlphaShape texture.

Heal This blending mode uses only the AlphaShape texture. This is the inverse of the Cut blending mode, and will add alpha using alpha from the AlphaShape texture.

Subtract This blending mode uses both the ColorShape and AlphaShape textures. This works like the Cut blending mode, but it will also subtract RGB using RGB from the ColorShape texture.

Subtract Inv Color This blending mode uses both the ColorShape and AlphaShape textures. This works like the Subtract blending mode, but it will invert the RGB values from the color tint you specify.

Cut Min RGB This blending mode uses both the ColorShape and AlphaShape textures. This works like the Cut blending mode, but it will also set the RGB to the minimum of the current RGB vs the RGB from the ColorShape texture. This allows you to darken your texture with the specified ColorShape, but not make things too dark.

Alpha Blend RGB This blending mode uses both the ColorShape and AlphaShape textures. This works like the Cut blending mode, but it will also alpha blend the RGB using RGB from the ColorShape texture. This allows you to paint the underlying destructible object with a new color.

NOTE  This paint mode requires your destructible objects to be generated using Full RGBA channels, and for their material to only use destructible RGB data (i.e. ignore the original sprite RGB).



Optimizing Performance

The best way to optimize performance of your destructible sprites is to use less pixels. If you click the "Optimize" button on the D2dDestructibleSprite component, then the width & height of your alpha sprite will be halved. This increases the performance of your sprite by 4x, and can be done multiple times. However, each time you optimize it, the visual quality of the destruction will reduce.

NOTE  If you've optimized your sprite too many times, then clicking the "Rebuild" button will reset it back to its original state.

You can also optimize your colliders by increasing the Straighten setting, don't set this too high though, otherwise you will lose collider accuracy.



Splitting/Slicing Parts Off

By default, a destructible sprite will remain as one single GameObject, even if you slice it in half.

If you want sliced parts to fall off, then you need to add the D2dSplitter component. This can be done manually, or by pressing the "+Splitter" button.

NOTE  Splitting is a complex operation, and may reduce the performance of your game. To speed this up, make sure you Optimize your sprite as much as possible. If your destructible sprite is large then consider splitting it up into multiple smaller parts, or designing your game in such a way that avoids having large singular splittable objects.


Using Semi-Transparent Sprites

By default, the shape of your destructible sprite is read from the sprite's alpha channel. This normally works well, but if your sprite has semi-transparent areas then it may not work, because these areas will be treated as already having received damage.

To fix this, you must:

Step 1 Create a second version of your sprite that doesn't contain any semi-transparent areas.
Step 2 Drag and drop this new sprite into the Shape setting of your D2dDestructibleSprite component.
Step 3 Click the Rebuild button of your D2dDestructibleSprite component.
Step 4 Change the Material setting of your SpriteRenderer component to the KeepAlpha material.

This "KeepAlpha" material uses a custom shader that combines the alpha data in the visual sprite with the alpha data from the destruction. Without this, only the alpha data from the destruction will be used, and therefore your semi-transparent areas will become opaque.

NOTE  If your destructible object was originally optimized, then after you click Rebuild, make sure you click Optimize again!


Collision Damage

By default, nothing happens when an object hits your destructible object.

If you'd like your object to react in some way (e.g. fracture, make a sound), then you need to manually configure it to do this.


Spawn On Impact

The most flexible approach is to add the D2dImpactSpawner component to your Rigidbody2D GameObject (e.g. on a flying rock).

Whenever the current object hits something, it will check the impact force. If this force exceeds the Threshold value, then the specified Prefab will be spawned at the hit point.

If you'd like to play a sound upon hit, then this prefab can have the AudioSource component.

If you'd like to emit particles upon hit, then this prefab can have the ParticleSystem component.

If you'd like to apply damage to the hit (and nearby) destructible objects, then this prefab can have the D2dExplosion component.



Damage On Impact

Destructible 2D comes with a damage system that can store how much impact force and explosion damage the current object has received.

This can be done by adding the D2dImpactDamage component to your object (e.g. a wall), which will automatically add the D2dDamage component as well.

Whenever the current object gets hit by something (e.g. a flying rock), it will check the impact force. If this force exceeds the Threshold value, then the specified D2dDamage component's Damage value will be increased.

NOTE  These components don't do anything by default, because there are many ways this Damage value can be used. The steps below outline some ways it can be used.


Fracture On Impact

NOTE  This feature requires you to first follow the above "Damage On Impact" steps.

If you'd like your object to fracture into smaller pieces when it receives enough damage, then you can:

Step 1 Add the D2dFracturer component to your destructible object.
Step 2 Enable its Damage setting.
Step 3 (Optional) Configure its settings, like the Damage Required,Damage Multiplier, Points Per Solid Pixel, etc.

Your object will now automatically fracture when it gets hit enough.



Fissure On Impact

NOTE  This feature requires you to first follow the above "Damage On Impact" steps.

If you'd like your destructible object to develop a chip/cut/fissure when it gets hit by something, you can add the D2dImpactFissure component to it.

This component is ideal for certain kinds of objects/materials. For example, if you have a thin glass sheet and need it to fracture/crack at the exact point of impact, then you can use the fissure feature to cut the object at the hit point. This also allows you to filter by layer, so you can have different kinds of damage type for different kinds of objects.

NOTE  I recommend you check the Impact Fissure demo scene to better see how this feature can be implemented.


Manual Event On Damage

NOTE  This feature requires you to first follow the above "Damage On Impact" steps.

If you want to trigger a custom event when your object receives a specific amount of damage, then you can add the D2dRequirements component to it.

If you enable its Damage setting, then you can specify the minimum and maximum damage required for the OnRequirementsMet event to get invoked. This event can then used to do anything you like. For example, in many example scenes this is used to enable the D2dDestroyer component, which can destroy the current GameObject after it's received too much damage.



Sprite Swap On Damage

NOTE  This feature requires you to first follow the above "Damage On Impact" steps.

The D2dDamage component has the States setting. If you add some states, then this allows you define which visual sprite will be used for your destructible object based on a specified damage range. This can be used to make the class sprite swap damage effect.

NOTE  I recommend you check the Cracking Eggs demo scene to better see how this feature can be implemented.



Sprite Shape

If your project uses SpriteShape objects, then they can be made destructible using Destructible 2D. The process is almost the same as normal SpriteRenderers, except you must open the context menu (the ⋮ button) for the SpriteShapeRenderer component, and select one of the presets. This will add the D2dDestructibleRenderer component instead of the normal D2dDestructibleSprite component.

Your SpriteShape should now have destruction!


Editing The SpriteShape Spline

If you want to edit the spline of your SpriteShape, I recommend you click the D2dDestructibleRenderer component's "Revert Materials" button first. This will hide the current destruction state, which would otherwise make it difficult to see the new shape of your object.

Once you're happy with your new spline, you can click the "Rebuild" button. If you need to put the materials back, then click the "Revert Materials" button again.




URP Lit

If your project uses the Universal Render Pipeline with the 2D Renderer, then you can add support for the Lit shader by installing one of the packages in the "Plugins/CW/Destructible 2D" folder.

If you're using Unity 2021.2 or newer, install the "URP 2021.2" package. If not, install the "URP 2020" package.

You can now apply the "D2D Sprites-Lit-Default" material to your destructible object, which will show destruction and 2D lighting.



Attaching GameObjects to Splittable Destructible Sprites

When a destructible sprite splits in half using the D2dSplitter component, it will be cloned/instantiated to make the other side, and D2dSplitter will automatically separate the destruction data between the two destructible sprites. This works well for simple destructible sprites, but if your destructible sprite has child GameObjects, then they will also be cloned, and multiply. This will look incorrect because you will now have two copies of your child GameObject, one on the original, and one on the clone. To fix this, you can use the D2dFixture component.

To add a fixture you can manually add a child GameObject with the D2dFixture component, or open the context menu for the D2dDestructibleSprite component, and select the "Add Fixture" option. The D2dFixture component automatically detects when the current (parent) destructible sprite is splitting, and forces it to stick to only one destructible sprite after the split.

NOTE  The D2dFixture component will also destroy itself if/when the pixel underneath it gets destroyed, or if it gets moved off of a solid pixel.


More Tutorials & Demos

For more information and examples of Destructible 2D features I recommend you check the "Destructible 2D/Examples" folder.

Inside this folder you will see many numbered scenes that go step-by-step through all of the features in Destructible 2D.

At the bottom of this scene list you will see game scenario examples that combine multiple features.



Component Documentation

To view documentation about each component in Destructible 2D, simply click the Documentation button at the top right of each component.



Custom Shaders

Destructible 2D comes with custom shaders that modify the opacity of your sprite's Main Tex with the current Alpha Tex. If you want to use your own custom shaders then you will have to make some simple modifications to them, because by default they won't be using the Alpha Tex data required to show the destruction.


Step 1 - Update your shader properties

In your shader's Property { ... } block, you need to add the following properties:

[PerRendererData] _D2dAlpha("D2D Alpha", 2D) = "white" {}
[PerRendererData] _D2dScale("D2D Scale", Vector) = (1,1,0,0)
[PerRendererData] _D2dOffset("D2D Offset", Vector) = (0,0,0,0)
[PerRendererData] _D2dSharpness("D2D Sharpness", Float) = 1.0
[Header(DESTRUCTIBLE 2D)]
[KeywordEnum(Original, Destructible, Combined)] _D2dOutputRgb(" Output RGB", Float) = 0
[KeywordEnum(Destructible, Combined)] _D2dOutputAlpha(" Output Alpha", Float) = 0
[Toggle(_D2D_OUTLINE)] _D2dOutline(" Outline", Float) = 0
_D2dOutlineColor(" Outline Color", Color) = (0,0,0,1)
_D2dOutlineMin(" Outline Min", Float) = 0.0
_D2dOutlineMax(" Outline Max", Float) = 1.0
_D2dOutlinePower(" Outline Power", Float) = 10.0


Step 2 - Update your variable declarations

In your shader's variable section (e.g. where you should have sampler2D _MainTex; or similar), add the following variables:

#pragma shader_feature_local _D2DOUTPUTRGB_ORIGINAL _D2DOUTPUTRGB_DESTRUCTIBLE _D2DOUTPUTRGB_COMBINED
#pragma shader_feature_local _D2DOUTPUTALPHA_DESTRUCTIBLE _D2DOUTPUTALPHA_COMBINED
#pragma shader_feature_local _ _D2D_OUTLINE
#include "Destructible2D.cginc"


Step 3 - Update your fragment or surface function

Inside your fragment function, e.g. fixed4 frag(v2f IN) : SV_Target { ... }

Or inside surface function, e.g. void surf (Input IN, inout SurfaceOutput o) { ... }

You need to modify your final color & alpha like this:

D2dModifyColorAndAlpha(finalColor.rgb, finalColor.a, IN.localPos);

or like this:

D2dModifyColorAndAlpha(o.Albedo, o.Alpha, IN.localPos);
NOTE  You may need to add additional code to send the "localPos" variable (you can see the provided "Default.shader" and "Diffuse.shader" for examples of how this can be done).
NOTE  The variable names like "IN" and "finalColor" may be different in your shader.



What Demos Are Included?

Here's a list of all demo scenes currently included in Destructible 2D.

Destructible Sprite

This shows you how the D2dDestructibleSprite component can be used to turn your normal SpriteRendThis shows you how to make a sprite destructible and damage it. First add the D2dDestructibleSprite component alongside your sprite's SpriteRenderer, then click the Rebuild and Change Material buttons. You can then add the D2dTapToStamp component to your scene, and specify a stamp Shape texture (this uses the alpha channel).rer into a destructible one. The D2dTapToStamp component is then used to stamp holes in the sprite using mouse clicks.

Optimize Sprite

This shows you how the width & height of your destruction data can be halved, giving you a 4x performance boost. This is done by clicking the Optimize button on your D2dDestructibleSprite component. While you can optimize multiple times, keep in mind it reduces the visual quality of the destruction each time. If you optimize too much, then click Rebuild to start again. To maximize performance I recommend you optimize as many times as possible until you reach the best balance between visual quality and performance.

Edge Collider

This shows you how the D2dEdgeCollider component can be added to your D2dDestructibleSprite, giving it an edge collider that automatically updates when you damage the sprite. Keep in mind Edge colliders should only be used for non-moving objects.

Polygon Collider

This shows you how the D2dPolygonCollider component can be added to your D2dDestructibleSprite, giving it a polygon collider that automatically updates when you damage the sprite. Keep in mind polygon colliders should be used for moving objects (e.g. ones with Rigidbody2D).

Splitter

This shows you how the D2dSplitter component can be added to your D2dDestructibleSprite, allowing it to split in half when you cut across the sprite with damage.

Slice

This shows you how the D2dDragToSlice component can be used to slice across destructible sprites.

Transparency

This shows you how the VisualSprite and AlphaSprite settings of the D2dDestructibleSprite component can be different, allowing you to have solid objects that are transparent. Keep in mind this effect requires you to use the Keep Alpha sprite material.

Explosion

This shows you how the D2dTapToSpawn component can be used to spawn a prefab with the D2dExplosion component. The D2dExplosion component allows you to stamp destructible sprites, add physics force to them, and increment their numerical damage value (SgtSprite.Damage).

Impact Fissure

This shows you how the D2dDragToThrow component can be used to spawn a Rigidbody2D prefab with velocity based on the drag vector. This also shows you how the D2dCollisionHandler and D2dImpactFissure components can be used to split the glass at the impact point.

Fixture

This shows you how the D2dFixture component can be added to a child GameObject of your D2dDestructibleSprite. Fixtures can only be attached to one D2dDestructibleSprite, and will automatically follow the one they are on top of when splitting. If the pixel underneath the fixture is destroyed, then the fixture will automatically destroy itself.

Break Off

This shows you how the D2dFixtureGroup component can be connected to a fixture. When all fixtures are detached from the curent D2dDestructibleSprite, the D2dFixtureGroup.OnAllDetached event will be called. This event is set to disable the Rigidbody2D.isKinematic setting, which causes the split sprite parts to break off.

Impact Spawner

This shows you how the D2dDragToThrow component can be used to throw a bomb prefab. The bomb prefab uses the D2dCollisionHandler and D2dImpactSpawner components, which are used to spawn an explosion prefab when the bomb hits another object. The D2dImpactSpawner.OnImpact event is also used to enable the D2dDestroyer component, causing the bomb to get destroyed on impact.

Damage

This shows you how the D2dDamage component can receive damage from rock impacts using the D2dImpactDamage component. The D2dDamage.States list can then be used to swap the SpriteRenderer.sprite setting based on the amount of damage taken.

Tap Fracture

This shows you how the D2dTapToFracture component can be used to fracture destructible objects under the mouse. If you disable the D2dClickToFracture.RequireFracturer setting, then any destructible object in the scene can be destroyed, even if it doesn't have a D2dFracturer.

Lightbulb

This shows you how the D2dFixtureGroup component can be used on the light source to check to see if a sibling power source D2dFixture is connected to the same destructible sprite. If not, D2dFixtureGroup.OnAllDetached is used to enable D2dDestroyer to turn the light off.

Swap

This shows you how the D2dRequirements component can be used to trigger the D2dSwap component when the D2dDestructibleSprite.AlphaRatio goes between 0.0 and 0.9, or when you do more than 10% damage.

Layers

This shows you how after doing 60% damage to a D2dDestructibleSprite the D2dRequirements component can be used to disable the D2dDestructible.Indestructible setting, allowing you to destroy the layer beneath.

Pierce

This shows you how to apply damage to one layer at a time, but you can damage the layer underneath if the pixel you hit above it has been destroyed. This is done by changing the D2dTapToStamp.Hit setting to First.

Cracking Eggs

This shows you how to combine D2dDamage sprite swapping with D2dFracturer splitting after you damage the eggs enough.

Heal

This shows you how to heal a damaged sprite. First you must add the D2dSnapshot component to your scene, and drag and drop your destructible object into its Save setting. Once saved, you can drag and drop this component into the D2dDestructible component's HealSnapshot setting. You can now heal this destructible object by stamping it with the Paint = Heal setting.

Heal Cuts

This shows you how the D2dHealCuts component can be used to automatically heal the current destructible sprite over time.

Camera Shake

This shows you how the D2dCameraShake component can be added to the child GameObject of your camera. The D2dTapToSpawn component is then used to spawn an explosion prefab. This explosion prefab uses the D2dShake component, which adds shake when it spawns.

Follow

This shows you how the D2dFollow component can be used, allowing it to move the camera to follow the egg. Keep n mind D2dFollow cannot be on the same GameObject as D2dCameraShake.

Melt

This shows you how the D2dClickToSpawn component can be used to spawn the Angry Sun prefab. This prefab uses the D2dRepeatStamp component, which constantly stamps the current GameObject position, allowing you to create a melting effect.

Animation

This shows you how you can animate a destructible sprite using the SpriteRenderer.sprite setting like normal. To make it compatible with D2dDestructibleSprite, you must use the Keep Alpha material, and your D2dDestructibleSprite.AlphaSprite must be a combination of the alpha of all of your animation frames. Keep in mind that while modifying your sprite animation you should keep your D2dDestructibleSprite component disabled.

Static Joint

This shows you how to bind a static Rigidbody2D to a destructible object with a HingleJoint2D. This is done using the standard HingeJoint2D setup, but the D2dFixtureJoint component is also added, and a D2dFixture is added on the destructible object to define the point that the joint attaches to. This component automatically updates the HingeJoint2D component's ConnectedRigidBody setting based on the body the specified fixture belongs to.

Fixed Joint

This shows you how to bind two destructible objects together using a single FixedJoint2D. This is done using the D2dFixtureJoint component with two fixtures to define the start and end points associated with the joint. This component will then manage the joint, even if you split either of the destructible objects.

Intermediary Joint

This shows you how to bind two destructible objects together using a non-destructible intermediary object. This is done using two FixedJoint2D and D2dFixtureJoint components associated with each destructible object.

Scorch Marks

This shows you how the Channels setting can be used to paint more than just the alpha/opacity of your destructible sprites. Keep in mind using more channels requires you to use the Default + Color material. Keep in mind Full RGBA should only be used if your D2dDestructibleSprite.Shape is set to a custom sprite. Using a normal color sprite will darken your image.

Filesize Optimization

This shows you how pressing the Clear button on the D2dDestructibleSprite component clears all destructible data, allowing you to save the scene with a very small filesize, which makes your final game builds very small. You can then use the D2dDestructibleSprite.RebuildInGame setting to cause it to be rebuilt in game, and the D2dDestructibleSprite.RebuildOptimizeCount setting to automatically optimize it.

Read Alpha

This shows you how the D2dTapToRead component allows you to read the current destructible sprite color under the current mouse position. This can also be done from C# using the D2dDestructible.TrySampleAlphaAll method.

Pixelated

This shows you how the D2dDestructibleSprite.Pixels setting can be used to give your destructible sprites a pixelated look. The Pixelated Binary setting forces any damaged pixels to either be fully solid, or fully destroyed. Keep in mind you must select the Threshold setting from your D2dDestructibleSprite component's context menu to convert the pixels to binary.

Trigger Overlap

This shows you how the D2dOverlapDamage component can be used with a Trigger collider to detect when a Rigidbody overlaps it. This can increment the D2dDamage.Damage value, and also trigger an action like D2dSpawner.Spawn from the D2dOverlapDamage.OnOverlap event.

Impact Explosion

This shows you how the D2dImpactSpawner component can be used to detect when the current Rigidbody2D hits something. The D2dImpactSpawner.Prefab setting can be used to spawn an explosion on impact, and the OnImpact event can be used to enable the D2dDestroyer component, which automatically destroys the current GameObject.

Cut Opacity

This shows you how the D2dDragToSlice.Color opacity can be lowered, requiring multiple slices to cut through objects. Keep in mind that if you're using optimized sprites, then you should set the D2dDestructibleSprite.OverrideSharpness setting to 1, so you can see the partial damage more clearly.

Paint Multiplier

This shows you how the D2dDestructibleSprite.PaintMultiplier setting can be used to make objects harder or easier to damage.

Slicing Beam

This shows you how the D2dSlicer component can be used to create a laser beam that constantly tries to cut through any object in the way. Select the Handle/Laser GameObject see where the beam starts and ends in the Scene view.

Dynamic Texture

This shows you how the D2dDestructibleSprite.OverrideTexture setting can be used to create a destructible sprite that has a dynamic texture. This is done using a Render Texture asset, and a scene camera to render to it. Keep in mind this requires your layers and camera mask to isolate each rendering scene.

Solid Range

This shows you how the D2dDestructibleSprite component's SolidRange setting can be used to create pixels that are harder or impossible to destroy. When this is set, pixels with an alpha of 255 will be impossible to destroy, and pixels within the range will be increasingly easier to destroy. The optional SolidMask setting can be used to easily define which pixels fall within this range. Keep in mind that you must click Rebuild for the mask changes to update.

Damage Threshold

This shows you how the D2dImpactDamage.Threshold setting can be used to make it harder or easier to damage an object. The D2dFracturer component is then used to fracture the object when it receives enough damage by enabling its Damage setting.

Monitor Pixels

This shows you how to spawn particles each time you destroy a pixel in the current sprite. This is done by enabling the D2dDestructibleSprite component's MonitorPixels setting, and adding the D2dModifiedPixelParticle component. This component detects when a pixel is destroyed, and spawns a new particle there.

Procedural Setup

This shows you how to create a destructible sprite entirely from code. Check out the D2dProceduralSetup.cs code to see how it works.

Painting RGB

This shows you how to cut holes and paint the RGB with alpha blending. First, make sure your D2dDestructibleSprite component's Channels setting is set to FullRGB so that the underlying sprite RGB values get stored in the destructible data. Next, make sure the destructible object is using a + Destructible RGB material, which ensures the Output RGB uses only the Destructible RGB data, and ignores the original sprite RGB. You can now stamp/damage your objects using the Paint = Alpha Blend RGB setting, with a ColorShape set to a normal sprite, and the AlphaShape set to the hole shape. Keep in mind that when using this technique, optimizing your sprites will result in reduced RGB quality.

Asteroid Blaster

This shows you how to combine various features to make a spaceship you can fly around in zero gravity. This spaceship has guns that fire in an alternating pattern whose bullets expode when impacting the asteroids. The asteroids are given red scorch marks and given enough damage they can split into smaller pieces.

Asteroid Laser

This shows you how to combine various features to make a spaceship you can fly around in zero gravity. This spaceship has guns that fire in an alternating pattern whose bullets expode when impacting the asteroids. The asteroids are given red scorch marks and given enough damage they can split into smaller pieces.

Crash Damage

This shows you how to make a top down car with simple controls. When the car hits an object an explosion is spawned, and this explosion can damage the shape of the car, which changes the way it handles.

Exploder

This shows you how the D2dTapToFracture component's Prefab setting can be combined with explosions and particle effects to look more interesting.

Glass Panels

This shows you how to make a scene with many glass panels that can be smashed using finger drags.

Jumping Spaceship

This shows you how to make a spaceship you can control, and instead of shooting, it causes the spaceship to jump forward a distance. When a jump is performed, all destructible objects between the previous and current position are sliced in half.

Scorch

This shows you how to make a forest scene with finger slicing that also add black scorch marks to the trees.

Shooting Gallery

This shows you how to make a shooting gallery where you can damage the targets when they're facing the camera.

Snake

This shows you how to make a snake that can dig in all directions and still have normal physics including gravity. This is done by adjusting the Rigidbody2D drag and acceleration based on the solid surfaces surrounding the snake head.

Swinging Weight

This shows you how to make a swinging weight that you can slice up. This uses a combination of HingeJoint2D and D2dFixtureJoint components.

Trees

This shows you how to make a forest scene and slice to cut the trees down or stop the bees from animating.







Assets

Here's a list of all my other assets, please check them out!

You can also view this list on my Asset Store page.

Lean Touch

Lean Touch

Rapidly develop your game with consistent input across desktop & mobile using Lean Touch. This lightweight asset comes with many modular components, allowing you to customize them to your exact project needs!


Lean Touch+

Lean Touch+

Lean Touch+ is an extension to the popular Lean Touch asset, adding many more example scenes.


Lean Localization

Lean Localization

Lean Localization is a localization library that's designed to be as simple to use as possible for both designers, and programmers.


Lean Pool

Lean Pool

Quickly optimize the performance of your games using Lean Pool. Within minutes you can use this lightweight asset to preload, recycle, and limit the spawning of your prefabs.


Lean Transition

Lean Transition

Quickly polish your games using Lean Transition. This asset allows you to easily tween or animate almost anything in your game, making it transition smoothly.


Lean GUI

Lean GUI

Lean GUI is a colllection of components that extend Unity's GUI system, allowing you to rapidly enhance the user experience (UX) of your game's UI.


Lean GUI Shapes

Lean GUI Shapes

Lean GUI Shapes allows you to quickly add lines, rounded boxes, polygons, and much more to your GUI!


Lean Texture

Lean Texture

Lean Texture allows you quickly modify textures in your project with a range of filters, pack them together into channels, and much more!


Lean Texture+

Lean Texture+

Lean Texture+ is an extension to Lean Texture, adding many new types of texture modification tools!


CW Spaceships - Build & Destroy

Spaceships - Build & Destroy

Build your dream spaceship, and then have fun destroying it!


Modular Backgrounds

Modular Backgrounds

Unlock a universe of visual possibilities with Modular Backgrounds. Simply drag and drop these graphics into the background of your scenes.


Paint in 3D

Paint in 3D

Paint all your objects using Paint in 3D - both in game, and in editor. All features are optimized with GPU accelerated texture painting, so you can enjoy consistent performance, even if you paint your objects one million times!


Paint in 2D

Paint in 2D

Paint all your sprites with Paint in 2D. With incredible performance on mobile, WebGL, and much more!


Paint in Editor

Paint in Editor

Paint in Editor unlocks the ability to paint objects in your scene - great for making small tweaks, or even creating entirely new texture sets!


FLOW

FLOW

FLOW allows you to add large scale interactive fluids to your scene - all highly optimized using GPU acceleration.


Destructible 2D

Destructible 2D

Unlock the full potential of your 2D games using Destructible 2D, this asset allows you to quickly convert all your boring solid sprites into fully destructible ones!


Space Graphics Toolkit

Space Graphics Toolkit

Quickly make the space scene of your dreams using Space Graphics Toolkit. This huge collection of space effects can be customized and combined in any way you like, allowing you to quickly make realistic or fantasy worlds. Each feature has been heavily optimized to run on almost any device and platform.


Space Graphics Planets

Space Graphics Planets

Enhance your space scenes using this large pack of high detail volumetric planets. These planets are finished using the powerful planet features from Space Graphics Toolkit (not required).


Volumetric Audio

Volumetric Audio

Unity sounds only emanate from a single point source. This is great for explosions and footsteps, but quite often you need something more advanced. Volumetric Audio is an easy to use package that allows you to define boxes, spheres, capsules, paths, or meshes that sounds can emanate from.






Versions

4.2.0

Updated CW/Common code to latest version.



4.1.1

Moved main build to Unity 2021.3.0f1.
Updated shaders to latest version.



4.1.0

Updated shaders for URP and HDRP.
Removed D2dShapeBuilder.
Split all Shape texture settings into ColorShape and AlphaShape settings.
Fixed D2dDestroyer component's Shrink setting.
Added Painting RGB setting.
Added Alpha Blend RGB paint mode.
Added ExcludeShape setting to D2dExplosion component.
Added Exclude setting to D2dTapToStamp component.
Added Exclude setting to D2dDragToStamp component.
Added Exclude setting to D2dDragToSlice component.
Added Exclude setting to D2dSlicer component.
Added Exclude setting to D2dRepeatStamp component.
Added ShrinkPivot setting to D2dDestroyer component.
Added D2dExplosion.DamageFalloff setting.



4.0.5

Moved main build to Unity 2020.3.0f1.
Fixed scenario where a sprite's Halve or Optimize operation could throw an error.
Fixed scenario where sprites would have incorrect destruction data on the Metal graphics API.



4.0.4

Merged "Default + Color" shader into "Default" shader.
Merged "Keep Alpha + Color" shader into "Default" shader.
Merged "Keep Alpha" shader into "Default" shader.
Merged "Outline" shader into "Default" shader.
Simplified custom shader integration.
Updated URP shaders.



4.0.3

D2dTimer no longer updates outside of play mode.
Fixed D2dDestructibleRenderer rebuild when using a skybox in the Lighting Settings.



4.0.2

Added D2dTimer component.
Fixed D2dEdgeCollider inspector changes not applying instantly.
Fixed D2dEdgeCollider inspector warning.
Fixed D2PolygonCollider inspector changes not applying instantly.
Fixed D2PolygonCollider inspector warning.
Added D2PolygonCollider.Density setting.
Added D2PolygonCollider.UsedByEffector setting.
Added D2PolygonCollider.UsedByComposite setting.
Added D2dEdgeCollider.Density setting.
Added D2dEdgeCollider.UsedByEffector setting.
Added D2dEdgeCollider.UsedByComposite setting.
Fixed D2dEdgeCollider potential gaps.
Improved D2dEdgeCollider collider quality.



4.0.1

Updated URP packages.
Removed global shader keywords.



4.0.0

NOTE  This is a massive update. To update you must first back up your project, delete the root Destructible2D folder, then install the new version.

Changed folder structure to be inside Plugins/CW/Destructible2D.
Updated inspector code to support third party assets that implement nested inspectors.



3.1.4

Fixed example scene errors when using certain keyboard layouts.
Added support for URP 2021.2.
Added D2dDestructibleRenderer.RebuildLayer setting.
Added D2dDestructibleRenderer.PixelsPerUnit setting.



3.1.3

Fixed transform gizmos not appearing in Unity 2021.2.



3.1.2

Added support for SpriteShape destructible objects.
Added support for URP lit shader.



3.1.1

Fixed mouse hover bug with input code.
Fixed rock throwing prefab playing impact sound immediately.
Improved Glass Panels demo scene.



3.1.0

NOTE  This update changes a lot of features. Back up your project before updating!

Moved main build to Unity 2019.4.12f1.
Rewrote input code to support fingers, mouse, and keyboard.
Redesigned all demo scenes to have a simpler structure.
Added Procedural Setup demo scene.
Added ShapeBuilder tool.
Added D2dClickToStamp.Interval setting.
Added D2dClickToStamp.ScaleMin / Max settings.
Added D2dClickToStamp.TwistMin / Max settings.
Added D2dClickToStamp.Camera setting.
Added D2dClickToSpawn.IndicatorPrefab setting.
Added D2dClickToSpawn.TwistMin / Max settings.
Added D2dClickToRead.OnColor event.
Added D2dClickToRead.OnDestructibleColor event.
Added D2dClickToRead.OnNothing event.
Renamed D2dClickToStamp to D2dTapToStamp.
Renamed D2dClickToSpawn to D2dTapToSpawn.
Renamed D2dClickToFracture to D2dTapToFracture.
Renamed D2dClickToRead to D2dTapToRead.
Split sprites will now retain the original parent.



3.0.10

Added D2dDestructibleSprite.MonitorPixels setting.
Added D2dDestructibleSprite.OnModifiedPixels event.
Added D2dDestructibleSprite.OnGlobalModifiedPixels event.
Added Monitor Pixels demo scene.



3.0.9

Moved main build to Unity 2018.4.13f1.
Added support for the new input system.
Added Fixed Joint demo scene.
Added Damage Threshold demo scene.
Added Intermediary Joint demo scene.
Added D2dFixtureJoint component.
Added D2dDamage.Threshold setting.
Updated demo scenes to use touch controls.
Fixed UI buttons not working in example scenes.
Fixed D2dPolygonCollider collider generation in some scenarios.
Changed D2D shader properties to avoid SRP clashes.
Rewrote D2dEdgeCollider.
Renamed D2dEdgeCollider.Straighten to Optimize.



3.0.8

Moved main build to Unity 2018.4.0f1.
Updated documentation.
Added asmdef.
Added Snake demo scene.



3.0.7

Added D2dDestructibleSprite.SolidRange setting.
Added D2dDestructibleSprite.SolidRangeMask setting.
Added Solid Range demo scene.
Fixed error when adding D2dDestructibleSprite with no sprite.
Fixed component documentation URL.



3.0.6

Improved D2dSplitForce behavior.
Improved D2dRetainVelocity behavior.
Added D2dSplitForce.ForcePerSolidPixel setting.
Added D2dSplitForce.ApplyTo setting.
Added D2dClickToSpawn.Interval setting.
Added SubtractInvRGB paint mode.
Added Explosion Interval demo scene.
Added Fracture Click demo scene.



3.0.5

Improved Slicing Beam demo scene.
Added Impact Explosion demo scene.
Added Asteroid Laser demo scene.
Exposed D2dSlicer.LocalStart setting.
Exposed D2dSlicer.LocalEnd setting.



3.0.4

Fixed color value being ignored when performing a Cut.
Fixed D2dDragToSlice.Color value being hidden.
Added the Cut Opacity demo scene.
Added the Paint Multiplier demo scene.
Added the Slicing Beam demo scene.
Added the Dynamic Texture demo scene.



3.0.3

Added "20 Pierce" demo scene.
Added D2dSplitter.HealThreshold setting.



3.0.2

Improved all demo scenes.
Redesigned documentation.
Re-organized example files.
Added Fracture Force demo scene.



3.0.1

Improved sprite atlas support.
Added Jumping Spaceship demo scene.
Added D2dDestructible.CropSprite setting.
Replaced D2dDestructible.AlphaRect setting with AlphaOffset + AlphaScale settings.
Removed D2dDestructible.VisualSprite setting.
Renamed D2dDestructible.AlphaSprite to Shape.
Renamed D2dDestructible component to D2dDestructibleSprite.



3.0.0

Added 26 new tutorial scenes.
Rewritten D2dDestructible to use SpriteRenderer directly.
Simplified D2dDestructible settings.
Added multiple channel support to D2dDestructible.
Improved D2dPolygonCollider accuracy.
Improved D2dPolygonCollider performance.
Simplified D2dRequirements.
Moved splitting code to D2dSplitter.
Added D2dCollisionHandler.
Added D2dImpactFissure.







Components

D2dBlur

This class allows you to blur a D2dDestructible's alphaData.



D2dCache

This class handles various ways to cache values to improve performance.


static void
Clear

Call this before using any of the returned arrays.



static T[]
ToArray
List<T> list

This will return a cached array copy of the specified list, and can be called multiple times with the same list length.




D2dCalculateMass

This component automatically sets the Rigidbody2D.mass based on the D2dDestructible.AlphaCount.


float
MassPerSolidPixel

The amount of mass added to the Rigidbody2D by each solid pixel in the attached D2dDestructible.



bool
FactorInSharpness

Automatically multiply the mass by the D2dDestructible.AlphaSharpness value to account for optimizations?




D2dCollider

This is the base class for all collider types.


float
Density

This allows you to control the density setting on each generated collider.



PhysicsMaterial2D
Material

This allows you to set the material setting on each generated collider.



bool
IsTrigger

This allows you to set the isTrigger setting on each generated collider.



bool
UsedByEffector

This allows you to set the usedByEffector setting on each generated collider.



bool
UsedByComposite

This allows you to set the usedByComposite setting on each generated collider.



void
SetDensity
float value

This allows you to set the Density value without causing Refresh to be called.



void
SetMaterial
PhysicsMaterial2D value

This allows you to set the Material value without causing Refresh to be called.



void
SetIsTrigger
bool value

This allows you to set the IsTrigger value without causing Refresh to be called.



void
SetUsedByEffector
bool value

This allows you to set the UsedByEffector value without causing Refresh to be called.



void
SetUsedByComposite
bool value

This allows you to set the UsedByComposite value without causing Refresh to be called.




D2dCollisionHandler

This component listens for collision events and sends them to other components via the OnCollision event.


event System.Action<Collision2D>
OnCollision

This is invoked once for each collision.



event System.Action<Collider2D>
OnOverlap

This is invoked once for each collision.




D2dContext

This class is used to add context menu options to various components for integration with Destructible2D.



D2dDamage

This component stores numerical damage for the current GameObject. This damage can then be used to swap the sprite to show different damage states.


event System.Action
OnDamageChanged

This is invoked when the damage field is modified.



float
Damage

This tells you how much numerical damage this sprite has taken. This is automatically increased by nearby explosions and such.



float
Threshold

The incoming damage must be at least this value to change this component's damage value.



float
Multiplier

This allows you to reduce or increase the rate at which damage changes.



List<State>
States

This allows you to modify the damage value directly without invoking NotifyDamageChanged/OnDamageChanged.



void
Add
float value

This method allows you to add to the damage value.

NOTE  The Multiplier and Threshold values will be taken into account.


void
InvokeDamageChanged

Call this if you manually modified the damage value.




D2dDestroyer

This component will automatically destroy the current GameObject after a certain amount of time.


float
Life

This will decrease by 1 every second, and the current GameObject will be destroyed when it reaches 0.



GameObject
Target

If you want a different GameObject to be destroyed then specify it here.



bool
Fade

If you enable this then the attached SpriteRenderer.color will be faded out before destruction.



float
FadeDuration

The amount of seconds the fade out effect spans.



bool
Shrink

If you enable this then the Transform.localScale value will shrink to 0 before destruction.



float
ShrinkDuration

The amount of seconds the shrink effect spans.



Rigidbody2D
ShrinkPivot

If this object has a Rigidbody then you may want the shrink to work relative to the physics pivot point.



bool
RandomizeOnEnable

Should these settings get randomized when this component is enabled?



float
LifeMin

The minimum randomized Life value.



float
LifeMax

The minimum randomized Life value.




D2dDestructible

This is the base class for all destructible objects.


event System.Action
OnRebuilt

This is invoked when the whole destruction state changes.



event System.Action<D2dRect>
OnModified

This is invoked when a subset of the destruction state changes.



event System.Action
OnSplitStart

This is invoked before the destructible is about to be split into separate parts.



event System.Action<List<D2dDestructible>, SplitMode>
OnSplitEnd

This is invoked after the destructible is split into separate parts, with a list of all the parts.

Last Element = This Destructible.



event System.Action<List<int>>
OnModifiedPixels

This event is invoked after the destructible is modified, and contains indices of all pixels that crossed the 128 opacity boundary.

NOTE  This requires the MonitorPixels setting to be enabled.


static event System.Action<D2dDestructible, List<int>>
OnGlobalModifiedPixels

This event works like OnModifiedPixels, but is statically invoked with a reference to the D2dDestructible whose pixels were modified.



D2dSnapshot
HealSnapshot

If you want to be able to heal this destructible sprite, then set a snapshot of the healed state here.



float
OverrideSharpness

This allows you to manually control the sharpness of the alpha gradient (0 = AlphaSharpness) (+ = OverrideSharpness) (- = AlphaSharpness * -OverrideSharpness).



float
PaintMultiplier

This allows you to control how easily this object can be painted.

1.0 = Default.

2.0 = Twice as much damage.

0.5 = Half as much damage.



int
SolidRange

This allows you to make it so some pixels are harder to destroy than others, based on their alpha value (0 .. 255).

0 = Every pixel is equally easy to destroy.

1 = Values between 0 and 254 receive normal damage, but 255 receives no damage.

10 = Values between 0 and 245 receive normal damage, but 246 receives 90% damage, 247 receives 80%, etc.



PixelsType
Pixels

This allows you to control how the alphaTex pixels are handled.



bool
Indestructible

This keeps your destructible sprite active, but prevents it from taking visual damage.



bool
MonitorPixels

If you enable this then all destroyed or healed pixel will be sent to the OnModifiedPixels event, which contains a list of the AlphaData array indices of the pixels.



bool
Ready

If this destructible has been generated correctly, this will be set.



Color32[]
AlphaData

This stores the current visual damage state of the destructible.



int
AlphaWidth

This stores the current width of the visual damage data.



int
AlphaHeight

This stores the current height of the visual damage data.



int
AlphaCount

This tells you how many pixels in the alphaData/alphaTex are solid (above 127).



int
AlphaCountRaw

This allows you to read the alphaCount value directly without causing it to be recalculated.



int
OriginalAlphaCount

This tells you the original AlphaCount value, if it was set.



int
OriginalAlphaCountRaw

This allows you to read the originalAlphaCount value directly without causing it to be recalculated.



float
AlphaRatio

This will return the ratio of remaining alpha (0 = no pixels remain, 1 = all pixels remain).



Vector2
AlphaOffset

This tells you offset of the alpha data in local space.



Vector2
AlphaScale

This tells you scale of the alpha data in local space.



float
AlphaSharpness

Each time you optimize/halve this sprite, this value will double.



Texture2D
AlphaTex

This stores the current texture of the visual destruction state.



D2dRect
AlphaModified

This stores the pixel region of the alphaData that hasn't been copied to the texture yet. These pixels will be copied in LateUpdate.



bool
CanHeal

This returns true if the healSnapshot is in a valid state for healing this destructible sprite.



TextureFormat
FinalFormat

This tells you the format the alphaTex should have based on your settings.



Matrix4x4
LocalToAlphaMatrix

This matrix allows you to transform a point from local space to alpha space.

NOTE  Alpha space is where 0,0 is the bottom left (first) pixel, and 1,1 is the top right (last) pixel.
NOTE  Depending on your AlphaWidth and AlphaHeight, the center of the pixels will be offset half a pixel in from each corner.


Matrix4x4
WorldToAlphaMatrix

This matrix allows you to transform a point from world space to alpha space.

NOTE  Alpha space is where 0,0 is the bottom left (first) pixel, and 1,1 is the top right (last) pixel.
NOTE  Depending on your AlphaWidth and AlphaHeight, the center of the pixels will be offset half a pixel in from each corner.


Matrix4x4
AlphaToLocalMatrix

This matrix allows you to transform a point from alpha space to local space.

NOTE  Alpha space is where 0,0 is the bottom left (first) pixel, and 1,1 is the top right (last) pixel.
NOTE  Depending on your AlphaWidth and AlphaHeight, the center of the pixels will be offset half a pixel in from each corner.


Matrix4x4
PixelToLocalMatrix

This matrix allows you to transform a point from pixel space to local space.

NOTE  Alpha space is where 0,0 is the bottom left (first) pixel, and AlphaWidth-1,AlphaHeight-1 is the top right (last) pixel.


Matrix4x4
PixelToWorldMatrix

This matrix allows you to transform a point from pixel space to world space.

NOTE  Alpha space is where 0,0 is the bottom left (first) pixel, and AlphaWidth-1,AlphaHeight-1 is the top right (last) pixel.


void
Trim

This allows you to cut and smooth the edges of your destructible. This is automatically done in many cases, but when making a new destructible it isn't, so you can control how the edges look yourself.



void
Blur

This allows you to blur the pixels in your current destruction state. This can be used for certain effects, or to smooth the edges.



void
Threshold

This allows you to threshold all the pixels in your current destruction state. This will set them to full opacity if they are above half opacity, otherwise they will be set to zero opacity.



void
Halve

This allows you to halve the width & height of your destruction pixels.



void
Optimize

This allows you to reduce the amount of pixels used to store the destruction state of your sprite. Each time you do this you will increase performance 4x, but there will be some visual quality loss.



void
Clear

This allows you to clear all destruction data from the sprite, reverting it to a normal non-destructible sprite. NOTE: You will need to manually revert the material to completely revert the sprite state.



void
NotifyRebuilt

Call this if you manually modified the whole destruction state.



Color32
SampleAlphaLocal
Vector3 localPosition

This method allows you to sample the AlphaData at the specified local space position.



Color32
SampleAlphaWorld
Vector3 worldPosition

This method allows you to sample the AlphaData at the specified world space position.



Color32
SampleAlpha
Vector2 uv

This method allows you to sample the AlphaData at the specified UV.



static bool
TrySampleThrough
Vector3 worldPosition, ref D2dDestructible hitDestructible, byte threshold = 127

This method allows you to find the destructible object below the specified world space position as long as the sampled alpha value is above the threshold value.

This allows you to go through holes in objects that are on top.



bool
IsAbove
D2dDestructible other

This method allows you to see if the current destructible object is being drawn above the specified object.



static Color32
TrySampleAlphaAll
Vector3 worldPosition

This method allows you to sample the AlphaData of the top most object at the specified world space position.



static bool
TrySampleAlphaAll
Vector3 worldPosition, ref D2dDestructible hitDestructible, ref Color32 hitAlpha

This method allows you to sample the AlphaData of the top most object at the specified world space position and also find out which destructible object it came from.




D2dDestructibleRenderer D2dDestructible

This component allows you to turn any Renderer into a destructible one. The destruction is stored using a copy of the alpha/opacity of the original renderer, and you have many options to reduce/optimize the amount of destruction pixels used, as well as cut holes in the data.


List<Material>
OriginalMaterials

To rebuild this destructible object its original (non-destructible) material is used.



ChannelType
Channels

This allows you to set which color channels you want the destructible texture to use.



ChannelType
ChannelsRaw

This allows you to set channels without triggering a rebuild.



int
RebuildLayer

When this destructible object is rebuilt, it will be rendered using a temporary camera with everything set to this layer.

NOTE  There must be no visible objects on this layer, otherwise this component will not function properly.


bool
RebuildInGame

To save scene file size you can Clear your destructible, and allow it to Rebuilt on Start.



int
RebuildOptimizeCount

This allows you to set how many times the rebuilt alpha data will be optimized when rebuilt on Start.



int
PixelsPerUnit

This allows you to set how many destructible pixels are generated per unit in local space. For example, if your object is 10 units in width + height, and this value is set to 3, then this destructible object will have a resolution of 30x30 pixels.



Renderer
CachedRenderer

This gives you the attached Renderer.



bool
InvalidMaterial

This tells you if the attached Renderer's sharedMaterial uses the default Unity sprite material, which isn't compatible with destructible objects.



void
ChangeMaterial

If you're using the normal Unity sprite material, then this swaps it to the Destructible 2D supported equivalent.



void
Rebuild

This allows you to rebuild the destruction state using the current sprite settings.



void
RevertMaterials

This method allows you to revert the associated renderer's materials to the original values before you made it destructible.



void
Rebuild
int optimizeCount

This allows you to rebuild the destruction state using the specified sprites.




D2dDestructibleSprite D2dDestructible

This component allows you to turn a normal SpriteRenderer into a destructible one. The destruction is stored using a copy of the alpha/opacity of the original sprite, and you have many options to reduce/optimize the amount of destruction pixels used, as well as cut holes in the data.


Sprite
Shape

This allows you to set the shape of the destructible sprite.\nNOTE: This should match the settings of your visual sprite.



Texture
OverrideTexture

This allows you to override the sprite texture with any Texture.



Sprite
SolidRangeMask

This mask can be used to more easily control which pixel alpha values fall into the SolidRange.

0 Alpha = This pixel will receive normal damage.

255 Alpha = This pixel will receive no damage.



ChannelType
Channels

This allows you to set which color channels you want the destructible texture to use.



ChannelType
ChannelsRaw

This allows you to set channels without triggering a rebuild.



bool
CropSprite

Enable this if you want the attached SpriteRenderer.sprite to automatically crop to the AlphaTex boundary, reducing the fill rate requirements for large splitting sprites.



bool
RebuildInGame

To save scene file size you can Clear your destructible, and allow it to Rebuilt on Start.



int
RebuildOptimizeCount

This allows you to set how many times the rebuilt alpha data will be optimized when rebuilt on Start.



SpriteRenderer
CachedSpriteRenderer

This gives you the attached SpriteRenderer.



bool
InvalidMaterial

This tells you if the attached SpriteRenderer's sharedMaterial uses the default Unity sprite material, which isn't compatible with destructible objects.



void
ChangeMaterial

If you're using the normal Unity sprite material, then this swaps it to the Destructible 2D supported equivalent.



void
Rebuild

This allows you to rebuild the destruction state using the current sprite settings.



void
Rebuild
int optimizeCount

This allows you to rebuild the destruction state using the specified sprites.




D2dDestructibleSpriteShape

This class adds context menu options to the SpriteShapeRenderer component for integration with Destructible2D.



D2dDistanceField

This component allows you to calculate a distance field from an array of pixels.



D2dEdgeCollider D2dCollider

This component allows you to generate edge colliders for a destructible sprite. Edge colliders should only be used for non-moving objects.


float
EdgeRadius

This allows you to set the edgeRadius setting on each generated collider.



CellSizes
CellSize

This allows you to change the pixel width & height of each collider cell to improve performance. The pixel size you choose should be in relation to the typical size of destruction in your scene.



float
Optimize

This allows you to control how easily the edges can merge together. A higher value gives better performance, but less accurate colliders.



void
SetEdgeRadius
float value

This allows you to set the EdgeRadius value without causing Refresh to be called.



void
SetCellSize
CellSizes value

This allows you to set the CellSize value without causing Rebuild to be called.



void
SetOptimize
float value

This allows you to set the Optimize value without causing Rebuild to be called.




D2dEdgeSquares

This allows you to calculate the edges of a specific alphaData area.



D2dFixture

This component can be attached to a child GameObject of a D2dDestructible, and when split this will automatically follow the correct split part. If the pixel underneath this fixture is destroyed then this fixture will also be destroyed.


Vector3
Offset

This allows you to set the local offset of the fixture point.




D2dFixtureGroup

This component allows you to perform an action when all the specified fixtures all become detached from the current GameObject.


bool
AutoDestroy

Automatically destroy this component if all fixtures are removed?



List<D2dFixture>
Fixtures

This allows you to set the fixtures that will be tracked by this group.



UnityEvent
OnAllDetached

This event will be invoked when all entries in the Fixtures list are destroyed.




D2dFixtureJoint

This component allows you to create a joint between the current Rigidbody2D, and a separate destructible Rigidbody2D. The joint will automatically be broken when the ConnectedFixture is detached, or the Fixture if the current Rigidbody is also destructible.


Joint2D
Joint

This is the joint whose ConnectedBody will be updated based on the ConnectedFixture, and will be destroyed when either of the fixtures detaches.



D2dFixture
Fixture

This is the fixture associated with the joint.



D2dFixture
ConnectedFixture

This is the fixture associated with the object the current joint attaches to.



bool
AutoDestroyJoint

Automatically destroy this joint if detached?



bool
AutoDestroyThis

Automatically destroy this component if detached?



void
UpdateFixtures

This method can be used to immediately update this component.




D2dFracturer

This component slices a shape at the collision impact point when another object hits this destructible object.


bool
Damage

If you enable this then this destructible sprite will automatically be fractured when the attached D2dDamage.Damage value is high enough.



float
DamageRequired

The D2dDamage.Damage value must be at or above this value.



float
DamageMultiplier

After a successful fracture, the damageRequired value will be multiplied by this, allowing for multiple fractures.



float
PointsPerSolidPixel

This lets you set how many fracture points there can be based on the amount of solid pixels.



int
MaxPoints

This lets you limit how many points the fracture can use.



bool
FactorInSharpness

Automatically multiply the points by the D2dDestructible.AlphaSharpness value to account for optimizations?



bool
SplitAfterFracture

Fracturing can cause pixel islands to appear, should a split be triggered on each fractured part to check for these?



int
SplitFeather

This allows you to set the Feather value used when splitting.



int
SplitHealThreshold

This allows you to set the HealThreshold value used when splitting.



static bool
TryFracture
D2dDestructible destructible, int pointCount, bool splitAfterFracture, int splitFeather, int splitHealThreshold

This method allows you to manually try and fracture the specified D2dDestructible.




D2dHalve

This class allows you to halve the width & height of the pixels in an alphaData.



D2dImpactDamage

This component increments the attached D2dDamage.Damage value when other objects hit this.


LayerMask
Mask

The collision layers you want to listen to.



float
Threshold

The impact force required.



float
Scale

This allows you to control the amount of damage inflicted relative to the force of the impact.



float
Delay

This allows you to control the minimum amount of time between fissure creation in seconds.



UnityEvent
OnImpact

This gets called when the prefab was spawned.




D2dImpactFissure

This component slices a shape at the collision impact point when another object hits this destructible object.


LayerMask
Mask

The collision layers you want to listen to.



float
Threshold

The impact force required.



float
Delay

This allows you to control the minimum amount of time between fissure creation in seconds.



GameObject
Prefab

If you want a prefab to spawn at the impact point, set it here.



D2dDestructible.PaintType
Paint

The paint type.



D2dShape
StampShape

The shape of the stamp.



Texture2D
ColorShape

The shape of the stamp when it modifies destructible RGB data.



Texture2D
AlphaShape

The shape of the stamp when it modifies destructible alpha data.



Color
Color

The stamp shape will be multiplied by this. Solid White = No Change



float
Thickness

This allows you to control the width of the fissure.



float
Depth

This allows you to control how deep into the impact point the fissure will go.



float
Offset

This allows you to move the start point of the fissure back a bit.



bool
UseSurfaceNormal

Use the surface normal instead of the impact velocity normal?



UnityEvent
OnImpact

This gets called when the prefab was spawned.




D2dImpactSpawner

This component spawns a prefab at the impact point when an object hits the current object.


LayerMask
Mask

The collision layers you want to listen to.



float
Threshold

The impact force required.



float
Delay

This allows you to control the minimum amount of time between fissure creation in seconds.



GameObject
Prefab

If you want a prefab to spawn at the impact point, set it here.



float
Offset

This allows you to move the start point of the fissure back a bit.



RotationType
RotateTo

How should the spawned prefab be rotated?



UnityEvent
OnImpact

This gets called when the prefab was spawned.




D2dLinkedBehaviour<T>

This class allows for quick registering and unregistering of class instances that can then be quickly looped through.



D2dOverlapDamage

This component increments the attached D2dDamage.Damage value when this object overlaps a trigger.


LayerMask
Mask

The collision layers you want to listen to.



float
DamagePerSecond

This allows you to control the amount of damage inflicted per second of overlap.



float
Delay

This allows you to control the minimum amount of time between damage in seconds.



UnityEvent
OnOverlap

This gets called when the prefab was spawned.




D2dPolygonCollider D2dCollider

This component allows you to generate polygon colliders for a destructible sprite. Polygon colliders should be used for moving objects.


CellSizes
CellSize

This allows you to change the pixel width & height of each collider cell to improve performance. The pixel size you choose should be in relation to the typical size of destruction in your scene.



float
Straighten

This allows you to control how easily the edges can merge together. A higher value gives better performance, but less accurate colliders.



void
SetCellSize
CellSizes value

This allows you to set the CellSize value without causing Rebuild to be called.



void
SetStraighten
float value

This allows you to set the Straighten value without causing Rebuild to be called.




D2dPolygonSquares

This allows you to calculate the polygons of a specific alphaData area.



D2dRect

This struct stores information for an int based 2D rectangle.



D2dRequirements

This component allows you to trigger an event when the attached D2dDestructible or D2dDamage component settings meet the specified threshold.


bool
Met

Has the specified Criteria been met?

NOTE  Manually changing this will not invoke any events.


bool
Damage

If you enable this then the D2dDamage.Damage value will be checked.



float
DamageMin

The D2dDamage.Damage value must be at or above this value.



float
DamageMax

The D2dDamage.Damage value must be below this value.



bool
AlphaCount

If you enable this then the D2dDestructible.AlphaCount value will be checked.



float
AlphaCountMin

The D2dDestructible.AlphaCount value must be at or above this value.



float
AlphaCountMax

The D2dDestructible.AlphaCount value must be below this value.



bool
AlphaRatio

If you enable this then the D2dDestructible.AlphaRatio value will be checked.



float
AlphaRatioMin

The D2dDestructible.AlphaRatio value must be at or above this value.



float
AlphaRatioMax

The D2dDestructible.AlphaRatio value must be below this value.



UnityEvent
OnRequirementsMet

When all requirements have been met, this method will be invoked.



void
UpdateMet

This will immediately update the requirements.




D2dRetainVelocity

This component allows a sprite to maintain its velocity after being split.



D2dShape

This struct stores the stamp shape color and alpha pair.



D2dSlice

This class allows you to slice every destructible object in the scene, or just calculate the slice matrix for later use.


static Matrix4x4
CalculateMatrix
Vector2 startPos, Vector2 endPos, float thickness

This will return the transformation matrix used to convert between world space and slice sprite space.




D2dSnapshot

This class stores a snapshot of a D2dSprite's current state of destruction.


D2dSnapshotData
Data

This gives you the snapshot data in a normal class.



D2dSnapshotData
DataRaw

This allows you to get the data value without causing it to automatically initialize.



void
Clear

This will clear all snapshot data.




D2dSnapshotData

This class stores a snapshot of a D2dDestructible at one point in time so it can later be reverted to, or gradually faded to.


static D2dSnapshotData
Create
D2dDestructible destructible

This will return a snapshot of the specified D2dDestructible.



void
Clear

This will clear all snapshot data.



void
Save
D2dDestructible destructible

This will store the specified D2dDestructible's state to this snapshot.



void
Load
D2dDestructible destructible

This will copy this snapshot to the specified D2dDestructible.




D2dSpawner

This component allows you to spawn the specified prefab by manually calling the Spawn method.


float
Delay

This allows you to control the minimum amount of time between prefab creation in seconds.



float
Interval

This allows you to control the amount of seconds between spawns.

-1 = Spawn once only.



int
Remaining

The amount of extra times this component can spawn.

-1 = Unlimited.



float
Spread

This allows you to control how far the spawned object can randomly rotate from its initial rotation.



Vector2
Forward

This allows you to specify which direction is forward for your sprite when applying the speed.



float
SpeedMin

This allows you to set the minimum random speed applied to the spawned object if it has a Rigidbody2D.



float
SpeedMax

This allows you to set the maximum random speed applied to the spawned object if it has a Rigidbody2D.



GameObject
Prefab

If you want a prefab to spawn at the impact point, set it here.




D2dSplitter

This component allows you to split the attached destructible sprite into multiple pieces if you slice it in half, or otherwise damage it in a way that leaves multiple separated pixel 'islands'.


int
Feather

If your destructible sprite has soft edges then you should increase the feather distance to the pixel thickness of your soft edges.



int
HealThreshold

Split pieces cannot be healed by default, this is because healing split pieces can often lead to unexpected behavior and worse performance. If you really want to allow healing of split pieces, then this setting allows you to control how many pixels must remain in the split piece for it to be eligible for healing.

-1 = Split pieces cannot be healed.

0 = All split pieces can be healed.

10 = Split pieces must have more than 10 AlphaCount to be healed.




D2dStamp

This class allows you to stamp every destructible object in the scene, or just calculate the stamp matrix for later use.


static Matrix4x4
CalculateMatrix
Vector2 position, Vector2 size, float angle

This will return the transformation matrix used to convert between world space and stamp sprite space.




D2dTrim

This class allows you to trim the edges of a destructible sprite's alphaData.



Index

Thank you for using Destructible 2D ❤️

How do I upgrade?

Making a Destructible Sprite

Adding Colliders

Stamp/Paint Modes

Optimizing Performance

Splitting/Slicing Parts Off

Using Semi-Transparent Sprites

Collision Damage

Sprite Shape

URP Lit

Attaching GameObjects to Splittable Destructible Sprites

More Tutorials & Demos

Component Documentation

Custom Shaders

What Demos Are Included?



Assets

Lean Touch

Lean Touch+

Lean Localization

Lean Pool

Lean Transition

Lean GUI

Lean GUI Shapes

Lean Texture

Lean Texture+

Spaceships - Build & Destroy

Modular Backgrounds

Paint in 3D

Paint in 2D

Paint in Editor

FLOW

Destructible 2D

Space Graphics Toolkit

Space Graphics Planets

Volumetric Audio



Versions

4.2.0

4.1.1

4.1.0

4.0.5

4.0.4

4.0.3

4.0.2

4.0.1

4.0.0

3.1.4

3.1.3

3.1.2

3.1.1

3.1.0

3.0.10

3.0.9

3.0.8

3.0.7

3.0.6

3.0.5

3.0.4

3.0.3

3.0.2

3.0.1

3.0.0



Components

D2dBlur

D2dCache

D2dCalculateMass

D2dCollider

D2dCollisionHandler

D2dContext

D2dDamage

D2dDestroyer

D2dDestructible

D2dDestructibleRenderer

D2dDestructibleSprite

D2dDestructibleSpriteShape

D2dDistanceField

D2dEdgeCollider

D2dEdgeSquares

D2dFixture

D2dFixtureGroup

D2dFixtureJoint

D2dFracturer

D2dHalve

D2dImpactDamage

D2dImpactFissure

D2dImpactSpawner

D2dLinkedBehaviour<T>

D2dOverlapDamage

D2dPolygonCollider

D2dPolygonSquares

D2dRect

D2dRequirements

D2dRetainVelocity

D2dShape

D2dSlice

D2dSnapshot

D2dSnapshotData

D2dSpawner

D2dSplitter

D2dStamp

D2dTrim