- Home /
How to randomly spawn objects above the ground?
Hello, everyone. I am making a simple game where the player must collect 30 (for now) objects randomly generated throughout the map. I've coded a simple random spawn script, but it does not take into account the terrain above and below the plane of spawn (y = 0) and thus many objects are spawned in and above the ground. How would I tell the objects to detect or search up and down for the ground above or below them, making them always spawn on top of the ground? Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinPlacer : MonoBehaviour {
int coins = 0;
public GameObject coin;
void Awake()
{
while (coins < 30)
{
Vector3 position = new Vector3(Random.Range(-100.0f, 100.0f), 0, Random.Range(-100.0f, 100.0f));
Instantiate(coin, position, Quaternion.identity);
coins += 1;
}
}
}
I am new to c#. Thanks for your help!
Answer by Captain_Pineapple · Apr 28, 2018 at 12:58 PM
try this Script:
public int coins = 30;
public GameObject coin;
void Awake()
{
RaycastHit hit;
for(int i=0;i<coins;i++)
{
Vector3 position = new Vector3(Random.Range(-100.0f, 100.0f), 0, Random.Range(-100.0f, 100.0f));
//Do a raycast along Vector3.down -> if you hit something the result will be given to you in the "hit" variable
//This raycast will only find results between +-100 units of your original"position" (ofc you can adjust the numbers as you like)
if (Physics.Raycast (position + Vector3 (0, 100.0f, 0), Vector3.down, out hit, 200.0f)) {
Instantiate (coin, hit.point, Quaternion.identity);
} else {
Debug.Log ("there seems to be no ground at this position");
}
}
}
perhaps you will ahve to adjust the position of the coins to hit.point + new Vector3(0,1.0f,0) or something so that they don't stick in the ground.
Your answer
Follow this Question
Related Questions
Any Reason this would make Unity Freeze up? 0 Answers
Placing Buildings on Terrain 1 Answer
Instantiate random object from Array 2 Answers
Random spawning, but one definite object 1 Answer
Random Terrain in 2d Game? 0 Answers