Specify the minimum required spacing between two meshes in THREE.JS

I'm working on a code that generates clouds with random positions, rotations, and scales. However, sometimes these clouds can end up clipping together when they are generated close to each other or near another object. I want to set a minimum distance between the clouds, something like

if(cloud position x and z is < 10 FROM ANOTHER CLOUD) then set distance
. How can I achieve this? Here's the current code snippet:

for(let i = 0; i < 10; i+= 1){

loader.load('/clouds/clouds2/scene.gltf', function (clouds2) {


 
 const cloud = clouds2.scene

 const child1 = cloud.children[0].children[0].children[0].children[2].children[0]
 const child2 = cloud.children[0].children[0].children[0].children[3].children[0]
 const child3 = cloud.children[0].children[0].children[0].children[4].children[0]
 
 child1.material = new THREE.MeshStandardMaterial({ emissive: 'white', emissiveIntensity: 0.3})
 child2.material = new THREE.MeshStandardMaterial({ emissive: 'white', emissiveIntensity: 0.3})
 child3.material = new THREE.MeshStandardMaterial({ emissive: 'white', emissiveIntensity: 0.3})

 cloud.scale.x = (Math.random() * (0.06 - 0.04 ) + 0.04)
 cloud.scale.y = (Math.random() * (0.06 - 0.04 ) + 0.04)
 cloud.scale.z = (Math.random() * (0.06 - 0.04 ) + 0.04)

 cloud.position.x = (Math.random() - 0.5) * 500
 cloud.position.y = (Math.random() + 80)
 cloud.position.z = (Math.random() - 1) * 500

 cloud.rotation.x = Math.random()
 cloud.rotation.y = Math.random() 
 cloud.rotation.z = Math.random() 

 scene.add(cloud)


})
}

Answer №1

Don't be afraid to start by placing objects statically and then add some randomness for variation. For instance, imagine having 4 clouds positioned at the corners of a square. By introducing random changes within a fixed range to their positions, you can achieve a randomized effect while still keeping them separate.

const clouds = [...] // array of cloud meshes
const maxChange = ... // maximum position change allowed

const staticPositions = [
  new THREE.Vector3(...),
  new THREE.Vector3(...),
  new THREE.Vector3(...),
  new THREE.Vector3(...)
]

for(let i = 0; i < 4; ++i){

  let cloud = clouds[i]

  cloud.position.copy(staticPositions[i])

  // introduce random variance
  cloud.position.x += (Math.random() * (maxChange * 2)) - maxChange
  cloud.position.y += (Math.random() * (maxChange * 2)) - maxChange
  cloud.position.z += (Math.random() * (maxChange * 2)) - maxChange

}

However, if you prefer total randomness, then you'll need to ensure that each new position doesn't overlap with any other clouds before finalizing it.

const clouds = [...] // array of cloud meshes
const minDistanceSquared = ... // minimum distance squared between clouds allowed

// check if a cloud is positioned far enough from all other clouds
function isFarEnoughAway(cloud){
  let retVal = true

  for(let i = 0, l = clouds.length; i < l && retVal; ++i){
    if(cloud !== clouds[i] && cloud.position.distanceToSquared(clouds[i].position) < minDistSquared){
      retVal = false
    }
  }

  return retVal
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the dynamic pairing of Three.js and CSS3 to bring life to animated 3D objects

I am currently working on a project that involves creating 3D Lego elements and assembling them into a figure using animation. I have successfully modeled the elements in Blender and exported them as .obj/mlt files without any issues. However, when it come ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

Switch the position of the Refer a friend button and the name button to the right

I am seeking assistance to align two buttons to the right. const getFullName = () => { if (authContext.user.first_name) { return `${authContext.user.first_name} ${authContext.user.last_name}`; } return authContext.use ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

Unexpected result when trying to return a value from a recursive function

Attempting to solve the problem of calculating the number of ways a number can be decoded, with 1 as a, 3 as c, and 26 as z. The function seems to calculate the correct count, but for some reason only returns undefined. It appears that the recursive calls ...

Troubleshooting problem with the oninput function of a custom JavaScript element

Assume I have a unique requirement to trigger a function within a custom element. The goal is to update text in the element only when a slider is moved within that specific element. Here's an example implementation in the main.js file: class Oninput ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

What is the best method for adding texture to a side of a ThreeJS extruded geometry?

When using ThreeJS, I create geometry by loading SVG with SVGLoader and extruding it. I also utilize materials for the face and sides. Below are the materials being used: const texture = new THREE.TextureLoader() .load('https://mail.dolodom. ...

Retrieve dimensions of text using the <a-text> component in Aframe

Having issues retrieving the height and width of an aframe text component in a custom aframe component. The text is visible in the scene and I can log the 'geometry' and 'material' properties. However, the 'layout' property is ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...

Encountered an issue with AWS S3: unable to retrieve the certificate from the local issuer

After completing my Protractor test suite execution, I am encountering an error while trying to upload my HTML result file to AWS S3 using JavaScript in my automation script. Can someone assist me in resolving this issue? static uploadtoS3() { con ...

Is it possible to correlate the position of a medical image segment with the position of a mouse click event in JavaScript?

Greetings and thank you for taking the time to read this! This query is closely linked to the following library: https://github.com/FNNDSC/ami I am interested in developing a function that can detect when a user clicks on a segment within an image, trigg ...

Updating dependencies of dependencies in npm: A step-by-step guide

I'm puzzled by the fact that I can't seem to find a solution to this seemingly easy question. It's surprising that even running npm update doesn't resolve the issue. While I can't post my entire dependency tree here, I'll do ...

Modify the label contents to reflect the selected file, rather than using the default text

Currently, I am working on customizing my file upload input to enhance its appearance. Everything is going smoothly so far, but I am facing difficulty in finding a suitable jQuery script that can meet my specific requirements. My objective is to have the ...

Tips for controlling the last size in a CSS grid

<div class="grid-layout"> <img class="grid-item unview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/53819/9.png"> <img class="grid-item unview" src="https://s3-us-west-2.amazonaws.co ...

Sorry, but we're unable to provide a unique rewrite of text that is an original error message

Trying to fetch data from a MySQL database using Next.js API routes, I encountered the following error: Error: No response returned from the route handler Below is an example of the code being used: import { NextResponse } from "next/server"; impor ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

Can you explain the distinctions between Vue JS and React JS?

As I delve into learning Vue Js and React Js, my search for a detailed comparison between the two on Google left me unsatisfied. I came across resources answering the singular questions "What is Vue js?" and "What is React Js," but none that directly comp ...