Push object away from edge/corner

I’m trying to place portals to the mouse click positions. How do I make sure that portal completely overlaps underlying plane when user clicks too close to the edge or corner? Here is an example.

The only solution I can think of is create another collider mesh (similar to nav mesh) where each wall or floor is shrunk (colored with blue on picture). And when user clicks on real wall, find nearest point on shrunk mesh and place portal there. But then I have to create manually “nav mash”. Is there easier way to place portal correctly?

Find nearest point from MeshCollider work only with convex. But in my case its just multiple planes separated from each other. So I’ll have to manually iterate through triangles to find nearest point.

Any other suggestions would be greatly appreciated. :slight_smile:

I think I found a solution using RayCast + SphereCast.

  1. RayCast mouse click to find hit with wall

  2. SphereCast from above that hit point to find hit with “nav mesh”

  3. Use point from 2nd hit and normal from 1st hit to place a portal

        Ray ray = Camera.main.ScreenPointToRay(click);
        RaycastHit rayHit;
        if (Physics.Raycast(ray, out rayHit, Mathf.Infinity, NOT_NAV_MESH_MASK))
        {
            RaycastHit sphereHit;
            if (Physics.SphereCast(rayHit.point + 1.001f * rayHit.normal, 1f, -rayHit.normal, out sphereHit, Mathf.Infinity, NAV_MESH_MASK))
            {
                OpenPortal(sphereHit.point, rayHit.normal);
            }
        }
    

Here is port mesh drawn with green lines.

Hey there !
I’ve made a small script using Bounds (Link to Docs).

You can download my scripts as an [113177-pushobjectintobounds.zip|113177] including an example !

Let me know if you need any help :slight_smile: