- Home /
modifing enemies target inside a radius
basically i am trying to set my players transform as the target of the enemies that pass by him, i have tried a couple of method but the only one that look like i am on the right track is this.
code :
var range : float = 5.0;
function Update {
var playerPosition = transform.position;
var colliders : Collider[] = Physics.OverlapSphere (playerPosition, range);
for (var i = 0; i < colliders.Length; i++) {
colliders[i].GetComponent(enemies).target = transform;
}
}
i believe that the line colliders[i].GetComponent(enemies).target = transform;
is not the way to go. so how can i manage to set my transform as the target of the enemies inside the given radius?
Answer by whydoidoit · Feb 14, 2014 at 04:39 AM
Well you should use maths instead of physics for this. On each enemy you just check how far away the player is.
Get a reference to the player in the enemy script Start function (use FindObjectsWithTag or perhaps a Singleton script).
On the enemy's Update check the distance to the player - use the square distance for performance
Player.js
static var instance : Transform; function Awake() { instance = transform; }
Enemy.js
var radius : float = 20; function Update() { if((Player.instance.position - transform.position).sqrMagnitude < (radius * radius)) { //Player is in range } }
why did i not tough about that its so simple thank you for your help and time :)
Your answer
Follow this Question
Related Questions
How to use "GetComponent" and "transform" code in dll file? 0 Answers
C# line into Javascript help 1 Answer
How to randomise object facing upon button down (using raycast to detect cursor over object) 1 Answer
NULL REFERENCE EXCEPTION,NULL REFERENCE EXCEPTION while accessing child objects unity2D 0 Answers
Need to change direction of transform? 2 Answers