threejs操纵粒子系统

时间:2014-06-12 09:39:36

标签: javascript three.js onmousemove

我有一个问题是检测我的鼠标是否在粒子上方以将其推离鼠标 使用threejs中的粒子系统

我使用raycaster但没有任何东西击中。

我也尝试向粒子添加一个命中空间,但是命中箱不会跟随粒子。

    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);
}

onmousemove功能

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


//controle
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);



 }

更新功能

   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);
}        

我的代码fiddle

1 个答案:

答案 0 :(得分:0)

要让您的hitbox正常运行,请确保使用particle.add(particle.hitbox)将其添加到粒子中。在这种情况下,hitbox位置很好(0,0,0),因为它将被添加到其父对象的确切位置。当hitbox是父粒子的子粒子时,也可以使用particle.children引用它。

否则,与使用raycaster相反,您可能会尝试检查是否有任何粒子落在光标2D位置的特定范围内,并遍历边界内的粒子以推开。当需要同时与多个粒子交互时,这可能是更容易的选择。希望有所帮助!