X, Y, Z Camera Code
X, Y, Z Camera Code
variables.
For now it just has code samples...
X, Y, Z camera code
' Data
dim camX#, camY#, camZ#, camAng# ' Camera position and direction
dim x, z ' Working variables
camX# = 135
camZ# = 50
' Main loop
while true
' Clear screen
glClear (GL_DEPTH_BUFFER_BIT or GL_COLOR_BUFFER_BIT)
glLoadIdentity ()
' Position camera
glRotatef (-camAng#, 0, 1, 0)
glTranslatef (-camX#, -camY#, -camZ#)
' Draw a city of pyramids
for z = 1 to 10
glPushMatrix ()
for x = 1 to 10
glBegin (GL_TRIANGLE_FAN)
glColor3f (0,.5, 1): glVertex3f ( 0, 10, 0)
glColor3f (1, 0, 0): glVertex3f (-10,-10, 10)
glColor3f (1, 1, 1): glVertex3f ( 10,-10, 10)
glColor3f (0, 0, 1): glVertex3f ( 10,-10,-10)
glColor3f (0, 1, 0): glVertex3f (-10,-10,-10)
glColor3f (1, 0, 0): glVertex3f (-10,-10, 10)
glEnd ()
glTranslatef (30, 0, 0)
next
glPopMatrix ()
glTranslatef (0, 0, -30)
next
SwapBuffers ()
' Move camera
while SyncTimer (10)
if ScanKeyDown (VK_LEFT) then camAng# = camAng# + 1: endif
if ScanKeyDown (VK_RIGHT) then camAng# = camAng# - 1: endif
if ScanKeyDown (VK_UP) then
camX# = camX# - sind (camAng#) * .5
camZ# = camZ# - cosd (camAng#) * .5
endif
if ScanKeyDown (VK_DOWN) then
camX# = camX# + sind (camAng#) * .5
camZ# = camZ# + cosd (camAng#) * .5
endif
wend
wend
Advantages.
2 lines of code saved.
No sin and cos math required.
Vector math describes more clearly what we are trying to do. That is:
Take a vector facing forward (vec3(0, 0, -1))
Rotate it around the Y axis by the camera angle#
Scale it to .5 units
Add it to the camera's previous position.
Here we construct an offset vector, and set offset#(0) to the X (left/right) direction of travel, and
offset#(2) to the Z (forward/backward).
We then use vector mathematics to rotate it around the Y axis by the camera angle and add it to the
camera's previous position.
Vector mathematics made this possible, and not too hard to understand. A camX#, camY#, camZ#
approach would have been a lot more mathematics intensive.
Notice how simple it was to add tilting up/down to the camera and the camera's movement.
We simply inserted a rotation around the X axis in at the appropriate position.
A lot easier than trying to figure out the mathematics for camX#, camY# and camZ# variables