- Home /
Question by
Agent27765 · Apr 14, 2019 at 02:48 PM ·
c#2dphysics2d-platformer2d-physics
How to check if my enemy hits the ground at a certain velocity then add explosive force.
Hello! Right now I am trying to make my first ever 2D game. I have an enemy who jumps in the air and when they fall they are supposed to cause a light explosive force to the player and also deal damage. The problem is that I do not know how to check if the enemy after jumping hits the floor at a certain velocity. I also do know how to add force to the player.
I tried using void onCollisions Enter2D but that calls it every time even if its moving.
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);
}
}
}
}
ExplosionForce2D script: Pre-Made
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
Answer by xxmariofer · Apr 14, 2019 at 05:29 PM
just add an if condicion comparing if the rb.velocity.magnitude is less or higher than your desired amount