[英]Can't detect collision in 3D JavaScript
我正在使用three.js进行布朗运动的仿真,并且被困在需要使小分子相互碰撞的部分上。 这是我到目前为止的内容:
function intersects(sphere, other){ //check if the distance between one sphere and the other is less than radius of both (4)
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');
}
}
}
当我运行代码时,我肯定知道球不会相互碰撞/相交,但是我不断收到警告框。 我试图检查它是否小于(sphere.radius + other.radius),但由于它似乎没有用,所以我认为这是不正确的。 另外,当我确实将其保持为“ <4”时,它会破坏性能,并开始以约5 fps或更低的速度缓慢运行。 在动画制作过程中会在这里使用checkCollision,因此基本上每次都会对其进行检查。
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();
}
我不知道为什么我不能使这个工作。 如果有人可以帮助我,将不胜感激。
编辑:这是当我取消注释球时的图片[current] .velocity.negate()行https://puu.sh/uG1eS.png 。 球不断地来回运动,但是它们彼此之间的距离甚至都不遥远,所以我不知道为什么要检测到碰撞
每个球都会相互碰撞。 您需要排除i === current
for(var i = 0; i < balls.length; i++) {
if(current === i) continue;
if(intersects(balls[current], balls[i]) == true){
alert('hey');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.