- Home /
2D explosion that targets specific gameobjects
Hey,
I'm making a 2D platformer and wanted to ask what is the best way to create a grenade like explosion? Basically a 2D circular area where anything with a specific tag that is within the circular area is destroyed. I've been using playmaker for most of the game and to be honest not entirely sure how to solve this via that.
In essence what I'm after is a way that any game object with the tag 'enemy' which are within an area has a message sent to it to do something, instead of everything with the tag 'enemy' in the level being told to do something (which I did manage through arraymaker).
Note: I'm relatively new to programming in Unity.
Thanks!
Answer by _joe_ · Apr 15, 2015 at 01:32 PM
I don't know how to make it via Playmaker, but in C# it's pretty simple. Create an overlap sphere at the point of explosion, and gather all the colliders of tag "anytagthatyouwant" in an array, And then simply loop that array and do whatever you want with them (like adding an ExplosionForce).
A link to Explosion Force, http://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html
And a small change to the script for you, Here you go:
void Start() {
Vector3 explosionPos = transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
foreach (Collider hit in colliders) {
if (hit.gameObject.tag =="yourtag" && hit.rigidbody)
hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 3.0F);
}
Hey not sure if you still need this, but for whoever wants the 2D version of this code use Physics2D:
void Start() {
Vector3 explosionPos = transform.position;
Collider2D[] colliders = Physics2D.OverlapCircleAll(explosionPos, radius);
}
The Physics2D.OverlapCircleAll method returns a list of of all colliders in the circle. Hope this helps!
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircleAll.html
Your answer
Follow this Question
Related Questions
Make grenade apply force to rigidbodies around it 3 Answers
3rd Person Throwing Grenade Question 0 Answers
OverlapSphere not causing damage? - Solved 2 Answers
Raycast collider detector lags horribly? 2 Answers
Null reference and GetComponent 1 Answer