- Home /
How to make an object with a random spawn position always spawn on the ground?
I am creating a game world in which the player will spawn in at a random location. It's a pretty simple function using Random.Range, and it works just fine for the X and Z coords. The only issue is that my gameworld uses a terrain with a very widely varied heightmap. It has some mountains, some valleys, etc.
I've been spawning the player in from a higher position, so that they fall to the terrain, but it is a makeshift solution more than anything. Would there be a way to find the height of the terrain at the specified X and Z coordinates?
Answer by Incode · Jan 21, 2021 at 04:29 AM
If you're using Unity's terrain you can do use the SampleHeight method
If there's no way to directly sample the height from the terrain, you can randomly select an X and Z position, and then do a Raycast down to get a point on the collider and set your player's y position.