- Home /
How to check if an empty GameObject is inside an object?
I'm working on a small project, where I'm creating a zombie-shooter-esque game as first project.
The enemies have two empty GameObject (origins) on either side of them, and every frame it performs a raycast out of both origins and checks if any see anything, and reacts accordingly.
The issue is however that sometimes an origin point ends up within an obstacle, after which the raycast won't detect anything. (Because of the same reason when you put a camera in an object and can still see out of the object). I tried fixing this by making it check if the origin is inside of an obstacle, before realizing I had no idea how to do that. So does anyone have any advice? I thought about adding an "ontriggerenter"-esque statement into the if-statements that check which colliders hit, but don't know how to do that, and whether the empty GameObject will even detect anything, because of the fact that it's a collider-less GameObject
Answer by NinjaISV · Nov 22, 2018 at 06:19 PM
You could easily check if the object is already within the collider's bounds (https://docs.unity3d.com/ScriptReference/Collider-bounds.html)
if (collider.bounds.Contains(object.transform.position) {
// do stuff
}
Or you could check if the object is within a certain distance of your collider:
public float range = 0.5f;
private void Update () {
// checks if the object is within 0.5 unit of the collider object
if (AbsoluteDifference(collider.transform.position, object.transform.position) <= range) {
// do stuff
}
}
private float AbsoluteDifference (Vector3 a, Vector3 b) {
return (Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y) + Mathf.Abs(a.z - b.z));
}
Hope this helps!
But wouldn't that only work from the perspective of the obstacles, not the enemy itself? That would mean that I'd have to add a script checking for origin points to every single obstacle, which doesn't seem like a very effective way to solve it. (I now notice that I miswrote what I was trying to say, I meant that sometimes the origin point would end up inside the obstacle, though that would usually end with the enemy ending up inside the obstacle.)
That solution would probably end up working for both. The one script per object solution is the best, I$$anonymous$$O. You could just fire the check once the point/enemy/obstacle interacts with each other.
Also, you should probably test between Vector3.Distance and AbsoluteDifference to know which performs the best here.
And, about you not having Trigger Colliders in your points, why is that? You could just add one, put that object in a different layer, and change your Raycasts so that they ignore that specific layer. And edit the Layer $$anonymous$$atrix so that unwanted objects don't mess with that layer.
Also, about adding an OnTriggerEnter statement to your ifs, just make a bool that turns on on OnTriggerEnter and turns off on OnTriggerExit.
Hopefully, this will somewhat help you! xD