Raycast object as far as possible?

Hello, i’m using a raycast to move objects picked up by the player as far away as possible. A raycast is created from the camera, in the forward direction, until it hit’s a wall (ignoring the picked up objects via layer masks).

(Just a note that many of the variables in scripts are used in other, unmentioned areas of my project)

As you can see, the picked up object is rendered on a layer above the standard camera layer.

My question is, how can i prevent the objects from being projected into positions where they would not fit, such as in corners, or through small gaps, or generally just walls and floors?

Here is a script added to every object, essentially it’s properties:

 var originalScaleX : float;
 var objectExtents : Vector3;
 var averageExtents : float;
 var avExtentsMag : float;
 var doubleExtentsMag : float;
 var preferedPositionX : float;
 var preferedPositionY : float;
 var preferedPositionZ : float;
 var preferedRotationX : float;
 var preferedRotationY : float;
 var preferedRotationZ : float;
 function Start()
 function Restart()
     originalScaleX = gameObject.transform.localScale.x;
 function Update()
     objectExtents = gameObject.GetComponent.<Collider>().bounds.extents;
     averageExtents = ((objectExtents.x + objectExtents.y + objectExtents.z) / 3);
     avExtentsMag = (Mathf.Sqrt(averageExtents * averageExtents) + (averageExtents * averageExtents));
     doubleExtentsMag = avExtentsMag * 2;

And here is the main part of the script moving the object to the raycast hit, which is added to the object only while it is picked up by the player:

 function Update()
     averageExtents = gameObject.GetComponent.<ObjectInfo>().averageExtents;
     var hit : RaycastHit;
     if(Physics.Raycast(cam.transform.position, cam.transform.forward, hit, 999999, ignoreObjectMask))
         gameObject.transform.position = hit.point - (cam.transform.forward * averageExtents);

You might want to look into these functions:




Just fill their parameters with the corresponding values from your world objects and they will be cast as far as they can before hitting something.

I should not these are more expensive than simple raycast.