- Home /
Spawn game object in random position on screen
I have a script which spawns a game object every fourth second, but I would like the objects, to spawn in random positions in a specific area, to make sure it won't appear off screen. How would I do this?
This is my script.
var Mines : Transform;
private var Timer : float;
function Awake () {
Timer = Time.time + 4;
}
function Update () {
if (Timer < Time.time) {
Instantiate(Mines, transform.position, transform.rotation);
Timer = Time.time + 4;
Debug.Log("Spawned Mine");
}
}
Answer by Cherno · Jan 11, 2015 at 03:56 AM
You could either...
use a random Camera.ViewportToWorldPoint (if it's a straight top-down view, as you will have to define the distance of these points from the camera),
or define the boundary x and z values (in world space) of your playing field if there's no scrolling involved, and then just roll random x and z values for the transform.position (I assume that y is always 0 = ground), but Mathf.Clamp them between the min and max x and z boundary values,
or, for the most flexibility but most complicated way, cast rays from the four corners of the camera view (= viewport) against the ground layer (again with Camera.ViewportToWorldPoint, but with a z values of 0), then use the hit.points as your min/max boundaries.
I just noticed that in my second suggestion, the $$anonymous$$athf.Clamp isn't needed because the Random.Range function already takes parameters for $$anonymous$$ and max values :) A fourth possibiltiy that gives more control over the spots where objects can spawn would be to have an array or list of Vector3s (or GameObjects) that are scattered over the landscape by the level designer, and then a random number is rolled for the position that is pulled from the array/list. (Empty) GameObjects can be used ins$$anonymous$$d so the level designer can see where his spots are, otherwise he would just have the plain V3s without visualization.