Shape that follows mouse and adjusts based on mesh height/terrain shape

I’m trying to implement functionality where when I click a button (let’s say, i click on the ‘x’ button), a circle appears that i can move around with the mouse, until i click. Then it disappears. I know I can just create a mesh and have it follow my mouse movements, but I’d like the shape to adjust it’s shape to respect the height map of the mesh below it. Think of something like WC3 (or similar) when you want to build a new building - the highlighted square is aware of the terrain height as I move my mouse around.

I was thinking of 1 approach, but I’m not sure if that’s the right way to do it. What I was thinking is to apply a material to the terrain mesh, and therefore it would respect the shape of the mesh it sits on. Does this seem like a viable solution? or should I use a mesh to follow the mouse around? How would I have it’s shape change to match the terrain height?

Welcome aboard!

You can try to use a decal (Use decals - Babylon.js Documentation) but it could be taxing on performance to do it at each mouse move…

You can also use ray casting to get the coordinates of the intersection with the ground (Raycasts - Babylon.js Documentation) - look in the sample of the decal doc for the code to get the intersection with a ray (scene.pick).

If you use a GroundMesh you may take advantage of getHeightAtCoordinates() for a faster way to retrieve the 3D coordinates corresponding to the position of the mouse on the screen.

1 Like

Hi Evgeni,

Thanks for the response! I decided to go with a GroundMesh. Also, thanks for pointing out the getHeightAtCoordinates() method, I didnt know this exists. Here’s another question related to that. That will give me the height at 1 specific coordinate, right? What if the ground mesh that follows my mouse cursor is 20x20? I’d want the entire mesh’s surface height to match the surface heights of the mesh below. How would I update the entire 20x20 surface to match the surface of the mesh below?

I’m going to guess that I’d have to dynamically get each coordinate’s height in all directions relative to the center of the ground mesh that’s following my mouse? So, if my current center point is: x: 10, z: 10, then I’d want to do the following:

determine start coordinate: start X = x - 10 start Z = z - 10 (0, 0)

then do a loop where I go through each x/z coordinate (until I cover a 20x20 area, so end coordinate would be x=20, z=20) and get the height for those coordinates, and then apply them to the ground mesh that follows my mouse? This seems like an expensive calculation, is it?

Yes that will be expensive.

I think you would need a custom shader to do what you want.

Maybe this will help: Circle/Ring around mouse pointer

1 Like