unity-game-enginecollisionvirtual-realityraycastingclipping

Unity - GameObject positioning at RayCast hit without clipping


So, I´m developing a VR game with base building functionalities and am using the position where the player hand Raycast hit as the position a preview GameObject has to go. But obviously when I do that, the gameObject clips through the Hit mesh. I am trying to find a way to avoid that.

I´ve came up with a solution but don´t get it to work in any way. Maybe it´s my idea, maybe my programming knowledge, no idea, but well. This would be it.

artist's rendition

So Preview GameObject Transform is set to the HitPoint transform and moved away from point of collision until not colliding anymore. I guess? I only come up with performance heavy solutions and they don´t even work anyways. Does someone know a good solution?

Thanks in advance!


Solution

  • This sounds like you are looking for Physics.ComputePenetration

    Compute the minimal translation required to separate the given colliders apart at specified poses.

    So you will need a Collider on your placed object (the hit one already has one anyway) and then do e.g.

    // Wherever you get this from
    Collider objectToPlace;
    
    if(Physics.Raycast(yourRay, out var hit))
    {
        objectToPlace.trabsform.position = hit.point;
    
        if(Physics.ComputePenetration(objectToPlace, objectToPlace.transform.position, objectToPlace.transform.rotation, hit.collider, hit.transform.position, hit.transform.rotation, out var direction, out var distance))
        {
            objectToPlace.position += direction * distance;
        }
    }