# Connexions

You are here: Home » Content » GAME 2302-0105: Getting Started

### Recently Viewed

This feature requires Javascript to be enabled.

# GAME 2302-0105: Getting Started

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Examine two sample programs and a sample game-programming math library intended to provide aspiring game programmers with the mathematical skills required for game programming.

## Preface

This module is one in a collection of modules designed for teaching GAME2302 Mathematical Applications for Game Development at Austin Community College in Austin, TX.

### General

Good math skills are required

In order to be a successful game programmer you must be skilled in technologies other than simply programming. Those technologies include mathematics. My purpose in writing this module is to help you to gain mathematical strengths in addition to your other strengths.

This collection is designed to teach you some of the mathematical skills that you will need (in addition to good programming skills) to become a successful game programmer. In addition to helping you with your math skills, I will also teach you how to incorporate those skills into object-oriented programming using Java. If you are familiar with other object-oriented programming languages such as C#, you should have no difficulty porting this material from Java to those other programming languages.

Lots of graphics

Since most computer games make heavy use of either 2D or 3D graphics, you will need skills in the mathematical areas that are required for success in 2D and 3D graphics programming. As a minimum, this includes but is not limited to skills in:

1. Geometry
2. Trigonometry
3. Vectors
4. Matrices
5. 2D and 3D transforms
6. Transformations between coordinate systems
7. Projections

