In Unity3d, my Raycast is always pointing to the (0,0,0) world coordinates

3.3k views Asked by At

I'm developping a car engine script and I want to use raycast to avoid obstacles. The problem is when I call raycast it points to the (0,0,0) world coordinates though I mentioned the direction to be forward from my object.

public float sensorLength = 10f;
public float frontSensorPosition = 3.65f;    // distance from the center of 
                                                   //the car to its front
public float frontSideSensorPosition = 1.1f;

private void FixedUpdate () {
    Sensors();
    ApplySteer();
    Drive();
    CheckWayPointDistance();
}
private void Sensors()
{
    RaycastHit hit;
    Vector3 sensorStartPos = transform.position;
    sensorStartPos.z += frontSensorPosition;
    Vector3 fwd = transform.TransformDirection(Vector3.forward);

    if (Physics.Raycast(sensorStartPos, fwd, out hit, sensorLength))
    {

    }
    Debug.DrawLine(sensorStartPos, hit.point, Color.green);
}

The output is this: https://i.imgsafe.org/00/0038d11730.png

1

There are 1 answers

4
Endrik On

Your codes, seem fine, except you are trying to draw line from start pos to the zero point of world space, why is that alway 0,0,0 ? because you have not hit something yet, and if the raycast didn't hit anything the hit.point will stay 0,0,0

The good way to Debug the line is by checking 'are we hit something?'

here's the full example

private void Sensors()
{
    RaycastHit hit;
    Vector3 sensorStartPos = transform.position;
    sensorStartPos.z += frontSensorPosition;
    Vector3 fwd = transform.TransformDirection(Vector3.forward);

    if (Physics.Raycast(sensorStartPos, fwd, out hit, sensorLength))
    {
        //if it a surface, then Draw Red line to the hit point
        Debug.DrawLine(sensorStartPos, hit.point, Color.red);
    } else
    {
        //If don't hit, then draw Green line to the direction we are sensing,
        //Note hit.point will remain 0,0,0 at this point, because we don't hit anything
        //So you cannot use hit.point
        Debug.DrawLine(sensorStartPos, sensorStartPos + (fwd * sensorLength), Color.green);
    }
}

It will draw green line if it's not hit, but we don't use hit.point because it's still zero.

And it will draw red line when hit Please tell me if this work, or tell if it doesn't