- Home /
Detect if a GameObject is partially behind another?
Hi all,
I have a map with many "Label" GameObjects scattered around. Unfortunately a few cover each over, making it quite messy.
I think that a good strategy is to check if a GameObject is over or behind another, so that I just display one in that area.
Problem is I have no idea how to do start, and there is likely to be a straightforward way to accomplish this in Unity.
An idea would be to calculate the bounds of each individual Label and check for intersections.
I imagine it might end up being hell if I decide to tilt the Camera! ...and as it always happens Unity already offers a way to do this out of the box... :)
Just for the record, I'm using an Orthogonal Camera, which I imagine should make this a lot easier and all the labels are placed on the XY axis.
Thanks! Hopefully someone can help :)
Did you try this ?
// detects if other transform is behind this object
var other : Transform;
function Update() {
if (other) {
var forward = transform.TransformDirection(Vector3.forward);
var toOther = other.position - transform.position;
if (Vector3.Dot(forward,toOther) < 0)
print ("The other transform is behind me!");
}
}
@prototype7 Thanks for this! Though, wouldn't this return true for all Labels more distant from the Camera, rather than just the ones strictly behind the object?
Answer by Jamora · Jul 24, 2013 at 12:30 PM
You are correct in saying Unity offers a way out of the box. You can use Bounds.Intersects. You will need a (Box)collider on every GameObject, then gain access to the bounds with gameObject.collider.bounds
. If you only needs the bounds for this intersection check, tick the isTrigger checkbox in the collider's inspector so it doesn't interact with other objects.
Depending on how many gameobjects you need to check, you might want to use Physics.OverlapSphere to only get the ones nearby. If you have hundreds of objects and you check each bounding box against all others, you will get lag.
Thanks! This is really damn useful! :) Also just in case, are there any gotchas I should be aware of?
Apart from the isTrigger checkbox, none that I can think of.
$$anonymous$$oving up in the community @Jamora, I've seen you posting some nice answers. $$anonymous$$eep it up :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613110742im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Quest Script Help 2 Answers
Generating Random Numbers on a Game Object 1 Answer
GetComponent, int error, if statement, problem. 1 Answer
Unity hangs on start when finding gameobject 0 Answers
text display on touch 1 Answer