# How would I make a system of randomly falling obstacles?

Updated on October 10, 2018 in
3 on October 10, 2018

I am creating a basic 3D platformer/scroller game in Unity 2018. I currently have a system where I can just place obstacles down and have a fixed, set level, but I feel that this doesn’t make the game very interesting and just gives people the same, repetitive challenge over and over again.

I want to make a more randomly-generated system, where I can have obstacles drop between one x-value and another at a certain distance from the player (or the main camera, either one works as the camera follows the player).

• Liked by
Reply
on October 10, 2018

To get a random number between 2 values, try this:

```public float min;
public float max;
private float diff = max - min;

void Update()
{
float randomNum = min + (Random.Range(0f, 1f) * diff);
}
```

randomNum is going to be equal to or greater than min because we set it to min + something

diff is the difference between min and max.

RandomRange is gonna give us a random number between 0 and 1

diff * 0 = 0.

min + (diff * 0) = min

diff * 1 = diff.

min + (diff * 1) = max

• Liked by
Reply on October 10, 2018

Thank you for your reply.

How would I go about having the objects spawn and drop down in front of the player? Wise
on October 10, 2018

Spawning you would use instantiation, or entity pooling.

Dropping would be done by the RigidBody.

and the position is just:

the direction the player is moving: Vector3 dir

multiplied by how far you want it to be in front: float dist

add how high in the air you want it to be: y + height

and x plus or minus the random value we got above: x + randomNum

```Vector3 spawnPos = player.transform.position;
spawnPos += (dir * dist); // the players normalized moving direction times the desired distance
spawnPos.y += height;
spawnPos.x += randomNum;

Instantiate(objectPrefab, spawnPos, Quaternion.identity);
```

for this, you’ll probably want to change randomNum to have a min of 0, a max of whatever distance you want, and change the 0f, and 1f in Random.Range() to be -1f, and 1f respectively

Show more replies
• Liked by
Reply  YOUR PREVIEW 