Ray picking

It would be great if we could interact with the game objects. In a 2D scene, it is easy as we can map the 2D coordinates of the game object with the input coordinates. However, in a 3D game, it is different as the game object is positioned in 3D world coordinates and the input is available as 2D screen coordinates. A familiar scenario is a first person shooter game, wherein on shooting the bullet it is traced through the scene until a collision is detected. Ray picking is the process of shooting a line or ray from the camera through the 2D view port into the 3D game world until it hits an object, as shown here:

Ray picking

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.

Note

Here, for simplicity, we extended the CameraInputController class. However, in your game, you need to implement your own event handler, InputListerner or InputAdapter class as learned in Chapter 3, Configuring the Game. To understand more about event handling, visit https://github.com/libgdx/libgdx/wiki/Event-handling.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset