Tutorials › dbpro Professional
First-person camera
Look with the mouse, walk with W, A, S and D: the controls of every first-person game.
Mouse look
MOUSEMOVEX and MOUSEMOVEY return how far the mouse moved since the last call, which
is what turning needs. Keep yaw (left-right) and pitch (up-down) in variables, and clamp the pitch so
the player cannot look past straight up or down. HIDE MOUSE hides the pointer.
fps_camera_look.dba excerptDownload
yaw# = wrapvalue(yaw# + mousemovex() * 0.2)
pitch# = pitch# + mousemovey() * 0.2
if pitch# > 80 then pitch# = 80
if pitch# < -80 then pitch# = -80
rotate camera pitch#, yaw#, 0WASD
KEYSTATE reads any key by its scancode: 17 is W, 31 is S, 30 is A and 32 is D.
Forward and sideways come from the yaw with SIN and COS. Moving on the ground plane
only, rather than with MOVE CAMERA, keeps the player from flying when looking up.
fps_camera_walk.dba excerptDownload
x# = camera position x() + sin(yaw#) * speed# + cos(yaw#) * side#
z# = camera position z() + cos(yaw#) * speed# - sin(yaw#) * side#
position camera x#, 12, z#fps_camera.dbaDownload
rem First-person camera - OpenDBC tutorial (DarkBASIC Professional)
sync on : sync rate 60
autocam off
hide mouse
color backdrop rgb(140, 180, 225)
fog on : fog color rgb(140, 180, 225) : fog distance 400
rem A floor and a forest of crates
make object box 1, 600, 1, 600
color object 1, rgb(70, 115, 70)
for n = 2 to 40
make object cube n, 10 + rnd(10)
position object n, rnd(400) - 200, 8, rnd(400) - 200
yrotate object n, rnd(90)
color object n, rgb(150 + rnd(60), 120 + rnd(40), 80)
next n
yaw# = 0.0 : pitch# = 0.0
position camera 0, 12, -150
do
rem The mouse turns the head; MOUSEMOVEX/Y are the movement since last call
yaw# = wrapvalue(yaw# + mousemovex() * 0.2)
pitch# = pitch# + mousemovey() * 0.2
if pitch# > 80 then pitch# = 80
if pitch# < -80 then pitch# = -80
rem W/S walk, A/D step sideways (scancodes 17, 31, 30, 32)
speed# = 0.0 : side# = 0.0
if keystate(17) = 1 then speed# = 1.5
if keystate(31) = 1 then speed# = -1.5
if keystate(30) = 1 then side# = -1.5
if keystate(32) = 1 then side# = 1.5
rem Nobody at the keyboard? Take a slow walk around
if speed# = 0 and side# = 0 and mouseclick() = 0
yaw# = wrapvalue(yaw# + 0.3) : speed# = 0.8
endif
rem Move on the ground plane only, so looking up does not make us fly
x# = camera position x() + sin(yaw#) * speed# + cos(yaw#) * side#
z# = camera position z() + cos(yaw#) * speed# - sin(yaw#) * side#
position camera x#, 12, z#
rotate camera pitch#, yaw#, 0
text 10, 10, "Mouse: look W A S D: walk"
sync
loopTry this
- Run with Shift:
SHIFTKEY. - Stop at the crates with
INTERSECT OBJECTbefore moving. - Change the field of view with
SET CAMERA FOVfor a zoom.