Game Development Reference
In-Depth Information
1.
Create a new C# Script in the Game Scripts folder named PlantVeggies .
Some of the code is the same as in the SpawnBunnies script. Feel free to copy and paste.
2.
Below its class declaration, add the following variables:
public GameObject veggie; // the plant prefab
float minX; // variables to hold the object's bounding box location
float minZ;
public bool rotate; // flag to rotate the rows to match the bed
public int rows = 6; // the number of rows to make
public int columns = 6; // number of columns to make
float spacingX;
float spacingZ;
In the Start function, do all the math to get the grid numbers:
3.
// calculate box position
minX = transform.position.x - transform.localScale.x/2;
minZ = transform.position.z - transform.localScale.z/2;
spacingX = transform. localScale.x / rows;
spacingZ = transform. localScale.z / columns;
PopulateBed(); // plant the Veggies
4.
Create the function:
void PopulateBed () {
}
5.
Inside it add
float y = transform.position.y; // ground level
for (int x = 0; x < columns; x++) {
for (int z = 0; z < rows; z++) {
Vector3 pos = new Vector3(x * spacingX + minX, y, z * spacingZ + minZ);
GameObject newVeggie = (GameObject) Instantiate(veggie, pos, Quaternion.identity);
}
}
6.
Save the script.
7.
Drag it onto the Plant Zone object.
8.
Drag one of the smaller plant prefabs in as its Veggie.
9.
Click Play, and note the positioning of the plants.
An offset of half the spacing values should center it nicely.
 
Search WWH ::




Custom Search