Random Placement

This example explores several simple ways to automatically position objects in your scene. This is a great starting point if you want to procedurally generate terrain or other scenes. Taking these methods as a starting point, you’ll hopefully be able to find the approach that suits your project.

Manually placing objects is also a good enough approach in many projects. A hybrid approach involves starting out with random scenery, and then saving all the object properties to create a static scene from it.

Basic Random

The simplest starting point is using Math.random as is. Every object will be independently placed, this is called a uniform distribution. Starting with a plane, a couple of svelte’s {#each ... as ...} blocks and some random numbers; you can position objects like in the simple scene below.

Preventing Object Overlap

There is a limitation in using just Math.random: it does not prevent objects from overlapping. This means that sometimes you’ll see a tree growing from a rock, or two bushes growing into each other.

In order to prevent this you can use Poisson disk sampling. This algorithm guarantees a minimum distance between your objects.

If you reduce the minimum distance to something smaller than your objects size then there will look like there’s collisions. For the bushes in this example, even a distance of 1 still looks good.

Different object sizes

In many scenes this approach works well. However, sometimes you’ll want different spacing for different objects: a large tree needs more space than a small bush. Below is a variation of poisson disc sampling, but this time it allows for some different spacing, depending on the object type.

An important parameter to play with when generating scenes with this last approach is the window size. It is inferred from the difference between the largest and smallest radius given. You’ll need to play around with the details if your usecase starts running into performance issues because of this algorithm.