- Home /
Random Range BUT only on specific Co Ords
Hey guys, I have a maze Game in development. when i run the game my Maze generates randomly and everything is fine, but i'm trying to implement items to spawn through-out the maze. The maze is drawn from a prefab of cubes, so all the maze walls always fall into the same positions. the code just deletes certain segments to then create a working maze.
Anyway im using Random.Range to instantiate collectable objects into the maze. but i was wandering if there was a way i could make it so the items would only fall into certain spots. for example only multiplications of 5 (5,10,15,20,25,30)
When i use this code, i spawn items fine but they fall in the walls and all over the place
// Instantiates prefab somewhere between -50.0 and 50.0 on the x-z plane
var prefab : GameObject;
function Start () {
var position: Vector3 = Vector3(Random.Range(-50.0, 50.0), 0, Random.Range(-50.0, 50.0));
Instantiate(prefab, position, Quaternion.identity);
}
But if there was a way i could get code to choose one of the numbers 5,10,15,20,25,30,35,40,45,50 on the x and 5,10,15,20,25,30,35,40,45,50 randomly that would be perfect.
im sorry if this is confusing, even i dont know how to properly communicate this problem.
Answer by kromenak · Jul 20, 2013 at 03:57 AM
Since you are generating the maze from prefabs, I'm guessing that you define the size of the maze somewhere - you say that you want to make the maze a 5x5 maze or a 10x10.
If each tile in the maze is 5x5 units, you can actually still use the Random.Range method after a fashion:
var prefab : GameObject;
function Start ()
{
var position: Vector3 = Vector3(Random.Range(0, mazeWidth) * tileSize, 0, Random.Range(0, mazeHeight) * tileSize);
Instantiate(prefab, position, Quaternion.identity);
}
This will randomly select one of the tiles in the maze, then use the size of a tile to get the world position of the tile. Since you are using -50 and +50, I'm guessing that the origin of the maze is in the center; in that case you can use "Random.Range(-halfMazeWidth, halfMazeWidth)". But it might be easier to put the origin point in the lower-left corner if possible.