- Home /
Trying to find whether a point is close to the edge of a surface
Struggling with spherecasting, maybe you folks can help me out:
I am casting downwards, trying to find out whether the center of the cast is close to the edge of a horizontal surface. For example, if my glass of milk is spawned on the edge of the table, I want to know about so I can grab it before it falls.
The way I thought would make sense to do this is to get all the objects hit by a spherecast, then check the y position of each hit. If one of the hit points is lower than the center of the cast, the center must be close to an edge.
The problem with this approach is that Physics.SpherecastAll returns every single object in its path, not just the ones blocking it. This means that a cast performed above the center of a table will return the same objects as a cast which overlaps the edge of the table: they will each return both the table and the floor.
Doing a regular spherecast doesn't seem to be what I'm looking for either, since Physics.Spherecast seems to only retrieve information about the first thing it hits. I've never used SphereCastNonAlloc, maybe that's what I'm looking for?
Spherecasting may not be useful for this at all, I don't know - I'm considering just shooting a bunch of raycasts instead. I'm kind of having a stupid brain day tbh, so I feel like a simple solution is probably staring me in the face.
Edit: Layer masks wouldn't be flexible enough for me, because I want it to work for any random surfaces in any random level. Imagine jillions of glasses of milk being spawned all over castle battlements.
Answer by dane-wheaton · Jun 04, 2020 at 07:44 AM
In case a better solution doesn't come along, I'll post this since I already know it will work:
Shoot a ring of raycasts out around one central raycast. If any of the ring hits are lower than the central one, voila! You are close to an edge.
Answer by michaelfelleisen · Jun 04, 2020 at 07:27 AM
if you want to test against multiple objects but not every object you can use a layerMask for your Physics.SpherecastAll and but all objects you want to check against in a special layer https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html
if you want to detect if your glass is almost falling off the table multiple raycasts are probably the best idea. lets say you have 4 raycasts down from the edge of you glass you can test if all 4 raycasts hit the table. if one or more do not hit the table your glass is about to fall off
Ah, should have specified that layer masks wouldn't be flexible enough for me - I'll update the description