What is the best way to add objects to a 3D terrain?

I’m quite a noob with threejs but I have managed to create a 3D terrain with lots of trees, now the problem is to get the trees’ correct Y position. I have tried raycasting but that seems to be too slow as I dynamically add more objects to terrain as I move in world. What is the recommended way to position lots of objects on to a mesh surface?

How do you create terrain?

Can you post a screenshot of the terrain (or part of it), rendered as wireframe?

At the moment I have no access to the code but basically I create a Plane and go through its vertices array to set height data, dimensions are 256 * 256 for the height data where one unit correlates to 32 units on threejs dimension. So the plane width for the x and z is 32 * 256. I’ll add images with the code later :slight_smile:

Why don’t you use the height data y at the x,z Position of the grid as the base for your tree?

That would be ideal, I have tried it but I don’t know how to do the math behind it so that I could get the Y position between height points:




Depends on your goal, but I would use a height map, shared across the objects in the scene.
For that, you have to modify objects’ materials though.

Heightmap for both the ground and instanced firtrees.
PS Top left corner is a foliage map.


Hi prisoner849,

Would you mind sharing your code with us :wink:.

This looks exactly what I need for my project.


1 Like

Thanks, thats seems to be exactly what I would need, any advice how that shared heightmap should implemented?

A texture of heightmap, passed in a uniform into materials modified with .onBeforeCompile.
It’s easy to apply it to a terrain, the way like a displacement map works (using UV coords to get the value of displacing; displacement involves normals, buf for a plane, that represents the terrain, it’s enough to shift on Y-axis).
But for instances, you need to know their positions to compute UVs.
I used this to get positions of instances in vertex shader: vec4 instPos = instanceMatrix * vec4(0, 0, 0, 1);. Not sure if it’s perfectly correct way, but it worked for me.

Thanks for sharing, Very informatic post for me.

Thank you! A lots of stuff to learn for me yet but its good to know its doable!