Game Development Reference
In-Depth Information
The following code will explain the process of ray picking in LibGDX. We will
extend and update CameraInputController in the create() function as follows:
@Override
public void create() {
...
final BoundingBox box= model.calculateBoundingBox(new
BoundingBox());
camController = new CameraInputController(cam) {
private final Vector3 position = new Vector3();
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int
button) {
Ray ray = cam.getPickRay(screenX, screenY);
for (int i = 0; i < instances.size; i++) {
ModelInstance instance = instances.get(i);
instance.transform.getTranslation(position);
if (Intersector.intersectRayBoundsFast(ray, position,
box.getDimensions())) {
instances.removeIndex(i);
i--;
}
}
return super.touchUp(screenX, screenY, pointer, button);
}
};
Gdx.input.setInputProcessor(camController);
}
Here, in touchUp() , the getPickRay() function creates a ray from the input
coordinates. Now, we iterate through all the instances to check whether that ray
hits an object. LibGDX provides a class Intersector that offers various static
methods for intersection checking between different geometric objects. In order
to check whether the ray collides with any game objects, we use the function
intersectRayBoundsFast() . On collision, we remove that model instance from the
instances array so when you touch any car in the game scene, it simply vanishes.
 
Search WWH ::




Custom Search