Explosion damage problem

I have the script:

var explosionRadius = 20.0;
var explosionDamage = 1;
var explosionTimeout = 5.0;

function Awake(){
	var explosionPosition = transform.position;
	
	var colliders : Collider[] = Physics.OverlapSphere (explosionPosition, explosionRadius);
	for (var hit in colliders) {
		var closestPoint = hit.ClosestPointOnBounds(explosionPosition);
		var distance = Vector3.Distance(closestPoint, explosionPosition);

		var hitPoints = 1.0 - Mathf.Clamp01(distance / explosionRadius);
		hitPoints *= explosionDamage;

		hit.SendMessage("ApplyDamage", hitPoints, SendMessageOptions.DontRequireReceiver);
	}
	
	Destroy (gameObject, explosionTimeout);
}

and it is not working correctly. It is supposed to be causing damage to the enemy, with the health script:

var health = 1.0;
var hitsound : AudioClip;

function OnCollisionEnter (hit : Collision) {
	if (hit.gameObject.tag == "cube") {
		SendMessage("ApplyDamage", .5);
	}
}

function ApplyDamage (damage : float) {
	health -= damage;
	
	SendMessage("CheckHealth");
}

function CheckHealth () {
	if (health == 0) {
		Destroy (gameObject);
		
		if (hitsound)
			AudioSource.PlayClipAtPoint(hitsound, transform.position);	
	}
}

but it is not working.

Actually I have

var explosionRadius = 20.0;
var explosionDamage = 1;
var explosionTimeout = 5.0;

function Awake(){
	var explosionPosition = transform.position;
	
	var colliders : Collider[] = Physics.OverlapSphere (explosionPosition, explosionRadius);
	for (var hit in colliders) {
		var closestPoint = hit.ClosestPointOnBounds(explosionPosition);
		var distance = Vector3.Distance(closestPoint, explosionPosition);

		var hitPoints = 1.0 - Mathf.Clamp01(distance / explosionRadius);
		hitPoints *= explosionDamage;

		hit.gameObject.SendMessage("ApplyDamage", hitPoints, SendMessageOptions.DontRequireReceiver);
	}
	
	Destroy (gameObject, explosionTimeout);
}

Start debugging…

Debug.Log("Does the awake function get fired");

Debug.Log("Does the for loop get entered");

Debug.Log("Whats the distance: " + distannce);

Debug.Log("Whats the hit points: " + hitPoints);

Debug.Log("Is ApplyDamage being called on an object: " + this.name);

Debug.Log("What is the current health for object: " + this.name + " , " + health);

… etc etc… :slight_smile:

I think i found a problem, on the log, it says 0 for the distance

With great power comes great responsibility… :wink:

Debug is your friend.

Do you possibly have a solution? I am very good at scripting, but I am still a beginner

Maybe try this

Replace

var closestPoint = hit.ClosestPointOnBounds(explosionPosition);
var distance = Vector3.Distance(closestPoint, explosionPosition);

With

var distance = Vector3.Distance(hit.transform.position, explosionPosition);

it still didn’t work

I fixed it!!! it was a simple == vs <= typo