Game programming requires mathematical skills beyond those required for graphics. This collection will concentrate on items 3, 4, and 5 in the above list. (I will assume that you either already have, or can gain the required skills in geometry and trigonometry on your own. There are many tutorials available on the web to help you in that quest including the Brief Trigonometry Tutorial at http://cnx.org/content/m37435/latest/ .)

Insofar as vectors and matrices are concerned, I will frequently refer you to an excellent interactive tutorial titled Vector Math for 3D Computer Graphics by Dr. Bradley P. Kjell for the required technical background. I will then teach you how to incorporate the knowledge that you gain from Kjell's tutorial into Java code with a heavy emphasis on object-oriented programming.

In the process, I will develop and explain a game-programming math library that you can use to experiment with and to confirm what you learn about vectors and matrices from the Kjell tutorial. The library will start out small and grow as we progress through more and more material in subsequent modules.

I will also provide exercises for you to complete on your own at the end of most of the modules. Those exercises will concentrate on the material that you have learned in that module and previous modules.

### Viewing tip

II recommend that you open another copy of this module in a separate browser window and use the following links to easily find and view the Images and Listings while you are reading about them.

#### Images

• Image 1 . Graphics illustration of four points and two lines.
• Image 2 . First of three views in the construction of a 3D human figure.
• Image 3 . Second of three views in the construction of a 3D human figure.
• Image 4 . Third of three views in the construction of a 3D human figure.
• Image 5 . Screen output from the program named PointLine02.
• Image 6 . Sample output from updated programming-math library.
• Image 7 . Graphic output from Exercise 1.
• Image 8 . Text output from Exercise 2.
• Image 9 . Text output from Exercise 3.

## Preview

In this module, I will introduce you to an excellent interactive tutorial titled Vector Math for 3D Computer Graphics written by Dr. Bradley P. Kjell, (which you can also download in zip-file format from a link in the first module in this collection) . Then I will present and explain two sample programs and a sample game-programming math library intended to implement concepts from Dr. Kjell's tutorial in Java code.

## Discussion and sample code

### Points, lines, and vectors

Your homework assignment from the previous module was to study CHAPTER 0 -- Points and Lines and also to study CHAPTER 1 -- Vectors, Points, and Column Matrices down through the topic titled Variables as Elements in Kjell's tutorial.

You may have previously believed that you already knew all there was to know about points and lines. However, I suspect that you found explanations of some subtle issues that you never thought about before when studying those tutorials. In addition, Kjell begins the discussion of vectors and establishes the relationship between a vector and a column matrix in this material.

Represent a point with a column matrix

Hopefully you understand what Kjell means by a column matrix and you understand that a column matrix can be used to represent a point in a given coordinate frame. The same point will have different representations in different coordinate frames. (You must know which coordinate frame is being used to represent a point with a column matrix.)

### Writing, compiling, and running Java programs

One of the reasons that I chose Java as the main programming language for this course is that while Java is a very powerful object-oriented programming language, the mechanics of writing, compiling, and running Java programs are very simple.

First you need to confirm that the Java development kit (jdk) version 1.7 or later is installed on the computer. (The jdk is already installed in the CIT computer labs at the NRG campus of ACC, and perhaps in the labs on other ACC campuses as well.) If you are working at home, see Oracle's JDK 7 and JRE 7 Installation Guide .

Next, you need to use any text editor to create your Java source code files as text files with an extension of .java. (I prefer the free JCreator editor because it produces color-coded text and includes some other simple IDE features as well. JCreator is normally installed in the CIT computer labs at the NRG campus of ACC.)

The name of each source code file should match the name of the Java class defined in the file.

Assume that your source code file is named MyProg.java . You can compile the program by opening a command prompt window in the folder containing the source code file and executing the following command at the prompt:

#### Note:

Command to compile the source code:
javac MyProg.java


Once the program is compiled, you can execute it by opening a command prompt window in the folder containing the compiled source code files (files with an extension of .class) and executing the following command at the prompt:

#### Note:

Command to execute the program:
java MyProg

Using a batch file

If you are running under Windows, the easiest approach is to create and use a batch file to compile and run your program. (A batch file is simply a text file with an extension of .bat instead of .txt.)

Create a text file named CompileAndRun.bat containing the text shown in the note-box below.

#### Note:

Contents of batch file are shown below:

del *.class
javac MyProg.java
java MyProg
pause


Place this file in the same folder as your source code files. Then double-click on the batch file to cause your program to be compiled and executed.

That's all there is to it.

### The program named PointLine01

Before we go any further, let's take a look at a simple Java program that illustrates one of the ways that points and lines are represented in Java code. (See Image 1 .)

The Point2D.Double class

This program illustrates one implementation of the concepts of point and line segment in Java code.

Four points (locations in space) are defined by passing the coordinates of the four points as the x and y parameters to the constructor for the Point2D.Double class. This results in four objects of the Point2D.Double class.

( Point2D.Double is a class in the standard Java library.)

The Line2D.Double class

Two line segments are defined by passing pairs of points as parameters to the constructor for the Line2D.Double class. This results in two objects of the Line2D.Double class.

( Line2D.Double is a class in the standard Java library.)

#### Note:

Testing:

All of the programs in this module were tested using JDK 1.7 running under Windows XP.

The draw method

The draw method belonging to an object of the Graphics2D class is used to draw the two line segments on a Canvas object for which the origin has been translated to the center of the Canvas . The result is shown in Image 1 .

( Graphics2D and Canvas are classes in the standard Java library.)

The coordinate values of the points and the selection of point-pairs to specify the ends of the line segments is such that the final rendering is a pair of orthogonal lines that intersect at the origin.

(You could think of these lines as the axes in a Cartesian coordinate system.)

Will explain in fragments

I will present and explain this program in fragments. A complete listing of the program is provided in Listing 14 near the end of the module.

(Use the code in Listing 14 and the instructions provided above to write, compile, and run the program. This will be a good way for you to confirm that Java is properly installed on your computer and that you are able to follow the instructions to produce the output shown in Image 1 .)

The first code fragment is shown in Listing 1 .

2
Listing 1: The controlling class named PointLine01.
class PointLine01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine01


Listing 1 shows the definition of the controlling class, including the main method for the program named PointLine01 .

The main method simply instantiates a new object of a class named GUI and saves that object's reference in the variable named guiObj.

(GUI is not a class in the standard Java library. It is defined below.)

The GUI object produces the screen image shown in Image 1 .

The class named GUI

Listing 2 shows the beginning of the class named GUI , including the constructor for the class.

3
Listing 2: Beginning of the class named GUI.
class GUI extends JFrame{
//Specify the horizontal and vertical size of a JFrame
// object.
int hSize = 200;
int vSize = 200;

GUI(){//constructor

//Set JFrame size and title
setSize(hSize,vSize);
setTitle("R.G.Baldwin");

//Create a new drawing canvas and add it to the
// center of the JFrame.
MyCanvas myCanvas = new MyCanvas();

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

}//end constructor


Listing 2 begins by declaring and initializing a pair of instance variables that will be used to specify the size of the JFrame shown in Image 1 .

(A JFrame object in Java might be called a window in other programming environments.)

The constructor for the class named GUI

The constructor begins by using the two instance variables to set the size of the JFrame and by setting the title for the JFrame to R.G.Baldwin .

Create a new drawing canvas and add it to the center of the JFrame

Then the constructor instantiates a Canvas object and adds it to the JFrame . Without getting into the details as to why, I will simply tell you that the Canvas object fills the entire client area of the frame, which is the area inside of the four borders.

Define the behavior of the X-button and make the JFrame visible

Finally, the constructor defines the behavior of the X-button in the top right corner of the JFrame and causes the JFrame to become visible on the screen.

Hopefully, everything that I have discussed so far is familiar to you. If not, you may want to spend some time studying my earlier tutorials in this area. You will find links to many of those tutorials at www.DickBaldwin.com .

Beginning of the inner class named MyCanvas

Listing 3 shows the beginning of an inner class definition named MyCanvas including the beginning of an overridden paint method.

(The Canvas class was extended into the MyCanvas class to make it possible to override the paint method.)

This overridden paint method will be executed whenever the JFrame containing the Canvas is displayed on the computer screen, whenever that portion of the screen needs to be repainted, or whenever the repaint method is called on the canvas.

4
Listing 3: Beginning of the inner class named MyCanvas.
  class MyCanvas extends Canvas{

public void paint(Graphics g){
//Downcast the Graphics object to a Graphics2D
// object. The Graphics2D class provides
// capabilities that don't exist in the Graphics
// class.
Graphics2D g2 = (Graphics2D)g;

//By default, the origin is at the upper-left corner
// of the canvas. This statement translates the
// origin to the center of the canvas.
g2.translate(
this.getWidth()/2.0,this.getHeight()/2.0);


An object of the Graphics class

The paint method always receives an incoming reference to an object of the class Graphics . As a practical matter, you can think of that object as representing a rectangular area on the screen on which the instructions in the paint method will draw lines, images, and other graphic objects.

#### Note:

Incoming reference:

The paint method actually receives a reference to an object of the class Graphics2D , but to maintain backward compatibility, Sun elected to pass it in as the superclass type Graphics .

The Graphics2D class

The Graphics class was defined early in the life of the Java programming language, and it is of limited capability. Later on, Sun defined the Graphics2D class as a subclass of Graphics . Significant new capabilities, (including the ability to deal with coordinate values as real numbers instead of integers) , were included in the Graphics2D class. In order to access those new capabilities, however, it is necessary to downcast the incoming reference to type Graphics2D as shown by the cast operator (Graphics2D) in Listing 3 .

Translate the origin

The last statement in Listing 3 translates the origin from the default position at the upper-left corner of the canvas to the center of the canvas. This is equivalent to creating a new coordinate frame as explained by Kjell.

The default coordinate frame has the origin at the upper-left corner of the canvas. The new coordinate frame has the origin at the center of the canvas.

Note, however, that even though the origin has been translated, the positive vertical direction is still toward the bottom of the canvas.

Define two points as two locations in space

Listing 4 defines two points in space by instantiating two objects of the class named Point2D.Double , and saving references to those objects in variables of the superclass type Point2D .

5
Listing 4: Define two points as two locations in space.
      Point2D pointA =
new Point2D.Double(-this.getWidth()/2.5,0.0);
Point2D pointB =
new Point2D.Double(this.getWidth()/2.5,0.0);


The left and right ends of the horizontal line

The object referred to as pointA represents the location in 2D space at the left end of the horizontal line shown in Image 1 .

As explained by Kjell, the values used to represent this location in space are relative to the current coordinate frame in which the origin is at the center of the canvas. Had the origin not been translated to the center of the canvas in Listing 3 , a different set of values would have been required to represent that same location in space.

Similarly, the object referred to as pointB represents the location in space at the right end of the horizontal line shown in Image 1 .

Construct a line segment

Listing 5 uses the two points described above to construct an object that represents a line segment connecting the two points by instantiating an object of the class named Line2D.Double .

As shown in Image 1 , the values of the points relative to the current coordinate frame causes this line segment to be horizontal when the coordinate frame is displayed with the orientation shown in Image 1 . On the other hand, a different rendering of the coordinate frame may have caused the line segment to be something other than horizontal.

6
Listing 5: Construct a line segment.
      Line2D.Double horizLine =
new Line2D.Double(pointA,pointB);


Not the true line segment

The main point here is that the line segment created in Listing 5 represents a line segment between two points in space but it is not the true line segment. According to Kjell, the true line segment has no width, and therefore is not visible to the human eye.

The line segment constructed in Listing 5 is simply a visual representation of the true line segment. When rendered on the screen, that line segment could take on an infinite number of appearances depending on how the space is rendered on the screen. It just happens that in the case of Image 1 , the rendering of that space on the screen causes the line segment to appear to be parallel to the bottom of a rectangular screen.

Construct an object that represents a vertical line segment

Listing 6 uses a similar procedure to construct an object that represents a line segment that is perpendicular to the previous line segment, and which intersects the previous line segment at the origin of the current coordinate frame.

7
Listing 6: Construct an object that represents a vertical line segment.
      Point2D pointC =
new Point2D.Double(0.0,-this.getHeight()/2.5);
Point2D pointD =
new Point2D.Double(0.0,this.getHeight()/2.5);

Line2D.Double vertLine =
new Line2D.Double(pointC,pointD);


Draw the two lines on the screen

Finally, Listing 7 calls the draw method of the Graphics2D class twice in succession to draw the two lines on the screen as shown in Image 1 .

8
Listing 7: Draw the two lines on the screen.

g2.draw(horizLine);
g2.draw(vertLine);

}//end overridden paint()
}//end inner class MyCanvas
}//end class GUI


Listing 7 also signals the end of the overridden paint method, the end of the inner class named MyCanvas , and the end of the top-level class named GUI .

### But wait, there's something wrong here

Kjell describes his points and lines in a very general way that is suitable for use in mathematical operations later on. However, in the above program, I fell into the trap of defining my points and lines using Java classes that are intended primarily for rendering graphics on the screen. That approach is probably not conducive to mathematical operations. We need to step back and take another look at what we are doing here.

Points, points, and more points

There will be many occasions when you, as a game programmer, will need to define the coordinate values for a point (or a set of points) that you have no intention of displaying on the screen. Instead, you will use those points for various mathematical operations to produce something else that may or may not be displayed on the screen.

The Alice ice skater

For example, Image 2 , Image 3 , and Image 4 show three views in the construction of the Ice skater object in the Alice programming language .

Points as the vertices of triangles

The image in Image 2 shows a graphical representation of a set of points. These points were used to define the vertices of the set of polygons shown i n Image 3 . The polygons, in turn, were used in the construction of the ice skater object shown in Image 4 .

As you can see, neither the points in Image 2 , nor the lines that comprise the sides of the polygons in i n Image 3 appear in the final rendering of the object in Image 4 .

However, both the points and the polygons were required to support the mathematical operations that ultimately resulted in the ice skater object.

(Only the image in Image 4 is typically displayed on the computer screen. I had to do some extra work to cause the points and the lines to be displayed.)

Another look at points and lines

We'll take another look at points and lines, and will introduce column matrices and vectors in the next sample program.

What is a vector?

According to Kjell, "A vector is a geometrical object that has two properties: length and direction." He also tells us, "A vector does not have a position."

In addition, Kjell tells us that we can represent a vector with two real numbers in a 2D system and with three real numbers in a 3D system.

Use a column matrix to represent a vector

A column vector provides a good way to store two real numbers in a computer program. Therefore, in addition to representing a point, a column matrix can also be used to represent a vector.

However, the column matrix is not the vector . The contents of the column matrix simply represent certain attributes of the vector in a particular reference frame. Different column matrices can be used to represent the same vector in different reference frames, in which case, the contents of the matrices will be different.

An absolute location in space

The fact that a column matrix can be used to represent both points and vectors can be confusing. However, as you will see later, this is convenient from a programming viewpoint.

The two (or three) real number values contained in the matrix to represent a point specify an absolute location in space relative to the current coordinate frame.

A vector specifies a displacement

A vector does not have a position. Rather, it has only two properties: length and direction. Kjell tells us that the two (or three) real number values contained in the matrix to represent a vector (in 2D or 3D) specify a displacement of a specific distance from an arbitrary point in a specific direction.

In 2D, the two values contained in the matrix represent the displacements along a pair of orthogonal axes (call them x and y for simplicity) .

As you will see in a future module, in the case of 2D, the length of the vector is the length of the hypotenuse of a right triangle formed by the x and y displacement values.

The direction of the vector can be determined from the angle formed by the x-displacement and the line segment that represents the hypotenuse of the right triangle. Similar considerations apply in 3D as well but they are somewhat more complicated.

The bottom line is that while a point is an absolute location , a vector is a displacement .

Do we need to draw vectors?

It is very common to draw vectors in various engineering disciplines, such as when drawing free-body diagrams in theoretical mechanics. My guess is that it is unusual to draw vectors in the final version of computer games, but I may be wrong.

Normally what you will need to draw in a computer game is the result of one or more vectors acting on an object, such as the velocity and acceleration vectors that apply to a speeding vehicle going around a curve. In that case, you might draw the results obtained from using the vector for mathematical computations (perhaps the vehicle turns over) but you probably wouldn't draw the vectors themselves.

### The program named PointLine02 and the library named GM2D01

The purpose of this program is to introduce you to a game-math library named GM2D01 .

(The class name GM2D01 is an abbreviation for GameMath2D01. Later in this collection, I will develop and present a combination 2D/3D game-math library named GM03. I will develop and present several intermediate 2D and 3D libraries along the way.)

This program instantiates objects from the following static top-level classes belonging to the class named GM2D01 :

• GM2D01.ColMatrix
• GM2D01.Line
• GM2D01.Point
• GM2D01.Vector

(See the documentation for the library named GM2D01 .)

Then the program displays the contents of those objects on the standard output device in two different ways.

A complete listing of the program named PointLine02 is provided in Listing 15 near the end of the module and a complete listing of the game-math library named GM2D01 is provided in Listing 16 .

Screen output from the program named PointLine02

Image 5 shows the screen output produced by running this program. I will refer back to the material in Image 5 in subsequent paragraphs.

12
Image 5: Screen output from the program named PointLine02.
Instantiate and display the contents
of a new ColMatrix object
2.5,6.8
2.5
6.8

Instantiate and display the contents
of a new Point object
3.4,9.7
3.4
9.7

Instantiate and display the contents
of a new Vector object
-1.9,7.5
-1.9
7.5

Instantiate and display the contents
of a new Line object
Tail = 1.1,2.2
1.1,2.2
3.3,4.4
Press any key to continue...


The game-math library named GM2D01

As mentioned earlier, the name GM2D01 is an abbreviation for GameMath2D01. (I elected to use the abbreviated name to keep the code from being so long.) This is a game-math class, which will be expanded over time as I publish sample programs and additional modules in this collection.

For educational purposes only

The game-math class is provided solely for educational purposes. Although some things were done to optimize the code and make it more efficient, the class was mainly designed and implemented for maximum clarity. Hopefully the use of this library will help you to better understand the programming details of various mathematical operations commonly used in graphics, game, and simulation programming.

Each time the library is expanded or modified, it will be given a new name by incrementing the two digits at the end of the class name to make one version distinguishable from the next. No attempt will be made to maintain backward compatibility from one version of the library to the next.

Static top-level methods

The GM2D01 class contains several static top-level classes (See Java 2D Graphics, Nested Top-Level Classes and Interfaces if you are unfamiliar with static top-level classes.) . This organizational approach was chosen primarily for the purpose of gathering the individual classes together under a common naming umbrella while avoiding name conflicts within a single package.

For example, as time passes and this library is expanded, my default package may contain class files with the following names, each representing a compiled version of the Point class in a different version of the overall library.

• GM2D01$Point.class • GM2D02$Point.class
• GM2D03$Point.class Real numbers represented as type double All real-number values used in the library are maintained as type double because double is the default representation for literal real numbers in Java. Will explain in fragments I will explain the code in Listing 15 and Listing 16 in fragments, switching back and forth between the code from the program named PointLine02 and the library class named GM2D01 to show how they work together. Beginning of the class named PointLine02 Listing 8 shows the beginning of the class named PointLine02 including the beginning of the main method. 13 Listing 8: Beginning of the class named PointLine02. class PointLine02{ public static void main(String[] args){ System.out.println( "Instantiate and display the contents\n" + "of a new ColMatrix object"); GM2D01.ColMatrix colMatrix = new GM2D01.ColMatrix(2.5,6.8); System.out.println(colMatrix); try{ System.out.println(colMatrix.getData(0)); System.out.println(colMatrix.getData(1)); //This statement will throw an exception on purpose System.out.println(colMatrix.getData(2)); }catch(Exception e){ System.out.println("Bad index"); }//end catch  The GM2D01.ColMatrix class You learned about a column matrix in the Kjell tutorial. The GM2D01 class contains a class named ColMatrix . (You will see the code for that class definition later.) An object of the ColMatrix class is intended to represent a column matrix as described by Kjell. The code in Listing 8 instantiates and displays the contents of a new object of the ColMatrix class. (Note the syntax required to instantiate an object of a static top-level class belonging to another class as shown in Listing 8 .) After instantiating the object, the remaining statements in Listing 8 display the numeric contents of the ColMatrix object using two different approaches. The overridden toString method The first approach causes the overridden toString method belonging to the ColMatrix class to be executed. (The overridden toString method is executed automatically by the call to the System.out.println method, passing the object's reference as a parameter to the println method.) The overridden toString method returns a string that is displayed on the standard output device. That string contains the values of the two real numbers stored in the column matrix. The getData method The second approach used to display the data in Listing 8 calls the getData method on the ColMatrix object twice in succession to get the two numeric values stored in the object and to display those two values on the standard output device. As you will see shortly, the getData method requires an incoming index value of either 0 or 1 to identify the numeric value that is to be returned. Listing 8 purposely calls the getData method with an index value of 2 to demonstrate that this will cause the method to throw an IndexOutOfBoundsException . (The text output produced by the code in Listing 8 is shown near the top of Image 5 .) Beginning of the class named GM2D01 Listing 9 shows the beginning of the library class named GM2D01 , including the entire static top-level class named ColMatrix . 14 Listing 9: Beginning of the class named GM2D01. public class GM2D01{ public static class ColMatrix{ double[] data = new double[2]; ColMatrix(double data0,double data1){//constructor data[0] = data0; data[1] = data1; }//end constructor public String toString(){ return data[0] + "," + data[1]; }//end overridden toString method public double getData(int index){ if((index < 0) || (index > 1)) throw new IndexOutOfBoundsException(); return data[index]; }//end getData }//end class ColMatrix  #### The GM2D01.ColMatrix class As mentioned earlier, an object of the ColMatrix class represents a 2D column matrix as described by Kjell. Furthermore, an object of this class is the fundamental building block for several of the other classes in the library. (The static ColMatrix class will be expanded in future modules to provide various matrix arithmetic capabilities.) Constructor for the ColMatrix class The constructor for the class requires two incoming parameters of type double . (For this example, the code in Listing 8 passes the values 2.5 and 6.8 to the constructor for the class.) The two incoming parameter values are stored in the first two elements of a two-element array of type double where they can be easily accessed later for whatever purpose they may be needed. Overridden toString method Listing 9 also overrides the toString method to construct and return a reference to a String object containing the two values stored in the array. When the println method is called for the second time, (near the middle of Listing 8 ), the overridden toString method is called automatically and the output shown in the third line of text in Image 5 is produced. The getData method Finally, Listing 9 defines a method named getData . The purpose of this method is to retrieve and to return the individual values stored in the array. The method requires an incoming parameter value of 0 or 1. This value is used as an index to identify the specific data value that is to be returned. If the method receives any other value, it throws an IndexOutOfBoundsException . As mentioned earlier, the code in Listing 8 calls this method three times in succession. The first two calls get and display the two data values shown at the top of Image 5 . The third call causes the method to throw an exception producing the first "Bad index" message shown in Image 5 . The Point class The GM2D01 class contains a static top-level class named Point . Recall that Kjell tells us that a point is simply a location in space. A point can be represented by a pair of coordinate values in a specific coordinate frame. A convenient way to handle the pair of coordinate values in a program is to store them in a column matrix. An object of the GM2D01.Point class is intended to represent a point in 2D space. Instantiating a Point object As you will see shortly, the constructor for the Point class requires a single incoming parameter, which is a reference to an object of the class ColMatrix . Listing 10 , (which is a fragment from the PointLine02 program) , instantiates a new ColMatrix object and populates it with the values 3.4 and 9.7. Then it instantiates a new Point object, passing the aforementioned ColMatrix object's reference as a parameter to the Point constructor. 15 Listing 10: Exercising the Point class.  //A fragment from the PointLine02 program System.out.println(/*blank line*/); System.out.println( "Instantiate and display the contents\n" + "of a new Point object"); colMatrix = new GM2D01.ColMatrix(3.4,9.7); GM2D01.Point point = new GM2D01.Point(colMatrix); System.out.println(point); try{ System.out.println(point.getData(0)); System.out.println(point.getData(1)); //This statement will throw an exception on purpose System.out.println(point.getData(-1)); }catch(Exception e){ System.out.println("Bad index"); }//end catch Coding for clarity ##### Note: Coding for clarity: Ordinarily I would compress those two statements into a single statement by instantiating an anonymous object of the ColMatrix class in the call to the constructor for the Point class, and I recommend that you do the same if you know how. However, I elected to separate the code into two statements in this case to provide clarity and make it somewhat easier for you to understand. Display the values Following that, the code in Listing 10 displays the coordinate values that represent the point in the same two ways described earlier for the ColMatrix object. The screen output is shown in Image 5 . #### The GM2D01.Point class The complete definition of the static top-level class named Point is shown in Listing 11 . 16 Listing 11: The static top-level class named Point.  //A fragment from the GM2D01 class public static class Point{ GM2D01.ColMatrix point; Point(GM2D01.ColMatrix point){ this.point = point; }//end constructor public String toString(){ return point.getData(0) + "," + point.getData(1); }//end toString public double getData(int index){ if((index < 0) || (index > 1)) throw new IndexOutOfBoundsException(); return point.getData(index); }//end getData }//end class Point  Less detail in the discussions By now, you may be getting a little bored with the detail in which I have been discussing and explaining the code so I will be more brief in my explanations from here on. The code in Listing 11 is straightforward and shouldn't require a lot of explanation. Perhaps the most significant thing to note about Listing 11 is that the coordinate values that represent the point are actually stored internally in an object of the type ColMatrix . That approach will prove to be convenient for certain mathematical operations that will be explained in future modules. #### The GM2D01.Vector class The static top-level class named Vector is shown in Listing 12 . (Note that this is a different class from the class named java.util.Vector in the standard Java library.) You will find the code that exercises this class and produces the output shown in Image 5 in the complete listing of the program named PointLine02 in Listing 15 . That code is straightforward and shouldn't require an explanation. 17 Listing 12: The static top-level class named Vector.  //A fragment from the GM2D01 class public static class Vector{ GM2D01.ColMatrix vector; Vector(GM2D01.ColMatrix vector){ this.vector = vector; }//end constructor public String toString(){ return vector.getData(0) + "," + vector.getData(1); }//end toString public double getData(int index){ if((index < 0) || (index > 1)) throw new IndexOutOfBoundsException(); return vector.getData(index); }//end getData }//end class Vector  Storing a vector in a column matrix Recall that Kjell tells us that both points and vectors can be conveniently stored in a column matrix. As a result, the code in Listing 12 , (at this stage in the development of the library) , is essentially the same as the code for the Point class in Listing 11 . The only differences are a few differences in names. You may be wondering why I didn't simply define a single class that can serve both purposes. I probably could have done that. Recall however that this library is being designed for clarity. I believe that such clarity is best served by having consistent names for the kinds of items represented by objects of the classes. Also, it is likely that the definitions of the two classes will be different later when I expand the library to provide additional capabilities. #### The GM2D01.Line class Kjell tells us that a line segment is the straight path between two points, and that it has no thickness. The class named GM2D01 contains a class named Line that is intended to represent a mathematical line segment as described by Kjell. Listing 13 is a complete listing of the class named Line . As before, you will find the code that exercises this class and produces the output shown in Image 5 in the complete listing for the program named PointLine02 in Listing 15 . That code is straightforward and shouldn't require an explanation. 18 Listing 13: The static top-level class named Line.  //A fragment from the GM2D01 class //A line is defined by two points. One is called the // tail and the other is called the head. public static class Line{ GM2D01.Point[] line = new GM2D01.Point[2]; Line(GM2D01.Point tail,GM2D01.Point head){ this.line[0] = tail; this.line[1] = head; }//end constructor public String toString(){ return "Tail = " + line[0].getData(0) + "," + line[0].getData(1) + "\nHead = " + line[1].getData(0) + "," + line[1].getData(1); }//end toString public GM2D01.Point getTail(){ return line[0]; }//end getTail public GM2D01.Point getHead(){ return line[1]; }//end getTail }//end class Line  Represent a line segment by two points Since a line segment is the straight path between two points, a line segment in this library is represented by an object that encapsulates two Point objects. One of those points is referred to as the tail and the other is referred to as the head , simply as a means of distinguishing between the two ends of the line segment. The constructor for the Line class requires two points as incoming parameters and stores them in a two-element array of type GM2D01.Point . Beyond that, the code in Listing 13 is straightforward and shouldn't require further explanation. ## The GM2D01 library is purely mathematical The library named GM2D01 is purely mathematical. By that, I mean that the library doesn't provide any mechanism for rendering objects of the ColMatrix , Line , Point , or Vector classes in a visual graphics context. That capability will be added to the next version of the library in the next module. ## Documentation for the GM2D01 library Click here to download a zip file containing standard javadoc documentation for the library named GM2D01 . Extract the contents of the zip file into an empty folder and open the file named index.html in your browser to view the documentation. Although the documentation doesn't provide much in the way of explanatory text (see Listing 16 and the explanations given above) , the documentation does provide a good overview of the organization and structure of the library. You may find it helpful in that regard. ## Homework assignment Your homework assignment for this module was to study Kjell's CHAPTER 0 -- Points and Lines plus CHAPTER 1 -- Vectors, Points, and Column Matrices down through the topic titled Variables as Elements . The homework assignment for the next module is to make certain that you have carefully studied that material, and to mentally reflect on how it correlates with what you have learned in this module. In addition to studying the Kjell material, you should read at least the next two modules in this collection and bring your questions about that material to the next classroom session. Finally, you should have begun studying the physics material at the beginning of the semester and you should continue studying one physics module per week thereafter. You should also feel free to bring your questions about that material to the classroom for discussion. ## Run the programs I encourage you to copy the code from Listing 14 , Listing 15 , and Listing 16 into your text editor. Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make sure you understand why your changes produce the results that they do. ## Summary In this and the previous module, I introduced you to an excellent interactive tutorial titled Vector Math for 3D Computer Graphics written by Dr. Bradley P. Kjell. Then I presented and explained two sample programs and a sample game-programming math library intended to represents concepts from Dr. Kjell's tutorial in Java code. ## What's next? While you probably won't have a frequent need to present points, lines, and vectors in graphical form in computer games that you write, it is often very useful to provide graphical representations of these items during the testing and debugging of the program. I will update the programming-math library to make it easy to provide graphical representations of points, lines, and vectors in the next module in this collection. An example of such graphical output is shown in Image 6 . The image on the left consists of graphical objects that represent points and lines. The image on the right consists of graphical objects that represent vectors. (The head of each vector is represented by a small circle.) ## Miscellaneous This section contains a variety of miscellaneous information. ### Note: Housekeeping material • Module name: GAME 2302-0105: Getting Started • File: Game0105.htm • Published: 10/13/12 • Revised: 12/31/12 ### Note: Disclaimers: Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF. I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module. In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge. Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX. ## Complete program listings Complete listings of the programs discussed above are provided in Listing 14 , Listing 15 , and Listing 16 below. 20 Listing 14: Source code for the program named PointLine01. /*PointLine01.java Copyright 2008, R.G.Baldwin This program illustrates the implementation of the concept of a point and a line segment in Java. Four points (locations in space) are defined by using the coordinates of the four points as the x and y parameters to the constructor for the Point2D.Double class. This results in four objects of the Point2D.Double class. Two line segments are defined by using pairs of points as parameters to the Line2D.Double class. This results in two objects of the Line2D.Double class. The draw method belonging to an object of the Graphics2D class is used to draw the two line segments on a Canvas object for which the origin has been translated to the center of the Canvas. The coordinate values of the points and the selection of point-pairs to specify the ends of the line segments is such that the final rendering is a pair of orthogonal lines that intersect at the origin. Tested using JDK 1.6 under WinXP. *********************************************************/ import java.awt.geom.*; import java.awt.*; import javax.swing.*; class PointLine01{ public static void main(String[] args){ GUI guiObj = new GUI(); }//end main }//end controlling class PointLine01 //======================================================// class GUI extends JFrame{ //Specify the horizontal and vertical size of a JFrame // object. int hSize = 200; int vSize = 200; GUI(){//constructor //Set JFrame size and title setSize(hSize,vSize); setTitle("R.G.Baldwin"); //Create a new drawing canvas and add it to the // center of the JFrame. MyCanvas myCanvas = new MyCanvas(); this.getContentPane().add(myCanvas); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }//end constructor //----------------------------------------------------// //This is an inner class of the GUI class. class MyCanvas extends Canvas{ //Override the paint() method. This method will be // called when the JFrame and the Canvas in its // contentPane are displayed on the screen. public void paint(Graphics g){ //Downcast the Graphics object to a Graphics2D // object. The Graphics2D class provides // capabilities that don't exist in the Graphics // class. Graphics2D g2 = (Graphics2D)g; //By default, the origin is at the upper-left corner // of the canvas. This statement translates the // origin to the center of the canvas. g2.translate( this.getWidth()/2.0,this.getHeight()/2.0); //Define two points. Point2D pointA = new Point2D.Double(-this.getWidth()/2.5,0.0); Point2D pointB = new Point2D.Double(this.getWidth()/2.5,0.0); //Use the points to construct an object that // represents a line segment that connects the two // points. The values of the points causes this // line segment to be horizontal. Line2D.Double horizLine = new Line2D.Double(pointA,pointB); //Use the same procedure to construct an object that // represents a vertical line segment. Point2D pointC = new Point2D.Double(0.0,-this.getHeight()/2.5); Point2D pointD = new Point2D.Double(0.0,this.getHeight()/2.5); Line2D.Double vertLine = new Line2D.Double(pointC,pointD); //Draw the horizontal and vertical line segments on // the canvas. g2.draw(horizLine); g2.draw(vertLine); }//end overridden paint() }//end inner class MyCanvas }//end class GUI  . 21 Listing 15: Source code for the program named PointLine02. /*PointLine02.java Copyright 2008, R.G.Baldwin The purpose of this program is to introduce the use of a game-math class library named GM2D01. The class name GM2D01 is an abbreviation for GameMath2D01. The program instantiates objects from the following static top-level classes belonging to the class named GM2D01 and then displays the contents of those objects in two different ways on the standard output device. ColMatrix Point Vector Line Tested using JDK 1.6 under WinXP. *********************************************************/ class PointLine02{ public static void main(String[] args){ System.out.println( "Instantiate and display the contents\n" + "of a new ColMatrix object"); GM2D01.ColMatrix colMatrix = new GM2D01.ColMatrix(2.5,6.8); System.out.println(colMatrix); try{ System.out.println(colMatrix.getData(0)); System.out.println(colMatrix.getData(1)); //This statement will throw an exception on purpose System.out.println(colMatrix.getData(2)); }catch(Exception e){ System.out.println("Bad index"); }//end catch System.out.println(/*blank line*/); System.out.println( "Instantiate and display the contents\n" + "of a new Point object"); colMatrix = new GM2D01.ColMatrix(3.4,9.7); GM2D01.Point point = new GM2D01.Point(colMatrix); System.out.println(point); try{ System.out.println(point.getData(0)); System.out.println(point.getData(1)); //This statement will throw an exception on purpose System.out.println(point.getData(-1)); }catch(Exception e){ System.out.println("Bad index"); }//end catch System.out.println(/*blank line*/); System.out.println( "Instantiate and display the contents\n" + "of a new Vector object"); colMatrix = new GM2D01.ColMatrix(-1.9,7.5); GM2D01.Vector vector = new GM2D01.Vector(colMatrix); System.out.println(vector); try{ System.out.println(vector.getData(0)); System.out.println(vector.getData(1)); //This statement will throw an exception on purpose System.out.println(vector.getData(2)); }catch(Exception e){ System.out.println("Bad index"); }//end catch System.out.println(/*blank line*/); System.out.println( "Instantiate and display the contents\n" + "of a new Line object"); GM2D01.ColMatrix colMatrixTail = new GM2D01.ColMatrix(1.1,2.2); GM2D01.ColMatrix colMatrixHead = new GM2D01.ColMatrix(3.3,4.4); GM2D01.Point pointTail = new GM2D01.Point(colMatrixTail); GM2D01.Point pointHead = new GM2D01.Point(colMatrixHead); GM2D01.Line line = new GM2D01.Line(pointTail,pointHead); System.out.println(line); pointTail = line.getTail(); System.out.println(pointTail); pointHead = line.getHead(); System.out.println(pointHead); }//end main }//end controlling class PointLine02  . 22 Listing 16: Source code for the game-programming math library named GM2D01. /*GM2D01.java Copyright 2008, R.G.Baldwin The name GM2D01 is an abbreviation for GameMath2D01. This is a game-math class, which will be expanded over time. The class is provided solely for educational purposes. No effort has been expended to optimize it in any way. Rather, it was designed and implemented for maximum clarity in order to help students understand the programming details of various mathematical operations commonly used in game programming. Each time the class is expanded or modified, it will be given a new name by incrementing the two digits at the end of the name. No attempt will be made to maintain backward compatibility from one version of the class to the next. This class contains a number of static top-level classes. This organizational approach was used primarily for the purpose of gathering such classes under a single naming umbrella while avoiding name conflicts within a single package. For example, as time passes, and this library is expanded, my default package may contain class files with the following names: GM2D01$Point.class
GM2D02$Point.class GM2D03$Point.class

All real-number values used in this class are maintained
as type double.

Tested using JDK 1.6 under WinXP.
*********************************************************/

public class GM2D01{

//An object of this class represents a 2D column matrix.
// An object of this class is the fundamental building
// block for several of the other classes in the
// library.
public static class ColMatrix{
double[] data = new double[2];

ColMatrix(double data0,double data1){
data[0] = data0;
data[1] = data1;
}//end constructor

public String toString(){
return  data[0] + "," + data[1];
}//end overridden toString method

public double getData(int index){
if((index < 0) || (index > 1))
throw new IndexOutOfBoundsException();
return data[index];
}//end getData

}//end class ColMatrix
//====================================================//

public static class Point{
GM2D01.ColMatrix point;

Point(GM2D01.ColMatrix point){
this.point = point;
}//end constructor

public String toString(){
return point.getData(0) + "," + point.getData(1);
}//end toString

public double getData(int index){
if((index < 0) || (index > 1))
throw new IndexOutOfBoundsException();
return point.getData(index);
}//end getData

}//end class Point
//====================================================//

public static class Vector{
GM2D01.ColMatrix vector;

Vector(GM2D01.ColMatrix vector){
this.vector = vector;
}//end constructor

public String toString(){
return vector.getData(0) + "," + vector.getData(1);
}//end toString

public double getData(int index){
if((index < 0) || (index > 1))
throw new IndexOutOfBoundsException();
return vector.getData(index);
}//end getData

}//end class Vector
//====================================================//

//A line is defined by two points. One is called the
// tail and the other is called the head.
public static class Line{
GM2D01.Point[] line = new GM2D01.Point[2];

this.line[0] = tail;
}//end constructor

public String toString(){
return "Tail = " + line[0].getData(0) + ","
+ line[0].getData(1) + "\nHead = "
+ line[1].getData(0) + ","
+ line[1].getData(1);
}//end toString

public GM2D01.Point getTail(){
return line[0];
}//end getTail

return line[1];
}//end getTail

}//end class Line

}//end class GM2D01


## Exercises

### Exercise 1

Without using the game math library, use the programming environment of your choice to write a program that draws a diagonal line from the upper-left to the lower-right corner of a window as shown in Image 7 .

### Exercise 2

Using Java and the game math library named GM2D01 , write a program that:

• Creates a new GM2D01.Point object with coordinate values of 3.4 and 9.7.
• Uses the overridden toString method to get and display the location of the point in 2D space in the format shown by the first line of text in Image 8 .
• Uses the getData method to get and display the location of the point in 2D space in the format shown by the last two lines of text in Image 8 .

Your screen output should display numeric values in the format shown in Image 8 where each ? character represents a single digit.

24
Image 8: Text output from Exercise 2.

?.?,?.?
?.?
?.?


### Exercise 3

Using Java and the game math library named GM2D01 , write a program that:

• Represents a line segment using a GM2D01.Line object with the ends of the line segment being located at the following coordinates:
• x=2.2, y=5.3
• x=5.2, y=9.3
• Displays the information shown in Image 9 to describe the line segment.

Your screen output should display numeric values in the format shown in Image 9 where each ? character represents a single digit. (Note that the number of digits to the right of the decimal point in the last line of text may be greater or less than that shown in Image 9 .)

25
Image 9: Text output from Exercise 3.

Tail = ?.?,?.?
Length = ?.???

-end-

## Content actions

PDF | EPUB (?)

### What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks