- Home /
Question by
Agent27765 · Apr 14, 2019 at 02:53 PM ·
c#2d2d game2d-platformer2d-physics
How to check if an object hits the ground hard enough then add explosive force around it (2D)
Hello! I am trying to create my first every 2D game. The problem I am having at the moment is trying to add force to my character if my enemy jumps and lands hard enough. I know how to deal damage to the player but I need to know how to add a force to "push" the player back if they are close enough to the enemy.
I tried using onCollisionsEnter2D but it calls it every single time even if the enemy is just moving. I want it to detect once it hits the ground hard enough.
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Ground")
{
foreach (Collider2D Obj in Physics2D.OverlapCircleAll(transform.position, radius))
{
if (Obj.GetComponent<Rigidbody2D>() != null && Obj.gameObject != gameObject)
{
Debug.Log("Calling Function");
Rigidbody2D rb = Obj.GetComponent<Rigidbody2D>();
ExplosionForce2D forceScript = GetComponent<ExplosionForce2D>();
forceScript.AddExplosionForce(rb, force, transform.position, radius);
}
}
}
}
This is the function I am calling to add the force
public class ExplosionForce2D : MonoBehaviour
{
public void AddExplosionForce (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);
}
}
Comment
Best Answer
Answer by TreyH · Apr 14, 2019 at 04:26 PM
You probably want to check Collision.relativeVelocity:
void OnCollisionEnter (Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
if (collision.relativeVelocity >= 2)
{
foreach (Collider2D Obj in Physics2D.OverlapCircleAll (transform.position, radius))
{
// ..
}
}
}
}