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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The simplest option would be to use the euclidean distance between the two objects, using Vector3’s distanceTo() or distanceToSquared functions.
e.g.
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.
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.