- Home /
JS script for applying damage to player when within a certain proximity to the Enemy.
Hello there. I'm very new to unity and am just now getting into scripting specifically Javascript. Right now I'm trying to come up with a script for an enemy to apply damage to the player when the player is within a certain distance to the enemy.Kinda in the same vain of Slender the arrival where the closer you get to slender man the more damage he does to you. I know the best way to do it is to have the enemy send a message to the player and call on the payer script, I just don't know how I would write that. Can anyone point me in the right direction, of where I can learn to do that?
Answer by W1k3 · Nov 26, 2013 at 05:51 AM
I would start out creating a big sphere collider around the enemy and setting it as a trigger. Then whenever the player gets inside it's proximity zone the player script detects that it's in the collider and takes damage.
player script: public static var intrigger : bool = false;
if(intrigger == true){ takedamage(); }
enemy script:
function OnTriggerEnter (other : Collider) { player.intrigger = true; }
Might be wrong as I don't use javascript.
Answer by highpockets · Nov 26, 2013 at 06:05 AM
Ya, I really easy way to do this is to have a Sphere collider that is attached to the enemy. Scale it to the size you need and make sure that the isTrigger is checked on the collider in the editor.
Then attach a script to the enemy that includes the function, OnTriggerEnter ( http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnTriggerEnter.html ), in it and you may want to use OnTriggerStay and OnTriggerExit accordingly as well.
It would look something like this on the enemy side:
function OnTriggerEnter (other : Collider)
{
if( other.gameObject.tag == Player )
{
other.gameObject.GetComponent(HealthScript).DamageCaused();
}
}
function OnTriggerStay (other : Collider)
{
if( other.gameObject.tag == Player )
{
other.gameObject.GetComponent(HealthScript).DamageCaused();
}
}
In the example above, it expects you to set the Player tag in the editor to "Player"
And like this on the player side:
var health : float = 100;
var damage : float = 5;
function DamageCaused()
{
health = health - damage;
if( health <= 0 )
{
Die();
}
}
I haven't tested this and I rarely use JS, but something like this should work.
Your answer
Follow this Question
Related Questions
SendMessage every second? 2 Answers
SendMessage and RaycastHit 2 Answers
send message from android to me 0 Answers
incomplete Enemy Ai (move/attack on sight) js script 0 Answers
Trouble with apply damage to enemy 2 Answers