Update #15: Implementation of the 2D Breaking SystemFor this update, I want to talk about how I implemented the 2D sprite breaking system that I used for the egg hatching.
Block CompositionHere is the concept, let's say you have the following blocks in the game.
Each block is a game object that consists of the following:
- Sprite Renderer
- Polygon Collider 2D (or any Collider 2D)
With that composition, if an object where to collide with it, it would not make it move an inch. If we were to add Rigidbody2D component to the blocks above, then they would react to the impact. However, that's not really breaking part. At that point they would just be movable objects standing next to each other.
Breakable ScriptSo to give it the feel of breaking off, I created a script called Breakable and added it to each individual block. The script holds the following Rigidbody2D metadata:
- Mass
- Linear Drag
- Angular Drag
- Gravity Scale
This metadata is used to create a Rigidbody2D component when the block breaks off. It also uses the 'Mass' value to determine how many hits that piece will have to take before it breaks off. For example, a mass of 1 will only take 1 hit to break off, where as mass of 10 will take 10 hits to break off. So once a block breaks off, the Rigidbody2D component gets added to the block and the Breakable script destroys itself.
Impact CalculationsThe other piece of information is what determines a valid hit? If I touch it lightly, is that valid hit that can cause it to break? Maybe, depends on the mass of the piece, the velocity of the object hitting it, and the mass of the object. First, I have to get the impact of the hit by combining the velocity and the mass of the object that is doing the hitting.
var hitImpact = collision.rigidbody.relativeVelocity.magnitude * collision.rigidbody.mass;
Then I do a check to see if the block is weak enough to be damaged by the hit:
var minimumImpactVelocity = 100;
var blockDurability = blockRigidbody.mass * minimumImpactVelocity;
if (hitImpact > blockDurability){
//We have a hit
}
The 'minimumImpactVelocity' is for minimum speed an object needs to be in order to cause damage to the block. Here are some examples
BreakingSo now we know what a valid hit is. But how many hit does it take to cause the piece to break off? That depends on the hitImpact of the object the durability of the block. First I need to determine the maximum health of the block by multiplying it's durability by 10:
var maximumHealth = blockDurability * 10;
This is saying that an object with the same mass and a velocity of 100 will take 10 hits to break it off. Next up is taking the 'hitImpact' adding it the currentDamage value.
currentDamage += hitImpact;
if (currentDamage >= maximumHealth) {
// break off
}
Finally, we do a check to if the current damage is great then maximumHealth before breaking it off.
The result of all this is the following: