I’m trying to find the distance to edge of an object from the player. The image shows what I need.
That’s actually hard to say… considering what is an “edge”?
For rectoid’s it’s obvious, but for non-rectoids, not so much.
…
Now if you make the assumption that it’ll always be done to a rectoid that is oriented essentially like yours is there (so not tumbled, but where the top is always facing up). You can naively get it in 2 raycasts.
This all presumes the box has a collider on it.
- raycast from player towards wall, this will give you the position and normal of the wall in front of you.
- get the bounds of the box, this will give you some normal distance to start your 2nd raycast at
- get a vector orthogonal to the normal, and parallel to the ground (this is half of why you need the box facing up like in your pic) by using a CrossProduct of the normal and Vector3.up
- get a point the distance of the bounds in the direction of this vector from the point of collision (and move in a tiny bit, 0.1f? calculated off the bounds?, in the direction -normal to deal with overlap)
- cast from this new point towards the box (-vector)
This will give you a corner.
Do it again in the opposite vector direction to get the other corner.
Now you can just take the distance of those points from the point contact point of the first raycast, and that’s how far to either end.
…
With all that said, there are more algorithmic routes of doing this.
Like using Separation of Axis theorem to project your cube over the axis in question and measure the length of that projection. This would be more efficient then all that raycasting.
Unfortunately Unity does not offer an interface (that I know of) to access this information. Though if you define your own cube struct, you can do this.
You can see this here in my ‘Box’ struct at the ‘Project’ method:
…
Another option is to allow for overcompensation.
Get the bounds of the collider, use the edges of that (simple addition of vectors).
It won’t be a perfect distance… but rather an over estimation. But it would satisfy any shape collider, and your AI would definitely make it around the corner. Even if it seems like the go slightly further out of the way than necessary.
…
Anyways, there’s 3 possible ways all with 3 different approaches/overhead/gotchas.
Take a pick.
Or maybe someone else will have yet another way to calculate it.
Or maybe, though I’d be surprised since I’m pretty darn familiar with unity, maybe there is a simple function that does this for you in Unity hidden under some dark rock.
Thanks for the response. The first solution worked perfectly for me.