I'm currently using three.js to develop a simulation of Brownian Motion, but I've hit a roadblock when it comes to getting the tiny molecules to collide with each other. This is the snippet I have at the moment:
function intersects(sphere, other){
var distance = Math.sqrt((sphere.position.x - other.position.x) * (sphere.position.x - other.position.x) +
(sphere.position.y - other.position.y) * (sphere.position.y - other.position.y) +
(sphere.position.z - other.position.z) * (sphere.position.z - other.position.z));
if(distance < 4){
return true;
} else {
return false;
}
}
function checkCollision(current){
for(var i = 0; i < balls.length; i++) {
if(intersects(balls[current], balls[i]) == true){
// balls[current].velocity.negate();
alert('hey');
}
}
}
Even though the code is running, none of the balls seem to actually collide or intersect with each other, yet an alert box keeps popping up. I tried checking if the distance was less than (sphere.radius + other.radius), but that didn't work either. Keeping it '< 4' does affect performance, causing it to drop to around 5 fps or lower. The checkCollision function is executed every frame during the animation.
function animate(){
for(var i = 0; i < balls.length; i++){
balls[i].position.add(balls[i].velocity);
checkWallBoundaries(i);
checkCollision(i);
}
THREEx.WindowResize(renderer, camera);
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
stats.update();
}
I'm stuck on why this collision detection isn't functioning properly. Any assistance would be greatly appreciated.
edit: After uncommenting the balls[current].velocity.negate() line, this is what happens . The balls oscillate back and forth, but they're nowhere near each other. It's puzzling as to why collisions are being triggered in this scenario.