Prevent cube from going inside walls?

Hello. My player is holding a rigidbody cube out in front of them and when i walk into a wall the cube goes into the wall and looks very glitchy. I have attempted to use a second camera in order to mask the cube’s layer to make it appear that it isn’t going in the wall. The problem with this is, if i drop my cube down and I walk around to the other side of the wall i can still see the cube through the wall, as my second camera is masked to only to see the cube’s layer. What other options do I have? Thank you deeply.

How is the cube setup? Does it have a Box Collider component? You mention dropping the cube, does this mean it has a Rigidbody component also?

If it is a Rigidbody and your are moving it using the transform instead of applying forces then the object will indeed move through walls because the collision detection is not applied when you directly change the objects transform.

As suggested by Shingox, you may need to use Raycasts to prevent your player from moving forward while carrying the cube.

In order to make it so that the cube doesn’t hit the wall and stops before it goes through the wall, raycasting would be the most viable solution.

	void CheckPlayerMovement()
		Ray ray = new Ray(cubeTransform.position, movementScript.movementDirectionVector);  // Shoot from the cube's position in the movement direction
		RaycastHit hit; 
		if (Physics.Raycast(ray, out hit, rayDistance)) //If ray hits in the current movement direction
			playerUnitScript.movementVector =;

What this does is shoot a ray from the cube’s current position, offset by the movement direction. So basically, if you’re going forward, you will shoot a ray forward. If left, you’ll shoot a ray left. Doing it this way will enable you to move as long as you’re outside of ray distance, meaning you can’t move any “closer” to the wall unless it’s in a different direction.

You can either decide to change either the input vector (right after direction calculation) OR you can change a “canMove” bool to false. The bool would probably be easier.

If you use UnityScript… can’t really help you out much aside from telling you that it’s MOSTLY the same.