manipulate particle systems using Three.js

I am struggling to determine if my mouse is hovering over a particle in order to move it away using a particlesystem in threejs.

Despite using a raycaster, I am not getting any hits.

I also attempted to attach a hitbox to the particle, but unfortunately, the hitbox does not follow the particle properly.

    for (var p = 0; p < particleCount; p++) {

// create a particle with random
// position values, -250 -> 250
var pX = Math.random() * 200 - 200 / 2,
pY = Math.random() * 150-150/2,
pZ = -5,
particle = new THREE.Vector3(pX, pY, pZ);
// create a velocity vector
particle.velocity = new THREE.Vector3(
0,              // x
Math.random()*maxVelocity, // y: random vel
0);             // z
// add it to the geometry
// add hitbox on particle
var material = new THREE.MeshBasicMaterial({color : 0x45a314});
var circleGeometry = new THREE.CircleGeometry(maxDistance, 8);
particle.hitbox = new THREE.Mesh(circleGeometry,material);
particle.hitbox.position.set(pX,pY,pZ);
particles.vertices.push(particle);
}

The onMouseMove function:

function handleMouseMove(event) {
event.preventDefault();
mousePos.x = (event.clientX / window.innerWidth) * 2 - 1;
mousePos.y = -(event.clientY / window.innerHeight) * 2 + 1;


//control
mouse_vector.set(mousePos.x,mousePos.y,mousePos.z);

projector.unprojectVector(mouse_vector,camera);

var direction = mouse_vector.sub(camera.position).normalize();

ray.set(camera.position, direction);

}

The update function:

function update() {

var pCount = particleCount;
while(pCount--){
// get the particle
var particle = particles.vertices[pCount];

// check if we need to reset
if (particle.y > 80 ) {
particle.z = -4;
particle.x = Math.random() * 200 - 200 / 2;
particle.y = -75;
particle.velocity.y = Math.random()*maxVelocity;
// particle.velocity.x = Math.random()*0.4-0.2;
// particle.velocity.y = Math.random()*0.4-0.2;
}

intersects = ray.intersectObject(particle.hitbox);

if(intersects.length){
console.log("hit");

}


// and the position
particle.add(
particle.velocity);
}
// flag to the particle system
// that we've changed its vertices.
particleSystem.geometry.__dirtyVertices = true;

// draw
renderer.render(scene, camera);

// set up the next call
requestAnimationFrame(update);
}        

Check out a fiddle of my code

Answer №1

To ensure your hitbox works effectively, remember to include it in the particle by using particle.add(particle.hitbox). In this scenario, setting the hitbox position as (0, 0, 0) is sufficient since it will align with its parent object's location. If the hitbox is a child of the parent particle, you can also access it through particle.children.

Alternatively, instead of relying on a raycaster, you can consider checking if any particles are within a specific range of the cursor's 2D position and then iterate through them to apply pushing forces. This method may be more straightforward when dealing with interactions involving multiple particles simultaneously. I hope this explanation proves helpful!

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

When the page is scrolled to 50 pixels, a modal pop-up will appear

I attempted to use cookies to store a value when the user clicks on a popup to close it, ensuring that the popup does not show again once closed. However, I am encountering an issue where the popup continues to open whenever I scroll, even after closing it ...

The Node module's package.json does not have a main "exports" defined

After recently adding the zx NPM package to my project, I encountered a puzzling issue. The installation went smoothly, and I proceeded to import it into my code: import { $ } from 'zx' (async () => { await $`mkdir test` })() However, u ...

An Uncaught TypeError is thrown when using setTimeout()

Currently, I am configuring the .hover() function in the code below: $(".portfolio_overlay").hover(function(){ setTimeout(function(){ $(this).fadeTo(750, 0.72, "swing", function(){}); }); }); An error is being displayed on the console: U ...

Refresh the div by clicking it

$(window).load(function() { $("#Button").click(function() { alert('clicked') $("#div").load(" #div > *"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script ...

three.js - The backside texture of the cube is vertically inverted

I'm currently working on creating a spinning cube with textures. I want the cube to rotate back and forth along its x- and y-axis using controls (arrow images that trigger rotation on mouseover). However, when rotating it along the x-axis, the texture ...

When trying to call a function inside jQuery's $.post, undefined is not recognized as an object

My attemptSearch function utilizes jQuery $.post to retrieve JSON results, but I'm encountering an error The error states: Undefined is not an object This error occurs on the call this.getSearchResults.bind(this) Interestingly, I have a simi ...

Uncovering classes and selectors in CSS files that match an element with JavaScript

Trying to explain my idea with an example since it's a bit tricky. Imagine we have this HTML code: <ul> <li id="myli" class="myclass">Hello</li> </ul> along with the corresponding CSS: .myclass{ color:red; } li.m ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

What is the best way to reset the selected label in a React Material AutoComplete component when the state is

I currently have a state declared as: const [searchEntryNo, setSearchEntryNo] = useState(''); In addition, there is a function set up to clear the state when needed. const handleClear = () => { setSearchEntryNo(''); }; Ne ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

When you're downloading a file in Safari, the filename ends up being displayed as 'unidentified'

I am encountering an issue with the code I implemented that downloads a file in Safari, but the filename appears as 'untitled'. Interestingly, it works fine in other browsers. var saveData = (function () { var base64 = "data:application/mswo ...

Is there a way to incorporate multiple conditions into the ternary operator in React Native?

When the item is of diaryClass.name "pack" in react native, if diaryId is 778 I want to render chicken, 776 renders burger, and 775 renders pizza. However, my code only displays the chicken value while burger and pizza are not displayed. How can I correct ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Tips for generating a list of sorted indexes by value within an object

In my project, I have multiple objects named stations, each containing a property called money. stations[0].money = 2000 stations[1].money = 500 stations[2].money = 1200 stations[3].money = 2200 My goal is to create an array of station indexes (0, 1, 2, ...

Error on my React website: Exceeded the maximum call stack size

I am currently utilizing the useEffect hook within my React component to update a local state whenever there is a change in the global redux state. The issue arises in my component when trying to update imgList upon receiving updated photos using useSelec ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

I'm having trouble locating the airtable module, even after I successfully ran npm install airtable

Currently attempting to integrate the airtable api into my website's backend using node.js. However, upon writing var Airtable = require('airtable'); and running the file with node [filepath], I encounter an error in the command prompt: ...

What is the method for incorporating a CSRF token into BootstrapTable when using the POST data method?

How can I include a CSRF token in bootstrapTable when using the POST method for data? I am working on a project and trying to add a CSRF token in bootstrapTable. There is some information about CSRF on bootstrap-table.com. Can anyone help me with this iss ...