I have a 3D game in which I want the player character to be prevented from ever going off the edge of the ground objects. I have read that a common way to achieve this is to create invisible walls, but because of my geometry this would be quite fiddly and time consuming.
I’ve thought I could use Raycasts down to detect the ground and not allow movement in a direction where there would be no ground under the player.
Currently my Raycasts seem to be fired from the center of my object, I was wondering how I should go about firing four Raycasts from each corner of my object, because currently my player can walk halfway off the edge before my “isGround” bool sets to false, and I’d like the player not to be able to go over the edge at all, as if there were an invisible wall there.
I’m also anticipating a complication in preventing movement over the edge, because I can’t simply not allow movement once “!isGround”, as I expect this will just freeze my player once it is set, any advice on this would also be appreciated.
Thanks for any help.
The trouble is, you need world space for the raycast. This wouldn’t be corners, but you could add 1/2 width to the x, -1/2 width to the x, +1/2 length to the z, -1/2 length to the z. That would give four points kind of on the perimeter because it could be in some rotation.
Otherwise, finding the four corners is more or less the same thing in local space, but you add and subtract both 1/2 the width and 1/2 the height to the center at the same time. Then you would have to convert it somehow to world space.
Use the character’s intended movement vector as the offset for your ray, that will account for all possible directions. If they’re moving forward off a cliff, they could still move sideways or backwards. Likewise, it would stop backpedalling or sidestepping off as well.
Vector3 movement = // however you collect this information;
Vector3 rayOrigin = player.transform.position + movement.normalized * 2.0f; // 2 units ahead of their current position to stop them sooner rather than later
// do the raycast
Thanks for the replies, I will give these ideas a try!