Example: Rotating Cube

The Cube program uses Fastgraph's 3D geometry system and polygon backface removal to draw a 40x40x40 cube, with each face of the cube drawn in a different color. Unlike the Geometry example, you can move the cube in 3D world space and rotate the cube about its own object space axes through keyboard controls. The four arrow keys move the cube in 3-unit increments along the world space x and y axes, while the + and - keys move the cube toward or away from the viewer in 3-unit increments along the world space z axis. The x, y, and z keys rotate the cube in 6 increments counterclockwise around the corresponding object space axis; pressing shift with these keys rotates the cube clockwise.

The Cube program uses a 640x480 virtual buffer whose color depth is the same as the display color depth. Initially, the cube is centered on the z-axis at z=100 with no rotation, so we see only its front face (the pink face). Using the animation-based form of the message loop, the program's CheckForMovement() function checks for any keystrokes that control the cube's movement, and if necessary, redraws the cube at its new position and orientation. Cube sets the render state to enable 3D clipping, so cube faces will completely or partially disappear as they move behind the viewer.

CheckForMovement() first tests for 3D movement using the + key, - key, and the four arrow keys. The movement occurs in 3-unit increments, so if one of these keys is pressed, we add or subtract 3 from the variables xWorld, yWorld, or zWorld. CheckForMovement() next checks for 3D rotations. The x, y, and z keys rotate the cube counterclockwise around its corresponding object space axis; pressing shift with these keys rotates it clockwise. In all cases, the rotation occurs in 6 increments, and we keep track of the current rotation angles in the variables xAngle, yAngle, and zAngle. If we modify any of these six variables, we set Redraw to TRUE so CheckForMovement() will draw the updated cube.

If the cube's position or rotation changes in the current frame, CheckForMovement() then redraws the cube to reflect these changes. When this occurs, we first fill the virtual buffer with white pixels, which of course erases the previous frame. Next we call fg_3Dsetobject() with the new position and rotation values, and then we call the program's DrawCube() function to draw the resulting cube, with backface removal. Finally, we call fg_vbscale() to display what we just drew, and set Redraw to FALSE in preparation for the next frame.

C/C++ version

C++Builder version

Delphi version

Visual Basic version

<< Prev

Next >>

Fastgraph Home Page


copyright 2001 Ted Gruber Software, Inc.