Geometry is making its debut appearance in ThreeJS for the very first time!

Currently, I am experimenting with a simple script using ThreeJS to create a point wherever you click on the screen.

Below is the function responsible for adding the point:

function addPoint(coord){
  var geometry = new THREE.BufferGeometry();
  var vertices = [];

  const sprite = new THREE.TextureLoader().load( 'textures/disc.png' );
                
  vertices.push( coord.x, coord.y, coord.z );

  geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );

  var material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: true, map: sprite, alphaTest: 0.5, transparent: true } );
                material.color.setHSL( 1.0, 0.3, 0.7 );

  const particles = new THREE.Points( geometry, material );
  //scene.add( particles );
  group.add( particles );
}

However, it seems that only the first point created is being added to the scene. What's interesting is that when I include the original example that generates random points within the same function, it adds all the generated vertices and works each time you click:

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

  const x = 2000 * Math.random() - 1000;
  const y = 2000 * Math.random() - 1000;
  const z = 2000 * Math.random() - 1000;

  vertices.push( x, y, z );
}

I can't figure out why the random point generator functions perfectly, while my simple script is struggling. Any insights would be greatly appreciated!

Thank you!

Answer №1

In order to tackle this issue, I decided to revamp the click logic by introducing a new approach. I began by generating a plane and adding it to the "objects" array.

const geometry = new THREE.PlaneGeometry( 100, 100 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00, side: THREE.DoubleSide} );
const plane = new THREE.Mesh( geometry, material );
scene.add( plane );
objects.push(plane);

Next, I extracted the coordinates from the plane's intersection.

var raycaster = new THREE.Raycaster(); // instantiate once
var mouse = new THREE.Vector2(); // instantiate once

mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects );
console.log(intersects);

for(var int of intersects){
  addPoint( int.point );
}

And that concludes the process.

Answer №2

Ensure that the size of your points (1) is adequately set to be visible. Remember, you cannot resize a geometry once created. When working with buffer attributes, make sure to allocate enough space initially as adding data beyond the buffer size is not possible. Utilize BufferGeometry.drawRange() to manage which parts of the geometry should be rendered.

Below is a snippet of code for reference:

let camera, scene, renderer;

init();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 2000;

  scene = new THREE.Scene();

  const geometry = new THREE.BufferGeometry()
  const vertices = [];

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

    const x = 2000 * Math.random() - 1000;
    const y = 2000 * Math.random() - 1000;
    const z = 2000 * Math.random() - 1000;

    vertices.push(x, y, z);
  }

  geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));

  const sprite = new THREE.TextureLoader().load('https://threejs.org/examples/textures/sprites/disc.png');

  const material = new THREE.PointsMaterial({
    size: 50,
    sizeAttenuation: true,
    map: sprite,
    alphaTest: 0.5,
    transparent: true
  });
  material.color.setHSL(1.0, 0.3, 0.7);

  const particles = new THREE.Points(geometry, material);
  scene.add(particles);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setAnimationLoop(animate);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  renderer.render(scene, camera);

}
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a4e52485f5f7a0a140b0909140b">[email protected]</a>/build/three.min.js"></script>

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

What level of trust can be placed in MUI Global Class names when using JSS?

Here is my current code snippet: const formControlStyles = { root: { '&:hover .MuiFormLabel-root': { } } } Would it be considered secure to utilize the class name in theme overrides for connecting with other components? Furthe ...

Create a unique bar chart plugin using Javascript/jQuery that allows users to drag and drop data

My current project involves developing a custom bar chart generator that must meet specific criteria: Input fields for entering data to display on the chart The ability to drag and resize bars once the chart is generated I've conducted research and ...

Cannot access a Typescript method variable within an inline function

I've encountered an issue with my code involving loading values into the array usageCategory within an inline function. Despite successfully adding values to the array inside the function, I am unable to print them outside it. getAllUsageCategoryElem ...

How to programmatically update one input value in AngularJS and trigger validation as if it was manually entered by the user?

I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...

Exploring the power of Google Charts in conjunction with PHP arrays

I have three PHP arrays with key-value pairs: $needles = ["Needle1", "Needle2", "Needle3", "Needle4", "Needle5"]; $uph1 = ["Needle1" => 3, "Needle3" => 5, "Needle4" => 7]; $uph2 = ["Needle1" => 4, "Needle2" => 2, "Needle3" => 4]; ...

What is the best method to determine the currency associated with the code in dinero.js?

Is there an easy way to locate the dinero currency in the dinero.js/currencies package using its code? For example, a function called getCurrency that accepts a string as input and outputs the corresponding dinero currency. ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

Learn the position of a div element that appears following the lazy loading of images

I am struggling to make a div sticky below a set of lazy load images. The issue lies in the fact that the offset of the div keeps changing due to the lazy loading images pushing it down. There are 4 images with unknown heights, making it difficult to acc ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Harness the power of Ionic by utilizing the same HTML template across various pages, while easily customizing the content

I need help with streamlining my Ionic app that has multiple pages with similar HTML structures but different content. Is there a way to use just one HTML file and dynamically fill in the content? Should I use a controller for each page, or is there a more ...

In order to have JavaScript showcase a random word from a list when a button is clicked and then display it in a heading 3, follow these steps:

How can I create a JavaScript function that displays a random word from a list when a button is clicked and prints it in a heading 3? I would appreciate a quick response. //Start of Js code let display = document.getElementById("motivato"); console.log(di ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

Having trouble submitting a date input form generated with vuejs on Safari browser

I am a huge fan of Vuejs and it's my go-to at work. The other day, I came across a rather perplexing scenario. If you have any insights into this, please do share. Here is the code in question: <script setup lang="ts"> import { ref ...

Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible. I have been given an assignment that requires me to ut ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

What is the best way to display recently added information?

I'm curious about why the newly added data isn't showing up in the template, even though it does appear when using console.log (check out ViewPost.vue). After adding a new post, this is the result: result.png. Does anyone know how to fix this? ...

Error in the Syntax of Project Image Slider

I'm encountering an issue with a WordPress script called Project Slides. Initially, this script was working fine but suddenly stopped. After investigating in the console, I found the following error: VM138 plupload-image.js?ver=4.2.2:67 Uncaught Err ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Variables in an Angular application are not appearing in the HTML rendering

Currently learning AngularJS as I develop a web application. After going through tutorials, I started with a basic list but am baffled as to why my browser only shows {{title}}. In my app.js module, here's the snippet where I defined the controller: ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...