Holding objects, How to deal with object clipping

I’m working on a object holding script and have this so far (WASD, mouse click to pickup and drop)

http://kennyist.com/unity/2playergame/foranswers.html

But on this, You can clip objects through walls also it seems generally laggy. How would you go about stopping this from happening.

The script:

public class PickUpObjects : MonoBehaviour {

public Camera camera;
private RaycastHit hit;
bool carry = false;

void FixedUpdate () {
	if(Input.GetMouseButtonUp(0)){
		if(carry){
			
			carry = false;
			hit.rigidbody.useGravity = true;
			hit = new RaycastHit();
			
		} else {
			
			if(Input.mousePosition.x < Screen.width / 2){
				Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit, 100f);
				Debug.Log(hit.transform.gameObject.name);
				
				if(Vector3.Distance(transform.position, hit.transform.gameObject.transform.position) < 1){
					hit.rigidbody.useGravity = false;
					carry = true;
				}
			}
		}
	}
	
	if(carry){
		Carry();	
	}
	
}

void Carry(){
	Rigidbody hitRidg = hit.transform.gameObject.rigidbody;
	
	hitRidg.MoveRotation(transform.rotation);
	
	Vector3 newPos = new Vector3(transform.position.x,transform.position.y + 0.2f,transform.position.z);
	hitRidg.MovePosition(newPos + transform.forward * 0.2f);
	
}

}

Lots of big budget games let weapons and carried objects clip through walls, but I agree it doesn’t look great.

One way to do this is to have the walls push the object aside as you move up against them:

  • Put the object you are holding as a sibling (not a child) to the rigidbody player controller, with a common non-rigidbody parent.
  • Make the object you are holding a rigidbody if it is not one already.
  • Make a physics layer that interacts with the environment, but not the player. Put the carried object on this layer.
  • Attach the carried object to the player by a joint with the desired properties, e.g. a spring joint, or construct a custom (or purchase an) IK apparatus for the arms. Adjust settings such that the carried object tends not to intersect the player in undesirable ways.

…or if you’re ok with the player not being able to get as close to walls when carrying something, set the carried object up as a compound collider by making it have a collider and be a child of the player’s rigidbody. See “Compound Colliders” at the following location.

Also, if you want the carried object to just snap / teleport to the carried position, you might try setting its transform directly instead of MovePosition, which may or may not succeed if there is a static obstacle in the way.

You can use a second camera that only renders the things you are holding, and set this camera’s rendering depth to be below the one from your main camera.