How to make an object your carrying with your gravity gun not pass through a wall?

The object I’m carrying does have a rigidbody with no kinematic checked and set to continuous or continuous dynamic already and it has a collider that does not have a trigger checked.

I researched and researched and still kind find a way. searched it up on google about it and found this DontGoThroughThings
script but still passes through. I tried experimenting but still can’t figure it out.

my project is suppose to be inspired by my favorite game called Rochard

Define a position at the GravityGun where the rigidbody will be held; either as a local Vector3, a distance from the forward of the GravityGun, or an empty gameObject as a child of the GravityGun.

Use RigidBody.MovePosition to position the held object without going through other colliders : Unity - Scripting API: Rigidbody.MovePosition

Example (C#) :

public GameObject gravityGun;

public float holdDistance = 3f;

public float grabLerpFactor = 10f; // how fast does the grabbed object move to the player

RigidBody rigidObject; // the object currently held (assigned from raycast hit for example)


void Grab()
{
    // lerp the rigidbody object from the current position to the holding position
    Vector3 currentPos = rigidObject.transform.position;
    Vector3 desiredPos = gravityGun.transform.position + ( gravityGun.transform.forward * holdDistance );
    Vector3 calcPos = Vector3.Lerp( currentPos, desiredPos, grabLerpFactor * Time.deltaTime );
    
    // reset the velocity of the rigidObject so it doesn't fly off when released
    rigidObject.velocity = Vector3.zero;
    
    // disable gravity on the held object, or else it will slip down while held
    // ** ideally this would be done when the object is first assigned to the rigidObject variable
    // ** and then set back to true when the object is thrown/dropped
    rigidObject.useGravity = false;
    
    // move the object in relation to the GravityGun (without going through other colliders)
    rigidObject.MovePosition( calcPos );
}
  • Put a camera as a child object of your main camera
  • Make that child camera to render only one layer
  • Put your object you will carry to that layer
  • Remove that layer from your main camera