# Raycast goes horizontal instead of down

Hello,
I have a strange problem.

In order to change the terrainheight to the collider of a trench I have made this Code

``````for (float TX = minx; TX < maxx; TX = TX + 0.1f)
{
for (float TZ = minz; TZ < maxz; TZ = TZ + 0.1f)
{
Vector3 Rayorigin = new Vector3(TX, startPos.y, TZ);
Ray ray = new Ray(Rayorigin, Vector3.down);
RaycastHit hit;

if (collider.Raycast(ray, out hit, 10))
{
//Debug.DrawLine(Rayorigin, hit.point, Color.green, 5);
Debug.Log("Good hit: origin: " + Rayorigin + " hit: " + hit.point);
float yHit = hit.point.y;
var height = yHit / terrainSize.y;
//temporary
height -= 0.5f;
int tery = (int)(TX * umrechnung);
int terx = (int)(TZ * umrechnung);
heightMapCurrent[terx, tery] = height;
}
else
{
Debug.DrawLine(Rayorigin, hit.point, Color.red, 5);
Debug.Log("No hit: origin: " + Rayorigin + " hit: " + hit.point);
}
}
}
``````

I wondered why it doesnâ€™t work sometimes and later I figured out that the ray isnâ€™t going down but horizontal. But I have no idea why.

When it works:

Same x and z values:

When it doesnâ€™t work:

or:

I noticed that a new start of unity will solve this problem partially.

How on earth can the direction of the ray be changed when there is â€śVector3.downâ€ť? I have no idea.
You?

I donâ€™t get why youâ€™re trying to find meaning behind a point that is a result of no hit.

There are no guarantees that the hit point will contain anything of value, the reason: there is no hit.
You detect this and then print out these junk values.

This has nothing to do with the orientation of the ray. It is still pointing down.

1 Like

I want to find out why my code isnâ€™t working properly. The elsepath is just for debugging. To me it seems it isnâ€™t working because the ray is not going down therefore it canâ€™t hit the collider which is underneath the origin.

Or: I want to see where the ray is going when it should hit the collider but it isnâ€™t.

But it says right there â€śno hitâ€ť and indeed you print this out only when there is no hit.
And you have observed yourself that when it does hit, there is nothing wrong with the values.
You simply donâ€™t hit anything, and the reasons why this is so are beyond that piece of code.

In any case you really donâ€™t want to draw nonsensical lines that connect invalid junk points.
If you want to draw a ray I believe there is a DrawRay method in the Gizmos class or you can make your own:

``````Debug.DrawLine(ray.origin, ray.origin + ray.direction, Color.red, 5);
``````

You can also make it longer if you want to, just multiply ray.direction with some scalar

``````Debug.DrawLine(ray.origin, ray.origin + length * ray.direction, Color.red, 5);
``````
1 Like

Hello,
Iâ€™m sorry for the late reply. Had a lot of other troubles going on.

Ah ok now I get it. This kind of debugging was wrong in the first place.

But I managed to find the error. Wellâ€¦like most times it was elsewhere.