What is the reason behind the particles being set at the center of the x-axis in THREE.JS?

I'm currently learning THREE.JS and I'm facing some challenges while trying to create a particle system. The issue I'm encountering is that all the particles seem to be aligned in the center on the X-axis, while the Y and Z axes appear to be working correctly.

Here is the image of the current result: https://i.sstatic.net/xUuAn.png My goal is to achieve something similar to this: https://i.sstatic.net/vA0tL.jpg

Below is the code snippet:

    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth - 10 / window.innerHeight,
      1,
      1000
    );

    camera.position.z = 300;

    const ambientLight = new THREE.AmbientLight(
      0xFFFFFF
    );

    const particleBufferGeometry = new THREE.BufferGeometry();
    const positionArray = [];

    for (let i = 0; i < 10000; i++) {
      positionArray.push((Math.random() * 2 - 1) * 200);
      positionArray.push((Math.random() * 2 - 1) * 200);
      positionArray.push((Math.random() * 2 - 1) * 200);
    }

    particleBufferGeometry.setAttribute("position", new THREE.Float32BufferAttribute(positionArray, 3));

    const particlePointsMaterial = new THREE.PointsMaterial({
      size: 0.1
    });

    const particlePoints = new THREE.Points(particleBufferGeometry, particlePointsMaterial);

    const renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true,
      canvas: canvasRef.current!
    });

    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setClearColor(0xFFFFFF, 0);
    renderer.setSize(
      window.innerWidth - 10,
      window.innerHeight
    );

    scene.add(ambientLight, particlePoints);
    
    renderer.render(scene, camera);

Answer №1

Issues arise during the initialization of your camera. The problem lies within the aspect ratio calculation:

window.innerWidth - 10 / window.innerHeight

For instance: 1920 - 10 / 1080 = 1919.99 (incorrect aspect ratio)

This discrepancy is due to the sequence of operations, with division taking precedence over subtraction. To rectify this, ensure proper usage of parentheses as shown below:

(window.innerWidth - 10) / window.innerHeight

Example: (1920 - 10) / 1080 = 1.76 (Correct aspect ratio)

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
    45,
    (window.innerWidth - 10) / window.innerHeight,
    1,
    1000
);
camera.position.z = 300;

const particleBufferGeometry = new THREE.BufferGeometry();
const positionArray = [];

for (let i = 0; i < 10000; i++) {
    positionArray.push((Math.random() * 2 - 1) * 200);
    positionArray.push((Math.random() * 2 - 1) * 200);
    positionArray.push((Math.random() * 2 - 1) * 200);
}

particleBufferGeometry.setAttribute("position", new THREE.Float32BufferAttribute(positionArray, 3));

const particlePointsMaterial = new THREE.PointsMaterial({
    size: 0.1
});

const particlePoints = new THREE.Points(particleBufferGeometry, particlePointsMaterial);

const canvasRef = document.querySelector("#canvas");

const renderer = new THREE.WebGLRenderer({
    antialias: true,
    canvas: canvasRef
});

renderer.setSize(window.innerWidth - 10, window.innerHeight);

scene.add(particlePoints);

function animate() {
  particlePoints.rotation.y += 0.01;
  renderer.render(scene, camera);

  requestAnimationFrame(animate);
}

animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r126/three.min.js"></script>

<canvas id="canvas"></canvas>

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

Utilize Quasar CSS breakpoints within Vue expressions for responsive design

I am currently using the QDialog component from Quasar Framework and I want to set the value of the maximized property based on the current screen size, specifically being maximized for small screens only. Is there a way for me to reference a variable in ...

Trying out the Angular resolve feature

I am utilizing Angular with ui-router, so the toResolve variable will be resolved in my SomeController. .state('some.state', { url: '/some', controller: 'SomeController', templateUrl: '/static/views/som ...

Having trouble with php isset function not functioning properly during search?

if (isset($_GET['k'])) { $k=$_GET['k']; $query="SELECT * FROM `upload` WHERE `keywords` LIKE '%$k%' "; @mysql_connect("localhost","root","") or die("error"); mysql_select_db("lol") ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Guide to creating and downloading a csv file using feathers api

I'm working on setting up an API to export data in CSV file format using Feathers services. Essentially, the goal is to enable users to download a CSV file through the API. app.service('/csv').hooks({ before: { create: [ function(hook ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

AngularJS Compile directive allows you to specify functions that you want to run in

Can someone assist me in understanding how to call an external function from a built-in compile directive? Here is a code example: http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview This is the HTML: <!DOCTYPE html> <html ng-app="app"> ...

Using Three.js, generate a series of meshes that combine to create a seamless 90-degree donut shape

I'm on a quest to discover an algorithm that can create the following shape in Three.js. Here is my rough sketch of the expected shape The number of meshes needed to form the 90 degree donut, as well as the thickness and spacing between them, should a ...

Ways to ensure that a function completes in an Express route

I currently have a route set up like this: app.get("/api/current_user", (req, res) => { //It takes about 3 seconds for this function to complete someObj.logOn(data => { someObj.setData(data); }); //This will return before ...

What is the best way to integrate JavaScript and Python for seamless collaboration?

I'm looking to create a bidirectional communication model between JavaScript and Python. The idea is for JavaScript to handle data processing, send it to Python for further processing, and then receive the results back from Python. However, I'm u ...

What is the best way to prevent content from spilling over into the div on the right

I'm having trouble with a two column div where the text in the left column is overflowing into the right column. How can I prevent this? http://example.com <div id="wrapper-industry"> <div id="wrapper-form"> <div id="form_row"> ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Alter the color scheme of the website depending on the information provided by the user on the previous page

On the previous page, I have created a form with a checklist containing options for colors: red, green, and blue. If the user selects red, the background color on the next page should change to red. If green is selected, the background color will be green ...

Using the getElementById function in javascript to modify CSS properties

Here is the setup I am working with: <div id="admin"> This element has the following style applied to it: display: none; I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript co ...

Tips for retrieving a value from an async function called within the .map function in React?

After doing some research, I discovered that async functions return a promise whose result value can be accessed using .then() after the function. This is the reason why it's not rendering properly. My question is: how can I render the actual value fr ...

Are you making the most of data exchange between JavaScript and Node.js?

I've been doing some research but I haven't found the exact solution I'm looking for. Here's what I need: I want to generate data using client-side JavaScript, perform manipulations on it with server-side Node.js, and then send it back ...

Issue with Angular's date filter when used in combination with ng-repeat

JavaScript Controller app.controller("MarketController", function ($scope) { $scope.dates = [ { date: Date.parse("01/01/1999"), value: 123.456 }, { date: Date.parse("02/05/2004"), value: 789.123 } ]; }); HTML Template <li ng-r ...

Display a concealed text box upon clicking BOTH radio buttons as well as a button

Below is the HTML code for two radio buttons and a button: <body> <input data-image="small" type="radio" id="small" name="size" value="20" class="radios1"> <label for=&qu ...

A guide on accessing information from a post form using an express.js server

Issue: Whenever the client submits a form using a post request to the server, the express server receives an empty body (req.body = {}). Objective: My goal is to retrieve req.body.username and req.body.password on a post request from the client (using the ...

I am looking to integrate a "reveal password" feature using Bootstrap 5

I had hoped for something similar to this Image from bootstrap However, what I ended up with was this Image on my local host This is the code I have: <input type="password" class="form-con ...