Problems with MULTIPLE RAYCAST

I have a character that is capable of colliding with moving obstacles from in front or behind. I need to know the velocity of only the first incoming object from each side (if a threat to collide soon) so that I can displace the character on contact with the obstacle.

The solution I have come up with so far involves a raycast forwards and backwards from the character originating in the middle of the character controller. This gives me first contact info only and works fairly well in isolation. I have two major problems though:

  1. The collision is not detected for the total height of the character since the ray covers only one point (and not a plane).
  2. The two raycasts are not working simultaneously. Each one works as expected when isolated, but when tested in tandem only one raycast works as expected.

Any help with fixing the tandem raycast bug would be greatly appreciated. Any help with a more comprehensive collision solution would be even better! I supplied the basic pseudocode for my raycasts in the hopes that someone spots my error.

Thanks for the help. :slight_smile:

 // Pseudocode
var hitRight : RaycastHit;
var hitLeft  : RaycastHit;

FixedUpdate(){
  if(Physics.Raycast(origin, Vector3.right, hitRight, 5.0)){
    rightTransform = hitRight.collider.transform;
  }
  if(Physics.Raycast(origin, -Vector3.right, hitLeft, 5.0)){
    leftTransform = hitLeft.collider.transform;
  }
  else{
    rightTransform = null;
    leftTransform = null;
  }
}

Two raycasts should work too. Without further testting I guess the problem is your malformed else-part. Try this sqequence:

// Pseudocode 
var hitRight : RaycastHit; 
var hitLeft  : RaycastHit; 

FixedUpdate(){ 
  if(Physics.Raycast(origin, Vector3.right, hitRight, 5.0)){ 
    rightTransform = hitRight.collider.transform; 
  } 
  else
    rightTransform = null; 
  if(Physics.Raycast(origin, -Vector3.right, hitLeft, 5.0)){ 
    leftTransform = hitLeft.collider.transform; 
  } 
  else{ 
    leftTransform = null; 
  } 
}

I will check that out, thanks for the reply. I figured I had some funky structural issue and I’d bet this works correctly. That’s what happens when artists try to program, lol!

As of last night I officially abandoned the character controller in my project in lieu of a capsule collider with a rigid body. This solves the physical interactions without all of the hurdles and it’s not difficult to implement proper character controls on a collider. Crossing my fingers that iPhones don’t melt when running my project, lol!