- Home /
How to make my function only search for objects in the same axis? Code included...
I need help only looking for the objects that are on the same height as me. Nothing below or above me. Thanks and here:
public Transform GetNearestTaggedObject() {
var nearestDistanceSqr = Mathf.Infinity;
var taggedGameObjects = GameObject.FindGameObjectsWithTag("cover");
Transform nearestObj = null;
foreach (var obj in taggedGameObjects) {
var objectPos = obj.transform.position;
var distanceSqr = (objectPos - transform.position).sqrMagnitude;
if (distanceSqr < nearestDistanceSqr) {
nearestObj = obj.transform;
nearestDistanceSqr = distanceSqr;
}
}
return nearestObj;
}
Comment
It checks for objects with the tag "cover" that are way too far. How can I limit it to a certain radius? Thanks
Best Answer
Answer by whydoidoit · Apr 27, 2013 at 07:02 AM
var heightDistance = Mathf.Abs(objectPos.y - transform.positon.y);
var closeInHeight = (heightDistance < SOME_SMALL_NUMBER);
Where do I put this? Can you put that line inside my code? Thanks (PS I got this code from online. I understand it but I need help placing that piece) thanks!
public Transform GetNearestTaggedObject() {
var nearestDistanceSqr = $$anonymous$$athf.Infinity;
var taggedGameObjects = GameObject.FindGameObjectsWithTag("cover");
Transform nearestObj = null;
foreach (var obj in taggedGameObjects) {
var objectPos = obj.transform.position;
var heightDistance = $$anonymous$$athf.Abs(objectPos.y - transform.positon.y);
var closeInHeight = (heightDistance < 0.1f); //Adjust as necessary
if (closeInHeight) {
nearestObj = obj.transform;
var distanceSqr = (objectPos - transform.position).sqr$$anonymous$$agnitude;
if(distanceSqr < nearestDistanceSqr)
{
nearestDistanceSqr = distanceSqr;
nearestObj = obj;
}
}
}
return nearestObj;
}
That will find the nearest enemy that is close in height.
Your answer
Follow this Question
Related Questions
character collider colliding with another character collider 1 Answer
Whats the best way to access other Game Objects? 2 Answers
Find how many are there in the scene 1 Answer
Find GameObject in Canvas 2 Answers
Camera.main look up 1 Answer