[英]Can't detect collision in 3D JavaScript
I am using three.js to make a simulation of the Brownian Motion and I'm stuck on a part where I need to get the little molecules to collide against each other. 我正在使用three.js进行布朗运动的仿真,并且被困在需要使小分子相互碰撞的部分上。 This is what I have so far:
这是我到目前为止的内容:
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');
}
}
}
When I run the code, I know for certain that the balls don't collide/intersect with each other, however I continuously get an alert box. 当我运行代码时,我肯定知道球不会相互碰撞/相交,但是我不断收到警告框。 I've tried to check if it's less than (sphere.radius + other.radius) but I don't think that's correct since it didn't seem to work.
我试图检查它是否小于(sphere.radius + other.radius),但由于它似乎没有用,所以我认为这是不正确的。 Also when I do keep it '< 4', it messes up the performance and it starts to run slowly at around 5 fps or less.
另外,当我确实将其保持为“ <4”时,它会破坏性能,并开始以约5 fps或更低的速度缓慢运行。 checkCollision gets used here during the animation, so basically it checks it every time.
在动画制作过程中会在这里使用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();
}
I don't know why I can't get this to work. 我不知道为什么我不能使这个工作。 If someone could help me, that'd be greatly appreciated.
如果有人可以帮助我,将不胜感激。
edit: Here's a picture of what happens when I uncomment the balls[current].velocity.negate() line https://puu.sh/uG1eS.png . 编辑:这是当我取消注释球时的图片[current] .velocity.negate()行https://puu.sh/uG1eS.png 。 The balls keep going back and forth but they're not even remotely close to each other, so I don't know why collision is being detected
球不断地来回运动,但是它们彼此之间的距离甚至都不遥远,所以我不知道为什么要检测到碰撞
Every ball collides with itself. 每个球都会相互碰撞。 You need to exclude
i === current
您需要排除
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.