Converting an arbitrary cube into an arbitrary sphere using three.js

My current project involves creating a random star chart within three.js that transforms into a planet (sphere) when zoomed out.

The issue I am facing is that the code I am using randomly generates stars, but when I zoom out, it appears as a cube instead of a sphere.

    for (var i = 0;i<2000;i++){
                var mesh = new THREE.Mesh( geometry, material);
                mesh.position.x = ( Math.random() - 0.5) * 4000 * Math.random();
                mesh.position.y = ( Math.random() - 0.5) * 4000* Math.random() ;
                mesh.position.z = ( Math.random() - 0.5) * 4000* Math.random() ;

                mesh.rotation.x = Math.random();
                mesh.rotation.y = Math.random();
                mesh.rotation.z = Math.random();

                scene.add(mesh);
                objects.push(mesh);
            }

In this for loop, the spawning of stars occurs, and lines 3-6 are crucial in determining how the stars are positioned. However, my attempts to create a sphere by multiplying the positioning with Math.random have only resulted in a less defined cube instead.

Answer №1

Remove the excess stars around a sphere:

let radius = 2000;
for (let j = 0; j < 2000;) {
    let star = new THREE.Mesh(geometry, material);
    star.position.x = (Math.random() - 0.5) * radius * 2 * Math.random();
    star.position.y = (Math.random() - 0.5) * radius * 2 * Math.random();
    star.position.z = (Math.random() - 0.5) * radius * 2 * Math.random();

    star.rotation.x = Math.random();
    star.rotation.y = Math.random();
    star.rotation.z = Math.random();

    let distSquared = star.position.x * star.position.x + star.position.y * star.position.y + star.position.z * star.position.z;

    if (distSquared <= radius * radius) {
        scene.add(star);
        objects.push(star);
        ++j;
    }
}

Answer №2

To avoid setting the mesh's position using x, y, z directly, consider implementing it in this alternate way:

var newPos = new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 ).normalize().multiplyScalar( 4000 * Math.random() );
mesh.position.copy(newPos);

This approach involves generating a random vector, normalizing it to a length of 1, and then multiplying it by a random value to determine both direction and distance.

You can access a demo showcasing both methods (mine and Adder's) on this jsfiddle link.

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

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

Error: The variable "user" has not been declared in server.js when using passportjs

As a novice with limited experience and a tendency to borrow code snippets from various sources, I'm struggling to identify the root cause of the Reference Error: User is not defined. This particular error crops up when I try to input or submit a new ...

What is the best way to export from a default-exporting module in ReactJS?

How can I fix this issue where the named export 'destinations' is being imported from a default-exporting module (only default export is available soon)? Here's the code snippet: import React from 'react'; import { useState } from ...

Having trouble converting a string to an array in JS? Splitting doesn't seem to be doing

I encountered an issue where I am reading data from a CSV file, storing the innerHTML to a variable (named content), which the browser recognizes as a string. However, when attempting to convert it to an array, I am facing difficulties. I attempted to use ...

Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right? static reloadAndSortItems() { let array = []; const items = Store. ...

Having trouble retrieving the iframe document using JavaScript

I'm currently facing an issue when trying to fetch an image from a website (not specifically Bing, this problem arises with every site). Upon running the code, it seems to be failing at the 'if' statement, indicating that there might not b ...

Alter the font color once the page has finished loading

Is there a way to change the color of the "View Results" text below? <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6352993.js"></script> <noscript><a href="http://polldaddy.com/poll/6352993/"> ...

Setting limits in HTML input values is quite simple and effective

Is there a way to create a form where each user has a limit on the quantity they can request from their database, and prevent them from requesting more than their limit using JavaScript? Maximum Allowed Quantity: <input type="number" value ...

How to eliminate the validation icon from a select tag in Bootstrap 5?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c57505751425363160d110d11" ...

Button that vanishes when clicked, using PHP and HTML

I am in the process of creating an online store and I am seeking to implement a button that directs users to a new page, but then disappears permanently from all pages within the store. Here is the code snippet I have developed so far: <input class="b ...

Storing transformed values in a React Functional Component: Best Practices and Considerations

Imagine having a complex calculation function like this: function heavyCalculator(str:string):string{ //Performing heavy calculations here return result; } function SomeComponent({prop1,prop2,prop3,prop4}:Props){ useEffect(()=>{ const result ...

Trouble with Clicking to Show Content

<div id="uniqueDiv"> <button id="uniqueButton1" class="uniqueClass">Hit</button> <button id="uniqueButton2" class="uniqueClass">Run</button> </div> <div id="uniqueDiv2"> <p id="uniqueId1"></p>< ...

AngularJs upon completion of the rendering process

I have been struggling for hours to find a solution without any success. In my angularjs application, I am trying to implement a loading spinner that will display until the page is fully loaded or rendered, especially during state transitions where there i ...

What is the origin of function parameters in javascript?

I have implemented the following code: handleOwnerMode = ownerChecked => { this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner})) // this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner ...

Utilize Express.js routes to deliver static files in your web application

I am looking to serve a collection of HTML files as static files, but I want the routes to exclude the .html extension. For example, when someone visits example.com/about, I'd like it to display the contents of about.html In my research on serving ...

Searching for the index of an element in an array using JavaScript

I am working with an array where each element is another array: var array = [ [0,1], [0,2], [0,3], [0,0] ]; However, when I try to use the indexOf method on this array like so: array.indexOf([0,1]); it returns -1. ...

What is the best way to conceal an HTML table using jquery?

How can I toggle the visibility of an entire table based on user input in another field? My code seems to work with regular div elements, but not with tables. What could be causing this issue? $(function() { $('#DD').change(function() { ...

Ensuring that the content fits perfectly inside a div using either Bootstrap or

I am facing an issue with two nested divs. One of them has a button that I want to stick to the bottom of the parent div, while the other contains text or a list of persons. The problem arises when the text is lengthy, causing it to overflow the div. I am ...

Dynamically highlight a MySQL table based on user preferences and store this information permanently

I'm working on a project that involves creating a table with highlight options on each row. The table is generated dynamically from data retrieved from MySQL. Currently, when a user selects a color from a drop-down menu, the color of the row changes a ...

I am able to fill in the ServiceType field, but I am struggling to find the correct options for the ServiceName dropdown menu

Is there a way to dynamically update the ServiceName dropdown options based on the selected value in the ServiceType dropdown? $scope.ServiceTypeAndName = [ { "id":0, "type":"", "list":"" }, { "id":1, "ty ...