- Home /
lookAt nearest object to another object
hi, i need a turret to look at the nearest object with a certain tag to another object. basically i'm making a sort of tower defence game where the enemies aren't set to a track and i need the turrets to shoot the nearest enemy to the place that the user is attempting to protect, which can be a variable in this script. I only understand java so answers in java would be appreciated, thanks.
look forward to your answers :) oinkoinkflapflap
Answer by Mortoc · Jun 09, 2012 at 11:09 PM
There's lots of ways to do spacial look ups. I recommend using Physics.OverlapSphere of the weapon range since this will use the built in spacial partitioning to do an efficient look up in your scene, then linearally searching through the results and figuring out which enemy is closest.
float nearest = Mathf.Infinity;
Collider nearestEnemy = null;
foreach(Collider enemyCollider in Physics.OverlapSphere(turretPosition, turretRange, enemyLayer))
{
float distSqr = (enemyCollider.transform.position - turretPosition).sqrMagnitude;
if( distSqr < nearest )
{
nearest = distSqr;
nearestEnemy = enemyCollider;
}
}
if( nearestEnemy )
turretTransform.LookAt(nearestEnemy);
thanks for your answer, but i may need more guidance, for staters there are a few errors: it's telling me to add ; to the end of the first two lines, for the third that its expecting a ')' ins$$anonymous$$d of enemyCollider and two more, i expect you wanted me to add some more script myself? but i'm not that great in this field of java. also how does it recognise the enemies and object that they're nearest to? thanks
Your answer
Follow this Question
Related Questions
tag distance script 2 Answers
Distance thing with gameobject ? 4 Answers
Find child of a Game Object using tag 4 Answers
Find the first game object created with a given name 1 Answer