- Home /
Question by
Juanchipum · Feb 15, 2019 at 08:15 PM ·
terrainenemiesspawner
How do I spawn enemies at the correct height in a terrain?
I'm making a FPS game and I want to spawn 10 enemies in a random position when I load a level. To do this I create two a random integers for the X and Z position and with SampleHeight I get the height of my terrain in that position. Some of the enemies spawn correctly in the ground but some of them spawn on the air and I can´t figure out how to fix this.
Here's my code: using UnityEngine; using System.Collections;
public class spawner : MonoBehaviour {
public int quantity;
public float height;
public GameObject enemy;
public Terrain terrainobj;
public Vector3 positionspawn;
public int xrandom;
public int zrandom;
void Start () {
quantity= 10;
}
void Update () {
if(quantity>0) {
quantity--;
xrandom = Random.Range (-370, 120);
zrandom = Random.Range (0, 480);
height= terrainobj.SampleHeight (new Vector3 (xrandom, 0, zrandom));
positionspawn = new Vector3 (xrandom, -height, zrandom);
Instantiate (enemy, positionspawn, gameObject.transform.rotation);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Enemy Spawner based on enemies values ! 0 Answers
How to have multiple enemies spawn in a wave? 1 Answer
Camera is dislocated after build. 0 Answers
Set RenderQueue for Terrain 2 Answers