Search Unity

Slant Physics Raycast Implementation

Discussion in 'Physics' started by siddharth3322, Aug 8, 2019.

  1. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    For my 3d car game, I was doing Physics raycast to detect obstacles and based on detect take turn left or right side. Currently, I was doing straight raycast and I can't able to detect left and right side existed obstacles.

    So I decided to do little bit slant raycast to detect something from the left and right side.
    The following image explains a better way my question:

    drifter_car_raycast.PNG

    This code is running at present:

    Code (CSharp):
    1.  Ray rayRight = new Ray(thisTransform.position + Vector3.up * 0.2f + thisTransform.right * detectAngle * 0.5f + transform.right * detectAngle * 0.0f * Mathf.Sin(Time.time * 50), transform.TransformDirection(Vector3.forward) * detectDistance);
    2.         Ray rayLeft = new Ray(thisTransform.position + Vector3.up * 0.2f + thisTransform.right * -detectAngle * 0.5f - transform.right * detectAngle * 0.0f * Mathf.Sin(Time.time * 50), transform.TransformDirection(Vector3.forward) * detectDistance);
    3.  
    4.         Debug.DrawRay(rayRight.origin, rayRight.direction * detectDistance, Color.red);
    5.         Debug.DrawRay(rayLeft.origin, rayLeft.direction * detectDistance, Color.red);
    Now please give me a guidance to do slant physics raycast to detect obstacles.
     
  2. YondernautsGames

    YondernautsGames

    Joined:
    Nov 24, 2014
    Posts:
    353
    First up, in the ray constructor, you don't need
    transform.TransformDirection(Vector3.forward)
    . You can just use
    transform.forward
    instead.

    For a simple way to add a bit of an angle, you could add the side direction:
    Code (CSharp):
    1. Vector3 rayVector = thisTransform.forward + (thisTransform.right * 0.5f);
    2. rayVector *= detectDistance / rayVector.magnitude;
    The amount you multiply the right vector by dictates the angle. If you want precise control, multiplied by 1 is 45 degrees. Multiplied by another value you can use trig to work it out: the multiplier is tan of the angle from forwards

    tan angle = opposite (multiplier) / adjacent (1)
     
    siddharth3322 likes this.