Android collision detection opengl-es
This gave me a headache for several days, so I finally accepted defeat and am going to ask here.
My game consists of cubes of different sizes that need to be moved around in a small area. I have the cube movement working fine, the only thing I can't show with my head is collision detection.
The earth is completely flat, so I don't have to worry about the y-axis, the coordinates of the cube relative to the center of the cube at ground level. I should probably also add that each level is made up of several rectangular ground planes that are next to each other.
Any suggestions on how this can be done (pseudocode is fine) with minimal cpu usage is welcome. Many thanks.
source to share
Collision detection is very easy with things like cubes or spheres.
you can use a sphere to detect a sphere, which basically draws an imaginary sphere around the cubes and then checks if the distance between the two center points of the spheres is less than the radius of the sphere. So: -
float x, y, z;
x = SmallModel->GetX() - LargeModel->GetX();
y = SmallModel->GetY() - LargeModel->GetY();
z = SmallModel->GetZ() - LargeModel->GetZ();
float collisionDist = sqrt( x*x + y*y + z*z );
if (collisionDist < sphereRadius)
{
// Collision occurredβ¦
}
or you can use bounding boxes, which are more appropriate here, as the above is not so accurate when the bounding boxes are accurate, since you are using cubes and they are axially aligned.
The process here is also quite simple: a collision occurs if the minimum and maximum of each cube lie within each other. That is, a collision if:
Cube1XMin > Cube2XMin && Cube1XMax < Cube2XMax &&
Cube1YMin > Cube2YMin && Cube1YMax < Cube2YMax &&
Cube1ZMin > Cube2ZMin && Cube1ZMax < Cube2ZMax
so you need to declare 6 variables for each cube as above and these minimum and maximum values ββare found by first knowing the size of the cube and secondly knowing the position of the cubes.
So, if the cube is 10 * 10 * 10 and is located at 100.0 100
then xmin = 95 ymin = -5 zmin = 95 xmax = 105 ymax = 5 zmax = 105
find the values ββfor the other cubes and run the above equation and you should figure out if you have a collision.
To handle the collision you need to move the cubes back into the frame earlier and then maybe bring them back in, I think it is possible to get stuck inside each other if you don't bring them back in the frame.
To save on CPU usage, you can probably send the computation to the GPU using shaders, but that's a different topic.
source to share