I have some terrain in my scene that I have added to the Terrain layer. It is not flat, so I am trying to use a Raycast in order to grab the y-coordinate for spawning entities. Here is the code I use for the Raycast:
var maxAttemptsToSpawnOnNavMesh = 15;
int layerMask = 1 << 8;
while (maxAttemptsToSpawnOnNavMesh > 0)
{
RaycastHit hit;
Vector3 upDir = transform.TransformDirection(Vector3.up);
if (Physics.Raycast(spawnPos, upDir, out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(spawnPos, upDir * hit.distance, Color.green, 5f);
Debug.Log($"Raycast found position: {hit.point}\nUpdating y-value for spawn ...");
spawnPos.y = hit.point.y;
break;
}
else
{
Debug.DrawRay(spawnPos, upDir * 1000, Color.red, 5f);
Debug.Log($"Raycast did not hit. Retry number {16-maxAttemptsToSpawnOnNavMesh} ...");
spawnPos = partitionCenter + Random.insideUnitSphere * spawnRadius;
maxAttemptsToSpawnOnNavMesh -= 1;
}
}
For some reason, the raycast is not detecting the terrain and always returns false. I added the Debug.DrawRay()to see if maybe I was pointing it the wrong way, but it shows the ray going straight through the terrain layer. I’ve included a picture of the rays in the Scene view below:
Including all layers by removing the LayerMask in the Raycast() call.
Using Vector3.up directly instead of transform.TransformDirection(Vector3.up).
I also added Mathf.Infinity to the Raycast() call since I didn’t include it originally.
I’m not too sure what else to try and thought I would ask here. I am very much a noob when it comes to Unity, so any help or explanation is appreciated.
Are you raycasting upwards from a spawn position below the terrain?
If so, I don’t think rays hit the underside of the terrain unless you turn on Physics.queriesHitBackfaces?
Or if you pick a point above the terrain and cast down, that should also work (and I’d guess “better” than turning on global backface thingy)?
My kids are all home, so I’m operating at reduced mindpower, sorry in advance if this is obvious or unhelpful, but hopefully it fixes it for you:)