Reputation: 40709
I have 2 simple 3D objects in my scene (a sphere and a cube), and I would like to detect if they are colliding or not.
How can this be achieved?
Upvotes: 3
Views: 4671
Reputation: 1462
Unfortunately, three.js doesn't have any collision detector: Collision detection?.
I think you need to use plugin libraries. Like this: http://yomotsu.github.com/threejs-examples/cannonjs_box/.
Upvotes: 2
Reputation: 51837
The simplest option would be to use the euclidean distance between the two objects, using Vector3's distanceTo() or distanceToSquared functions.
e.g.
console.log(yourCube.position.distanceToSquared(yourSphere.position));
If the distance between the two objects is greater than the sum between of the sphere's radius and cube's side, then that would be a potential collision. I'm also suggesting distanceToSquared because it's faster(since it's not calling sqrt) and it's still useful to check for collisions.
Note that this method is not super exact - it's essentially checking collisions between two spheres (estimating the cube as a sphere with the radius equal to half the cube side), but I'm hoping it's close/good enough for your setup since it's the easiest and fastest to implement in my opinion.
You might notice that the corners of the cube will be colliding without triggering a collision until a certain distance. You can adjust a 'threshold' by passing a different cube side ratio. Imagine a sphere around your cube and how large should that sphere's ratio be to get a decent estimated collision for your setup.
Another method that comes to mind is to find the point on the sphere closest to the cube:
e.g.
var pointOnSphere = yourSphere.position.clone().sub(yourCube.position).normalize(). multiplyScalar(yourSphereRadius);
This if off the top of my head, so I can't guarantee the above snippet will work, might be worth placing a particle at pointOnSphere's coordinates to check first.
There are other more advanced collision detection algorithms in 3D you can check out in this book, but it's best to keep things as simple/fast as possible.
Upvotes: 6