Random object placing parameters
Hello, so i got this script and it is amazing but I would like to add something so that the objects don't spawn in certain areas. I am unsure on how to do this, here is the script.
using UnityEngine;
using System.Collections;
public class RandomObjects : MonoBehaviour
{
public Terrain terrain;
public int numberOfObjects; // number of objects to place
private int currentObjects; // number of placed objects
public GameObject objectToPlace; // GameObject to place
private int terrainWidth; // terrain size (x)
private int terrainLength; // terrain size (z)
private int terrainPosX; // terrain position x
private int terrainPosZ; // terrain position z
void Start()
{
// terrain size x
terrainWidth = (int)terrain.terrainData.size.x;
// terrain size z
terrainLength = (int)terrain.terrainData.size.z;
// terrain x position
terrainPosX = (int)terrain.transform.position.x;
// terrain z position
terrainPosZ = (int)terrain.transform.position.z;
}
// Update is called once per frame
void Update()
{
// generate objects
if(currentObjects <= numberOfObjects)
{
// generate random x position
int posx = Random.Range(terrainPosX, terrainPosX + terrainWidth);
// generate random z position
int posz = Random.Range(terrainPosZ, terrainPosZ + terrainLength);
// get the terrain height at the random position
float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));
// create new gameObject on random position
GameObject newObject = (GameObject)Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity);
currentObjects += 1;
}
if(currentObjects == numberOfObjects)
{
Debug.Log("Generate objects complete!");
}
}
}
As it is now, you are sampling positions from the entire width x and depth z to create the location used to instantiate. For instance, If you were trying to exclude spawning objects on the edges you could alter the range of values your Random.Range is returning, something like; Random.Range(terrainPosX + DistanceFromLeftSideToNotSpawn, terrainPosX + terrainWidth - DistanceFromRightSideToNotSpawn)
with those distance variables being integers. How are you trying to define your regions to not spawn in?
Thank you for the reply. That is what I am trying to figure out, I want to define certain areas where they cannot spawn in
Follow this Question
Related Questions
Destroy moving objcts through touch on screen 0 Answers
How to change variables that were the origins for parameters of a function with parameters. 1 Answer
Game works on most computers but half the scene vanishes on one of them. 1 Answer
how do i rotate an object? C# 1 Answer
Objects lose shape on collision. 1 Answer