Appendix 5: Camera Control

Below are some examples of programming your own camera control. The code is meant to be called every frame.

First Person Camera

            if (env.getKeyDown(Keyboard.KEY_W)) {
                env.setCameraXYZ(env.getCameraX()-step*Math.sin(Math.toRadians(env.getCameraYaw())),
                                    env.getCameraY(),
                                    env.getCameraZ()-step*Math.cos(Math.toRadians(env.getCameraYaw())));
            }
           
            if (env.getKeyDown(Keyboard.KEY_S)) {
                env.setCameraXYZ(env.getCameraX()+step*Math.sin(Math.toRadians(env.getCameraYaw())),
                                    env.getCameraY(),
                                    env.getCameraZ()+step*Math.cos(Math.toRadians(env.getCameraYaw())));
            }
           
            if (env.getKeyDown(Keyboard.KEY_A)) {
                env.setCameraXYZ(env.getCameraX()-step*Math.cos(Math.toRadians(env.getCameraYaw())),
                                    env.getCameraY(),
                                    env.getCameraZ()+step*Math.sin(Math.toRadians(env.getCameraYaw())));
            }
            if (env.getKeyDown(Keyboard.KEY_D)) {
                env.setCameraXYZ(env.getCameraX()+step*Math.cos(Math.toRadians(env.getCameraYaw())),
                                    env.getCameraY(),
                                    env.getCameraZ()-step*Math.sin(Math.toRadians(env.getCameraYaw())));
            }
           
            double newPitch = env.getCameraPitch()+env.getMouseDY();
            
            // Restrict the pitch to within a "reasonable" amount
            if (newPitch > 70) {
                env.setCameraPitch(70);
            } else if (newPitch < -50) {
                env.setCameraPitch(-50);
            } else {
                env.setCameraPitch(newPitch);
            }
           
            env.setCameraYaw(env.getCameraYaw()-env.getMouseDX());

3rd Person Camera (a.k.a. chase cam)

            // assuming that doty1 is your player object
            env.setCameraXYZ(doty1.getX() - 2 * Math.sin(Math.toRadians(doty1.getRotateY())),
                    doty1.getY()+2,
                    doty1.getZ() - 2 * Math.cos(Math.toRadians(doty1.getRotateY())));

            env.setCameraYaw(doty1.getRotateY() - 180);