Raycasting weird?

if I use the following code for my raycast:

RaycastHit hit;

if (Physics.Raycast(transform.position,Vector3.forward, out hit)){
float distanceToGround = hit.distance;
}

RaycastHit hit;

if (Physics.Raycast(transform.position,Vector3.up, out hit)){
float distanceToGround = hit.distance;
}

The raycast will start at an corner of the terrain and end at the transform.position of the player. instead of starting at the players position and moving forward or moving up.

but when I use -vector3.forward,-vector3.up,vector3.right or -vector3.right it works perfectly fine.

So what am I doing wrong? or is it just not posible to raycast forward or up?

I’m pretty sure i know what’s your fault, but you’ve missed to include that little detail in your question. Fact is the raycast function returns a boolean whether it hits something or not. When it did not hit anything, It won’t fill the RaycastHit struct since there is no hit. I guess you just use the point in your hit structure which is just invalid / zero.

Your Debug.DrawLine doesn’t represent the raycast. It just draws a line between your starting point and the “hit point” which is invalid when Physics.Raycast returns false.

If you want to draw your raycast direction, use:

Debug.DrawRay(transform.position, Vector3.forward*10000.0f);

You can still draw a line to the hit point, but only when there is a hit.