- Home /
The question is answered, right answer was accepted
Decrease ExplosionForce and damage continously by distance
Hi,
I am struggeling on how to apply damage and force by the distance from the center of the explosion. The distance of each founded collider is converted to a ratio, with 0 being at the edge of the explosion radius / away from the explosion center and 1 at the explosion center. The applied force and damage should be multiplied with that value, but I am doing wrong calculations.
This is the OnCollisionEnter function of the Proximity Mine:
void OnCollisionEnter(Collision hit){
Collider[] col = Physics.OverlapSphere(transform.position, explosionRadius, detectionLayer);
foreach(Collider c in col){
float dist = Vector3.Distance(transform.position, c.transform.position);
float ratio = 0;
ratio = Mathf.InverseLerp(explosionRadius, dist, ratio);
if(c.gameObject.layer != LayerMask.NameToLayer("Projectile")){
c.transform.SendMessage("ReceiveDamage", damage*ratio);
c.transform.GetComponent<Rigidbody>().AddExplosionForce(explosionPower*ratio,
c.transform.position, explosionRadius, 30.0F, ForceMode.VelocityChange);
}
}
}
Answer by DavidWatts · Sep 08, 2016 at 09:45 PM
you are using lerp wrong the last argument is meant to be a value between 0 and 1 but in your script it is always 0. try this for the ratio. forget about using lerp and try this for the ratio
float ratio = Mathf.Clamp01( 1 - dist / explosionRadius );
Answer by maxxa05 · Sep 08, 2016 at 09:55 PM
A simple model for an explosion would be that the strength of the explosion decreases with the Inverse-Square law. It won't be a physically exact model, but close enough for a game. It would be something like:
float ratio = 1 / (transform.position - c.transform.position).sqrMagnitude;
Note that it won't be at 0 at the edge of your radius (in fact, it won't be exactly zero ever). But if the radius is small enough or the explosion is weak enough, the result at the edge will be pretty small
Edit: if you want to use a Lerp absolutely: it would go like this:
ratio = Mathf.InverseLerp(0, explosionRadius, dist);
Follow this Question
Related Questions
Exploide GameObjects Into BrokenParts : Unity 1 Answer
How to calculate force from explosion on a rigidbody 1 Answer
AddExplosionForce 0 Answers
How to I calculate damage when using AddExplosionForce? 0 Answers
Directional Explosion 1 Answer