I’m recently working on an assignment where I must build a 3D game for the ipad or Android Tablet. The problem that I must resolve is how to detect collision using the multitouch screen in a 3D environment.
Every 3D environment has an camera that has interested information about the frustum (field of view) and position. The first problem is the conversion from 2D screen into a 3 dimensional space. I need to look-up the unit specs of opengl in order to make a successful conversion from floating points to a location that is pixel based.
1. Conversion (may differ if you use a specific engine).
When we have successfully established a begin point we can then make a end point by using the z-axis in the 3 dimensional space. The next problem is how to detect an intersection with a object using the 3D line constructed using as begin point your finger (2D screen) -> converted into 3D space (using position/center and conversion method). End point defined by a z-axis number (positionCam.z + 1000.0f).
2. Calculate if there is a intersection
The final problem you will face is how to return a pointer towards the object that intersect with the 3D line. There are multiple objects in a 3D environment. It is important that you manage those objects probably in a list or linked list (if you dynamically want to add objects). In my game I use a list with a defined amount of objects. There is no need for a linked list because certain objects will appear on the exact same location when destroyed by the game logic in the code.
3. Return the object who has a intersection with the line.
I described a bit in pseudo how to resolve the problem. Now it’s time to begin with the method’s and calculations. I will be using just a plain simple raycast method.
1. Define Starting position (pseudo)
Event touch called
Get the location (2D position screen)
Get Camera position
Get Perspective Camera
Use Perspective and position to detern the begin position of the line
End Position used with axis z = CamPos.z + 1000.0f.
Use vector on method Collision
Collision check if any objects are in a area around using the 2D method of collision
check x and y.
return object (pointer)
1. Define starting position (c++)
<code will be published soon
>