Rotation to Closest Enemy with Tag

Ive been looking around but i cant seem to find how to make Object rotate to closes Object with tag
so Enemies have this script attached.

#pragma strict

var damping:int=2;
var target:Transform;

function Update()

  {
var lookPos = target.position - transform.position;

   lookPos.y = 0;
   var rotation = Quaternion.LookRotation(lookPos);
   transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
   }

Which i have simply set the target to the Player but how would i make the Player face the closest enemy with the tag Monster

Please and Thankyou in Advance.

Sorry if this is written all messy its never been my strong point.

well first off that’s not how you use slerp. It’s a purely mathematical function to figure out a value at some given point between the given start and end points. Since “Time.deltaTime * anything” is very unlikely to ever give you a progression from 0 to 1 over time it’s not going to rotate from the start to the end point.

as to your question about finding things by tag, there are several methods depending on how your project is setup.

Pure “brute force” approach would be to retrieve all said tagged objects in the scene and iterate over them to work out their relative distances.

(you can google “unity sort list by distance” to get the various approaches on the iterations…)

If you have alot of objects in the scene with relatively few objects that are likely to be in range in any given frame you might consider using something like OverlapSphere to get a list of the local colliders and iterate over those to check their tags/distances.

Alternatively you can use the OnTriggerEnter / Exit functions and maintain a collection of things in range (be careful with objects getting destroyed, they dont call OnTriggerExit at all, so you might want to look into OnDestroyed() for some cleanup, as such you might want to drive this behaviour from the “tagged object” and register/deregister to the things looking for them as they move)

I normally use c# so my javascript might have some syntax problems:
This code assumes the user will press a key to target nearest monster (In this case… F). If you wan to constantly be turning towards the nearest monster just take out the if (Input.GetKeyDown) wrappered around the turning code.

#pragma strict

// set this in the inspector
// its degrees per second
public var turnSpeed : float;
var damping:int=2;
var target:Transform;
var isTurning: bool = false;
var startRotation: Quaternion;
var endRotation: Quaternion;
var currentTime: float;
var totalTurningTime : float;
function Update()
{
     if (Input.GetKeyDown(KeyCode.F)
     {
              target = GetNearestMonster();
              if (target != null)
              {
                 var lookPos = target.position - transform.position;
                  lookPos.y = 0;
                  endRotation = Quaternion.LookRotation(lookPos);
                  startRotation=transform.rotation;
                  var angle = Quaternion.Angle(startRotation,endRotation);
                  totalTurningTime = angle/turnSpeed;
                 isTurning = true;
                currentTime = 0;
           }
     }
     if (isTurning)
     {
            currentTime+=time.DeltaTime;
            var t = currentTime/totalTurningTime;
            transform.rotation = Quaternion.Slerp(startRotation,endRotation,t);
            if (t>=1)
                 isTurning = false;
      }
}

// This uses the brute force method of all "Monster" objects
// optimize this as you need.  It will depend on how your
// game is setup
private Transform GetNearestMonster()
{
        var monsters : GameObject[];
        monsters = GameObject.FindGameObjectsWithTag("Monster");
         var distance : float = Float.MaxValue;
         var closest : GameObject = null;
         for (var go : GameObject in monsters)
         {
               var diff = (go.transform.position - position);
               var curDistance = diff.sqrMagnitude;
               if (curDistance < distance)
               {
                   closest = go;
                   distance = curDistance;
               }
        }
        return closest;
}

Thank you guys got it to work :slight_smile: