From Unify Community Wiki
Revision as of 20:23, 25 August 2007 by Danielbrauer (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Author: Daniel Brauer


This script uses raycasting to avoid the physics engine letting fast-moving objects go through other objects (particularly meshes).


Attach the script to any object that might move fast enough to go through other colliders. Make sure that the LayerMask does not include the layer of the object the script is attached to, otherwise the object will collide with itself. Leave Skin Width at 0.1 unless the object still passes through other colliders. If this happens, increase the skin width until the issue stops or you reach a value of 1.0.

JavaScript - DontGoThroughThings.js


  1. pragma strict

var layerMask : LayerMask; //make sure we aren't in this layer var skinWidth : float = 0.1; //probably doesn't need to be changed private var minimumExtent : float; private var partialExtent : float; private var sqrMinimumExtent : float; private var previousPosition : Vector3; private var myRigidbody : Rigidbody; //initialize values function Awake() {

  myRigidbody = rigidbody; 
  previousPosition = myRigidbody.position; 
  minimumExtent = Mathf.Min(Mathf.Min(collider.bounds.extents.x, collider.bounds.extents.y), collider.bounds.extents.z); 
  partialExtent = minimumExtent*(1.0 - skinWidth); 
  sqrMinimumExtent = minimumExtent*minimumExtent; 


function FixedUpdate() {

  //have we moved more than our minimum extent? 
  if ((previousPosition - myRigidbody.position).sqrMagnitude > sqrMinimumExtent) { 
     var movementThisStep : Vector3 = myRigidbody.position - previousPosition; 
     var movementMagnitude : float = movementThisStep.magnitude; 
     var hitInfo : RaycastHit; 
     //check for obstructions we might have missed 
     if (Physics.Raycast(previousPosition, movementThisStep, hitInfo, movementMagnitude, layerMask.value)) 
        myRigidbody.position = hitInfo.point - (movementThisStep/movementMagnitude)*partialExtent; 
  previousPosition = myRigidbody.position; 


Personal tools