Game Development Reference
In-Depth Information
We will now add a toggle key to choose whether the arrow keys should control the
player character or the camera. The camera should follow the player's character
while being in the player control mode. Otherwise, the camera can be freely moved
around. We will also add another key to let the player character jump.
Let's begin with the camera that is set to follow the player character at the start
of the level. Add the highlighted line of code to the
initLevel()
method of
WorldController
:
private void initLevel () {
score = 0;
level = new Level(Constants.LEVEL_01);
cameraHelper.setTarget(level.bunnyHead);
}
Next, change the
handleDebugInput()
and
keyUp()
methods of
WorldController
:
private void handleDebugInput (float deltaTime) {
if (Gdx.app.getType() != ApplicationType.Desktop) return;
if (!cameraHelper.hasTarget(level.bunnyHead)) {
// Camera Controls (move)
float camMoveSpeed = 5 * deltaTime;
float camMoveSpeedAccelerationFactor = 5;
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT))
camMoveSpeed *= camMoveSpeedAccelerationFactor;
if (Gdx.input.isKeyPressed(Keys.LEFT))
moveCamera(-camMoveSpeed, 0);
if (Gdx.input.isKeyPressed(Keys.RIGHT))
moveCamera(camMoveSpeed, 0);
if (Gdx.input.isKeyPressed(Keys.UP))
moveCamera(0, camMoveSpeed);
if (Gdx.input.isKeyPressed(Keys.DOWN))
moveCamera(0, -camMoveSpeed);
if (Gdx.input.isKeyPressed(Keys.BACKSPACE))
cameraHelper.setPosition(0, 0);
}
// Camera Controls (zoom)
...
}
@Override
public boolean keyUp (int keycode) {
// Reset game world