- Home /
OnTriggerEnter2D doesn't apply forces correctly,if at all
Problem:
I have a cluster of balloons in my scene in which I shoot darts at. Ideally I would like the balloon that was hit to
instantiate a particle effect to simulate a balloon pop
apply a force to its surroundings
Destroy the dart that hit the balloon
Eventually I'll have the balloon gameObject destroyed after all these steps are completed. so naturally I used OnTriggerEnter2D(Collider2D coll) but so far it seems like forces aren't being applied while in this function.
code
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.tag == "Dart")
{
Debug.Log("dart hit balloon!");
isHitVector = new Vector3(coll.gameObject.transform.position.x, coll.gameObject.transform.position.y,10.0f);
Rigidbody2DExtension.AddExplosionForces(gameObject.rigidbody2D,Power * 100,isHitVector,Radius);
rigidbody2D.AddForce(transform.position);
ParticleSystem p = Instantiate (balloonExplosionParticle, transform.position, Quaternion.identity) as ParticleSystem;
isHit= true;
//rigidbody2D.AddForce(Power*1000 *Vector3.one);
Destroy (coll.gameObject);
}
}
//Static method to apply an explosive force located in the Rigidbody2DExtension class
public static void AddExplosionForces (Rigidbody2D body, float expForce, Vector3 expPosition, float expRadius)
{
var dir = (body.transform.position - expPosition);
float calc = 1 - (dir.magnitude / expRadius);
if (calc <= 0) {
calc = 0;
}
body.AddForce (dir.normalized * expForce * calc);
}
What I've noticed It seems that I am reaching the condition of that the dart is hitting the balloon as I'm able to print out "dart hit balloon!". I've noticed that if I were to add the Rigidbody2DExtension function in FixedUpdate (shown below) it works perfectly fine and does exactly what I want it to.
void FixedUpdate()
{
if (Input.GetButtonDown("Fire1")){
Vector3 mousePos = Input.mousePosition;
mousePos.z = 10;
Vector3 objPos1 = Camera.main.ScreenToWorldPoint(mousePos);
Rigidbody2DExtension.AddExplosionForces(rigidbody2D, Power * 100, objPos1, Radius);
}
}
Main Question
Is there something I'm not seeing in using onTriggerEnter? It's behaving extremely strangely..
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Multiple rigidbody coming to rest on top of rigidbody causing strange forces. 0 Answers
How can I get a responsive rigidbody FPS controller without acceleration that reacts to forces? 2 Answers
Unexpected token: collider? 1 Answer
Why OnTriggerEnter2D is triggered on an Object which doesn't include trigger collider? 1 Answer