giulehm
giulehm

Reputation: 41

Three.js random position from mesh coordonates

I'm really new to three.js,

I would like to give a simple mesh a random position from another mesh coordinates. Just like that :

example

I want to little yellow box to randomly positionate above the M letter.emphasized text

I tried this

var points = THREE.GeometryUtils.randomPointsInGeometry( geometry, nPoints );
        const cube2 = new THREE.Mesh(cube, jaune);
        cube2.position.set(1, 0, 0);
        scene.add(cube2);

but it doesn't seems to work. Sorry in advance if it's too obvious ;)

Upvotes: 2

Views: 1510

Answers (1)

M -
M -

Reputation: 28487

You might be looking for THREE.MathUtils.randFloat(). You basically provide a low/high range, and it'll give you a random number within that range.

I'm guessing by your screenshot that the letter M is on the x/z plane, so you'll have to provide a random range for both the x position and z position:

let xPos = THREE.MathUtils.randFloat(-10, -8);
let zPos = THREE.MathUtils.randFloat(-2, 2);
cube2.position.set(xPos, 0, zPos);

(I don't know how big the letter M is, so I'm just guessing numbers. You'll have to play with the low/high values to get the actual range of where you want your cube to randomly show up)

Upvotes: 1

Related Questions