Math For Game Develop
Math For Game Develop
By:
Richard Baldwin
GAME 2302 - Mathematical Applications
for Game Development
By:
Richard Baldwin
Online:
< http://cnx.org/content/col11450/1.29/ >
CONNEXIONS
Welcome
Welcome to the course material for GAME 2302 Mathematical Applications for Game Develop-
ment , which I teach at Austin Community College 2 in Austin, TX.
Ocial information about the course
The college website for this course is: http://www.austincc.edu/baldwin/ 3
As of December 2012, the description for this course reads:
"GAME 2302 - Mathematical Applications for Game Development
Presents applications of mathematics and science in game and simulation programming. Includes the
utilization of matrix and vector operations, kinematics, and Newtonian principles in games and simulations.
Also covers code optimization."
The course material
This course material consists of about 20 dierent modules arranged in the following major sections:
• Math
• Physics
The modules in the Math section use Java OOP to develop a game math library.
Many of the topics consist of three separate modules:
Miscellaneous
This section contains a variety of miscellaneous information.
1
2
• Revised: 01/05/13
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
Math
• Preface (p. 3)
• Course description (p. 3)
• Adherence to the course description (p. 3)
• Course resources (p. 4)
• Homework assignments (p. 4)
• What's next? (p. 5)
• Miscellaneous (p. 5)
• Download source code (p. 5)
1.1.2 Preface
This module is the rst in a series of modules designed for teaching GAME2302 Mathematical Applications
for Game Development at Austin Community College in Austin, TX.
See the Download source code (p. 5) section to download source code les for the modules contained in
this collection.
As of September 2012, the ocial course description reads: "Presents applications of mathematics and
science in game and simulation programming. Includes the utilization of matrix and vector operations,
kinematics, and Newtonian principles in games and simulations. Also covers code optimization."
Online resources (p. 4) are provided to the student for each of the topics identied in the above description.
The topics merge in the nal module of the collection, which explains an animated simulation of the rst-
person view of a human cannonball from the point in time that the human cannonball leaves the cannon
until the human cannonball lands in the safety net, or fails to land in the safety net. The trajectory and the
point of impact are determined by such factors as:
3
4 CHAPTER 1. MATH
This course does not use a printed textbook. Instead, the primary resources for the course are:
1. An interactive tutorial by Dr. Bradley P. Kjell titled Vector Math for 3D Computer Graphics 2 .
You can also download a copy in a zip le here 3 . (Extract the contents of the zip le and open the
le named index.html in your browser to view the tutorial.)
2. A sub-collection of physics modules beginning with 2302-0300 Introduction to Physics Component 4
published at cnx.org 5 .
3. This collection 6 of modules published at cnx.org 7 .
4. Most of the programming examples in the course will be written in Java/OOP. Therefore, you may
need some reference material on Java/OOP programming. The collection named Object-Oriented
Programming (OOP) with Java 8 at cnx.org 9 contains the course material for two complete Java/OOP
programming courses at Austin Community College. The modules in the section named ITSE 2321
Object-Oriented Programming (Java) contains the material for the rst course. The section named
ITSE2317 - Java Programming (Intermediate) contains the material for the second course.
5. Here are some additional Java/OOP references that you may nd useful:
a. Java Platform Standard Edition 7 Documentation 10
b. Java Platform, Standard Edition 7 API Specication 11
c. Reading the Javadoc 12 - how to read the API
d. The Java Tutorials 13
e. Simplied Java tutorial 14
Main item 3 in the above list (this collection 15 ) will serve as the major resource for classroom lectures.
Main item 1 ( Vector Math for 3D Computer Graphics 16 ) and main item 2 ( physics sub-collection
17 ) will serve as major homework study assignments.
Main items 4 and 5 (including sub-items 1 through 5) are provided for reference only.
The material in this collection 18 (item 3) explains how to implement the concepts developed in the rst
two items in programming (Java) code. While this will serve as the major resource for classroom lectures,
students are encouraged to bring questions about the other items to class for discussion.
The rst classroom session will be dedicated primarily to explaining the mechanics of the course, discussing
the syllabus, etc.
2 http://chortle.ccsu.edu/vectorlessons/vectorindex.html
3 http://cnx.org/content/m44983/latest/VectorLessons2011.zip
4 http://cnx.org/content/m44992/latest
5 http://cnx.org/
6 http://cnx.org/content/col11450/latest/
7 http://cnx.org/
8 http://cnx.org/content/col11441/latest/
9 http://cnx.org/
10 http://docs.oracle.com/javase/7/docs/
11 http://docs.oracle.com/javase/7/docs/api/index.html
12 http://www.otherwise.com/Lessons/ReadingTheJavadoc.html
13 http://docs.oracle.com/javase/tutorial/
14 http://www.otherwise.com/Lessons/index.html
15 http://cnx.org/content/col11450/latest/
16 http://chortle.ccsu.edu/vectorlessons/vectorindex.html
17 http://cnx.org/content/m44992/latest/
18 http://cnx.org/content/col11450/latest/
Once those items have been taken care of, students will be asked to go online, access or download the
Kjell tutorials, and begin studying Kjell's CHAPTER 0 Points and Lines and CHAPTER 1 Vectors,
Points, and Column Matrices down through the topic titled Variables as Elements in Chapter 1 , in
preparation for the next classroom session.
Students should also begin studying item 2 ( physics 19 ) and should study one physics module per
week thereafter.
Finally, in addition to studying the Kjell material, students should read at least the next two modules in
this collection and bring their questions about that material to the next classroom session.
In the next module, we will begin the examination of sample programs and a game-programming math library
intended to provide aspiring game programmers with the mathematical skills needed for game programming.
1.1.8 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Click here 20 to download a zip le containing the source code for all of the sample programs and many of
the exercises in this collection.
Extract the contents of the zip le into an empty folder. Each program should end up in a separate
folder. Double-click the le named CompileAndRun...bat in each folder to compile and run the
program contained in that folder.
-end-
19 http://cnx.org/content/m44992/latest/
20 http://cnx.org/content/m44983/latest/AllCode.zip
This module contains lecture slides keyed to the module titled GAME 2302-0100: Introduction 22 .
Click here 23 to open an index to the slides.
Then use the links beginning with the label "aa" to open the rst slide that you want to view in a new
window in your browser.
Then use the [Next] and [Prev] links on the individual slides to navigate back and forth through the
slides.
You can also use the links on the index page to jump to a particular slide to avoid having to cycle through
the slides in sequence.
1.2.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
21 This content is available online at <http://cnx.org/content/m45611/1.2/>.
22 http://cnx.org/content/m44983
23 http://cnx.org/content/m45611/latest/a0-Index.htm
• Preface (p. 7)
· General (p. 7)
· Viewing tip (p. 8)
* Images (p. 8)
* Listings (p. 9)
• Preview (p. 9)
• Discussion and sample code (p. 9)
· Points, lines, and vectors (p. 9)
· Writing, compiling, and running Java programs (p. 9)
· The program named PointLine01 (p. 10)
· But wait, there's something wrong here (p. 17)
· The program named PointLine02 and the library named GM2D01 (p. 20)
* The GM2D01.ColMatrix class (p. 24)
* The GM2D01.Point class (p. 26)
* The GM2D01.Vector class (p. 26)
* The GM2D01.Line class (p. 27)
• The GM2D01 library is purely mathematical (p. 29)
• Documentation for the GM2D01 library (p. 29)
• Homework assignment (p. 29)
• Run the programs (p. 29)
• Summary (p. 29)
• What's next? (p. 29)
• Miscellaneous (p. 30)
• Complete program listings (p. 31)
• Exercises (p. 37)
· Exercise 1 (p. 37)
· Exercise 2 (p. 37)
· Exercise 3 (p. 38)
1.3.2 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.
1.3.2.1 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
24 This content is available online at <http://cnx.org/content/m44990/1.4/>.
Java. If you are familiar with other object-oriented programming languages such as C#, you should have no
diculty 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 con-
centrate on items 3, 4, and 5 in the above list. (I will assume that you either already have, or can gain the re-
quired 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/
25 .)
Insofar as vectors and matrices are concerned, I will frequently refer you to an excellent interactive
tutorial titled Vector Math for 3D Computer Graphics 26 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 exper-
iment with and to conrm 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.
1.3.2.2.1 Images
• Image 1 (p. 11) . Graphics illustration of four points and two lines.
• Image 2 (p. 17) . First of three views in the construction of a 3D human gure.
• Image 3 (p. 18) . Second of three views in the construction of a 3D human gure.
• Image 4 (p. 19) . Third of three views in the construction of a 3D human gure.
• Image 5 (p. 21) . Screen output from the program named PointLine02.
• Image 6 (p. 30) . Sample output from updated programming-math library.
• Image 7 (p. 37) . Graphic output from Exercise 1.
• Image 8 (p. 38) . Text output from Exercise 2.
• Image 9 (p. 38) . Text output from Exercise 3.
25 http://cnx.org/content/m37435/latest/
26 http://chortle.ccsu.edu/vectorlessons/vectorindex.html
1.3.2.2.2 Listings
• Listing 1 (p. 12) . The controlling class named PointLine01.
• Listing 2 (p. 13) . Beginning of the class named GUI.
• Listing 3 (p. 14) . Beginning of the inner class named MyCanvas.
• Listing 4 (p. 15) . Dene two points as two locations in space.
• Listing 5 (p. 15) . Construct a line segment.
• Listing 6 (p. 16) . Construct an object that represents a vertical line segment.
• Listing 7 (p. 16) . Draw the two lines on the screen.
• Listing 8 (p. 22) . Beginning of the class named PointLine02.
• Listing 9 (p. 24) . Beginning of the class named GM2D01.
• Listing 10 (p. 25) . Exercising the Point class.
• Listing 11 (p. 26) . The static top-level class named Point.
• Listing 12 (p. 27) . The static top-level class named Vector.
• Listing 13 (p. 28) . The static top-level class named Line.
• Listing 14 (p. 32) . Source code for the program named PointLine01.
• Listing 15 (p. 34) . Source code for the program named PointLine02.
• Listing 16 (p. 36) . Source code for the game-programming math library named GM2D01.
1.3.3 Preview
In this module, I will introduce you to an excellent interactive tutorial titled Vector Math for 3D Computer
Graphics 27 written by Dr. Bradley P. Kjell, (which you can also download in zip-le format from a link in
the rst module 28 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.
First you need to conrm 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 29 .
Creating your source code
Next, you need to use any text editor to create your Java source code les as text les with an extension
of .java. (I prefer the free JCreator 30 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.)
Compiling your source code
The name of each source code le should match the name of the Java class dened in the le.
Assume that your source code le is named MyProg.java . You can compile the program by opening a
command prompt window in the folder containing the source code le and executing the following command
at the prompt:
javac MyProg.java
java MyProg
del *.class
javac MyProg.java
java MyProg
pause
Place this le in the same folder as your source code les. Then double-click on the batch le to cause your
program to be compiled and executed.
That's all there is to it.
Four points (locations in space) are dened 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 dened 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 (p. 11) .
( Graphics2D and Canvas are classes in the standard Java library.)
1.1
The coordinate values of the points and the selection of point-pairs to specify the ends of the line segments
is such that the nal 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 (p. 32) near the end of the module.
(Use the code in Listing 14 (p. 32) and the instructions provided above (p. 9) to write, compile, and run
the program. This will be a good way for you to conrm 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 (p. 11) .)
class PointLine01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine01
1.2
Listing 1 (p. 12) shows the denition 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 dened below.)
The GUI object produces the screen image shown in Image 1 (p. 11) .
The class named GUI
Listing 2 (p. 13) shows the beginning of the class named GUI , including the constructor for the class.
GUI(){//constructor
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}//end constructor
1.3
Listing 2 (p. 13) 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 (p. 11) .
(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 lls the entire client area of the
frame, which is the area inside of the four borders.
Dene the behavior of the X-button and make the JFrame visible
Finally, the constructor denes 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 nd links to many of those tutorials at
www.DickBaldwin.com 31 .
Beginning of the inner class named MyCanvas
Listing 3 (p. 14) shows the beginning of an inner class denition named MyCanvas including the
beginning of an overridden paint method.
31 http://www.dickbaldwin.com/toc.htm
(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.
1.4
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 .
Note, however, that even though the origin has been translated, the positive vertical direction is still
toward the bottom of the canvas.
Dene two points as two locations in space
Listing 4 (p. 15) denes 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 .
Point2D pointA =
new Point2D.Double(-this.getWidth()/2.5,0.0);
Point2D pointB =
new Point2D.Double(this.getWidth()/2.5,0.0);
1.5
Line2D.Double horizLine =
new Line2D.Double(pointA,pointB);
1.6
The line segment constructed in Listing 5 (p. 15) is simply a visual representation of the true line
segment. When rendered on the screen, that line segment could take on an innite number of appearances
depending on how the space is rendered on the screen. It just happens that in the case of Image 1 (p. 11) ,
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 (p. 16) 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.
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);
1.7
g2.draw(horizLine);
g2.draw(vertLine);
1.8
Listing 7 (p. 16) 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 .
1.9
32 http://www.alice.org/
1.10
1.11
1.3.4.5 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 (p. 29) for the library named GM2D01 .)
Then the program displays the contents of those objects on the standard output device in two dierent
ways.
A complete listing of the program named PointLine02 is provided in Listing 15 (p. 34) near the end
of the module and a complete listing of the game-math library named GM2D01 is provided in Listing 16
(p. 36) .
Screen output from the program named PointLine02
Image 5 (p. 21) shows the screen output produced by running this program. I will refer back to the
material in Image 5 (p. 21) in subsequent paragraphs.
1.12
Classes and Interfaces 33 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 conicts within a single package.
For example, as time passes and this library is expanded, my default package may contain class les with
the following names, each representing a compiled version of the Point class in a dierent version of the
overall library.
• GM2D01$Point.class
• GM2D02$Point.class
• GM2D03$Point.class
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));
1.13
33 http://www.dickbaldwin.com/java/Java300.htm
1.14
The method requires an incoming parameter value of 0 or 1. This value is used as an index to iden-
tify the specic 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 (p. 22) calls this method three times in succession. The rst
two calls get and display the two data values shown at the top of Image 5 (p. 21) . The third call causes
the method to throw an exception producing the rst "Bad index" message shown in Image 5 (p. 21) .
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 specic
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 (p. 25) , (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.
System.out.println(/*blank line*/);
System.out.println(
"Instantiate and display the contents\n"
+ "of a new Point object");
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
1.15
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 (p. 25) 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 (p.
21) .
Point(GM2D01.ColMatrix point){
this.point = point;
}//end constructor
1.16
(Note that this is a dierent class from the class named java.util.Vector in the standard Java library.)
You will nd the code that exercises this class and produces the output shown in Image 5 (p. 21) in the
complete listing of the program named PointLine02 in Listing 15 (p. 34) . That code is straightforward
and shouldn't require an explanation.
Vector(GM2D01.ColMatrix vector){
this.vector = vector;
}//end constructor
1.17
Listing 13 (p. 28) is a complete listing of the class named Line . As before, you will nd the code
that exercises this class and produces the output shown in Image 5 (p. 21) in the complete listing for the
program named PointLine02 in Listing 15 (p. 34) . That code is straightforward and shouldn't require
an explanation.
1.18
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.
Click here 34 to download a zip le containing standard javadoc documentation for the library named
GM2D01 . Extract the contents of the zip le into an empty folder and open the le 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 (p.
36) and the explanations given above) , the documentation does provide a good overview of the organization
and structure of the library. You may nd it helpful in that regard.
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 reect 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 35 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.
I encourage you to copy the code from Listing 14 (p. 32) , Listing 15 (p. 34) , and Listing 16 (p. 36)
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.
1.3.9 Summary
In this and the previous module, I introduced you to an excellent interactive tutorial titled Vector Math
for 3D Computer Graphics 36 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.
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.
34 http://cnx.org/content/m44990/latest/GM2D01docs.zip
35 http://cnx.org/content/m44992/latest/
36 http://chortle.ccsu.edu/vectorlessons/vectorindex.html
An example of such graphical output is shown in Image 6 (p. 30) . 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.)
1.19
1.3.11 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed above are provided in Listing 14 (p. 32) , Listing 15 (p. 34) ,
and Listing 16 (p. 36) below.
/*PointLine01.java
Copyright 2008, R.G.Baldwin
class PointLine01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine01
//======================================================//
GUI(){//constructor
/*PointLine02.java
Copyright 2008, R.G.Baldwin
ColMatrix
Point
Vector
Line
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){
Available for freeindex");
System.out.println("Bad at Connexions <http://cnx.org/content/col11450/1.29>
}//end catch
System.out.println(/*blank line*/);
35
Listing 16: Source code for the game-programming math library named GM2D01.
/*GM2D01.java
Copyright 2008, R.G.Baldwin
GM2D01$Point.class
GM2D02$Point.class
GM2D03$Point.class
1.3.13 Exercises
1.3.13.1 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 (p.
37) .
1.23
1.3.13.2 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 rst line of text in Image 8 (p. 38) .
• 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 (p. 38) .
Your screen output should display numeric values in the format shown in Image 8 (p. 38) where each ?
character represents a single digit.
?.?,?.?
?.?
?.?
1.24
1.3.13.3 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 (p. 38) to describe the line segment.
Your screen output should display numeric values in the format shown in Image 9 (p. 38) 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 (p. 38) .)
Tail = ?.?,?.?
Head = ?.?,?.?
Length = ?.???
1.25
-end-
1.4.2 Preface
This module contains review questions and answers keyed to the module titled GAME 2302-0105: Getting
Started 38 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
1.4.3 Questions
1.4.3.1 Question 1 .
Successful game programmers don't need good math skills.
True or False?
Answer 1 (p. 52)
1.4.3.2 Question 2
This set of modules relies strictly on procedural programming.
Answer 2 (p. 52)
1.4.3.3 Question 3
You will need skills in the mathematical areas that are required for success in 2D and 3D graphics program-
ming.
True or False?
Answer 3 (p. 51)
1.4.3.4 Question 4
As a minimum, you will need skills in:
Select the correct answers
1. Geometry
2. Trigonometry
3. Vectors
37 This content is available online at <http://cnx.org/content/m45585/1.3/>.
38 http://cnx.org/content/m44990
4. Matrices
5. 2D and 3D transforms
6. Transformations between coordinate systems
7. Projections
8. All of the above
Answer 4 (p. 51)
1.4.3.5 Question 5
A column matrix can be used to represent a point in a given coordinate frame.
True or False?
Answer 5 (p. 51)
1.4.3.6 Question 6
When representing a point with a column matrix, the same point will have the same representation in
dierent coordinate frames.
True or False?
Answer 6 (p. 51)
1.4.3.7 Question 7
You must use an IDE such as Eclipse or NetBeans to create Java source code.
True or False?
Answer 7 (p. 51)
1.4.3.8 Question 8
There is no relationship between the name of the source code le and the name of the class dened in the
le.
True or False?
Answer 8 (p. 51)
1.4.3.9 Question 9
The name of the Java compiler program is java.exe.
True or False?
Answer 9 (p. 51)
1.4.3.10 Question 10
The class named Point2D.Double is a class in the standard Java library.
True or False?
Answer 10 (p. 51)
1.4.3.11 Question 11
The following is the correct syntax for the main method in a Java application.
note:
True or False?
Answer 11 (p. 51)
1.4.3.12 Question 12
The following Java code instantiates a new object of a class named GUI and saves that object's reference
in the variable named guiObj.
note:
class PointLine01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine01
1.4.3.13 Question 13
The class named GUI is a class in the Java 7 Standard Edition library.
True or False?
Answer 13 (p. 50)
1.4.3.14 Question 14
The name of the constructor for a Java class must match the name of the class.
True or False?
Answer 14 (p. 50)
1.4.3.15 Question 15
The method named setDefaultCloseOperation can be called on a Java JFrame object to establish
the behavior of the button with the X in the upper-right corner of the visual manifestation of the JFrame
object.
True or False?
Answer 15 (p. 50)
1.4.3.16 Question 16
A Canvas object's 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.
True or False?
Answer 16 (p. 50)
1.4.3.17 Question 17
A Canvas object's overridden paint method always receives an incoming parameter as type Button .
True or False?
Answer 17 (p. 50)
1.4.3.18 Question 18
The class named Graphics2D is a superclass of the class named Graphics .
True or False?
Answer 18 (p. 50)
1.4.3.19 Question 19
Translating the origin from the default position at the upper-left corner of a Canvas object to the center
of the Canvas object is equivalent to creating a new coordinate frame as explained by Kjell.
True or False?
Answer 19 (p. 50)
1.4.3.20 Question 20
The default direction for increasing vertical coordinate values in a Canvas object is down the screen.
True or False?
Answer 20 (p. 50)
1.4.3.21 Question 21
The default direction for increasing horizontal coordinate values in a Canvas object is from right to left
across the screen.
True or False?
Answer 21 (p. 50)
1.4.3.22 Question 22
According to Kjell, a line drawn on the screen using an object of the Line2D.Double class is a true line
segment.
True or False?
Answer 22 (p. 49)
1.4.3.23 Question 23
Objects instantiated from the classes named Point2D.Double and Line2D.Double are well suited for
inclusion in mathematical operations.
True or False?
Answer 23 (p. 49)
1.4.3.24 Question 24
Creation of 2D and 3D graphics requires that you always display the points.
True or False?
Answer 24 (p. 49)
1.4.3.25 Question 25
A vector is a geometrical object that has two properties: length and direction." He also tells us, "A vector
does not have a position.
True or False?
Answer 25 (p. 49)
1.4.3.26 Question 26
A vector must always specify a position.
True or False?
Answer 26 (p. 49)
1.4.3.27 Question 27
Three real numbers are required to represent a vector in a 2D system.
True or False?
Answer 27 (p. 49)
1.4.3.28 Question 28
A column matrix can be used to represent a point and can also be used to represent a vector.
True or False?
Answer 28 (p. 49)
1.4.3.29 Question 29
Dierent column matrices can be used to represent the same vector in dierent reference frames, in which
case, the contents of the matrices will be dierent.
True or False?
Answer 29 (p. 49)
1.4.3.30 Question 30
The two (or three) real number values contained in a column matrix to represent a point specify an absolute
location in space relative to the current coordinate frame.
True or False?
Answer 30 (p. 49)
1.4.3.31 Question 31
The two (or three) real number values contained in a column matrix to represent a vector (in 2D or 3D)
specify a displacement of a specic distance from an arbitrary point in an arbitrary direction.
True or False?
Answer 31 (p. 48)
1.4.3.32 Question 32
With regard to a vector, in 2D, the two values contained in a column matrix represent the displacements
along three orthogonal axes.
True or False?
Answer 32 (p. 48)
1.4.3.33 Question 33
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.
True or False?
Answer 33 (p. 48)
1.4.3.34 Question 34
In 2D, the direction of a vector can be determined from the angle formed by the x-displacement and the line
segment that represents the hypotenuse of a right triangle formed by the x, y, and z displacements.
True or False?
Answer 34 (p. 48)
1.4.3.35 Question 35
A point is an absolute location , but a vector is a displacement .
True or False?
Answer 35 (p. 48)
1.4.3.36 Question 36
This program instantiates objects from the following non-static top-level classes belonging to the class named
GM2D01 :
• GM2D01.ColMatrix
• GM2D01.Line
• GM2D01.Point
• GM2D01.Vector
True or False?
Answer 36 (p. 48)
1.4.3.37 Question 37
Type int is the default representation for literal real numbers in Java.
True or False?
Answer 37 (p. 48)
1.4.3.38 Question 38
When an object's reference is passed as a parameter to the System.out.println method, the getClass
method belonging to the object is executed automatically.
True or False?
Answer 38 (p. 48)
1.4.3.39 Question 39
The toString method is overloaded in the ColMatrix class.
True or False?
Answer 39 (p. 47)
1.4.3.40 Question 40
If you call the getData method belonging to an object of the GM2D01.ColMatrix class and pass a
parameter value of 2, the program will throw an IndexOutOfBoundsException .
True or False?
Answer 40 (p. 47)
1.4.3.41 Question 41
The constructor for the GM2D01.ColMatrix class requires three incoming parameters of type double
.
True or False?
Answer 41 (p. 47)
1.4.3.42 Question 42
The constructor for the GM2D01.Point class requires a single incoming parameter, which is a reference
to an object of the class GM2D01.ColMatrix .
True or False?
Answer 42 (p. 47)
1.4.3.43 Question 43
GM2D01.Vector and java.util.Vector are simply dierent names for the same class.
True or False?
Answer 43 (p. 47)
1.4.3.44 Question 44
The constructor for the GM2D01.Vector class requires two incoming parameters, which are references
to objects of the class GM2D01.ColMatrix .
True or False?
Answer 44 (p. 47)
1.4.3.45 Question 45
A line segment is the straight path between two points. It has no thickness and therefore cannot be seen by
the human eye.
True or False?
Answer 45 (p. 47)
1.4.3.46 Question 46
The constructor for the GM2D01.Line class requires two incoming parameters, which are references to
objects of the class GM2D01.ColMatrix .
True or False?
Answer 46 (p. 47)
1.4.3.47 Question 47
The GM2D01 library provides methods for rendering objects of the ColMatrix , Line , Point , or
Vector classes in a visual graphics context.
True or False?
Answer 47 (p. 47)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
This image was also inserted for the purpose of inserting space between the questions and the answers.
1.4.4 Answers
1.4.4.1 Answer 47
False. The library named GM2D01 is purely mathematical. The library doesn't provide any mechanism
for rendering objects of the ColMatrix , Line , Point , or Vector classes in a visual graphics
context.
Back to Question 47 (p. 45)
1.4.4.2 Answer 46
False. The constructor for the GM2D01.Line class requires two incoming parameters, which are references
to objects of the class GM2D01.Point .
Back to Question 46 (p. 45)
1.4.4.3 Answer 45
True
Back to Question 45 (p. 45)
1.4.4.4 Answer 44
False. The constructor for the GM2D01.Vector class requires a single incoming parameter, which is a
reference to an object of the class GM2D01.ColMatrix .
Back to Question 44 (p. 45)
1.4.4.5 Answer 43
False. GM2D01.Vector is a dierent class from the class named java.util.Vector in the standard
Java library.
Back to Question 43 (p. 45)
1.4.4.6 Answer 42
True
Back to Question 42 (p. 45)
1.4.4.7 Answer 41
False. The constructor for the GM2D01.ColMatrix class requires two incoming parameters of type
double .
Back to Question 41 (p. 45)
1.4.4.8 Answer 40
True
Back to Question 40 (p. 44)
1.4.4.9 Answer 39
False. The toString method is overridden in the ColMatrix class.
Back to Question 39 (p. 44)
1.4.4.10 Answer 38
False. When an object's reference is passed as a parameter to the System.out.println method, the
toString method belonging to the object is executed automatically.
Back to Question 38 (p. 44)
1.4.4.11 Answer 37
False. Type double is the default representation for literal real numbers in Java.
Back to Question 37 (p. 44)
1.4.4.12 Answer 36
False.
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
1.4.4.13 Answer 35
True
Back to Question 35 (p. 44)
1.4.4.14 Answer 34
False. In 2D, the direction of a vector can be determined from the angle formed by the x-displacement and
the line segment that represents the hypotenuse of a right triangle formed by the x and y displacements.
Back to Question 34 (p. 44)
1.4.4.15 Answer 33
True
Back to Question 33 (p. 43)
1.4.4.16 Answer 32
False. With regard to a vector, in 2D, the two values contained in a column matrix represent the displace-
ments along a pair of orthogonal axes.
Back to Question 32 (p. 43)
1.4.4.17 Answer 31
False. 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 specic distance from an arbitrary point in a specic
direction.
Back to Question 31 (p. 43)
1.4.4.18 Answer 30
True
Back to Question 30 (p. 43)
1.4.4.19 Answer 29
True
Back to Question 29 (p. 43)
1.4.4.20 Answer 28
True
Back to Question 28 (p. 43)
1.4.4.21 Answer 27
False. 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.
Back to Question 27 (p. 43)
1.4.4.22 Answer 26
False. According to Kjell, "A vector does not have a position."
Back to Question 26 (p. 43)
1.4.4.23 Answer 25
True. 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."
Back to Question 25 (p. 42)
1.4.4.24 Answer 24
False. There will be many occasions when you, as a game programmer, will need to dene 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.
Back to Question 24 (p. 42)
1.4.4.25 Answer 23
False. Objects instantiated from the classes named Point2D.Double and Line2D.Double are intended
primarily for rendering graphics on the screen and are not well suited for inclusion in mathematical
operations. That is part of the rationale behind the development of the game-math library: separation of
data objects that are suitable for mathematical operations from graphics objects .
Back to Question 23 (p. 42)
1.4.4.26 Answer 22
False. According to Kjell, the true line segment has no width, and therefore is not visible to the human eye.
This is typically not the case with a line drawn on the screen using an object of the Line2D.Double class.
Back to Question 22 (p. 42)
1.4.4.27 Answer 21
False. The default direction for increasing horizontal coordinate values in a Canvas object is from left to
right across the screen.
Back to Question 21 (p. 42)
1.4.4.28 Answer 20
True
Back to Question 20 (p. 42)
1.4.4.29 Answer 19
True
Back to Question 19 (p. 42)
1.4.4.30 Answer 18
False. The class named Graphics2D is a subclass of (inherits from or is derived from) the class named
Graphics .
Back to Question 18 (p. 42)
1.4.4.31 Answer 17
False. A Canvas object's overridden paint method always receives an incoming parameter as type
Graphics .
Back to Question 17 (p. 41)
1.4.4.32 Answer 16
True
Back to Question 16 (p. 41)
1.4.4.33 Answer 15
True
Back to Question 15 (p. 41)
1.4.4.34 Answer 14
True
Back to Question 14 (p. 41)
1.4.4.35 Answer 13
False. There is no class named GUI in the Java 7 Standard Edition library. It is a name that I often use
for custom classes that present a Graphical User Interface.
Back to Question 13 (p. 41)
1.4.4.36 Answer 12
True
Back to Question 12 (p. 41)
1.4.4.37 Answer 11
False. The correct syntax is shown below. Note the formal argument list of the main method.
note:
1.4.4.38 Answer 10
True
Back to Question 10 (p. 40)
1.4.4.39 Answer 9
False. The name of the Java compiler program is javac.exe . The le named java.exe is the Java virtual
machine.
Back to Question 9 (p. 40)
1.4.4.40 Answer 8
False. The class having the main method must be contained in a le having the same name as the class
with an extension of .java. Good programming practice dictates that even for other classes, the name of
each source code le should match the name of the Java class dened in the le.
Back to Question 8 (p. 40)
1.4.4.41 Answer 7
False. You can use just about any text editor to create your Java source code les as text les with an
extension of .java.
Back to Question 7 (p. 40)
1.4.4.42 Answer 6
False. The same point will have dierent representations in dierent coordinate frames.
Back to Question 6 (p. 40)
1.4.4.43 Answer 5
True
Back to Question 5 (p. 40)
1.4.4.44 Answer 4
8. All of the above
Back to Question 4 (p. 39)
1.4.4.45 Answer 3
True
Back to Question 3 (p. 39)
1.4.4.46 Answer 2
False. 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.
Back to Question 2 (p. 39)
1.4.4.47 Answer 1
False. In order to be a successful game programmer you must be skilled in technologies other than simply
programming. Those technologies include mathematics.
Back to Question 1 (p. 39)
1.4.5 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
This module contains lecture slides keyed to the module titled GAME 2302-0105: Getting Started 40 .
Click here 41 to open an index to the slides.
Then use the links beginning with the label "aa" to open the rst slide that you want to view in a new
window in your browser.
Then use the [Next] and [Prev] links on the individual slides to navigate back and forth through the
slides.
You can also use the links on the index page to jump to a particular slide to avoid having to cycle through
the slides in sequence.
1.5.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
1.6.2 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.
What you have learned
In the previous module, I presented and explained two sample programs and a sample game-programming
math library named GM2D01 , which were intended to implement concepts from Kjell's tutorial in Java
code.
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 version that I will present in this module.
What you will learn
In this module, you will learn how to update the math library to provide a number of new capabilities
including the addition of graphics and various set methods. You will also learn that the addition of
set methods exposes certain vulnerabilities, and you will learn how to protect against those vulnerabilities.
Finally, you will learn how to draw on o-screen images.
1.6.2.1.1 Images
• Image 1 (p. 56) . Screen output from both sample programs.
• Image 2 (p. 85) . Graphic output from Exercise 1.
• Image 3 (p. 86) . Graphic output from Exercise 2.
• Image 4 (p. 87) . Graphic output from Exercise 3.
• Image 5 (p. 88) . Text output from Exercise 3.
1.6.2.1.2 Listings
• Listing 1 (p. 59) . Beginning of the class named PointLine03 and the class named GUI.
• Listing 2 (p. 60) . Beginning of the constructor for the GUI class.
• Listing 3 (p. 60) . Create two o-screen images.
• Listing 4 (p. 61) . Remaining code in the constructor.
• Listing 5 (p. 62) . Beginning of the drawOscreen method.
• Listing 6 (p. 63) . Dene four lines that will be used to draw borders.
• Listing 7 (p. 64) . Draw a visual manifestation of each line.
• Listing 8 (p. 65) . The draw method of the GM2D02.Line class.
• Listing 9 (p. 66) . Draw a visual manifestation of a GM2D02.Point object.
• Listing 10 (p. 66) . The draw method of the GM2D02.Point class.
• Listing 11 (p. 67) . Draw the vertices of a hexagon.
• Listing 12 (p. 68) . Draw six lines connecting the vertices of the hexagon.
• Listing 13 (p. 69) . Instantiate three objects of type GM2D02.Vector.
• Listing 14 (p. 69) . Call the draw method to draw the vector.
• Listing 15 (p. 70) . The draw method of the GM2D02.Vector class.
• Listing 16 (p. 71) . Three visual manifestations of the same vector.
• Listing 17 (p. 72) . Draw the blue vector.
• Listing 18 (p. 72) . The MyCanvas class and the overridden paint method.
• Listing 19 (p. 73) . The setData method of the ColMatrix class.
• Listing 20 (p. 74) . Updated constructor for the Point class in GM2D02.
• Listing 21 (p. 75) . The drawOscreen method of the program named PointLine04.
• Listing 22 (p. 75) . Instantiate a point at the upper-left corner.
• Listing 23 (p. 76) . Instantiate a moveable Point object.
• Listing 24 (p. 76) . Instantiate a moveable Line object.
• Listing 25 (p. 77) . Relocate the Line to three more locations.
• Listing 26 (p. 80) . Source code for the game-math library class named GM2D02.
• Listing 27 (p. 82) . Source code for the program named PointLine03.
• Listing 28 (p. 84) . Source code for the program named PointLine04.
• Listing 29 (p. 88) . Code for generating random values in Java.
So far, we have been dealing with column matrices, points, vectors, and lines. (We will get to other topics
in future modules.)
What is a point?
According to Kjell, a point is simply a location in space. It has no width, depth, or height. Therefore, it
cannot be seen by the human eye, which means that we can't draw a point on the computer screen. However,
it is possible to draw an object on the computer screen that indicates the location of the point.
What do I mean by this?
Suppose you go out onto your driveway and establish that one corner of the driveway represents the
origin in a rectangular Cartesian coordinate framework. Then you use measuring devices to identify a
specic location on the driveway. You can point to that location with your nger, and others can see your
nger, but they can't see the point. Once again, the point has no width, height, or depth, and therefore
cannot be seen by the human eye.
1.26
The left image in Image 1 (p. 56) contains seven small circles. Each of those seven circles marks the
location of a point in the 2D space of the image. However, those circles are not the points. The seven points
consist solely of coordinate values and are not visible to the human eye. The seven circles are graphics
objects that were placed there to mark the locations in space of the seven points. The points existed in
the 2D space before the graphics objects were created, and would have existed even if I had not caused the
circles to be drawn to mark the locations of the points.
What is a line segment?
This can be even more confusing. Kjell tells us that a line segment is the straight path between two
points, and that it has no thickness. Since it has no thickness, a line cannot be seen by the human eye.
The left image in Image 1 (p. 56) contains six graphic objects that we are likely to call lines or line
segments. True enough, those graphic objects mark the path taken by the lines that represent straight
paths between the pairs of points whose locations are indicated by the circles. However, those graphic objects
are not lines in the context of this discussion. Rather, they are simply graphic objects that were used to
mark the paths of the lines in a visual way for the benet of a human observer.
Why am I emphasizing this so heavily?
Shortly, you will see the changes that I made to the game-math library in preparation for this module.
That library makes it possible for you to easily create and manipulate underlying data objects for column
matrices, points, vectors, and lines. Those changes include the ability for points, lines, and vectors to create
graphical objects that represent themselves and to display those graphical objects on a specied graphics
context upon request.
The left image in Image 1 (p. 56) shows the manner in which GM2D02.Point objects and
GM2D02.Line objects represent themselves on a graphics context.
The right image in Image 1 (p. 56) shows the manner in which GM2D02.Vector objects represent
themselves on a graphics context.
It is very important to understand the dierence between the objects that encapsulate the underlying
data and the graphic objects that represent those objects for visible human consumption. Later on, we will
be doing math using the underlying data objects. However, it is generally not possible to do math using the
graphic objects shown in Image 1 (p. 56) .
Additional modications that I made to the library for this module makes it is easy to modify the values
encapsulated in one of the underlying data objects. However, once the graphical representation of one of
those data objects is drawn on the graphics context, it is fairly dicult to modify, particularly if it overlaps
another graphic object that you don't want to modify. The library does not provide that capability.
All Java parameters are passed to methods by value
Moving to a completely dierent topic, when you call out the name of a variable as a parameter to be
passed to a method in Java, a copy of the contents of that variable is made and the copy is passed to the
method. Code in the method can modify the copy but it cannot modify the contents of the original variable.
This is typically referred to as passing parameters by value . (Despite what you may have read elsewhere,
unlike C and C++, Java parameters are never passed by reference.)
However, Java supports both primitive variables and reference variables. Passing reference variables by
value exposes some vulnerabilities in the original version of the library when set methods are added to the
library. A complete explanation of this topic is beyond the scope of this module. However, I will show you
how I modied the code in the library to protect against such vulnerabilities.
1.6.4 Preview
I will explain the changes to the library in this module in conjunction with two programs that illustrate the
impact of those changes. Both programs produce the screen output shown in Image 1 (p. 56) , but they do
so in signicantly dierent ways.
The primary topics to be discussed have to do with:
• Making it possible for the underlying data objects to represent themselves by drawing graphical objects
on a specied 2D graphics context upon request.
• Making it possible to call set methods to modify the data encapsulated in the underlying data
objects.
• Protecting the data from corruption due to certain vulnerabilities exposed by adding set methods to
the library.
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this module and previous modules.
Much of the code in the library remains unchanged. I explained that code in the previous module and I
won't repeat that explanation in this module. Rather, in this module, I will concentrate on explaining the
modications that I made to the library.
Listing 1: Beginning of the class named PointLine03 and the class named GUI.
class PointLine03{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine03
//======================================================//
1.27
The code in the main method instantiates an object of the GUI class. The code showing in the
GUI class denition declares several instance variables, initializing some of them.
Beginning of the constructor for the GUI class
Listing 2 (p. 60) shows the beginning of the constructor for the GUI class.
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
1.28
The code in Listing 2 (p. 60) is straightforward and shouldn't require an explanation beyond the embed-
ded comments.
Create two o-screen images
Here is where things begin to get interesting. Listing 3 (p. 60) creates two o-screen images and gets a
graphics context on each of them.
osiA = createImage(osiWidth,osiHeight);
Graphics2D g2Da = (Graphics2D)(osiA.getGraphics());
osiB = createImage(osiWidth,osiHeight);
Graphics2D g2Db = (Graphics2D)(osiB.getGraphics());
1.29
Java programs are not constrained to simply draw on the screen. It is possible to create an o-screen
image, get a graphics context on it, and use methods of the Graphics and/or Graphics2D classes to
draw on the o-screen image.
The o-screen image can then be used for a variety of purposes including:
drawOffscreen(g2Da,g2Db);
myCanvas.repaint();
}//end constructor
1.30
Listing 4 (p. 61) begins by calling the method named drawOscreen to draw some points, lines, and
vectors on the two o-screen images. Note that references to each of the two graphics contexts are passed
as parameters to the drawOscreen method.
Then Listing 4 (p. 61) calls the repaint method belonging to the MyCanvas object to cause the
overridden paint method belonging to that object to be executed. Later, we will see that the overridden
paint method copies the two o-screen images to the canvas in the side-by-side format shown in Image 1
(p. 56) causing the contents of those o-screen images to be displayed in a JFrame object.
Beginning of the drawOscreen method
The beginning of the drawOscreen method is shown in Listing 5 (p. 62) . The purpose of this method
is to dene points, lines, and vectors as underlying data objects and then to cause a visual manifestation of
some of the points, lines, and vectors to be drawn onto the two o-screen images.
1.31
Before getting into the underlying data objects, however, Listing 5 (p. 62) calls the drawString method
belonging to the Graphics class to draw the two text strings shown in Image 1 (p. 56) on the two o-screen
images.
Instantiate four Line objects that will be used to draw borders
Listing 6 (p. 63) instantiates four GM2D02.Line objects that will ultimately be used to draw the
borders around the left and right images shown in Image 1 (p. 56) .
1.32
1.33
As you will see shortly, each of these calls to the draw method causes an object of the standard Java
Line2D.Double class to be rendered onto the specied o-screen image. When the o-screen image is
ultimately copied to the canvas object by the overridden paint method, this produces a visual manifestation
of the GM2D02.Line object.
Once again, however, it is very important to understand that the Line2D.Double object is a graphical
object and the GM2D02.Line is an underlying data object. They are completely independent objects.
Also, it is important to understand that the Line2D.Double class is a member of the standard Java
library, whereas the GM2D02.Line class is a member of my special game math library named GM2D02
.
The draw method of the GM2D02.Line class
Now it's time to explain one of the methods that was added to the original game-math library named
GM2D01 to produce the new library named GM2D02 . At this point, I will start switching back and
forth between code in the GM2D02 library and code in the program named PointLine03 .
Listing 8 (p. 65) shows the draw method that was called repeatedly on the GM2D02.Line objects
in Listing 7 (p. 64) . This code belongs to the GM2D02 library.
1.34
g2Da.translate(osiWidth/2.0,osiHeight/2.0);
1.35
This is equivalent to changing the coordinate frame described by Kjell and discussed in the previous
module.
Then the code in Listing 9 (p. 66) denes a GM2D02.Point object located at the origin of the new
coordinate frame and calls the draw method on that object to produce the visual manifestation of the
object in the center of the left image in Image 1 (p. 56) .
Once again, the GM2D02.Point object is an underlying data object. The visual manifestation will be
produced by an object of the Java standard class named Ellipse2D.Double , which will be a completely
independent object.
The draw method of the GM2D02.Point class
Listing 10 (p. 66) shows the draw method that was added to the GM2D02.Point class to produce
the updated game-math library. This method draws a small circle around the location of the point on the
specied graphics context.
1.36
The logic behind this method is very similar to the logic that I explained relative to Listing 8 (p. 65) .
The constructor for the Java standard Ellipse2D.Double class requires four incoming parameters that
specify the coordinates of the upper-left corner of a rectangle followed by the width and the height of the
rectangle. The new object of type Ellipse2D.Double represents an ellipse that is bounded by the four
sides of the rectangle. If the rectangle is square, the ellipse becomes a circle.
(In this case, the rectangle is a 6x6 square, thus producing a circle with a diameter of six pixels.)
Listing 10 (p. 66) calls the draw method of the Graphics2D class to render the ellipse (circle) at
the specied location on the graphics context specied by the incoming parameter. Thus the code in Listing
9 (p. 66) produces a visual manifestation of a point at the origin of the current coordinate frame. The visual
manifestation consists of a small circle centered on the location of the point, resulting in the small circle at
the center of the left image in Image 1 (p. 56) .
Draw the vertices of a hexagon
Returning once more to the drawOScreen method of the program named PointLine03 , Listing
11 (p. 67) instantiates six GM2D02.Point objects that represent the vertices of a hexagon that is
symmetrically located relative to the origin in the current coordinate frame
1.37
Then Listing 11 (p. 67) calls the draw method of the GM2D02.Point class six times in succession
to cause small circles that represent the six points to be rendered on the specied o-screen image. You can
see those six circles in the left image in Image 1 (p. 56) .
Draw six lines connecting the vertices of the hexagon
Listing 12 (p. 68) instantiates six objects of the GM2D02.Line class whose endpoints are specied
by the six GM2D02.Point objects from Listing 11 (p. 67) , taken in pairs.
Listing 12: Draw six lines connecting the vertices of the hexagon.
1.38
Then Listing 12 (p. 68) calls the draw method belonging to the GM2D02.Line class six times in
succession to cause visible lines to be rendered on the specied o-screen image. You can see those six lines
in the left image in Image 1 (p. 56) .
That completes the drawing that is performed on the o-screen image shown in the left image in Image
1 (p. 56) . Next I will explain the drawing that is performed on the o-screen image that is shown as the
right image in Image 1 (p. 56) .
Instantiate three objects of type GM2D02.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."
The right image in Image 1 (p. 56) shows visual manifestations of three dierent objects of the
GM2D02.Vector class. One vector is represented as a red line with a small red circle at its head. A
second vector is represented as a blue line with a small blue circle at its head. The third vector is shown in
three dierent positions represented by green lines with small green circles at their heads.
Listing 13 (p. 69) instantiates three objects of the GM2D02.Vector class, which are visually repre-
sented by the red, green, and blue lines in Image 1 (p. 56) . References to these three objects are saved in
the variables named vecA , vecB , and vecC in Listing 13 (p. 69) .
1.39
g2Db.setColor(Color.RED);
vecA.draw(g2Db,new GM2D02.Point(
new GM2D02.ColMatrix(0,0)));
1.40
Note that two parameter are passed to the draw method in Listing 14:
• A reference to the o-screen graphics context on which the visual manifestation of the vector will be
drawn.
• A new object of the class GM2D02.Point that will be used to determine the position on the
o-screen image in which the visual manifestation will appear.
Remember that according to Kjell, a vector doesn't have a position. Hence, there is nothing in the underlying
data for a GM2D02.Vector object that species a position. In other words, the visual manifestation of
a vector can be placed anywhere in space, and one placement is just as correct as the next. However, if you
become heavily involved in the use of vectors, you will learn that certain placements may be preferable to
others in some cases so as to better represent the problem being modeled by the use of vectors.
The draw method of the GM2D02.Vector class
Switching once again to the GM2D02 library, Listing 15 (p. 70) shows the draw method that was
added to the GM2D02.Vector class. This method is a little longer than the draw methods that I
explained earlier for points and lines. This is mainly because:
• it is necessary to deal with the issue of positioning the visual manifestation of the GM2D02.Vector
object, and
• it is necessary to embellish the drawing to make it possible to visually determine which end is the tail
and which end is the head.
This method renders a visual manifestation of a GM2D02.Vector on the specied graphics context, with
the tail of the vector located at a point specied by the contents of a GM2D02.Point object. A small
circle is drawn to visually identify the head of the vector.
1.41
g2Db.setColor(Color.GREEN);
vecB.draw(g2Db,new GM2D02.Point(new GM2D02.ColMatrix(
vecA.getData(0),vecA.getData(1))));
vecB.draw(g2Db,new GM2D02.Point(new GM2D02.ColMatrix(
vecA.getData(0)-10,vecA.getData(1)+15)));
vecB.draw(g2Db,new GM2D02.Point(new GM2D02.ColMatrix(
vecA.getData(0)+10,vecA.getData(1)-60)));
1.42
This is a perfectly legitimate thing to do since the underlying data encapsulated in the Vector object
does not contain any information relating to the position of the visual manifestation.
In one visual manifestation, Listing 16 (p. 71) causes the tail of vecB to coincide with the head of
vecA . This is one of those cases where drawing the vector in one position is preferable to drawing it in
a dierent position. Later on when we get into the topic of vector addition, I will explain that one way to
perform graphical addition of vectors is to position the vectors in a tail-to-head relationship as indicated by
the red and green vectors in Image 1 (p. 56) . The sum of the vectors can then be determined graphically
by drawing a line from the tail of the rst vector to the head of the last vector as indicated by the blue line
in Image 1 (p. 56) . The length of the sum (or resultant) vector is indicated by the length of that line, and
the direction of the resultant vector is indicated by the orientation of that line.
A practical example
This is the solution to a classical problem in a freshman engineering class. Assume that a boat is traveling
diagonally across a river with a strong current. Assume that the green vector in Image 1 (p. 56) represents
the speed and direction of the current in the river. Assume that the red vector represents the speed and
direction that the boat would travel if there were no current. Because of the eect of the current on the
boat, the actual speed and direction of the boat will be given by the blue vector, which is dierent from the
speed and direction indicated by the red vector. If the blue vector is pointing at the desired landing point
on the other side of the river, everything is okay. Otherwise, the captain needs to change the speed and/or
the direction of the boat to compensate for the eect of the current on the boat.
Draw the blue vector
Listing 17 (p. 72) produces the blue visual manifestation of the Vector object referred to by vecC
as shown in Image 1 (p. 56) .
g2Db.setColor(Color.BLUE);
vecC.draw(g2Db,new GM2D02.Point(
new GM2D02.ColMatrix(0,0)));
}//end drawOffscreen
1.43
Listing 17 (p. 72) also signals the end of the method named drawOscreen .
The MyCanvas class and the overridden paint method
Listing 18 (p. 72) shows the entire inner class named MyCanvas including the overridden paint
method belonging to that class.
Listing 18: The MyCanvas class and the overridden paint method.
1.44
The overridden paint method will be called when the JFrame and the Canvas appear on the
screen or when the repaint method is called on the Canvas object.
The method is also called when some screen activity requires the JFrame to be redrawn (such as
minimizing and then restoring the JFrame ) .
The purpose of the paint method in this program is to call the drawImage method twice in succession
to draw the two o-screen images on the screen in the side-by-side format shown in Image 1 (p. 56) .
The rst parameter to the drawImage method is the o-screen image that is to be drawn on the
canvas. The second and third parameters specify the location where the upper-left corner of the image will
be drawn.
The fourth parameter is a reference to an ImageObserver object, which is essentially a dummy image
observer in this case, because an actual image observer isn't needed. (To learn more about image observers,
see The AWT Package, Graphics- Introduction to Images 43 .)
43 http://www.dickbaldwin.com/java/Java170.htm
1.45
This is a very simple method, which should not require further explanation. I am presenting it here
mainly for the purpose of leading into a discussion of the vulnerabilities that this method could expose on
Point and Vector objects instantiated from the original math class named GM2D01 ,
You may recall from the module titled Getting Started that the constructor for the Point class in the
original library received and saved a reference to an object of the ColMatrix class that contained the two
values required to dene the Point . Now that it is possible to change the values stored in an object of
the ColMatrix class, if such an object is used to instantiate an object of the Point class and then the
values stored in the ColMatrix object are changed, the values that dene the Point object will change
accordingly. That is not good.
Updated constructor for the Point class in GM2D02
Continuing with code in the GM2D02 library, Listing 20 (p. 74) shows the updated constructor in
the new version of the library.
Point(GM2D02.ColMatrix point){//constructor
this.point =
new ColMatrix(point.getData(0),point.getData(1));
}//end constructor
1.46
The new version of the constructor for the Point class creates and saves a clone of the ColMatrix
object used to dene the point to prevent the point from being corrupted by a later change in the values
stored in the original ColMatrix object through the use of its new setData method.
Updated constructor for the Vector class in GM2D02
Because the constructor for the Vector class in the original library was essentially the same as the
constructor for the Point class, the addition of the setData method to the ColMatrix class created
the same vulnerability for objects instantiated from the Vector class. Essentially the same correction was
made for the constructor for the Vector class. You can view the new code in Listing 26 (p. 80) .
Additional changes to the library
In addition to the changes described above, the following changes were made to the game-math library to
update it from version GM2D01 to GM2D02 . All of the changes were straightforward and shouldn't
require an explanation beyond the embedded comments. You can view the new code for all of these changes
in Listing 26 (p. 80) .
1.47
As before, the purpose of the drawOscreen method is to dene points, lines, and vectors and then
to cause a visual manifestation of some of the points, lines, and vectors to be drawn onto two separate o-
screen images. Unlike before, however, this version of the method uses a minimum number of underlying data
objects to produce the output, thereby emphasizing the dierences between graphics objects and underlying
data objects.
The code in Listing 21 (p. 75) is essentially the same as before and doesn't require any explanation.
Borders
As before, and as shown in Image 1 (p. 56) , this method draws borders on each of the o-screen images
by drawing lines parallel to the edges of the o-screen images. Each line is oset by one pixel toward the
center of the o-screen image.
Instantiate a point at the upper-left corner
Listing 22 (p. 75) instantiates and saves an underlying data object of type Point containing coordinate
values for the upper left corner. This object will be used as one endpoint for a moveable Line object
from which the top and left borders will be drawn.
1.48
1.49
The location of this point will be modied several times during the drawing of the border by calling the
setData method on the point. The initial location of this point is the upper-right corner. (Recall that
the origin is at the upper-left corner of both o-screen images at this point in the program.) The call to
the Point constructor causes the y-coordinate to be the same as the y-coordinate for the Point object
instantiated in Listing 22 (p. 75) .
Instantiate a moveable Line object
Listing 24 (p. 76) instantiates a Line object that will be modied several times in succession by calling
its setHead and setTail methods to place it in four dierent locations.
1.50
This Line object will be used to draw the top, right, bottom, and left lines that make up the border. It
is used in Listing 24 (p. 76) to cause a graphical Line2D.Double object to be instantiated and rendered
as the line at the top of both of the o-screen images.
Relocate the Line to three more locations
Listing 25 (p. 77) calls various methods of the Point and Line classes (including setData ,
setTail , and setHead ) to relocate the GM2D02.Line object to three more locations, each parallel
to an edge of an o-screen image.
1.51
Click here 44 to download a zip le containing standard javadoc documentation for the library named
GM2D02 . Extract the contents of the zip le into an empty folder and open the le 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 (p. 80)
26 (p. 80) and the explanations given above) , the documentation does provide a good overview of the
organization and structure of the library. You may nd it helpful in that regard.
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 study the Kjell tutorial through Chapter 2 Column
and Row Matrix Addition .
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 45 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.
I encourage you to copy the code from Listing 26 (p. 80) , Listing 27 (p. 82) , and Listing 28 (p. 84) ,
compile it, and execute it. Experiment with it, making changes, and observing the results of your changes.
Make certain that you can explain why your changes behave as they do.
1.6.9 Summary
In this module, you learned how to update the game-math library to provide a number of new capabilities
including the addition of graphics to the library and the addition of set methods for column matrices,
points, vectors, and lines.
You also saw sample programs that illustrate the use of those new capabilities and you learned how to
draw on o-screen images.
In the next module, you will learn how to compare column matrices for equality, how to compare two points
for equality, how to compare two vectors for equality, how to add one column matrix to another, how to
subtract one column matrix from another, and how to get a displacement vector from one point to another.
1.6.11 Miscellaneous
• Revised: 12/31/12
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 26 (p. 80) through Listing
28 (p. 84) below.
Listing 26: Source code for the game-math library class named GM2D02.
/*GM2D02.java
Copyright 2008, R.G.Baldwin
Revised 02/03/08
/*PointLine03.java
Copyright 2008, R.G.Baldwin
Revised 02/03/08
class PointLine03{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine03
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*PointLine04.java
Copyright 2008, R.G.Baldwin
Revised 02/03/08
class PointLine04{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class PointLine04
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Available
//This object must be for free at Connexions
visible before you<http://cnx.org/content/col11450/1.29>
can get an
// off-screen image. It must also be visible before
// you can compute the size of the canvas.
setVisible(true);
85
1.6.13 Exercises
1.6.13.1 Exercise 1
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws a horizontal line segment and a vertical line segment representing
the x and y axes in a 2D Cartesian coordinate system as shown in Image 2 (p. 85) .
Cause the origin of your reference frame be at the center of your drawing.
Cause the positive x direction be to the right.
Cause the positive y direction be either up or down according to your choice.
Cause the program to display your name in some manner.
1.55
1.6.13.2 Exercise 2
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws x and y axes in a 2D Cartesian coordinate system as shown in
Image 3 (p. 86) .
Cause the origin of your reference frame be at the center of your drawing.
Cause the positive x direction be to the right.
Cause the positive y direction be either up or down according to your choice.
Then draw small circles that represent the locations of points at the following coordinates in the reference
frame as shown in Image 3 (p. 86) .
• x = -30, y = -40
• x = 30, y = -40
• x = 30, y = 40
1.56
1.6.13.3 Exercise 3
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws x and y axes in a 2D Cartesian coordinate system as shown in
Image 4 (p. 87) .
Cause the origin of your reference frame be at the center of your drawing.
Cause the positive x direction be to the right.
Cause the positive y direction be either up or down according to your choice.
Create six random values in the range from -128 to +127. Use those values as the x and y coordinates
for three points in the 2D reference frame. (The code fragment in Listing 29 (p. 88) shows how to generate
random values in the required range in Java.)
Display the six values on a text screen labeled in such a way that it is possible to associate the values
with the points as shown in Image 5 (p. 88) .
Draw three small circles that represent the locations of the points.
Draw three line segments that connect the three points in pairs creating the shape of a triangle.
Cause the program to display your name in some manner.
1.57
point0X: -55
point0Y: 17
point1X: 9
point1Y: -37
point2X: 14
point2Y: 62
1.58
1.59
1.6.13.4 Exercise 4
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws three small circles that represent the locations of points at the
following coordinates in a 2D reference frame.
• point0X = -30
• point0Y = 0
• point1X = 30
• point1Y = 40
• point2X = 30
• point2Y = -40
Then draw three line segments that extend from edge-to-edge of your drawing and intersect the three points
in pairs as shown in Image 6 (p. 89) .
Cause the origin of your reference frame be at the center of your drawing.
Cause the positive x direction to be to the right.
Cause the positive y direction be either up or down according to your choice.
Cause the program to display your name in some manner.
1.60
1.6.13.5 Exercise 5
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws 24 vectors tail-to-tail in alternating colors of red, green, and blue
as shown in Image 7 (p. 90) .
The rst vector is red.
The length of each vector is 100 pixels.
The direction of the rst vector is +7.5 degrees relative to the horizontal.
The direction of each successive vector is increased by 15 degrees.
For example, the directions of the rst four vectors are:
• 7.5
• 22.5
• 37.5
• 52.5
Draw the symbol of your choice to identify the head of each vector.
Draw the axes for a Cartesian coordinate system in the reference frame.
Cause the positive x direction to be to the right.
Cause the positive y direction be either up or down according to your choice.
Cause positive angles to be either clockwise or counter-clockwise according to your choice.
Cause the program to display your name in some manner.
1.61
1.6.13.6 Exercise 6
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws 24 vectors tail-to-head in alternating colors of red, green, and
blue as shown in Image 8 (p. 91) .
The rst vector is red.
1.62
1.6.13.7 Exercise 7
Using Java and the game-math library named GM2D02 , or using a dierent programming environment
of your choice, write a program that draws 24 vectors tail-to-head in alternating colors of red, green, and
blue as shown in Image 9 (p. 92) .
The rst vector is red.
Begin with a length of 24 pixels for the rst vector and reduce the length of each successive vector by
one pixel.
Draw the symbol of your choice to identify the head of each vector.
Draw the axes for a Cartesian coordinate system in the reference frame.
Cause the positive x direction to be to the right.
Cause the positive y direction be either up or down according to your choice.
Cause positive angles to be either clockwise or counter-clockwise according to your choice.
Cause the program to display your name in some manner.
1.63
-end-
1.7.2 Preface
This module contains review questions and answers keyed to the module titled GAME 2302-0110: Updating
the Game Math Library for Graphics 47 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
1.7.3 Questions
1.7.3.1 Question 1 .
A point is simply a location in space. It has no width, depth, or height. Therefore, it cannot be seen by the
human eye, which means that we can't draw a point on the computer screen. However, it is possible to draw
an object on the computer screen that indicates the location of the point.
True or False?
Answer 1 (p. 102)
1.7.3.2 Question 2
A point in space exists only after a visual object is created to mark the location of the point.
Answer 2 (p. 101)
1.7.3.3 Question 3
A point is a small black circle.
True or False?
Answer 3 (p. 101)
1.7.3.4 Question 4
Kjell tells us that a line segment is the straight path between two points, and that it has no thickness. Since
it has no thickness, a line cannot be seen by the human eye.
True or False?
Answer 4 (p. 101)
46 This content is available online at <http://cnx.org/content/m45586/1.3/>.
47 http://cnx.org/content/m45009
1.7.3.5 Question 5
GM2D02.Point objects represent themselves as small black squares in a graphics context for the benet
of human observers.
True or False?
Answer 5 (p. 101)
1.7.3.6 Question 6
GM2D02.Vector objects represent themselves as lines with arrow-heads at their heads in a graphics
context for the benet of human observers.
True or False?
Answer 6 (p. 101)
1.7.3.7 Question 7
A GM2D02.Vector object is:
Select the correct answer
• A. An underlying data object
• B. A graphics object
• C. Both of the above
• D. None of the above
Answer 7 (p. 101)
1.7.3.8 Question 8
All Java parameters are passed to methods by reference.
True or False?
Answer 8 (p. 101)
1.7.3.9 Question 9
Java supports both primitive variables and reference variables.
True or False?
Answer 9 (p. 101)
1.7.3.10 Question 10
The GM2D02 library is an update of the earlier game-math library named GM2D01 . This update
added the following new capabilities:
Select the correct answer.
• A. Draw circles to represent GM2D02.Point objects.
• B. Draw visible lines to represent GM2D02.Line objects.
• C. Draw visible lines and circles to represent GM2D02.Vector objects.
• D. Call a setData method to change the values in a GM2D02.ColMatrix object.
• E. Call a setData method to change the values in a GM2D02.Point object.
• F. Call a setData method to change the values in a GM2D02.Vector object.
• G. Call a setHead method or a setTail method to change one of the points that denes a
GM2D02.Line object.
• H. All of the above
• I. None of the above
Answer 10 (p. 101)
1.7.3.11 Question 11
The updated constructors in the GM2D02 library create and save clones of the ColMatrix and/or
Point objects originally used to dene the Point , Vector , and/or Line objects.
True or False?
Answer 11 (p. 101)
1.7.3.12 Question 12
The createImage method belonging to a JFrame object can be used to create an o-screen image.
True or False?
Answer 12 (p. 100)
1.7.3.13 Question 13
If the contents of an o-screen image are displayed on the screen, the units of width and height are measured
in pixels.
True or False?
Answer 13 (p. 100)
1.7.3.14 Question 14
The returned value of the createImage method is type JFrame .
True or False?
Answer 14 (p. 100)
1.7.3.15 Question 15
The return type of the getGraphics methods is Graphics .
True or False?
Answer 15 (p. 100)
1.7.3.16 Question 16
Objects instantiated from the GM2D02.Point and GM2D02.Line classes are not graphical objects.
True or False?
Answer 16 (p. 100)
1.7.3.17 Question 17
Objects instantiated from the GM2D02.Point and GM2D02.Line classes are underlying data objects
that are suitable for use in mathematical operations.
True or False?
Answer 17 (p. 100)
1.7.3.18 Question 18
draw method of the GM2D02.Line class causes an object of the standard Java
A call to the
Point2D.Double class to be rendered onto the specied graphics context.
True or False?
Answer 18 (p. 100)
1.7.3.19 Question 19
The Line2D.Double object is a graphical object and the GM2D02.Line is an underlying data object.
True or False?
Answer 19 (p. 100)
1.7.3.20 Question 20
The GM2D02.Line class is a member of the standard Java library, whereas the Line2D.Double class
is a member of the special game math library named GM2D02 .
True or False?
Answer 20 (p. 100)
1.7.3.21 Question 21
One of the problems with object-oriented programming is that objects don't know how to do useful things
for themselves.
True or False?
Answer 21 (p. 100)
1.7.3.22 Question 22
A call to the draw method of the GM2D02.Point class causes an object of the standard Java
Ellipse2D.Double class to be rendered onto the specied graphics context.
True or False?
Answer 22 (p. 99)
1.7.3.23 Question 23
The constructor for the Java standard Ellipse2D.Double class requires four incoming parameters that
specify the coordinates of the upper-left corner of a rectangle followed by the width and the height of the
rectangle.
True or False?
Answer 23 (p. 99)
1.7.3.24 Question 24
An object of type Ellipse2D.Double represents an ellipse that is bounded by the four sides of a rectangle.
If the rectangle is square, the ellipse becomes a square.
True or False?
Answer 24 (p. 99)
1.7.3.25 Question 25
Kjell tells us that a vector is a geometrical object that has two properties: length and direction. He also
tells us that a vector does not have a position.
True or False?
Answer 25 (p. 99)
1.7.3.26 Question 26
The draw method of the GM2D02.Vector class requires three parameters:
True or False?
Answer 26 (p. 99)
1.7.3.27 Question 27
The visual manifestation of a vector can be placed anywhere in space, and one placement is just as correct
as the next
True or False?
Answer 27 (p. 99)
1.7.3.28 Question 28
Although the visual manifestation of a vector can be placed anywhere in space, and one placement is just as
correct as the next, certain placements may be preferable to others in some cases so as to better represent
the problem being modeled by the use of vectors.
True or False?
Answer 28 (p. 99)
1.7.3.29 Question 29
The rendering of a GM2D02.Vector object by the draw method of the GM2D02.Vector class draws
a small circle to visually identify the head of the vector.
True or False?
Answer 29 (p. 99)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
This image was also inserted for the purpose of inserting space between the questions and the answers.
1.7.4 Answers
1.7.4.1 Answer 29
True
Back to Question 29 (p. 97)
1.7.4.2 Answer 28
True. One example is the graphical addition of vectors using the tail-to-head placement.
Back to Question 28 (p. 97)
1.7.4.3 Answer 27
True, because according to Kjell, a vector doesn't have a position. Hence, there is nothing in the underlying
data for a GM2D02.Vector object that species a position.
Back to Question 27 (p. 97)
1.7.4.4 Answer 26
False. The draw method of the GM2D02.Vector class requires two parameters:
1.7.4.5 Answer 25
True
Back to Question 25 (p. 96)
1.7.4.6 Answer 24
False. An object of type Ellipse2D.Double represents an ellipse that is bounded by the four sides of a
rectangle. If the rectangle is square, the ellipse becomes a circle .
Back to Question 24 (p. 96)
1.7.4.7 Answer 23
True
Back to Question 23 (p. 96)
1.7.4.8 Answer 22
True
Back to Question 22 (p. 96)
1.7.4.9 Answer 21
False. One of the hallmarks of object-oriented programming is that objects do know how to do useful things
for themselves.
Back to Question 21 (p. 96)
1.7.4.10 Answer 20
False. The Line2D.Double class is a member of the standard Java library, whereas the GM2D02.Line
class is a member of the special game math library named GM2D02 .
Back to Question 20 (p. 96)
1.7.4.11 Answer 19
True
Back to Question 19 (p. 96)
1.7.4.12 Answer 18
False. A call to the draw method of the GM2D02.Line class causes an object of the standard Java
Line2D.Double class to be rendered onto the specied graphics context.
Back to Question 18 (p. 95)
1.7.4.13 Answer 17
True
Back to Question 17 (p. 95)
1.7.4.14 Answer 16
True
Back to Question 16 (p. 95)
1.7.4.15 Answer 15
True
Back to Question 15 (p. 95)
1.7.4.16 Answer 14
False. The returned value of the createImage method is type Image .
Back to Question 14 (p. 95)
1.7.4.17 Answer 13
True
Back to Question 13 (p. 95)
1.7.4.18 Answer 12
True
Back to Question 12 (p. 95)
1.7.4.19 Answer 11
True
Back to Question 11 (p. 95)
1.7.4.20 Answer 10
H. All of the above
Back to Question 10 (p. 94)
1.7.4.21 Answer 9
True
Back to Question 9 (p. 94)
1.7.4.22 Answer 8
False. All Java parameters are passed to methods by value.
Back to Question 8 (p. 94)
1.7.4.23 Answer 7
A. An underlying data object
Back to Question 7 (p. 94)
1.7.4.24 Answer 6
False. GM2D02.Vector objects represent themselves as lines with small circles at their heads in a
graphics context for the benet of human observers.
Back to Question 6 (p. 94)
1.7.4.25 Answer 5
False. GM2D02.Point objects represent themselves as small black circles in a graphics context for the
benet of human observers.
Back to Question 5 (p. 94)
1.7.4.26 Answer 4
True
Back to Question 4 (p. 93)
1.7.4.27 Answer 3
False. A point is simply a location in space. It has no width, depth, or height. Therefore, it cannot be seen
by the human eye, which means that we can't draw a point on the computer screen. However, it is possible
to draw an object on the computer screen that indicates the location of the point.
Back to Question 3 (p. 93)
1.7.4.28 Answer 2
False. Points in space exist regardless of whether or not visual objects are created to mark the locations of
the points.
Back to Question 2 (p. 93)
1.7.4.29 Answer 1
True
Back to Question 1 (p. 93)
1.7.5 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
This module contains lecture slides keyed to the module titled GAME 2302-0110: Updating the Game Math
Library for Graphics 49 .
Click here 50 to open an index to the slides.
Then use the links beginning with the label "aa" to open the rst slide that you want to view in a new
window in your browser.
Then use the [Next] and [Prev] links on the individual slides to navigate back and forth through the
slides.
You can also use the links on the index page to jump to a particular slide to avoid having to cycle through
the slides in sequence.
48 This content is available online at <http://cnx.org/content/m45613/1.2/>.
49 http://cnx.org/content/m45009
50 http://cnx.org/content/m45613/latest/a0-Index.htm
1.8.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
1.9.2 Preface
This module is one in a series of modules designed for teaching GAME2302 Mathematical Applications for
Game Development at Austin Community College in Austin, TX.
What you have learned
In the previous module, you learned how to update the game-math library to provide new capabilities
including the addition of graphics and set methods for column matrices, points, vectors, and lines. You
also learned how to draw on o-screen images.
What you will learn
In this module, you will learn how to compare column matrices for equality, compare two points for
equality, compare two vectors for equality, add one column matrix to another, subtract one column matrix
from another, and get a displacement vector from one point to another.
1.9.2.1.1 Images
• Image 1 (p. 109) . Screen output from the program named ColMatrixEquals01.
• Image 2 (p. 112) . Screen output from the program named DisplacementVector01.
• Image 3 (p. 114) . Screen output from the program named ColMatrixAddSubtract01.
• Image 4 (p. 122) . Text output from Exercise 1.
• Image 5 (p. 122) . Text output from Exercise 2.
• Image 6 (p. 123) . Text output from Exercise 3.
1.9.2.1.2 Listings
• Listing 1 (p. 106) . Overridden equals method of the GM2D03.ColMatrix class.
• Listing 2 (p. 107) . Overridden equals method of the GM2D03.Point class.
• Listing 3 (p. 107) . The getColMatrix method of the GM2D03.Point class.
• Listing 4 (p. 108) . Beginning of the ColMatrixEquals01 class.
• Listing 5 (p. 110) . Remainder of the ColMatrixEquals01 class.
• Listing 6 (p. 111) . The getDisplacementVector method of the GM2D03.Point class.
• Listing 7 (p. 112) . The program named DisplacementVector01.
• Listing 8 (p. 113) . Source code for the program named ColMatrixAddSubtract01.
• Listing 9 (p. 113) . Source code for the add method of the GM2D03.ColMatrix class.
• Listing 10 (p. 114) . Source code for the subtract method of the GM2D03.ColMatrix class.
• Listing 11 (p. 117) . Source code for game-math library named GM2D03.
• Listing 12 (p. 119) . Source code for the program named ColMatrixEquals01.
• Listing 13 (p. 120) . Source code for the program named DisplacementVector01.
• Listing 14 (p. 121) . Source code for the program named ColMatrixAddSubtract01.
1.9.3 Preview
To assist you in this quest, I will present and explain modications that were made to update the game-math
library that you learned about in the previous two modules. In addition, I will present and explain three
sample programs that illustrate the new features of the game-math library.
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this module and previous modules.
Much of the code in the library remains unchanged. I explained that code in previous modules and I
won't repeat that explanation in this module. Rather, in this module, I will concentrate on explaining the
modications that I made to the library.
• Compare two ColMatrix objects for equality by implementing Kjell's rules for equality given in his
Chapter 1, topic "Column Matrix Equality." The equality test does not test for absolute equality.
Rather, It compares the values stored in two matrices and returns true if the values are equal or almost
equal and returns false otherwise.
• Get a reference to the ColMatrix object that denes a Point object.
• Compare two Point objects for equality based on a comparison of the ColMatrix objects that
dene them.
• Get a reference to the ColMatrix object that denes a Vector object.
• Compare two Vector objects for equality based on a comparison of the ColMatrix objects that
dene them.
• Add one ColMatrix object to a second ColMatrix object, returning a ColMatrix object.
• Subtract one ColMatrix object from a second ColMatrix object, returning a ColMatrix object.
• Get a displacement vector from one Point object to a second Point object. The vector points
from the object on which the getDisplacementVector method is called to the object passed as a
parameter to the method.
I will explain these updates in conjunction with the discussions of the programs that follow.
1.64
This method overrides the equals method inherited from the Object class. It compares the double
values stored in two matrices and returns true if the values are equal or almost equal and returns false
otherwise.
An inherent problem when comparing doubles and oats
There is always a problem when comparing two double or oat values for equality. If you perform
a series of computations twice, using a dierent computational order for each set of computations, you are
likely to end up with two values that are not absolutely equal even if they should be equal. Arithmetic
inaccuracies along the way may cause the two results to dier ever so slightly. However, they may be equal
from a practical viewpoint.
note: An example of the problem: See Image 3 (p. 114) where the a value that should be
0.0 is actually given by -1.7763568394002505E-15
Therefore, when comparing two double or oat values for equality, it is customary to subtract one from
the other, convert the dierence to an absolute value, and compare that absolute value with an arbitrarily
small positive value. If the dierence is less than that the test value, the two original values are declared to
be equal. Otherwise, they are declared to be unequal.
This is the logic that is implemented in Listing 1 (p. 106) , which shouldn't require further explanation.
Overridden equals method of the GM2D03.Point class
Listing 2 (p. 107) presents the overridden equals method of the GM2D03.Point class.
1.65
This method also overrides the equals method inherited from the Object class. It compares the
values stored in the ColMatrix objects that dene two Point objects and returns true if they are equal
and false otherwise.
One possible point of confusion
The one thing that can be confusing in Listing 2 (p. 107) has to do with the variable named point .
This is a reference to an object of type ColMatrix that denes the location of the Point object. Listing
2 (p. 107) calls another new method named getColMatrix to get access to the ColMatrix object
that denes the incoming Point object, and uses that object for the comparison. In eect, this method
actually compares two objects of the ColMatrix class by calling the method that I explained in Listing 1
(p. 106) . This illustrates the advantages of building up the library classes using objects of the fundamental
ColMatrix class.
The getColMatrix method of the GM2D03.Point class
This extremely simple new method, which is called by the code in Listing 2 (p. 107) , is presented in
Listing 3 (p. 107) .
1.66
Listing 3 (p. 107) shouldn't require any explanation beyond the embedded comments.
Overridden equals method of the GM2D03.Vector class
The overridden equals method of the GM2D03.Vector class is essentially the same as the code
shown for the Point class in Listing 2 (p. 107) so I won't bother to show and explain it. You van view
this new method in Listing 11 (p. 117) .
1.67
Listing 4 (p. 108) instantiates four dierent ColMatrix objects and then compares them in dierent
ways, displaying the results of the comparisons on the command-line screen.
Screen output from the program named ColMatrixEquals01
The rst four lines of text in Image 1 (p. 109) were produced by the code in Listing 4. (The remaining
output shown in Image 1 (p. 109) was produced by the code in Listing 5 (p. 110) , which I will explain
shortly.)
true
true
true
false
true
true
false
true
true
false
1.68
Because of the simplicity of the code in Listing 4 (p. 108) , you shouldn't need any help in understanding
why the code in Listing 4 (p. 108) produced the rst four lines of output in Image 1 (p. 109) .
The third and fourth lines of output in Image 1 (p. 109) are the result of comparing two matrices whose
values are almost equal but not absolutely equal.
Remainder of the ColMatrixEquals01 class
The remainder of the program named ColMatrixEquals01 is shown in Listing 5 (p. 110) . The
output produced by this code is shown in the last six lines of text in Image 1 (p. 109) .
}//end main
}//end ColMatrixEquals01 class
1.69
Once again, the code in Listing 5 (p. 110) is very straightforward and shouldn't require further explana-
tion. The screen output shown in Image 1 (p. 109) veries that the library methods called by this program
behave appropriately.
1.70
This method gets and returns a displacement vector from one Point object to a second Point object
and returns the result as a reference to a new object of the class GM2D03.Vector .
The direction of the vector
The displacement vector points from the Point object on which the method is called to the Point
object passed as a parameter to the method. Kjell describes the component parts of the new vector as the
distance you would have to walk, rst along the x-axis and then along the y-axis to get from the rst point
to the second point. Of course, you could take the short cut and walk directly from the rst point to the
second point but that's often not how we do it in programming.
The code in Listing 6 (p. 111) is straightforward and shouldn't require further explanation.
The program named DisplacementVector01
Once again, I will put the discussion of the updated GM2D03 library on hold and explain the program
named DisplacementVector01 .
Listing 7 (p. 112) shows the program named DisplacementVector01 in its entirety.
(For convenience, a second copy of this program is provided in Listing 13 (p. 120) near the end of the
module along with the other three programs discussed in this module.)
System.out.println(pointA.getDisplacementVector(
pointB));
System.out.println(pointB.getDisplacementVector(
pointA));
}//end main
}//end DisplacementVector01 class
1.71
The purpose of this program is to conrm the behavior of the getDisplacementVector method of
the GM2D03.Point class. The screen output shown in Image 2 (p. 112) provides that conrmation.
Screen output from the program named DisplacementVector01
The screen output from the program named DisplacementVector01 is shown in Image 2 (p. 112) .
-12.5,18.7
12.5,-18.7
1.72
You should be able to correlate the results shown in Image 2 (p. 112) with the code in Listing 6 (p. 111)
and Listing 7 (p. 112) without further explanation.
Very simple methods
By now you may be thinking that the code in the game-math library is very simple and easy to understand.
I hope that is the case. I went to great lengths to modularize the library into a set of simple and easily
understood methods. Taken as a whole, however, the library is becoming quite powerful, and will become
even more powerful as we progress through additional modules in this collection.
GM2D03.ColMatrix matrixA =
new GM2D03.ColMatrix(3.14,-6.01);
GM2D03.ColMatrix matrixB =
new GM2D03.ColMatrix(-14.0,-12.2);
System.out.println(matrixC);
System.out.println(matrixD);
System.out.println(matrixE);
}//end main
1.73
The purpose of this program is to conrm the behavior of the new add and subtract methods of the
GM2D03.ColMatrix class.
Source code for the add method of the GM2D03.ColMatrix class
Returning once more to a discussion of the updated GM2D03 library, the source code for this method
is shown in Listing 9 (p. 113) . The method adds one ColMatrix object to another ColMatrix object,
returning a ColMatrix object. As you should have learned from your studies of the Kjell tutorial, the
order in which the two objects are added doesn't matter. The result is the same either way.
Listing 9: Source code for the add method of the GM2D03.ColMatrix class.
1.74
Continuing with the discussion of the updated GM2D03 library, the source code for this method is
shown in Listing 10 (p. 114) . This method subtracts one ColMatrix object from another ColMatrix
object, returning a ColMatrix object. Also as you should have learned from the Kjell tutorial, in this case,
the order of the operation does matter. The object that is received as an incoming parameter is subtracted
from the object on which the method is called. Reversing the order of operations produces dierent results.
Listing 10: Source code for the subtract method of the GM2D03.ColMatrix class.
1.75
Once again, the code in the method is straightforward and shouldn't require an explanation.
Program output for program named ColMatrixAddSubtract01
Now, lets get back to the program named ColMatrixAddSubtract01 that is shown in Listing 8 (p.
113) . This program produces the output shown in Image 3 (p. 114) .
-10.86,-18.21
-14.0,-12.200000000000001
0.0,-1.7763568394002505E-15
1.76
By now, you should have no diculty understanding how the output shown in Image 3 (p. 114) was
produced by the code shown in Listing 8 (p. 113) . Note, however, that the last value on the third row
should be 0.0 instead of the extremely small value shown. This is an example of an inherent 52 problem
having to do with comparing double or oat values with other double or oat values for absolute
equality.
Click here 53 to download a zip le containing standard javadoc documentation for the library named
GM2D03 . Extract the contents of the zip le into an empty folder and open the le named index.html
in your browser to view the documentation.
52 http://cnx.org/content/m45010/latest/Java1704.htm#inherent
53 http://cnx.org/content/m45010/latest/GM2D03docs.zip
Although the documentation doesn't provide much in the way of explanatory text (see Listing 11
(p. 117) and the explanations given above) , the documentation does provide a good overview of the
organization and structure of the library. You may nd it helpful in that regard.
Your homework assignment for this module was to study Kjell's tutorial through Chapter 2 - Column and
Row Matrix Addition .
The homework assignment for the next module is to study the Kjell tutorial through Chapter 3 - Vector
Addition .
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 54 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.
I encourage you to copy the code from Listing 12 (p. 119) , Listing 13 (p. 120) , and Listing 14 (p. 121) .
Compile the code and execute it in conjunction with the game-math library provided in Listing 11 (p. 117)
. Experiment with the code, making changes, and observing the results of your changes. Make certain that
you can explain why your changes behave as they do.
1.9.8 Summary
In this module, you learned how to compare column matrices for equality, compare two points for equality,
compare two vectors for equality, add one column matrix to another, subtract one column matrix from
another, and get a displacement vector from one point to another.
The next module in the collection will show one way for you to visualize column matrices in graphical form.
In the module following that one, you will learn:
1.9.10 Miscellaneous
• Published: 10/14/12
• Revised: 12/31/12
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 11 (p. 117) through Listing
14 (p. 121) below.
/*GM2D03.java
Copyright 2008, R.G.Baldwin
Revised 02/10/08
/*ColMatrixEquals01.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
}//end main
}//end ColMatrixEquals01 class
Available for free at Connexions <http://cnx.org/content/col11450/1.29>
1.78
120 CHAPTER 1. MATH
/*DisplacementVector01.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
System.out.println(pointA.getDisplacementVector(
pointB));
System.out.println(pointB.getDisplacementVector(
pointA));
}//end main
}//end DisplacementVector01 class
1.79
/*ColMatrixAddSubtract01.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
GM2D03.ColMatrix matrixA =
new GM2D03.ColMatrix(3.14,-6.01);
GM2D03.ColMatrix matrixB =
new GM2D03.ColMatrix(-14.0,-12.2);
System.out.println(matrixC);
System.out.println(matrixD);
System.out.println(matrixE);
}//end main
1.80
1.9.12 Exercises
1.9.12.1 Exercise 1
Using Java and the game-math library named GM2D03 , or using a dierent programming environment of
your choice, write a program that creates four column matrix objects using the following names and values:
• matA = (1.5,-2.6)
• matB = (1.5,-2.6)
• matC = (8.5,-13.4)
• matD = (5.5,-8.2)
Then use matrix addition and subtraction to compute and display the values of the following matrices:
Prof. Baldwin
matE = 3.0,-5.2
matF = 3.0,-5.200000000000001
matE equals matF: ?
1.81
1.9.12.2 Exercise 2
Using Java and the game-math library named GM2D03 , or using a dierent programming environment
of your choice, write a program that creates and displays (in text form) three vectors having the names
and values shown in Image 5 (p. 122) .
Cause your program to test vecA for equality, rst against vecB , and then against vecC , and
display the results of the tests in place of the question marks shown in Image 5 (p. 122) .
Prof. Baldwin
vecA = -1.5,2.6
vecB = -1.5,2.6
vecC = 8.5,-13.4
vecA equals vecB: ?
vecA equals vecC: ?
1.82
1.9.12.3 Exercise 3
Using Java and the game-math library named GM2D03 , or using a dierent programming environment
of your choice, write a program that creates and displays four column matrices having the names and values
Prof. Baldwin
matA = 1.5,-2.6
matB = -1.5,2.6
dispVecE = ?,?
matC = 8.5,-13.4
matD = 5.5,-8.2
dispVecF = ?,?
dispVecE equals dispVecF: ?
1.83
-end-
1.10.2 Preface
This module contains review questions and answers keyed to the module titled GAME 2302-0115: Working
with Column Matrices, Points, and Vectors 56 .
The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the
question to the answer and back again.
1.10.3 Questions
1.10.3.1 Question 1 .
A method named equals is inherited from the Object class and overridden in several classes in the
GM2D03 game-math library.
True or False?
Answer 1 (p. 128)
1.10.3.2 Question 2
The overridden equals method in the GM2D03.Point class returns a value of type double .
True or False?
Answer 2 (p. 128)
1.10.3.3 Question 3
It is not dicult to compare double and oat values for absolute equality.
True or False?
Answer 3 (p. 128)
1.10.3.4 Question 4
The overridden equals method of the GM2D03.Point class compares two objects of type
GM2D03.ColMatrix for equality.
True or False?
Answer 4 (p. 128)
1.10.3.5 Question 5
The dierence between two points is a displacement vector.
True or False?
Answer 5 (p. 128)
55 This content is available online at <http://cnx.org/content/m45587/1.4/>.
56 http://cnx.org/content/m45010
1.10.3.6 Question 6
The getDisplacementVector method of the GM2D03.Point class computes the sums of the x and y
components of the points that are stored in two column matrix objects.
True or False?
Answer 6 (p. 128)
1.10.3.7 Question 7
ThegetDisplacementVector method of the GM2D03.Point class returns a value of type
GM2D03.ColMatrix .
True or False?
Answer 7 (p. 128)
1.10.3.8 Question 8
The displacement vector that is returned by the getDisplacementVector method of the GM2D03.Point
class points from the Point object on which the method is called to the Point object passed as a parameter
to the method.
True or False?
Answer 8 (p. 128)
1.10.3.9 Question 9
Kjell describes the component parts of the a displacement vector
True or False?
Answer 9 (p. 127)
1.10.3.10 Question 10
The add method of the GM2D03.ColMatrix class adds one ColMatrix object to another ColMatrix
object, returning a ColMatrix object.
True or False?
Answer 10 (p. 127)
1.10.3.11 Question 11
The order in which you add column matrix objects has a signicant impact on the result.
True or False?
Answer 11 (p. 127)
1.10.3.12 Question 12
The order in which two column matrix objects are subtracted doesn't matter. The result is the same either
way.
True or False?
Answer 12 (p. 127)
What is the meaning of the following two images?
This image was inserted here simply to insert some space between the questions and the answers to keep
them from being visible on the screen at the same time.
This image was also inserted for the purpose of inserting space between the questions and the answers.
1.10.4 Answers
1.10.4.1 Answer 12
False. As you should have learned from your studies of the Kjell tutorial, the order in which the two column
matrix objects are subtracted has a signicant impact on the result.
Back to Question 12 (p. 125)
1.10.4.2 Answer 11
False. As you should have learned from your studies of the Kjell tutorial, the order in which the two column
matrix objects are added doesn't matter. The result is the same either way.
Back to Question 11 (p. 125)
1.10.4.3 Answer 10
True
Back to Question 10 (p. 125)
1.10.4.4 Answer 9
True
Back to Question 9 (p. 125)
1.10.4.5 Answer 8
True
Back to Question 8 (p. 125)
1.10.4.6 Answer 7
False. The getDisplacementVector method of the GM2D03.Point class returns a value of type
GM2D03.Vector .
Back to Question 7 (p. 125)
1.10.4.7 Answer 6
False. The getDisplacementVector method of the GM2D03.Point class computes the dierences
(subtraction) of the x and y components of the points that are stored in two column matrix objects.
Back to Question 6 (p. 125)
1.10.4.8 Answer 5
True
Back to Question 5 (p. 124)
1.10.4.9 Answer 4
True. In eect, this method actually compares two objects of the ColMatrix class by calling the equals
method dened in the GM2D03.ColMatrix class. This is because the values that dene a point are
actually stored in a column matrix.
Back to Question 4 (p. 124)
1.10.4.10 Answer 3
False. There is an inherent problem when comparing two double or oat values for equality. If you
perform a series of computations twice, using a dierent computational order for each set of computations,
you are likely to end up with two values that are not absolutely equal even if they should be equal. Arithmetic
inaccuracies along the way may cause the two results to dier ever so slightly. However, they may be equal
from a practical viewpoint.
Back to Question 3 (p. 124)
1.10.4.11 Answer 2
False. The overridden equals method in the GM2D03.Point class returns a value of type boolean .
Back to Question 2 (p. 124)
1.10.4.12 Answer 1
True
Back to Question 1 (p. 124)
1.10.5 Miscellaneous
• File: Game0115r.htm
• Published: 12/31/12
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
This module contains lecture slides keyed to the module titled GAME 2302-0115: Working with Column
Matrices, Points, and Vectors 58 .
Click here 59 to open an index to the slides.
Then use the links beginning with the label "aa" to open the rst slide that you want to view in a new
window in your browser.
Then use the [Next] and [Prev] links on the individual slides to navigate back and forth through the
slides.
You can also use the links on the index page to jump to a particular slide to avoid having to cycle through
the slides in sequence.
1.11.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
1.12.2 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.
What you have learned
In the previous module, you learned:
1.12.2.1.1 Images
• Image 1 (p. 132) . Sample graphical program output.
• Image 2 (p. 133) . Text output from the program.
• Image 3 (p. 134) . Graphical output for equal vectors.
• Image 4 (p. 135) . Text output for equal vectors.
• Image 5 (p. 144) . Graphic output from Exercise 01.
1.12.2.1.2 Listings
• Listing 1 (p. 136) . Beginning of the method named displayColumnMatrices.
• Listing 2 (p. 136) . Use the slider values to create the two matrices.
• Listing 3 (p. 137) . Add and subtract the matrices.
• Listing 4 (p. 137) . Display text information about the matrices.
• Listing 5 (p. 138) . Create mathematical points.
• Listing 6 (p. 139) . Create mathematical displacement vectors.
• Listing 7 (p. 140) . Produce a graphical representation of the displacement vectors.
• Listing 8 (p. 143) . Source code for the program named ColMatrixVis01.
1.12.3 Preview
Abstract mathematical concepts are often easier to grasp if you can visualize them in graphical format. For
example, the nature of the following equation often becomes more apparent once you learn that it is the
equation of a straight line.
y = m*x + b
Similarly, the nature of the following equation often becomes more apparent once you learn that it is the
equation of a parabola and you learn the general shape of a parabola.
y = x^2 + k
where x^2 indicates x raised to the second power.
As mentioned earlier, in this module, you will learn how to display column matrices in a graphical
format. This may help you to get a better grasp of the nature of column matrices and the results of adding,
subtracting, and comparing them.
I will present and explain an interactive program that behaves as follows:
Two column matrices are created using values obtained from the sliders shown at the bottom of Image 1
(p. 132) . One matrix is named redMatrix and the other matrix is named greenMatrix .
1.84
Available for free at Connexions <http://cnx.org/content/col11450/1.29>
133
Two additional column matrices are created by adding and subtracting the original matrices. The matrix
created by adding the red and green matrices is named blueMatrix . The matrix created by subtracting
the green matrix from the red matrix is named orangeMatrix .
Mathematical points are created to represent the values in the four matrices in a 2D reference frame.
Then, mathematical displacement vectors are created for each of the points relative to the origin.
Graphical objects are created for each of the four displacement vectors and those objects are drawn along
with Cartesian coordinate axes in the 2D reference frame.
The vectors are shown in the top portion of Image 1 (p. 132) . The red and green vectors represent the
red and green matrices. The blue and orange vectors represent the sum and the dierence of the red and
green matrices.
Text output is displayed to show the matrix values as well as whether the two original matrices are equal.
The text values corresponding to the vectors in Image 1 (p. 132) are shown in Image 2 (p. 133) .
redMatrix = 53.0,53.0
greenMatrix = 79.0,-66.0
redMatrix equals greenMatrix: false
blueMatrix = redMatrix + greenMatrix = 132.0,-13.0
orangeMatrix = redMatrix - greenMatrix = -26.0,119.0
1.85
If you carefully adjust the sliders so that the two values contained in the redMatrix are the same as
the two values contained in the greenMatrix , the red and green vectors will overlay as shown in Image 3
(p. 134) and the third line of output text will show true as shown in Image 4 (p. 135) . In this case, only the
green vector and part of the blue (sum) vector are visible. The red vector is covered by the green vector,
and the orange (dierence) vector has a zero length.
1.86
Available for free at Connexions <http://cnx.org/content/col11450/1.29>
135
redMatrix = 100.0,100.0
greenMatrix = 100.0,100.0
redMatrix equals greenMatrix: true
blueMatrix = redMatrix + greenMatrix = 200.0,200.0
orangeMatrix = redMatrix - greenMatrix = 0.0,0.0
1.87
There are many other interesting combinations that I could show. However, I will leave it as an exercise
for the student to copy, compile, and run the program and use the sliders to experiment with dierent matrix
values.
I will also provide an exercise for you to complete on your own at the end of the module. The exercise
will concentrate on the material that you have learned in this module and previous modules.
Because of its interactive nature, much of the code in this program is at a complexity level that is beyond
the scope of this course. However, most of the interesting work is done in the method named display-
ColumnMatrices and I will concentrate on explaining that method.
You can view a complete listing of the program named ColMatrixVis01 in Listing 8 (p. 143) near
the end of the module.
Note that the program requires access to the game library named GM2D03 . The source code for that
library was provided in the earlier module titled GAME2302-0115: Working with Column Matrices, Points,
and Vectors 61 and you can copy it from there.
The method named displayColumnMatrices
The purpose of this method is to:
1. Create two column matrices named redMatrix and greenMatrix using values obtained from
sliders.
2. Create two more column matrices named blueMatrix and orangeMatrix by adding and sub-
tracting the red and green matrices.
3. Display text information about the matrices including whether or not the red and green matrices are
equal.
4. Create mathematical points in a 2D coordinate frame that represent the values in the matrices.
5. Create mathematical displacement vectors that represent the displacements of each of the points rela-
tive to the origin.
6. Create and draw graphics objects that represent each of the mathematical displacement vectors along
with Cartesian coordinate axes for the 2D reference frame.
1.88
1.89
There is nothing new in Listing 2 (p. 136) that you haven't seen before so further explanation should
not be necessary.
Add and subtract the matrices
Listing 3 (p. 137) creates two additional matrices by adding and subtracting the red and green matrices.
References to the new matrices are stored in the variables named blueMatrix and orangeMatrix .
1.90
Once again, there is nothing new in Listing 3 (p. 137) , so further explanation should not be necessary.
Display text information about the matrices
Listing 4 (p. 137) displays text information about the four matrices, including whether or not the red
and green matrices are equal.
1.91
The code in Listing 4 (p. 137) produced the text in Image 2 (p. 133) and Image 4 (p. 135) .
Displaying information about the matrices
There are many ways to display information about matrices, including the simple text displays shown
in Image 2 (p. 133) and Image 4 (p. 135) . The problem with text displays is that you have to study the
numbers in detail to get a feel for an individual matrix and a feel for the relationships among two or more
matrices.
A graphical display can often convey that sort of information at rst glance. Then you are faced with a
decision as to how you should construct the graphical display.
For the case of a column matrix with two elements, a good approach is to let the two matrix values
represent the x and y coordinate values of a mathematical point in a 2D reference frame and then to display
information about the point. That is the approach taken by this program.
Create mathematical points
Listing 5 (p. 138) creates mathematical points in a 2D coordinate frame that represent the values in the
matrices. Listing 5 (p. 138) also creates a point that represents the origin.
1.92
Listing 6 (p. 139) creates mathematical displacement vectors that represent the displacements of each of
the four points created earlier relative to the origin.
1.93
g2D.setColor(Color.ORANGE);
orangeVec.draw(g2D,origin);
g2D.setColor(Color.RED);
redVec.draw(g2D,origin);
g2D.setColor(Color.GREEN);
greenVec.draw(g2D,origin);
}//end displayColumnMatrices
1.94
There is very little new code in Listing 7 (p. 140) , and the new code that is there should be easy to
understand.
Analysis of results
The head of the red vector in Image 1 (p. 132) represents the two values in the column matrix known as
redMatrix . The length and direction of that vector shows how it relates to a column vector having two
elements, each with a value of zero.
Similarly, the head of the green vector in Image 1 (p. 132) represents the two values in the column matrix
known as greenMatrix .
The head of the blue vector represents the two values in the column matrix known as blueMatrix ,
which was created by adding the red and green matrices. In case you haven't noticed, a line drawn from the
head of the red vector to the head of the blue vector would have the same length and direction as the green
vector. This will come up again in a future module when we discuss the vector addition parallelogram.
The head of the orange vector represents the two values in the column matrix know as orangeMatrix
, which was created by subtracting the green matrix from the red matrix. Again, a line drawn from the head
of the red vector to the head of the orange vector would have the same length and opposite direction as the
green vector.
The homework assignment for this module was to study the Kjell tutorial through Chapter 3 - Vector
Addition . That is also the homework assignment for the next 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 62 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.
I encourage you to copy the code from Listing 8 (p. 143) . Compile the code and execute it in conjunction
with the game-math library named GM2D03 . The source code for that library was provided in the
earlier module titled GAME2302-0115: Working with Column Matrices, Points, and Vectors 63 and you can
copy it from there.. Experiment with the code, making changes, and observing the results of your changes.
Make certain that you can explain why your changes behave as they do.
1.12.7 Summary
In this module, you learned how to create column matrices using values obtained from sliders. You learned
how to create additional column matrices by adding and subtracting the original matrices.
You learned how to display text information about the matrices including whether or not they are equal.
You learned how to display the matrices in a graphical format where each matrix is represented by a
displacement vector in a 2D reference frame.
1.12.9 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation :: I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
A complete listing of the program named ColMatrixVis01 is provided in Listing 8 (p. 143) . The game
library named GM2D03 , which is required for compiling and executing this program, was provided in
the earlier module titled GAME2302-0115: Working with Column Matrices, Points, and Vectors 64 . You
can copy it from there.
64 http://cnx.org/content/m45010
/*ColMatrixVis01.java
Copyright 2012, R.G.Baldwin
class ColMatrixVis01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class ColMatrixVis01
//======================================================//
1.12.11 Exercises
1.12.11.1 Exercise 1
Using Java and the game-math library named GM2D03 , or using a dierent programming environment
of your choice, write a program that uses random values to generate two column matrix objects.
Generate two more column matrix objects as the sum and dierence of the two original column matrix
objects.
Display the two original column matrix objects in red and green and display the sum and dierence
matrix objects in blue and orange as shown in Image 5 (p. 144) .
1.96
-end-
This module contains lecture slides keyed to the module titled GAME 2302-0120: Visualizing Column
Matrices 66 .
Click here 67 to open an index to the slides.
Then use the links beginning with the label "aa" to open the rst slide that you want to view in a new
window in your browser.
Then use the [Next] and [Prev] links on the individual slides to navigate back and forth through the
slides.
You can also use the links on the index page to jump to a particular slide to avoid having to cycle through
the slides in sequence.
1.13.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
65 This content is available online at <http://cnx.org/content/m45615/1.2/>.
66 http://cnx.org/content/m45011
67 http://cnx.org/content/m45615/latest/a0-Index.htm
1.14.2 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.
What you have learned
In the previous couple of modules, you learned:
1.14.2.1.1 Images
• Image 1 (p. 150) . Screen output from the program named VectorAdd01.
• Image 2 (p. 157) . Screen output from CoordinateFrame01 at startup.
• Image 3 (p. 158) . Screen output from CoordinateFrame01 after changes to the coordinate frame.
• Image 4 (p. 164) . Screen output from the program named VectorAdd02.
• Image 5 (p. 167) . Graphic screen output from the program named VectorAdd03.
• Image 6 (p. 167) . Command-line output from the program named VectorAdd03.
• Image 7 (p. 168) . Screen output from the program named VectorAdd04.
• Image 8 (p. 183) . Screen output from Exercise 1.
• Image 9 (p. 185) . Screen output from Exercise 2.
1.14.2.1.2 Listings
• Listing 1 (p. 148) . The add method of the GM2D04.Vector class.
• Listing 2 (p. 149) . The getLength method of the GM2D04.Vector class.
• Listing 3 (p. 149) . The addVectorToPoint method of the GM2D04 class.
• Listing 4 (p. 151) . Beginning of the program named VectorAdd01.
• Listing 5 (p. 152) . Beginning of the method named drawOScreen.
• Listing 6 (p. 152) . The method named setCoordinateFrame.
• Listing 7 (p. 153) . Adding two vectors.
• Listing 8 (p. 153) . Draw vecA in RED with its tail at the origin.
• Listing 9 (p. 154) . Draw vecB in GREEN head-to-tail with vecA.
• Listing 10 (p. 154) . Draw sumOf2 in MAGENTA with its tail at the origin.
• Listing 11 (p. 155) . Extending the example to three vectors.
• Listing 12 (p. 160) . The actionPerformed method.
• Listing 13 (p. 161) . The setCoordinateFrame method.
• Listing 14 (p. 162) . Beginning of the drawOScreen method.
• Listing 15 (p. 162) . Dene a point to position the vectors.
• Listing 16 (p. 163) . Remaining code in the drawOScreen method.
• Listing 17 (p. 165) . Beginning of the method named drawOScreen of the program named Vec-
torAdd02.
• Listing 18 (p. 166) . Do the same operations in a dierent order.
• Listing 19 (p. 171) . Source code for the game-math library named GM2D04.
• Listing 20 (p. 173) . Source code for the program named VectorAdd01.
• Listing 21 (p. 175) . Source code for the program named CoordinateFrame01.
• Listing 22 (p. 177) . Source code for the program named VectorAdd02.
• Listing 23 (p. 179) . Source code for the program named VectorAdd03.
• Listing 24 (p. 181) . Source code for the program named VectorAdd04.
1.14.3 Preview
In this module, I will present and explain several updates to the game-math library. In addition, I will
present and explain ve sample programs that illustrate the use of the new features of the library.
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this module and previous modules.
The game-math library was updated and the name was changed to GM2D04 in preparation for this module.
Much of the code in the updated library remains unchanged. I explained that code in the previous modules
and I won't repeat that explanation in this module. I will concentrate on explaining the modications that
I made to the library in this module.
These three new methods are presented in Listing 1 (p. 148) , Listing 2 (p. 149) , and Listing 3 (p. 149)
below. These methods are so simple that no explanation should be required for you to understand them.
1.97
1.98
1.99
1.100
You will recall that the game-math library represents a Vector object graphically as a straight line
with a small circle at the head. Thus, there are ve vectors drawn in Image 1 (p. 150) . I will explain the
meaning of the output in conjunction with the explanation of the program.
Beginning of the program named VectorAdd01
Listing 4 (p. 151) shows the entire class named VectorAdd01 along with the beginning of the class
named GUI including the constructor for the GUI class.
class VectorAdd01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class VectorAdd01
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end constructor
Available for free at Connexions <http://cnx.org/content/col11450/1.29>
1.101
152 CHAPTER 1. MATH
1.102
Listing 5 (p. 152) begins by calling the method named setCoordinateFrame , which is shown in its
entirety in Listing 6 (p. 152) . I will put the discussion of the drawOScreen method on hold while I
explain the method named setCoordinateFrame .
The method named setCoordinateFrame
This method sets the origin to a point near the upper-left corner of the o-screen image (see Image 1
(p. 150) ) and draws orthogonal axes on the o-screen image intersecting at the origin.
g2D.drawLine(0,-(int)(0.2*osiHeight),
0,(int)(0.8*osiHeight));
1.103
69 http://cnx.org/content/m45009/latest/?collection=col11450/latest
There is no intention to perform mathematical operations on the axes, so they are drawn independently
of the classes and methods in the game-math library using the simplest method available for drawing a line.
The name of that simple method is drawLine , and it is a method of the standard Java Graphics
class. The translate method is also a method of the Graphics class. Given that information, the code
in Listing 6 (p. 152) is straightforward and should not require further explanation.
Adding two vectors
Returning to the method named drawOScreen , Listing 7 (p. 153) begins by instantiating two
objects of the GM2D04.Vector class.
1.104
Then Listing 7 (p. 153) calls the new add method (see Listing 1 (p. 148) ) on one of the vectors,
passing the other vector as a parameter to the method. The add method returns a third vector that is the
sum of the other two vectors. The new vector is referred to as sumOf2 in Listing 7 (p. 153) .
Draw vecA in RED with its tail at the origin
Recall that a vector has only two properties: length and direction. It does not have a position property.
Therefore, if you decide to draw a vector, you can draw it anywhere in space, and one position is equally as
valid as any other position.
Listing 8 (p. 153) sets the drawing color to RED and calls the draw method on vecA producing the
red visual manifestation of the Vector object shown in Image 1 (p. 150) .
(Note that there is also a magenta vector in Image 1 (p. 150) , and it may be dicult to distinguish
from the red vector, depending on the quality of the color on your monitor. The magenta vector is longer
than the red vector.)
g2D.setColor(Color.RED);
vecA.draw(g2D,new GM2D04.Point(
new GM2D04.ColMatrix(0,0)));
1.105
Note that I elected to draw the vector with its tail at the origin, but that was an arbitrary decision that
I will discuss in more detail later.
g2D.setColor(Color.GREEN);
vecB.draw(g2D,new GM2D04.Point(new GM2D04.ColMatrix(
vecA.getData(0),vecA.getData(1))));
1.106
Listing 10: Draw sumOf2 in MAGENTA with its tail at the origin.
g2D.setColor(Color.MAGENTA);
sumOf2.draw(g2D,new GM2D04.Point(new GM2D04.ColMatrix(
0.0,0.0)));
1.107
Furthermore, this rule will hold regardless of the number of vectors included in the sum.
Extending the example to three vectors
Listing 11 (p. 155) extends this example to three vectors.
}//end drawOffScreen
1.108
note: No overloaded operators: It is at times like this when I wish that Java supported
overloaded operators in a manner similar to C++. Overloading the + operator would make the
syntax much more intuitive than that shown by the code in Listing 11 (p. 155) .
The MyCanvas class also includes an overridden paint method. However, the code in that method
is very similar to code that I explained in the earlier module titled GAME 2302-0110: Updating the Math
Library for Graphics 70 . Therefore, I won't explain that code again in this module. You can view the
overridden paint method in Listing 20 (p. 173) .
That concludes the discussion of the program named VectorAdd01 .
1.109
Image 3: Screen output from CoordinateFrame01 after changes to the coordinate frame.
1.110
• actionPerformed
• setCoordinateFrame
• drawOScreen
You can view the remaining program code in Listing 21 (p. 175) near the end of the module.
The actionPerformed method
This method must be dened in the class named GUI because the GUI class implements the
ActionListener interface. Because an object of the GUI class is registered as a listener on the Replot
button shown in Image 2 (p. 157) , the actionPerformed method is called each time the user clicks the
button.
xOffset = osiWidth*xOffsetFactor;
yOffset = osiHeight*yOffsetFactor;
1.111
• Call the setCoordinateFrame method to reset the coordinate frame to world coordinates.
• Get user input values and use them to compute and save new oset values that will be used to dene
the origin of the new coordinate frame.
• Call the drawOScreen method to erase the current image from the o-screen image and draw a
new image on it using the new coordinate frame. Note that the drawOScreen method will call
the setCoordinateFrame method to establish the new coordinate frame before drawing the new
image on the o-screen image.
• Call the repaint method to cause the o-screen image to be copied to the canvas and displayed on
the computer screen.
1.112
1.113
The drawOScreen method begins by calling the setCoordinateFrame method to establish a new
coordinate frame using oset values entered by the user, (or default oset values of 0.0 at startup) .
Dene a point to position the vectors
Listing 15 (p. 162) instantiates a new GM2D04.Point object that will be used to locate the three
vectors that form the closed polygon shown in Image 2 (p. 157) . The location of the polygon relative to
the world coordinate frame will remain the same regardless of how the current coordinate frame is changed.
1.114
The code in Listing 15 (p. 162) is probably the most important code in the entire program relative to
the objective of the program. As I mentioned earlier, if you want the location of a point to remain the same
relative to the world coordinate frame when you change the current coordinate frame, you must modify the
values that represent that point whenever you cause the current coordinate frame to be dierent from the
world coordinate frame. The code in Listing 15 (p. 162) makes that modication.
Remaining code in the drawOScreen method
The remaining code in the drawOScreen method is shown in Listing 16 (p. 163) .
}//end drawOffScreen
1.115
With one exception, there is nothing in Listing 16 (p. 163) that I haven't already explained in earlier
programs in this or previous modules. Therefore, I won't repeat those explanations here.
The one exception
Recall from Image 2 (p. 157) that we need to draw the green vector with its tail located at the head of
the red vector. In order to do that, we must be able to determine the location of the head of the red vector
relative to the current coordinate frame.
The getData method of the Vector class knows nothing about position. That method simply returns
the X and Y coordinate values that describe the length of the vector relative to its tail.
(For the special case where the tail is located at the origin, the getData method returns the X and Y
coordinates of the head of the vector.)
However, because the tail of the red vector in this case is not necessarily located at the origin, we must
calculate the position of the head of the red vector taking the position of its tail ( startPoint ) into
account. The code in Listing 16 (p. 163) does just that.
That concludes the discussion of the program named CoordinateFrame01 .
1.116
A complete listing of this program is provided in Listing 22 (p. 177) near the end of the module. Most
of the new material is contained in the method named drawOScreen . Therefore, I will limit my
explanation to the method named drawOScreen , which begins in Listing 17 (p. 165) .
Listing 17: Beginning of the method named drawOScreen of the program named
VectorAdd02.
1.117
There is nothing new in Listing 17 (p. 165) . The code in Listing 17 (p. 165) produces the black vector
in Image 4 (p. 164) plus the red and green vectors that appear above the black vector.
Do the same operations in a dierent order
Listing 18 (p. 166) begins by drawing the red and green vectors again. However, this time the green
vector is drawn with its tail at the origin, and the red vector is drawn with its tail at the head of the green
vector as shown by the green and red vectors below the black vector in Image 4 (p. 164) . This is perfectly
legal because a vector has no location property. We can draw a vector anywhere we please provided we draw
it with the correct length and direction.
}//end drawOffScreen
1.118
Then Listing 18 (p. 166) creates another vector by adding the red and green vectors and refers to the
new vector as sumB . In the case of Listing 17, vecB is added to vecA to produce sumA . In
Listing 18, vecA is added to vecB to produce sumB . In other words, the two addition operations
are performed in reverse order in the two listings. As I have mentioned before, the order in which you add
vectors doesn't matter. The result will be the same no matter the order in which you add them.
This is demonstrated in Listing 18 (p. 166) by drawing the vector referred to by sumB in black. As
you can see in Image 4 (p. 164) , the drawing of sumB overlays the earlier drawing of sumA and you
can't tell one from the other.
(You know that the length of the two vectors is the same because the little circles at the heads of the
two vectors overlay one another. You know that the directions are the same because sumB completely
covers sumA .)
That concludes the discussion of the program named VectorAdd02 .
1.119
Command-line output
In addition to the graphic output shown in Image 5 (p. 167) , this program also produces three lines of
text on the command-line screen as shown in Image 6 (p. 167) .
1.120
The text output on the command-line screen shows the length of each vector. As you can see in Image
6 (p. 167) , the length of the black vector is much less than the length of either the red vector or the blue
vector.
Not much that is new
The only thing that is new in this program is the call to the new getLength method of the
GM2D04.Vector class to compute and display the length of each vector in Image 6 (p. 167) .
The source code for the getLength method is shown in Listing 2 (p. 149) . This code computes the
length of the vector as the square root of the sum of the squares of the X and Y components of the vector.
Other than that code, there is no code in this program that warrants further explanation.
You can view a complete listing of the program in Listing 23 (p. 179) near the end of the module.
1.121
The only thing that is new in this program is the call to the new addVectorToPoint method of the
GM2D04.Point class to add the vector to the point producing a new point.
The source code for the addVectorToPoint method is shown in Listing 3 (p. 149) . You can view a
complete listing of the program in Listing 24 (p. 181) near the end of the module.
A very powerful capability
Don't be fooled by the apparent simplicity of the addVectorToPoint method. The ability to add a
vector to a point provides a powerful new capability to the game-math library. As you will see in the next
module, this capability makes it possible not only to translate geometrical objects from one location in space
to another, but also makes it possible to animate geometrical objects.
Click here 71 to download a zip le containing standard javadoc documentation for the library named
GM2D04 . Extract the contents of the zip le into an empty folder and open the le 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 19 (p. 171)
and the explanations given above) , the documentation does provide a good overview of the organization
and structure of the library. You may nd it helpful in that regard.
The homework assignment for this module was to study the Kjell tutorial through Chapter 3 - Vector
Addition.
The homework assignment for the next module is to study the Kjell tutorial through Chapter 5 - Vector
Direction .
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 72 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.
I encourage you to copy the code from Listing 19 (p. 171) through Listing 24 (p. 181) . Compile the code
and execute it in conjunction with the game-math library provided in Listing 19 (p. 171) . Experiment with
the code, making changes, and observing the results of your changes. Make certain that you can explain
why your changes behave as they do.
1.14.8 Summary
In the next module you will learn how to use the game-math library for translation and animation in two
dimensions.
71 http://cnx.org/content/m45012/latest/GM2D04docs.zip
72 http://cnx.org/content/m44992/latest/
1.14.10 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 19 (p. 171) through Listing
24 (p. 181) below.
Listing 19: Source code for the game-math library named GM2D04.
/*GM2D04.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
/*VectorAdd01.java
Copyright 2008, R.G.Baldwin
Revised 02/10/08
class VectorAdd01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class VectorAdd01
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*CoordinateFrame01.java
Copyright 2008, R.G.Baldwin
Revised 02/14/08
class CoordinateFrame01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class CoordinateFrame01
//======================================================//
/*VectorAdd02.java
Copyright 2008, R.G.Baldwin
Revised 02/14/08
class VectorAdd02{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class VectorAdd02
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Available forimage
//Create an off-screen free at Connexions
and get a<http://cnx.org/content/col11450/1.29>
graphics
// context on it.
osi = createImage(osiWidth,osiHeight);
Graphics2D g2D = (Graphics2D)(osi.getGraphics());
178 CHAPTER 1. MATH
/*VectorAdd03.java
Copyright 2008, R.G.Baldwin
Revised 02/14/08
class VectorAdd03{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class VectorAdd03
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*VectorAdd04.java
Copyright 2008, R.G.Baldwin
Revised 02/15/08
class VectorAdd04{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class VectorAdd04
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
1.14.12 Exercises
1.14.12.1 Exercise 1
Using Java and the game-math library named GM2D04 , or using a dierent programming environment
of your choice, write a program that creates twelve random values in the approximate range from -64 to
+63. Use those values in pairs to dene six mathematical vectors.
Draw the six vectors in a head-to-tail arrangement in alternating colors of green and blue with the tail
of the rst vector at the origin as shown in Image 8 (p. 183) .
Compute and draw the sum of the six vectors in red with the tail of the sum vector at the origin.
Cause the origin of your reference frame to be at the center of your drawing and draw the axes for a
Cartesian coordinate system in the reference frame in black.
Cause the positive x direction to be to the right.
Cause the positive y direction be either up or down according to your choice.
Use a symbol of your choice to indicate the head of each vector.
Cause the program to display your name in some manner.
1.128
1.14.12.2 Exercise 2
Using Java and the game-math library named GM2D04 , or using a dierent programming environment
of your choice, write a program that creates four random values in the approximate range from -128 to +127.
Use those values in pairs to dene two mathematical vectors.
Create a third vector as the sum of the rst two vectors.
Using red, green, and blue, draw the three vectors in a way that illustrates the parallelogram rule for
vector addition as shown in Image 9 (p. 185) .
Cause the origin of your reference frame to be at the center of your drawing and draw the axes for a
Cartesian coordinate system in the reference frame in black.
Cause the positive x direction to be to the right. Cause the positive y direction be either up or down
according to your choice.
Use a symbol of your choice to indicate the head of each vector.
Cause the program to display your name in some manner.
Because of the random nature of the vectors, you may need to run your program more than once to open
up the vector diagram and get a clear picture of the parallelogram rule for vector addition.
1.129
-end-
This module contains lecture slides keyed to the module titled GAME 2302-0125: Vector Addition 74 .
Click here 75 to open an index to the slides.
Then use the links beginning with the label "aa" to open the rst slide that you want to view in a new
window in your browser.
Then use the [Next] and [Prev] links on the individual slides to navigate back and forth through the
slides.
You can also use the links on the index page to jump to a particular slide to avoid having to cycle through
the slides in sequence.
1.15.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
73 This content is available online at <http://cnx.org/content/m45618/1.3/>.
74 http://cnx.org/content/m45012
75 http://cnx.org/content/m45618/latest/a0-Index.htm
1.16.2 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.
What you have learned
In the previous module, you learned:
1.16.2.1.1 Images
• Image 1 (p. 190) . Translation of black hexagon to location of red hexagon.
• Image 2 (p. 192) . Screen output for geometric object with 50 vertices.
• Image 3 (p. 193) . Screen output without drawing the points at the vertices.
• Image 4 (p. 206) . Starting point for the hexagon in VectorAdd06.
• Image 5 (p. 207) . Possible ending point for the hexagon in VectorAdd06.
• Image 6 (p. 213) . String art with 15 vertices and 7 loops.
• Image 7 (p. 214) . String art with 25 vertices and 11 loops.
• Image 8 (p. 215) . String art with 100 vertices and 100 loops.
• Image 9 (p. 216) . Output from StringArt01 at startup.
• Image 10 (p. 232) . Screen output from Exercise 1 at startup.
• Image 11 (p. 233) . Screen output from Exercise 1 after clicking Replot button.
1.16.2.1.2 Listings
• Listing 1 (p. 195) . Instance variables in the class named GUI.
• Listing 2 (p. 196) . Abbreviated constructor for the GUI class.
• Listing 3 (p. 198) . Beginning of the drawOScreen method.
• Listing 4 (p. 199) . To draw or not to draw the lines.
• Listing 5 (p. 200) . Change the drawing color to RED.
• Listing 6 (p. 200) . Translate the geometric object.
• Listing 7 (p. 202) . Draw the lines if drawLines is true.
• Listing 8 (p. 203) . The actionPerformed method.
• Listing 9 (p. 204) . Abbreviated listing of the drawOScreen method.
• Listing 10 (p. 209) . The class named MyCanvas, the update method, and the paint method.
• Listing 11 (p. 210) . Abbreviated listing of actionPerformed method.
• Listing 12 (p. 210) . The inner Thread class named Animate.
• Listing 13 (p. 211) . Do the animated move.
• Listing 14 (p. 217) . Beginning of the drawOScreen method in StringArt01.
• Listing 15 (p. 218) . Implement the algorithm that draws the lines.
• Listing 16 (p. 219) . Draw the lines.
• Listing 17 (p. 222) . Source code for the game-math library named GM2D04.
• Listing 18 (p. 224) . Source code for the sample program named VectorAdd05.
• Listing 19 (p. 226) . Source code for the program named VectorAdd05a.
• Listing 20 (p. 228) . Source code for the program named VectorAdd06.
• Listing 21 (p. 230) . Source code for the program named StringArt01.
1.16.3 Preview
In this module, I will present and explain four programs that use the game-math library named GM2D04
. The purpose of the rst program named VectorAdd05 is to use the addVectorToPoint method of
the GM2D04.Point class to translate a geometric object from one location in space to a dierent location
in space.
The purpose of the program named VectorAdd05a is to accomplish the same translation operation,
but in a possibly more ecient manner.
The purpose of the program named VectorAdd06 is to teach you how to do rudimentary animation
using the game-math library.
The purpose of the program named StringArt01 is to teach you how to use methods of the game-math
library to produce relatively complex drawings.
All of the programs are interactive in that they provide a GUI that allows the user to modify certain
aspects of the behavior of the program.
I will also provide an exercise for you to complete on your own at the end of the module. The exercise
will concentrate on the material that you have learned in this module and previous modules.
1.130
These user-input features are shown at the bottom of Image 1 (p. 190) .
Changing the number of points
Changing the number of points causes the number of vertices that describe the geometric object to
change. For a large number of points, the geometric object becomes a circle as shown in Image 2 (p. 192) .
1.131
For only three points, the geometric object would become a triangle. For four points, it would become a
rectangle. For two points, it would become a line, etc.
Translation
Changing the components of the displacement vector causes the geometric object to be translated to a
dierent location before being drawn in red. In addition to increasing the number of vertices, Image 2 (p.
192) also shows the result of translating by 30 units along the x-axis and -40 units along the y-axis.
note: The positive y-axis: The positive direction for the y-axis is down in the gures in
this module. This is the default for Java graphics. I will resolve that issue and cause the positive
1.132
Similarly, the GUI can be used to cause only the points that dene the vertices to be drawn without the
connecting lines.
1.133
The code in Listing 1 (p. 195) declares a large number of instance variables, initializing some of them.
Those variables shouldn't require an explanation beyond the embedded comments. I show them here solely
to make it easy for you to refer to them later when I discuss them.
Extends JFrame and implements ActionListener
This class extends the JFrame class and implements the ActionListener interface. As you will see
later, implementing the ActionListener interface requires that the class contains a concrete denition of
the actionPerformed method. It also makes an object of the GUI class eligible for being registered as
a listener object on the Replot button shown in Image 1 (p. 190) .
Abbreviated constructor for the GUI class
An Abbreviated listing of the constructor for the GUI class is shown in Listing 2 (p. 196) . Much of
the code was deleted from Listing 2 (p. 196) for brevity. You can view the code that was deleted in Listing
18 (p. 224) .
GUI(){//constructor
//Instantiate the array objects that will be used to
// store the points that define the vertices of the
// geometric object.
points = new GM2D04.Point[numberPoints];
newPoints = new GM2D04.Point[numberPoints];
}//end constructor
1.134
1.135
In order to understand the code in the for loop in Listing 3 (p. 198) , you must have at least a
rudimentary knowledge of trigonometry.
For now, suce it to say that this code will instantiate a set of GM2D04.Point objects equally spaced
around the circumference of a circle with a radius of 50 units centered on the origin.
(When rendered on the o-screen image, these units will be translated to pixels.)
For the initial value of six points, the rst point will be located at an angle of zero degrees relative to the
horizontal, and each of the remaining ve points will located on the circumference of the circle at an angle
that is an even multiple of 360/6 or 60 degrees.
To draw or not to draw the points
Recall that a point has no width, no height, and no depth and is therefore not visible to the human
eye. However, when you call the draw method on an object of the GM2D04.Point class, a small circle
is drawn around the location of the point marking that location for human consumption.
An if statement embedded in the for loop in Listing 3 (p. 198) tests the value of the boolean
instance variable named drawPoints (see Listing 1 (p. 195) , which initializes the value to true) to
determine whether or not to draw the circle marking the location of each point as it is instantiated and saved
in the array object. If true , the circle is drawn as shown in Image 1 (p. 190) . If false , the circle is not
drawn as shown in Image 3 (p. 193) . As you will see later, the user can modify the value of the variable
named drawPoints using one of the checkboxes and the Replot button in Image 1 (p. 190) .
note: The default drawing color: The default drawing color is BLACK. When the points
are drawn the rst time the drawOScreen method is called, they will be drawn in BLACK,
which is a public static nal variable in the Color class.
GM2D04.Line line;
if(drawLines){//Instantiate and draw lines if true.
for(int cnt = 0;cnt < numberPoints-1;cnt++){
//Begin by drawing all of the lines but one.
line = new GM2D04.Line(points[cnt],points[cnt+1]);
line.draw(g2D);
}//end for loop
//Draw the remaining line required to close the
// polygon.
line = new GM2D04.Line(points[numberPoints-1],
points[0]);
line.draw(g2D);
}//end if
1.136
Drawing the lines is only slightly more complicated than drawing the points. A for loop is used in
Listing 4 (p. 199) to draw lines connecting successive pairs of points whose references were stored in the
array named points in Listing 3 (p. 198) . This takes care of all of the required lines but one. Following
the for loop, one additional statement is executed to draw a line connecting the points whose references
are stored in the rst and the last elements in the array.
(I will show you another way to accomplish this wraparound in the program named StringArt01 later
in this module.)
No need to save the GM2D04.Line objects
Note that the GM2D04.Line object that is used to draw each connecting line has no value in this
program after the line is drawn on the o-screen image. Therefore, there is no need to consume memory by
saving a large number of such objects. A single reference variable of the class GM2D04.Line is used to
refer to all the objects of the GM2D04.Line class that are used to draw the connecting lines. As each
new object of that class is instantiated, the object previously referred to by the reference variable becomes
eligible for garbage collection .
(Go to Google and search for the following keywords to learn more about this topic: baldwin java eligible
garbage collection.)
Change the drawing color to RED
After the BLACK geometric object shown in Image 1 (p. 190) has been drawn on the o-screen image,
it is time to change the drawing color to RED in preparation for translating the object and drawing the
translated version of the object. This is accomplished by the single statement in Listing 5 (p. 200) .
1.137
1.138
Listing 6 (p. 200) uses a call to the addVectorToPoint method of the GM2D04.Point class
embedded in a for loop to translate each of the vertices (points) that dene the original geometric
object to a second set of vertices that dene a geometric object having the same shape in a dierent location.
(The initial vector that was used to translate the points in Listing 6 (p. 200) was instantiated in
Listing 1 (p. 195) with values of 50,50. That vector may be modied later using the values in the elds
named Vector X and Vector Y in the GUI shown in Image 1 (p. 190) when the user clicks the Replot
button.)
The new vertices were saved in a dierent array object referred to by the reference variable named
newPoints . It is important to note that in this case, the original geometric object was not moved.
Rather, it was replicated in a new location with the new location being dened by a displacement vector
added to the value of each original point.
Make it appear to move
In many cases in game programming, you will want to make it appear that the object has actually
moved instead of being replicated. That appearance could be achieved by saving the reference to the new
GM2D04.Point object back into the same array, thereby replacing the reference that was previously
there. Make no mistake about it, however, when using this approach, the translated geometric object is a
dierent object, dened by a new set of GM2D04.Point objects that dene the vertices of the geometric
object in the new location.
A dierent approach
A dierent approach would be to call the setData method of the GM2D04.Point class to
modify the coordinate values stored in the existing object that dene the location of the point. In that
case, it would not be necessary to instantiate a new object, and I suppose it could be argued that such an
approach would actually move each vertex, thereby moving the geometric object. If execution speed is an
important factor (particularly in animation code) it would probably be useful to run some benchmarks to
determine which approach would be best. (I will show you how to implement this approach in the program
named VectorAdd05a later in this module.)
Drawing the points
Once again, an if statement is embedded in the code in Listing 6 (p. 200) to determine whether or not
to draw the new points on the o-screen image as the new GM2D04.Point objects are instantiated and
saved in the array. If the points are drawn, they will be drawn in RED due to the code in Listing 5 (p. 200)
.
Drawing the lines
The code in Listing 7 (p. 202) is essentially the same as the code in Listing 4 (p. 199) . This code tests
the variable named drawLines to determine whether or not to draw lines connecting the new points in
the current drawing color (RED) .
}//end drawOffScreen
1.139
if(drawPointsBox.getState()){
drawPoints = true;
}else{
drawPoints = false;
}//end else
if(drawLinesBox.getState()){
drawLines = true;
}else{
drawLines = false;
}//end else
1.140
1.141
points instead of instantiating new objects. None of the three approaches is either right or wrong. There
are pros and cons to all three approaches. This is indicative of the kinds of decisions that must be made by
developers who design class libraries containing classes and methods to accomplish common tasks.
End of the program discussion
That ends the discussion of the program named VectorAdd05a .
1.142
1.143
in space. In this program, however, the translation is performed in 100 incremental steps to produce an
animation. As shown in Image 5 (p. 207) , the animated geometric object is drawn in red to make it visually
distinct from the original object. The original object is not erased from the display.
The polygon
The program initially constructs and draws a black polygon in the upper-left corner of the canvas as
shown in Image 4 (p. 206) . (The polygon is a hexagon in Image 4 (p. 206) .) The six points that dene
the vertices of the hexagon lie on a circle with a radius of 50 units. The points at the vertices and the lines
that connect the points are drawn initially.
Also as shown in Image 4 (p. 206) , a GUI is provided that allows the user to specify the following items
and click a Replot button to cause the animation to begin:
As in the previous program, changing the number of points causes the number of vertices that describe the
geometric object to change, allowing you to create triangles, rectangles, pentagons, hexagons, circles, etc.
Changing the components of the displacement vector causes the geometric object to be translated to a
dierent location. Checking and unchecking the checkboxes causes the points and/or the lines to either be
drawn or not drawn.
Animation performance
On the computer that I am now using, which is not a new one (September 2012), the animation becomes
slightly jerky at about 3500 points when both the points and the lines are drawn.
Will explain in fragments
I will explain this program in fragments and will avoid repeating explanations that I have previously
given. A complete listing of this program is provided in Listing 20 (p. 228) near the end of the module.
Much of the code in this program is very similar to code that I explained earlier. The thing that is new
about this program is the animation aspect of the program. Therefore, I will concentrate mainly on the
animation code in my explanation of the program.
The class named MyCanvas, the update method, and the paint method
Before getting into the details of the program, I want to explain the inner workings of the class named
MyCanvas that I dened for this program. This class, which is an inner class of the GUI class, is shown
in its entirety in Listing 10 (p. 209) .
Listing 10: The class named MyCanvas, the update method, and the paint method.
1.144
to each click on the Replot button shown in Image 4 (p. 206) and Image 5 (p. 207) .
Listing 11 (p. 210) shows an abbreviated listing of the actionPerformed method.
public void
1.145
Most of the code in this method is the same as code that I explained in conjunction with Listing 8 (p.
203) , so I won't repeat that explanation here.
(I deleted that code for brevity in Listing 11 (p. 210) . You can view the method in its entirety in
Listing 20 (p. 228) .)
The code in Listing 11 (p. 210) picks up with a statement that sets the value of an instance variable
named animation to true. This variable is used simply to prevent the animation from starting until the
rst time the user clicks the Replot button.
Spawn an animation thread
This is where this program really departs from the previous programs. Listing 11 (p. 210) instantiates
an object of an inner Thread class named Animate and saves that object's reference in a local variable
named animate . Then Listing 11 (p. 210) uses that variable to call the start method on the Animate
object.
I won't attempt to go into all of the technical details involved in this operation. Suce it to say that
this eventually causes a method named run belonging to the Animate object to be executed.
The Animate class and the run method
The Animate class and the run method begin in Listing 12 (p. 210) .
1.146
The run method begins by computing incremental x and y displacement values that will be required
to move the geometric object from its initial position as shown in Image 4 (p. 206) to its nal position as
shown in Image 5 (p. 207) in 100 equal steps.
Do the animated move
Then Listing 13 (p. 211) executes 100 iterations of a for loop to cause the geometric object to actually
move through those 100 incremental steps and to be drawn on the screen once during each incremental step.
1.147
vector in one giant step. In this program, the values in the displacement vector are divided by 100 and the
drawOScreen method is called 100 times with ten-millisecond pauses between each call to the method.
Each time the drawOScreen method is called, the geometric object ends up closer to its nal position
and each of the 100 intermediate positions are displayed on the canvas for ten milliseconds.
End of discussion
That ends the discussion of the program named VectorAdd06 .
• Number Points
• Number Loops
As in earlier programs in this module, changing the number of points causes the number of vertices that
describe the geometric object to change. Changing the number of loops causes the number of lines that are
drawn to connect the vertices to change. For a Loop value of 1, each vertex is connected to the one next
to it. For a value of 2, additional lines are drawn connecting every other vertex. For a value of 3, additional
lines are drawn connecting every third vertex, etc.
Making the number of points and loops large produces some interesting patterns.
Some output from the program
Before getting into the technical details of the program, I am going to show you some sample screen
output from the program. Image 6 (p. 213) shows the result of drawing lines to connect the points in the
pattern described above among fteen points that are equally spaced around the circumference of the circle.
80 http://scratch.mit.edu/projects/Paddle2See/89023
81 http://info.scratch.mit.edu/About_Scratch
1.148
Image 7 (p. 214) shows the result of drawing lines in a more complex pattern among 25 points that are
equally spaced around the circumference of the circle.
1.149
Image 8 (p. 215) shows the result of drawing lines in an extremely complex pattern among 100 points
that are equally spaced around the circumference of the circle.
1.150
As you can see, there were so many lines and they were so close together in Image 8 (p. 215) that the
visual distinction between lines almost completely disappeared.
Finally, Image 9 (p. 216) shows the program output at startup, with six vertices and one loop.
1.151
1.152
Even some of the code in the method named drawOScreen was explained earlier, and that is the
case for the code in Listing 14 (p. 217) .
Implement the algorithm that draws the lines
Listing 15 (p. 218) begins the outer loop in a pair of nested loops that implement the algorithm to draw
the lines shown in Image 6 (p. 213) through Image 9 (p. 216) .
GM2D04.Line line;
1.153
The algorithm
As I mentioned earlier, the algorithm goes something like the following:
• Draw a line connecting every point to its immediate neighbor on the circumference of the circle.
• Draw a line connecting every other point on the circumference of the circle.
• Draw a line connecting every third point on the circumference of the circle.
• Continue this process until the number of iterations satises the number of Loops specied by the
user.
The code in the outer loop that begins in Listing 15 (p. 218) is responsible for identifying the beginning
and ending points for the lines that will be drawn during one iteration of the outer loop. Given the above
information and the embedded comments in Listing 15 (p. 218) , you should have no diculty understanding
the logic in Listing 15 (p. 218) .
Draw the lines
The inner loop in the pair of nested loops is shown in Listing 16 (p. 219) . This loop constructs a series
of GM2D04.Line objects and then causes visual manifestations of those objects to be drawn on the
o-screen image.
1.154
Once again, given what you now know, and given the embedded comments in the code, you should have
no diculty understanding the logic of the code. Note in particular the requirement to wrap around when
the element number exceeds the length of the array containing references to the GM2D04.Point objects
that specify the locations of the vertices of the geometric object.
End of the discussion of StringArt01
That ends the discussion of the program named StringArt01 .. It also ends the discussion of all ve
of the programs that I promised to explain in this module.
The homework assignment for this module was to study the Kjell tutorial through Chapter 5 - Vector
Direction .
The homework assignment for the next module is to study the Kjell tutorial through Chapter 6 - Scaling
and Unit Vectors .
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 82 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.
I encourage you to copy the code from Listing 18 (p. 224) through Listing 21 (p. 230) .Compile the code
and execute it in conjunction with the game-math library provided in Listing 17 (p. 222) . Experiment with
the code, making changes, and observing the results of your changes. Make certain that you can explain
why your changes behave as they do.
1.16.7 Summary
In this module, I presented and explained four programs that use the game-math library named GM2D04
. The purpose of the program named VectorAdd05 is to use the addVectorToPoint method of the
GM2D04.Point class to translate a geometric object from one location in space to a dierent location in
space.
The purpose of the program named VectorAdd05a is to accomplish the same translation operation,
but to do so in a possibly more ecient manner.
The purpose of the program named VectorAdd06 is to teach you how to do rudimentary animation
using the game-math library.
The purpose of the program named StringArt01 is to teach you how to use methods of the game-math
library to produce relatively complex drawings.
All of the programs are interactive in that they provide a GUI that allows the user to modify certain
aspects of the behavior of the program.
In the next module, you will learn how to update the game-math library to support 3D math, how to program
the equations for projecting a 3D world onto a 2D plane, and how to add vectors in 3D.
You will also learn about scaling, translation, and rotation of a point in both 2D and 3D, about the
rotation equations and how to implement them in both 2D and 3D, and much more.
1.16.9 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial compensation from the Connexions website even
if you purchase the PDF version of the module.
82 http://cnx.org/content/m44992/latest/
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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 17 (p. 222) through Listing
21 (p. 230) below.
Listing 17: Source code for the game-math library named GM2D04.
/*GM2D04.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
Listing 18: Source code for the sample program named VectorAdd05.
/*VectorAdd05.java
Copyright 2008, R.G.Baldwin
Revised 02/11/08
Number points
X-component of the displacement vector.
Y-component of the displacement vector.
A checkbox to specify whether points are to be drawn.
A checkbox to specify whether lines are to be drawn.
/*VectorAdd05a.java
Copyright 2008, R.G.Baldwin
Revised 02/19/08
Number points
X-component of the displacement vector.
Y-component of the displacement vector.
A checkbox to specify whether points are to be drawn.
A checkbox to specify whether lines are to be drawn.
/*VectorAdd06.java
Copyright 2008, R.G.Baldwin
Revised 02/22/08.
Number points
X-component of the displacement vector.
Y-component of the displacement vector.
A checkbox to specify whether points are to be drawn.
A checkbox to specify whether lines are to be drawn.
/*StringArt01.java
Copyright 2008, R.G.Baldwin
Revised 02/20/08
Number Points
Number Loops
class StringArt01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class StringArt01
//======================================================//
Available implements
class GUI extends JFrame for free at Connexions <http://cnx.org/content/col11450/1.29>
ActionListener{
//Specify the horizontal and vertical size of a JFrame
// object.
int hSize = 300;
231
1.16.11 Exercises
1.16.11.1 Exercise 1
Using Java and the game-math library named GM2D04 , , or using a dierent programming environment
of your choice, write a program that begins with an image showing:
• Cartesian coordinate axes with the origin at the center of the image,
• a small black pentagon centered on the origin, and
• a button labeled Replot
No user input controls other than the button should be visible in your image.
Make each side of the pentagon approximately one-half inch in length as shown in Image 10 (p. 232) .
Each time you click the Replot button, a red pentagon appears on top of the black pentagon and then
moves smoothly to a random location somewhere in the image as shown in Image 11 (p. 233) .
If you click the button more than once, the old red pentagon is erased and a new red pentagon appears
and moves as described above.
Move the red pentagon in a straight line in approximately 100 incremental steps over a time period of
approximately one second.
Cause the program to display your name in some manner.
1.160
Image 11: Screen output from Exercise 1 after clicking Replot button.
1.161
-end-
1.17.2 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.
What you have learned
In a previous module, I presented and explained four programs that used the game-math library named
GM2D04 . One of those programs taught you how to use the addVectorToPoint method of the
GM2D04.Point class to translate a geometric object from one location in space to a dierent location in
space.
Another program taught you how to do the same thing but in a possibly more ecient manner.
The third program taught you how to do rudimentary animation using the game-math library.
The fourth program taught you how to use methods of the game-math library to produce relatively
complex drawings.
All of the programs were interactive in that they provide a GUI that allows the user to modify certain
aspects of the behavior of the program.
What you will learn
The most important thing that you will learn in this module is how to update the game-math library to
support 3D math and how to produce 3D images similar to that shown in Image 1 (p. 235) .
1.162
• How to program the equations for projecting a 3D world onto a 2D plane for display on a computer
screen.
• How to cause the direction of the positive y-axis to be up the screen instead of down the screen.
• How to add vectors in 3D and how to conrm that the head-to-tail and parallelogram rules apply to
3D as well as to 2D.
• About scaling, translation, and rotation of a point in both 2D and 3D.
• About the rotation equations and how to implement them in both 2D and 3D.
• How to rotate a point around an anchor point other than the origin.
• About the right-hand rule.
1.17.2.1.1 Images
• Image 1 (p. 235) . A 3D image produced using the game-math library.
• Image 2 (p. 243) . Graphics output from the program named GM01test02.
• Image 3 (p. 244) . Command-line output from the program named GM01test02.
• Image 4 (p. 254) . Graphic output from the program named GM01test05.
• Image 5 (p. 257) . Graphic output from the program named GM01test06.
• Image 6 (p. 259) . Rotation equations for a point in 2D space.
• Image 7 (p. 262) . Initial graphic output from the program named StringArt02.
• Image 8 (p. 264) . Graphic output from the program named StringArt02 with Loops set to 3.
• Image 9 (p. 266) . Rotation by 30 degrees around the origin.
• Image 10 (p. 267) . Rotation around an anchor point that is not at the origin.
• Image 11 (p. 269) . Rotation around a point further out in space.
• Image 12 (p. 271) . The six 3D rotation equations.
• Image 13 (p. 276) . Graphic output from the program named StringArt03 at startup.
• Image 14 (p. 278) . Geometric object with 12 vertices, 4 loops, and no rotations.
• Image 15 (p. 279) . Rotation around the z-axis only.
• Image 16 (p. 281) . Rotation around the x-axis only.
• Image 17 (p. 282) . Rotation around the y-axis only.
• Image 18 (p. 284) . Rotation around all three axes with the anchor point at the origin.
• Image 19 (p. 285) . Perform all three rotations with the anchor point away from the origin.
• Image 20 (p. 303) . Screen output from Exercise 1.
• Image 21 (p. 304) . Screen output from Exercise 2.
• Image 22 (p. 305) . Screen output from Exercise 3.
• Image 23 (p. 306) . Screen output from Exercise 4.
• Image 24 (p. 307) . Screen output from Exercise 5.
• Image 25 (p. 308) . Screen output from Exercise 6.
1.17.2.1.2 Listings
• Listing 1 (p. 239) . The static method named convert3Dto2D.
• Listing 2 (p. 241) . Transform equations for an oblique parallel projection from 3D to 2D.
• Listing 3 (p. 245) . Code in the constructor for the GUI class in the program named GM01test02.
• Listing 4 (p. 246) . The method named GM01.Point3D.draw.
• Listing 5 (p. 247) . The method named GM01.Vector3D.draw.
• Listing 6 (p. 248) . The GM01.Line3D.draw method.
• Listing 7 (p. 249) . Beginning of the drawOScreen method in GM01test01.
• Listing 8 (p. 250) . Project eight points onto the 2D plane and draw them.
• Listing 9 (p. 251) . Draw twelve lines that connect the corners of the box.
• Listing 10 (p. 252) . Instantiate and draw a GM01.Vector3D object onto the 2D o-screen image.
• Listing 11 (p. 253) . The setCoordinateFrame method.
• Listing 12 (p. 255) . The drawOScreen method of the program named GM01test05.
In case you are wondering where we are heading as we go down this path, I recommend that you skip ahead
to the modules titled Our First 3D Game Program and A First-Person Shooter Game . Copy, compile
and run the 3D game programs named GM01Test08 and Cannonball01 along with the required
game-math libraries.
While the graphics and the story lines for those two game programs are rudimentary, the mathematics
involved are signicant. (After all, this is a course in game math and not a course in game design or
high-quality graphics.)
I will present and explain a signicantly updated game-math library in this module.
I will also present and explain six dierent sample programs that show how to use the new features in
the updated library.
By studying the library and the sample programs, you will learn
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this and previous modules.
In this section, I will present and explain a signicantly updated version of the game-math library named
GM01 (p. 238) .
In addition, I will present and explain the following programs that use the update game-math library.
• GM01.convert3Dto2D
• GM01.translate
• GM01.drawLine
• GM01.llOval
• GM01.drawOval
84 http://en.wikipedia.org/wiki/Oblique_projection
• GM01.llRect
It will probably be necessary for me to add more wrapper methods to the library in future modules. With
the exception of the rst method in the above list, the coding of these methods was straightforward and
explanations of that code are not warranted. Note, however, that it is the wrapper methods that resolve the
issue regarding the direction of the positive y-axis. You will see comments in this regard if you examine the
source code for the wrapper methods in Listing 27 (p. 291) . I will explain the code for the method named
GM01.convert3Dto2D shortly.
Other new methods
In addition to the new static methods listed above, a number of new methods were added to the existing
static top-level 2D classes and also included in the new static top-level 3D classes. A list of those new
methods follows:
• GM01.Vector2D.scale
• GM01.Vector2D.negate
• GM01.Point2D.clone
• GM01.Vector2D.normalize
• GM01.Point2D.rotate
• GM01.Point2D.scale
• GM01.Vector3D.scale
• GM01.Vector3D.negate
• GM01.Point3D.clone
• GM01.Vector3D.normalize
• GM01.Point3D.rotate
• GM01.Point3D.scale
With the exception of the two rotate methods, the coding of the methods in the above list was also
straightforward and an explanation of that code is not warranted. You can view all of the new code in
Listing 26 (p. 289) .
The two rotate methods are not straightforward at all. They are quite complicated (particularly
the 3D method) and require quite a lot of background information to understand. I will dedicate a large
portion of a future module to the task of rotating geometric objects in 2D and 3D worlds and will defer an
explanation of the two rotate methods until that module.
The static method named GM01convert3Dto2D
Note rst that this is a static method of the class named GM01 . Among other things, this means
that the method can be called simply by joining the name of the method to the name of the class. In other
words, an object of the class named GM01 is not necessary to make the method accessible.
A complete listing of the method is provided in Listing 1 (p. 239) .
1.163
As you can see, the method is quite short, and once you know how it is required to behave (p. 240) ,
coding the method is not dicult. The complexity comes in understanding the required behavior.
note: Keeping 2D and 3D classes separate: All of the static top-level 2D classes in the
existing game-math library were renamed with a sux of 2D to distinguish them from the new
top-level 3D classes. All of the new top-level 3D class names have a 3D sux.
1.164
results, so I decided to use them. You may nd it interesting to experiment with other values for one or
both angles to see the results produced by those other values.
The proper algebraic signs
Note in particular that the proper signs for the equations in Listing 2 (p. 241) depend on the assumed
positive directions of the angles as well as the assumed positive directions of the axes. The signs used in
the method make the assumptions shown in Listing 2 (p. 241) . (These assumptions will be particularly
important in future modules where we will be rotating objects in 3D space.)
The viewing position
Also as indicated in Listing 2 (p. 241) and shown in Image 1 (p. 235) , the viewing position is above the
x-axis and to the right of the z-y plane.
Typically, a game math library would provide the capability to modify the viewing position. That
capability is not supported directly by this library. However, that capability can be approximated by the
rotation capability discussed later. (Another exercise for the student to accomplish.)
The code in the method is straightforward
As I mentioned earlier, once you understand the requirements, the code for the method named con-
vert3Dto2D (see Listing 1 (p. 239) ) is relatively straightforward. If you have studied the code in the
previous modules in this series, the code in Listing 1 (p. 239) shouldn't require further explanation.
1.165
Listing 3: Code in the constructor for the GUI class in the program named GM01test02.
1.167
If you examine the source code for those two methods in Listing 27 (p. 291) , you will see that each of the
methods contains calls to library methods for the purpose of conrming that the library methods behave as
expected. The code in most of those methods is straightforward and should not require further explanation
beyond the embedded comments in Listing 27 (p. 291) .
End of the discussion for the program named GM01test02
That concludes the discussion of the program named GM01test02 . You will nd a complete listing
of this program in Listing 27 (p. 291) .
• GM01.Point3D.draw
• GM01.Vector3D.draw
• GM01.Line3D.draw
1.168
}//end draw
1.169
This method draws the 2D visual manifestation of a GM01.Vector3D object on the specied 2D
graphics context. Recall that a vector has no location property. Therefore, it can be correctly drawn
anywhere. The GM01.Vector3D.draw method requires the drawing location of the tail to be specied
by a reference to a GM01.Point3D object received as an incoming parameter.
A small lled circle is drawn at the head of the vector as shown by the magenta lled circle at the
origin in Image 1 (p. 235) . (Note that the other circles in Image 1 (p. 235) are not lled.)
Two calls to the convert3Dto2D method
Two calls are made to the convert3Dto2D method in Listing 5 (p. 247) . The rst call gets a 2D
projection of the 3D location of the tail of the vector. The second call gets a 2D projection of the 3D location
of the head of the vector. In both cases, the projected location in 2D space is returned as a reference to an
object of the GM01.ColMatrix2D class.
Draw the vector on the specied drawing context
The reference returned by the rst call to the convert3Dto2D method is used to call the static
GM01.drawLine wrapper method to
• handle the issue of the positive direction of the y-axis, and
• draw a line on the 2D o-screen image representing the body of the vector as shown by the magenta
line in Image 1 (p. 235) .
The reference returned by the second call to the convert3Dto2D method is used to call the static
GM01.llOval wrapper method to
• handle the issue of the positive direction of the y-axis, and
• draw a small lled circle on the 2D o-screen image representing the head of the vector as shown by
the magenta lled circle at the origin in Image 1 (p. 235) .
drawLine(g2D,tail.getData(0),
tail.getData(1),
head.getData(0),
head.getData(1));
}//end draw
1.170
The code in Listing 6 (p. 248) is so similar to the code in Listing 5 (p. 247) that no further explanation
should be required.
Now back to the program named GM01test01
A complete listing of the program named GM01test01 is provided in Listing 28 (p. 293) near the end
of the module.
Because all of the 3D classes in the game-math library are new to this update, I felt the need to write a
program that would step through and test the behavior of most of the 3D methods in the library. That was
the purpose of the program named GM01test01 .
Like the program named GM01test02 discussed earlier, this program produces both a graphic screen
output and lots of text on the command-line screen. The graphic output is shown in Image 1 (p. 235) . I
won't waste space printing the command-line output in this tutorial. If you want to see it, you can copy,
compile, and run the program from Listing 28 (p. 293) and produce that output yourself.
The graphic output
The graphic output shown in Image 1 (p. 235) is produced by the method named drawOScreen ,
which begins in Listing 7 (p. 249) . I will briey walk you through this method because everything in it is
new. However, much of the code is very similar to 2D code that I have explained before.
1.171
After translating the origin to the center of the o-screen image, Listing 7 (p. 249) instantiates eight
GM01Point3D objects that dene the corners of the 3D box shown in Image 1 (p. 235) . References to
the eight objects are stored in the elements of an array object referred to by the variable named points .
Although this code uses three coordinate values instead of two coordinate values to instantiate the objects,
the syntax should be very familiar to you by now.
Project eight points onto the 2D plane and draw them
Listing 8 (p. 250) calls the GM01.Point3D.draw method eight times in succession to cause the
locations of the eight points in 3D space to be projected onto the 2D o-screen image and to draw the points
as small circles on that image. This is the rst draw method from the earlier list (p. 245) that I explained
above.
Listing 8: Project eight points onto the 2D plane and draw them.
1.172
Seven of the points are drawn in BLACK and one is drawn in RED. The eight small circles appear at
the corners of the box in Image 1 (p. 235) .
As indicated in the comments, the RED point is drawn at the right top front corner of the box to help
you get the orientation of the box correct in your mind's eye.
Draw twelve lines that connect the corners of the box
Listing 9 (p. 251) calls the GM01.Line3D.draw method twelve times in succession to project the
lines that connect the corners of the 3D box onto the 2D o-screen image and to draw those lines on that
image. This is the second draw method from the earlier list (p. 245) that I explained above.
Listing 9: Draw twelve lines that connect the corners of the box.
//Left side
new GM01.Line3D(points[4],points[5]).draw(g2D);
new GM01.Line3D(points[5],points[6]).draw(g2D);
new GM01.Line3D(points[6],points[7]).draw(g2D);
new GM01.Line3D(points[7],points[4]).draw(g2D);
//Front
new GM01.Line3D(points[0],points[4]).draw(g2D);
new GM01.Line3D(points[3],points[7]).draw(g2D);
//Back
new GM01.Line3D(points[1],points[5]).draw(g2D);
new GM01.Line3D(points[2],points[6]).draw(g2D);
1.173
Listing 10: Instantiate and draw a GM01.Vector3D object onto the 2D o-screen image.
//Instantiate a vector.
GM01.Vector3D vecA = new GM01.Vector3D(
new GM01.ColMatrix3D(75,-75,-75));
}//end drawOffScreen
1.174
This is the third and nal draw method from the earlier list (p. 245) that I explained above. The vector
was drawn with its tail at the upper left corner of the box. The length and direction of the vector were such
as to cause the head of the vector to be at the origin in 3D space.
Draw the 3D axes
The red, green, and blue 3D axes shown in Image 1 (p. 235) were produced by the call to the setCo-
ordinateFrame method early in Listing 7 (p. 249) . The setCoordinateFrame method is shown in
Listing 11 (p. 253) .
1.175
This method is used to set the origin of the o-screen image. It also projects orthogonal 3D axes onto
the 2D o-screen image and draws the projected axes on that image. The axes intersect at the origin in 3D
space.
The lengths of the axes are set so as to match the interior dimensions of the box shown in Image 1 (p.
235) and points are drawn where the axes intersect the surfaces of the box. That was done to enhance the
optical illusion of a 3D object on a 2D plane.
There is nothing in Listing 11 (p. 253) that you haven's seen before, so further explanation should not
be required.
End of discussion
That concludes the discussion of the program named GM01test01 . You can view the code that was
not discussed here in Listing 28 (p. 293) near the end of the module.
1.176
This output shows the addition of a magenta vector to a light gray vector to produce a black vector as
the sum of the other two vectors. As you can see, both the parallelogram rule and the head-to-tail rule are
illustrated by the graphic output in Image 4 (p. 254) .
Very familiar code
Most of the code in this program will be very familiar to you by now. The new code is mostly contained
in the method named drawOScreen , which is shown in Listing 12 (p. 255) . A complete listing of this
program is provided in Listing 29 (p. 295) near the end of the module.
}//end drawOffScreen
1.177
At this point, you should not nd any code in Listing 12 (p. 255) that you don't understand. I have
explained the code in Listing 12 (p. 255) earlier in this module or in an earlier module, so I won't repeat
that explanation here.
End of discussion .
That concludes the discussion of the program named GM01test05 . You will nd a complete listing
of this program in Listing 29 (p. 295) .
In a previous module, you learned how to translate a geometric object. In this program, you will learn how
to scale a geometric object. In the next two programs, you will learn how to rotate geometric objects.
The new scaling methods
The additions to the game-math library included the following two methods:
• GM01.Point2D.scale
• GM01.Point3D.scale
As the names imply, these two methods can be used to scale a point in either 2D or 3D.
The game-math library method named GM01.Point3D.scale
This method is shown in Listing 13 (p. 256) .
1.178
This method multiplies each coordinate value of the Point3D object on which the method is called by
the corresponding values in an incoming ColMatrix3D object to produce and return a new Point3D
object. This makes it possible to scale each coordinate value that denes the location in space by a dierent
scale factor.
If a scale factor for a particular coordinate is less than 1.0 but greater than 0.0, the location of the new
point will be closer to the origin along that axis than was the location of the original point. If a scale factor is
greater than 1.0, the new point will be further from the origin along that axis. If the scale factor is negative,
the location of the new point will be on the other side of the origin along the same axis.
Graphic output from the program named GM01test06
The graphic output from the program named GM01test06 is shown in Image 5 (p. 257) . Compare
this with the graphic output from the program named GM01test01 shown in Image 1 (p. 235) .
1.179
These modications are so straightforward that no explanation of the actual code is justied. You can view
the modications in Listing 30 (p. 297) .
End of discussion .
That concludes the discussion of the program named GM01test06 . You will nd a complete listing
of this program in Listing 30 (p. 297) .
double tempX ;
double tempY;
1.180
The purpose of the GM01.Point2D.rotate method is to rotate a point around a specied anchor
point in the x-y plane. The location of the anchor point is passed in as a reference to an object of the class
GM01.Point2D . The rotation angle is passed in as a double value in degrees with the positive angle
of rotation being counter-clockwise.
x2 = x1*cos(alpha) - y1*sin(alpha)
y2 = x1*sin(alpha) + y1*cos(alpha)
1.181
I won't attempt to derive or justify these equations. I will simply use them. If you need more information
on the topic, simply Google 2D transform s and you will probably nd more information than you have
the time to read.
In Image 6 (p. 259) , the coordinates of the original point are given by x1 and y1 , and the coordinates
of the rotated point are given by x2 and y2 . The angle alpha is a counter-clockwise angle around the
origin.
Houston, we have a problem
We still have a problem however. The equations in Image 6 (p. 259) are for rotating a point around the
origin. Our objective is to rotate a point around any arbitrary anchor point in 2D space.
We could probably modify the equations in Image 6 (p. 259) to accomplish this. However, there is
another way, which is easier to implement. It can be shown that the same objective can be achieved by
translating the anchor point to the origin, rotating the object around the origin, and then translating the
rotated object back to the anchor point. Since we already know how to translate a point in 2D space, this
is the approach that we will use.
You must be very careful
I do want to point out, however, that you really have to think about what you are doing when you rotate
geometric objects, particularly when you combine rotation with translation. For example, rotating an object
around the origin and then translating it does not produce the same result as translating the object and
then rotating the translated object around the origin.
Clone the original Point2D object
Listing 14 (p. 258) begins by calling the new GM01.Point2D.clone method to create a clone of the
object on which the rotate method was called. The clone, referred to by newPoint , will be rotated and
returned, thus preserving the original object.
Following that, Listing 14 (p. 258) declares working variables that will be used later.
Incoming parameters
The GM01.Point2D.rotate method in Listing 14 (p. 258) requires two incoming parameters. The
rst parameter is a reference to a GM01.Point2D object that species the anchor point around which the
geometric object is to be rotated. The second parameter is the rotation angle in degrees, counter-clockwise
around the origin.
Translate the anchor point to the origin
87 http://www.ia.hiof.no/∼borres/cgraph/math/threed/p-threed.html
Listing 15 (p. 260) gets a Vector2D object that represents the displacement vector from the origin to
the anchor point.
GM01.Vector2D tempVec =
new GM01.Vector2D(anchorPoint.getColMatrix());
newPoint =
newPoint.addVectorToPoint(tempVec.negate());
1.182
The negative of the displacement vector is used to translate the clone ( newPoint ) object, thus
translating the anchor point to the origin.
Rotate the translated newPoint object around the origin
Listing 16 (p. 260) implements the two rotation equations shown in Image 6 (p. 259) to rotate the
translated newPoint object around the origin.
Listing 16: Rotate the translated newPoint object around the origin.
tempX = newPoint.getData(0);
tempY = newPoint.getData(1);
newPoint.setData(//new x coordinate
0,
tempX*Math.cos(angle*Math.PI/180) -
tempY*Math.sin(angle*Math.PI/180));
newPoint.setData(//new y coordinate
1,
tempX*Math.sin(angle*Math.PI/180) +
tempY*Math.cos(angle*Math.PI/180));
1.183
Note that the rotation angle is converted from degrees to radians to make it compatible with the sin and
cos functions from the standard Java Math library.
Translate the rotated newPoint object back to the anchor point
Finally, Listing 17 (p. 261) uses the displacement vector that was created and saved earlier to translate
the rotated newPoint object back to the anchor point.
Listing 17: Translate the rotated newPoint object back to the anchor point.
return newPoint;
}//end rotate
1.184
Then Listing 17 (p. 261) returns a reference to the rotated newPoint object.
Now back to the program named StringArt02
This is a 2D version of a string art program that supports rotation in two dimensions. This program
produces a 2D string art image by connecting various points that are equally spaced on the circumference
of a circle as shown in Image 7 (p. 262) .
1.185
Initial conditions
Initially, the circle is centered on the origin and there are six points on the circle connected by lines
forming a hexagon. The lines that connect the points are dierent colors. The radius of the circle is 50 units.
The points at the vertices of the hexagon are not drawn, but the lines that connect the vertices are drawn.
The anchor point is drawn in black, resulting in the small black circle at the origin in Image 7 (p. 262) .
A graphical user interface
A GUI is provided that allows the user to specify the following items and click a Replot button to
cause the drawing to change:
• Number Points
• Number Loops
• Rotation angle (deg)
• X anchor point
• Y anchor point
Changing the number of points causes the number of vertices that describe the geometric object to change.
Changing the number of loops causes the number of lines that are drawn to connect the vertices to change.
For a value of 1, each vertex is connected to the one next to it. For a value of 2, additional lines are
drawn connecting every other vertex. For a value of 3, additional lines are drawn connecting every third
vertex as shown in Image 8 (p. 264) .
Image 8: Graphic output from the program named StringArt02 with Loops set to 3.
1.186
The anchor point is initially located at the origin, but the location of the anchor point can be changed
by the user. If the anchor point is at the origin, the geometric object is rotated around the origin as shown
in Image 9 (p. 266) . (Compare the colors and the locations of the vertices in Image 8 (p. 264) and Image
9 (p. 266) to discern the result of the rotation in Image 9 (p. 266) .)
1.187
Rotating the geometric object around an anchor point away from the origin
Image 10 (p. 267) shows the result of rotating the geometric object by 90 degrees around an anchor point
that is not located at the origin.
Image 10: Rotation around an anchor point that is not at the origin.
1.188
The rotation angle is specied in degrees with a positive angle being counter-clockwise. For Image 10
(p. 267) , I purposely located the anchor point at the upper-right vertex in Image 8 (p. 264) and rotated
the geometric object by 90 degrees around that anchor point. Compare Image 10 (p. 267) with Image 8 (p.
264) to see the result of rotating the geometric object around the anchor point.
Rotating around an anchor point further out in space
In Image 11 (p. 269) , I moved the anchor point further out in space, but still on a line that runs through
the origin and the upper-right vertex in Image 8 (p. 264) . Then I rotated the geometric object by 30 degrees
around the anchor point.
(Note that the rotation examples in these images are not cumulative. In other words, each rotation is
relative to an un-rotated object at the origin.)
1.189
By now, you should have been able to predict in advance what you would see when the program was run
with these parameters.
Let's see some code
Given what you have already learned, the only interesting new code in this program is in the drawO-
Screen method. An abbreviated listing of that method is shown in Listing 18 (p. 270) . A complete listing
of the StringArt02 program is provided in Listing 31 (p. 299) near the end of the module.
}//end drawOffScreen
1.190
Within the method named drawOScreen , the only really interesting code is the statement that
calls the rotate method of the game-math library on each Point2D object inside a for loop. Knowing
what you do about the rotate method, you should have no problem understanding the code in Listing 18
(p. 270) .
End of the discussion
That concludes the discussion of the program named StringArt02 . You will nd a complete listing
Where:
x1, y1, and z1 are coordinates of original point
x2, y2, and z2 are coordinates of rotated point
1.191
Also, as before, these six equations are only good for rotation around the origin, but our objective is to
be able to rotate a point about any arbitrary anchor point in 3D space. Once again, we will use the trick
of translating the anchor point to the origin, rotating the object around the origin, and then translating the
object back to the anchor point.
Beginning of the method named GM01.Point3D.rotate
88 http://www.ia.hiof.no/∼borres/cgraph/math/threed/p-threed.html
public GM01.Point3D
1.192
The purpose of this method is to rotate a point around a specied anchor point in 3D space in the
following order:
note: A useful upgrade: A useful upgrade to the game-math library might be to write three
separate rotation methods, each designed to rotate a Point3D object around only one of the three
axes.
It is very important to understand that the order of the rotations is critical. You cannot change the order
of rotations and expect to end up with the same results. This method is designed to allow you to rotate an
object around all three axes with a single method call in the order given above. If you need to rotate your
object in some dierent order, you should call the method up to three times in succession, rotating around
only one axis with each call to the method.
Incoming parameters
The anchor point is passed in as a reference to an object of the GM01.Point3D class.
The rotation angles are passed in as double values in degrees (based on the right-hand rule (p. 272) )
in the order given above, packaged in an object of the class GM01.ColMatrix3D .
(Note that in this case, the ColMatrix3D object is simply a convenient container for the three
double angle values and it has no signicance from a matrix arithmetic viewpoint. Also pay attention to
the order of the three values and the rotation axes associated with those values. See Listing 20 (p. 273) . It
is z, x, y, and not x, y, z as you might assume.)
The right-hand rule
The right-hand rule states that if you point the thumb of your right hand in the positive direction of an
axis and curl your ngers to make a st, the direction of positive rotation around that axis is given by the
direction that your ngers will be pointing.
I will refer back to this rule later when describing rotations around various axes.
Original object is not modied
This method does not modify the contents of the Point3D object on which the method is called.
Rather, it uses the contents of that object to instantiate, rotate, and return a new Point3D object.
Rotation around the anchor point
For simplicity, this method translates the anchor point to the origin, rotates around the origin, and then
translates the object back to the anchor point.
Very familiar code
The code in Listing 19 (p. 272) is very similar to the code that I explained earlier beginning in Listing
14 (p. 258) . Therefore, this code should not require an explanation beyond the embedded comments.
Get the rotation angle values
Listing 20 (p. 273) extracts the rotation angle values from the GM01.ColMatrix3D object in which
they are contained.
1.193
newPoint.setData(//new y coordinate
1,
tempX*Math.sin(zAngle*Math.PI/180) +
tempY*Math.cos(zAngle*Math.PI/180));
1.194
This is the only rotation possibility in 2D rotation and the code in Listing 21 (p. 273) is essentially the
same as the code in Listing 16 (p. 260) for 2D rotation.
Rotate the Point 3D object around the x-axis
Before translating the partially rotated object back to the anchor point, it must still be rotated around
the x and y-axes. Listing 22 (p. 274) implements the middle two equations in Image 12 (p. 271) to rotate
the Point3D object in a plane that is perpendicular to the x-axis, modifying only the y and z coordinate
values.
newPoint.setData(//new z coordinate
2,
tempY*Math.sin(xAngle*Math.PI/180) +
tempZ*Math.cos(xAngle*Math.PI/180));
1.195
newPoint.setData(//new z coordinate
2,
-tempX*Math.sin(yAngle*Math.PI/180) +
tempZ*Math.cos(yAngle*Math.PI/180));
1.196
return newPoint;
}//end rotate
1.197
In order to rotate an entire 3D geometric object, such as the hexagon in Image 13 (p. 276) , every point
that comprises the geometric object must be rotated using the same set of rotation angles and the same
anchor point.
Now back to the program named StringArt03
This is a 3D version of a string art program that demonstrates rotation in three dimensions. This program
produces a 3D string-art image by connecting various points that are equally spaced on the circumference
of a circle. Initially, the circle is on the x-y plane centered on the origin as shown in Image 13 (p. 276) .
Image 13: Graphic output from the program named StringArt03 at startup.
1.198
At startup, there are six points (vertices) on the circle connected by lines forming a hexagon. The lines
that connect the points are dierent colors. The radius of the circle is 50 units. The points at the vertices
of the hexagon are not drawn, but the lines that connect the vertices are drawn.
You may have noticed that the startup graphic output in Image 13 (p. 276) looks a lot like the startup
graphic output of the 2D program in Image 7 (p. 262) . There is a signicant dierence however. Image
7 (p. 262) shows only two orthogonal axes whereas Image 13 (p. 276) shows three orthogonal axes using
oblique parallel projection to transform the 3D image to a 2D display plane.
A graphical user interface
A GUI is provided that allows the user to specify the following items and click a Replot button to
cause the drawing to change:
• Number Points
• Number Loops
• Rotate around Z (deg)
• Rotate around X (deg)
• Rotate around Y (deg)
• X Anchor point
• Y Anchor point
• Z Anchor point
Again, the 3D GUI in Image 13 (p. 276) looks similar to the 2D GUI in Image 7 (p. 262) . The big dierence
is that the 2D GUI in Image 7 (p. 262) allows only for rotation around one axis, and only two coordinate
values can be specied for the location of the anchor point.
As before, changing the number of points causes the number of vertices that describe the geometric object
to change. Changing the number of loops causes the number of lines that are drawn to connect the vertices
to change.
The geometric object can be rotated in any or all of three dimensions around an anchor point. Entering
a non-zero value in one or more of the Rotate elds causes the object to be rotated by the specied angle
or angles around the anchor point.
The anchor point is initially specied to be at the origin, but the location of the anchor point can be
changed by the user. If the anchor point is at the origin, the image is rotated around the origin.
Geometric object with 12 vertices, 4 loops, and no rotations
As a baseline case, Image 14 (p. 278) shows the string-art geometric object with 12 vertices, 4 loops,
and no rotations. At this point, the geometric object is an innitely thin disk in the x-y plane centered on
the origin. Note the break in color between yellow and blue that occurs where the circle crosses the positive
x-axis.
1.199
The rotation angle must be specied in degrees with a positive angle being given by the right-hand rule
(p. 272) as applied to the axis around which the image is being rotated.
Rotation around one axis only
Image 15 (p. 279) , Image 16 (p. 281) , and Image 17 (p. 282) show the results of rotating the object
around only one axis at a time with the anchor point at the origin.
Image 15 (p. 279) shows the result of rotating the object around the z-axis only by an angle of 60 degrees.
1.200
This results in the object still being in the x-y plane, but it has been rotated counter-clockwise by 60
degrees. Compare Image 15 (p. 279) with Image 14 (p. 278) and note how the color break between yellow
and blue has moved around to be near the intersection of the circle and the positive y-axis.
Rotation around the x-axis only
Image 16 (p. 281) shows the result of rotating the object around only the x-axis with a rotation angle of
-60 degrees.
1.201
The object is still a disk, but that disk is no longer in the x-y plane. Instead, it has been tilted so that it
is now closer to the x-z plane than to the x-y plane. Unfortunately, the oblique parallel projection does not
make it practical to do any quantitative measurements on the image.
1.202
Image 18: Rotation around all three axes with the anchor point at the origin.
1.203
Once again, I will let you interpret what you see there.
Perform all three rotations with the anchor point away from the origin
Image 19 (p. 285) performs the same three rotations as were performed in Image 18 (p. 284) . However,
in Image 19 (p. 285) , the anchor point was at a location dened by the coordinate values (50,50,50).
Image 19: Perform all three rotations with the anchor point away from the origin.
1.204
At the risk of being boring, I will state once again that I will let you interpret what you see there.
1.205
The only really interesting code in Listing 25 (p. 286) is the statement that calls the rotate method of
the game-math library on each Point3D object inside a for loop near the bottom of the listing. Knowing
what you do about the rotate method, you should have no problem understanding the code in Listing 25
(p. 286) .
End of the discussion
That concludes the discussion of the program named StringArt03 . You will nd a complete listing
of this program in Listing 32 (p. 301) .
Click here 89 to download a zip le containing standard javadoc documentation for the library named GM01
. Extract the contents of the zip le into an empty folder and open the le 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 26 (p. 289)
and the explanations given above) , the documentation does provide a good overview of the organization
and structure of the library. You may nd it helpful in that regard.
The homework assignment for this module was to study the Kjell tutorial through Chapter6 - Scaling and
Unit Vectors .
The homework assignment for the next module is to continue studying the same material.
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 90 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.
I encourage you to copy the code from Listing 26 (p. 289) through Listing 32 (p. 301) . Compile the code
and execute it in conjunction with the game-math library provided in Listing 26 (p. 289) . Experiment with
the code, making changes, and observing the results of your changes. Make certain that you can explain
why your changes behave as they do.
1.17.9 Summary
The most important thing that you learned in this module was how to update the game-math library to
support 3D math and how to produce 3D images similar to that shown in Image 1 (p. 235) . You learned
much more than that however. Some highlights of the things you learned are:
• You learned how to program the equations for projecting a 3D world onto a 2D plane for display on a
computer screen.
• You learned how to cause the direction of the positive y-axis to be up the screen instead of down the
screen.
• You learned how to add vectors in 3D and conrmed that the head-to-tail and parallelogram rules
apply to 3D as well as to 2D.
• You learned about scaling, translation, and rotation of a point in both 2D and 3D.
• You learned about the rotation equations and how to implement them in both 2D and 3D.
• You learned how to rotate a point around an anchor point other than the origin.
• You learned about the right-hand rule.
89 http://cnx.org/content/m45016/latest/GM01docs.zip
90 http://cnx.org/content/m44992/latest/
In the next module in this collection, you will learn how to write your rst interactive 3D game using the
game-math library. You will also learn how to write a Java program that simulates ocking behavior such
as that exhibited by birds and sh and how to incorporate that behavior into a game.
1.17.11 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 26 (p. 289) through Listing
32 (p. 301) below.
Listing 26: Source code for the updated game-math library named GM01.
/*GM01.java
Copyright 2008, R.G.Baldwin
Revised 02/24/08
http://local.wasp.uwa.edu.au/∼pbourke/geometry/
classification/
/*GM01test02.java
Copyright 2008, R.G.Baldwin
Revised 02/18/08
class GM01test02{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class GM01test02
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*GM01test01.java
Copyright 2008, R.G.Baldwin
Revised 02/18/08
class GM01test01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class GM01test01
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*GM01test05.java
Copyright 2008, R.G.Baldwin
Revised 02/24/08
class GM01test05{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class GM01test05
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*GM01test06.java
Copyright 2008, R.G.Baldwin
Revised 02/24/08
class GM01test06{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class GM01test06
//======================================================//
GUI(){//constructor
//Set JFrame size, title, and close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Available forimage
//Create an off-screen free at Connexions
and get a<http://cnx.org/content/col11450/1.29>
graphics
// context on it.
osi = createImage(osiWidth,osiHeight);
Graphics2D g2D = (Graphics2D)(osi.getGraphics());
298 CHAPTER 1. MATH
/*StringArt02.java
Copyright 2008, R.G.Baldwin
Revised 02/22/08
Number Points
Number Loops
Rotation angle (deg)
X anchor point
Y anchor point
/*StringArt03.java
Copyright 2008, R.G.Baldwin
Revised 02/22/08
Number Points
Number Loops
Rotate around Z (deg)
Rotate around X (deg)
Rotate around Y (deg)
X Anchor point
Y Anchor point
Z Anchor point
1.17.13 Exercises
1.17.13.1 Exercise 1
Using Java and the game-math library named GM01 , or using a dierent programming environment of
your choice, write a program that creates and draws a 20-level stepped pyramid as shown in Image 20 (p.
303) .
Each level is a box. The dimensions of the bottom box are:
The height of each box is the same. The decrease in the width and depth dimensions of the boxes is linear
going from the largest box at the bottom to the smallest box at the top.
The sides of the pyramid may be transparent or opaque - your choice.
The bottom box sits on the x-z plane, is centered on the vertical axis, and the sides are parallel with the
x and z axes.
Draw the axes in the approximate location shown in Image 20 (p. 303) in red, green, and blue.
The positive direction for x is to the right. The positive direction for y is up, and the positive direction
for z protrudes from the screen (down and to the left).
Display your name in the drawing in some manner.
1.213
1.17.13.2 Exercise 2
Beginning with the pyramid that you created in Exercise 1 (p. 302) , create a replica of that pyramid
positioned at a point that is twice the width of the bottom box from the origin in the positive x direction.
Draw that pyramid in red as shown in Image 21 (p. 304) .
1.214
1.17.13.3 Exercise 3
Beginning with the two pyramids that you created in Exercise 2 (p. 303) , rotate the red pyramid by -30
degrees around an imaginary vertical line at the center of the pyramid as shown in Image 22 (p. 305) .
1.215
1.17.13.4 Exercise 4
Beginning with the two pyramids that you created in Exercise 2 (p. 303) , rotate each box around an
imaginary vertical line at the center of the pyramid by a negative angle with a progressively greater magnitude
so that the rotation of the bottom box is zero and the rotation of the top box is approximately -85 degrees
as shown in Image 23 (p. 306) . This produces a 3D object similar to a spiral staircase with the length of
each step being less than the length of the step below it.
1.216
1.17.13.5 Exercise 5
Beginning with the two pyramids that you created in Exercise 2 (p. 303) , rotate each box in the red pyramid
around an imaginary line that is parallel to the z-axis and lies in the x-z plane at the center of the bottom
1.217
1.17.13.6 Exercise 6
Beginning with the two pyramids that you created in Exercise 2 (p. 303) , rotate each box in the red pyramid
around the z-axis as shown in Image 25 (p. 308) .
Make the rotation angles for each box progressively larger in such a way that the rotation of the bottom
box is zero and the rotation of the top box is approximately 28 degrees.
1.218
-end-
1.18.2 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.
What you have learned
In the previous module, you learned how to update the game-math library to support 3D math, how to
program the equations for projecting a 3D world onto a 2D plane, how to add vectors in 3D, about scaling,
translation, and rotation of a point in both 2D and 3D, about the rotation equations and how to implement
them in both 2D and 3D, and much more.
What you will learn
In this module, you will learn how to write your rst interactive 3D game using the game-math library
named GM01 . You will also learn how to write a Java program that simulates ocking behavior such as
that exhibited by birds and sh and how to incorporate that behavior into a game. Finally, you will examine
three other programs that illustrate various aspects of both 2D and 3D animation using the game-math
library.
91 This content is available online at <http://cnx.org/content/m45017/1.3/>.
1.18.2.1.1 Images
• Image 1 (p. 312) . A school of red prey sh being attacked by a blue predator.
• Image 2 (p. 314) . Screen shot of the graphic output from GM01test04.
• Image 3 (p. 315) . Screen shot of the graphic output from GM01test03.
• Image 4 (p. 317) . Screen shot of the graphic output from StringArt04.
• Image 5 (p. 319) . Prey sh in a large swirling cluster.
• Image 6 (p. 321) . Formation starting to break up due to closeness of the predator.
• Image 7 (p. 334) . 100 prey sh trying to occupy the same location in 3D space.
• Image 8 (p. 335) . 100 prey sh maintaining a reasonable separation in 3D space.
• Image 9 (p. 348) . Twelve predators swimming in a hexagon formation in GM01test04.
• Image 10 (p. 349) . Six predators swimming in a diamond formation.
• Image 11 (p. 363) . Screen output from Exercise 1.
• Image 12. (p. 365) Screen output from Exercise 4.
• Image 13 (p. 366) . Screen output from Exercise 5.
1.18.2.1.2 Listings
• Listing 1 (p. 323) . Abbreviated constructor for the GUI class in GM01test08.
• Listing 2 (p. 324) . Beginning of the actionPerformed method in GM01test08.
• Listing 3 (p. 325) . Code that services the Attack button.
• Listing 4 (p. 326) . Code that services the Stop button.
• Listing 5 (p. 327) . Beginning of the Animate class and the run method.
• Listing 6 (p. 328) . Create the population of prey sh.
• Listing 7 (p. 328) . Create and position the predator object.
• Listing 8 (p. 329) . A few more housekeeping details.
• Listing 9 (p. 330) . Beginning of the animation loop.
• Listing 10 (p. 331) . Cause all of the prey sh to spiral toward the center.
• Listing 11 (p. 331) . Create a rotated vector.
• Listing 12 (p. 332) . Move the prey sh object based on the sum of the vectors.
• Listing 13 (p. 332) . Save a clone of the relocated prey sh object.
• Listing 14 (p. 333) . Save a normalized direction vector.
• Listing 15 (p. 333) . Code for when the population contains only one prey sh.
• Listing 16 (p. 336) . Separate the prey sh.
• Listing 17 (p. 337) . The remainder of the inner loop.
• Listing 18 (p. 338) . Save the primary prey sh object and do another iteration.
• Listing 19 (p. 338) . Prey sh objects react to the predator.
• Listing 20 (p. 339) . Prey sh object takes evasive action.
• Listing 21 (p. 339) . Test the separation again.
• Listing 22 (p. 340) . Restore the prey sh to the population.
• Listing 23 (p. 341) . Keep the prey sh in the playing eld.
• Listing 24 (p. 342) . Erase the o-screen image and draw the large circle.
• Listing 25 (p. 343) . Draw the prey sh on the o-screen image.
• Listing 26 (p. 344) . Cause the predator to slowly circle the cluster of prey sh.
• Listing 27 (p. 345) . Execute the attack.
• Listing 28 (p. 346) . Draw the predator on the o-screen image.
• Listing 29 (p. 346) . Copy o-screen image, insert time delay, etc.
• Listing 30 (p. 353) . Source code for the game-math library named GM01.
• Listing 31 (p. 355) . Source code for the game program named GM01test08.
• Listing 32 (p. 357) . Source code for the program named GM01test04.
• Listing 33 (p. 359) . Source code for the program named GM01test03.
• Listing 34 (p. 361) . Source code for the program named StringArt04.
1.18.3 Preview
It's time to kick back and have a little fun with what you have learned. In this module, I will present four
programs, (one of which is an interactive 3D game) , that use the current capabilities of the game-math
library to produce some fairly serious animation. The programs are named:
• GM01test08
• GM01test04
• GM01test03
• StringArt04
I will explain the game program in detail and will provide a brief description of the other three programs.
GM01test08
The rst three programs are based on an articial life 92 concept frequently referred to as boids 93 ,
which is "a computer model of coordinated animal motion such as bird ocks and sh schools."
note: Flocking sh: I got the idea for this game while watching a segment of a documentary
series named Blue Earth on one of the cable channels. I even surprised myself as to how well I was
able to simulate some of the scenes in that TV program using programming concepts similar to
those used by Reynolds in boids.
1.219
The predator in Image 1 (p. 312) has penetrated the school of sh by swimming from left to right, eating
sh all along the way, and has emerged from the right side of the school. The prey sh, which were originally
in a small tight cluster, have reacted to the presence of the predator by scattering in an attempt to avoid
being eaten.
Fully three-dimensional
This game program is fully three-dimensional. Any or all of the sh are capable of swimming in any
direction at any time in the 3D world. This is evidenced by the prey sh near the center that appear to have
very short or non-existent tails. The sh that appear to have no tails actually have tails that are the same
length as the tails on all of the other sh. These sh appear to have no tails because they are swimming
either directly toward or directly away from the viewer. I will have more to say about this later.
GM01test04 and GM01test03
These two programs provide essentially the same behavior (as one another) , except that one is a 2D
program and the other is a 3D program. They are not game programs. Rather, they are demonstration
programs that show another aspect of ocking behavior. In these two programs, a large number of predators
pursue a single prey object.
A screen shot of the animated output from the 2D version is shown in Image 2 (p. 314) and a screen
shot of the output from the 3D version is shown in Image 3 (p. 315) .
1.220
1.221
I included these two programs in this module primarily to provide a good comparison between 2D and
3D, both from a programming viewpoint and a behavior viewpoint.
Eight predator objects and one prey object
In both versions shown in Image 2 (p. 314) and Image 3 (p. 315) , you see eight predator objects (colored
black) pursuing a red prey object. The actual length of every predator object is the same as the length
of every other predator object and the length of the prey object is the same as the length of the predator
objects.
Some signicant dierences
At rst glance, the two versions may look the same. However, they are signicantly dierent. In Image 2
(p. 314) , the prey and the predators are constrained to move in a single plane. Hence, the apparent length
of each predator is the same as the length of every other predator and is also the same as the length of the
prey regardless of the direction in which the object is moving.
However, in Image 3 (p. 315) , the predators and the prey are free to move in any direction in a 3D
world. As a result, at any point in time, the objects may be moving parallel to or at an angle to the x-y
plane. When the 3D world is projected onto the viewing plane, those objects that are moving at an angle
to the viewing plane will be foreshortened. In the extreme case, (as shown earlier in Image 1 (p. 312) ) ,
when an object is moving directly toward or directly away from the viewer, its apparent length will go to
zero. (At least one predator is almost in that state in Image 3 (p. 315) .)
In Image 3 (p. 315) the apparent lengths of the predator and prey objects are all dierent indicating
that they are all moving in slightly dierent directions in the 3D world.
The ocking algorithms in these two programs are much simpler than the algorithm used in Image 1 (p.
312) . I encourage you to experiment with the ocking algorithms for these two programs to see what you
can produce that is new and dierent from my version of the two programs.
StringArt04
The fourth program named StringArt04 is completely dierent from the other three programs. In a
previous module, I presented and explained a program that rotates a disk around an arbitrary anchor point
in 3D space with the ability to rotate by dierent angles around each of the three axes. It can be very
dicult to visualize exactly what is happening with such complex rotations. This program animates the
rotation process and runs it in slow motion so that you can see exactly what is happening as the disk moves
and rotates from its initial position and orientation to its nal position and orientation.
For example. set the values as follows, click the Animate button, and watch the rotations take place.
• Number Points = 24
• Number Loops = 10
• Rotate around Z (deg) = 360
• Rotate around X (deg) = 360
• Rotate around Y (deg) = 360
• X anchor point = 50
• Y anchor point = 0
• Z anchor point = 0
This should give you a good idea as to the process. Then change the parameters to other values, click the
button, and observe the results.
It is also useful to set only one of the rotation angles to a non-zero value and watch the rotation around
a line parallel to that axis take place.
A stop-action screen shot
Image 4 (p. 317) shows a screen shot of the disk in motion somewhere between the beginning and the
end of its very complex trajectory for one particular set of rotation and anchor point parameters.
1.222
Exercises
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this and previous modules.
1.223
Predator behavior
The predator, (shown in blue in Image 5 (p. 319) ) , swims around the cluster, darting into and through
the cluster when the user clicks the Attack button. During an attack, the predator attempts to eat as
many prey sh as possible. When the predator attacks, the prey sh tend to scatter (as shown in Image 1
(p. 312) ) , breaking up their tight formation and making it more dicult for the predator to catch them.
If the predator is allowed to swim around them again for a short period following an attack, they will form
back into a cluster.
Proper timing is important
The attacks should be timed so that the prey sh are in a reasonably tight cluster at the beginning of
each attack so that multiple prey sh will be eaten during the attack. However, allowing too much time
between attacks is detrimental because it increases the total elapsed time. Thus, the player must make
a tradeo between elapsed time between attacks and the tightness of the cluster at the beginning of each
attack. Another disadvantage of waiting too long between attacks will be explained later.
The graphical user interface
In addition to some other controls, the GUI provides an Attack button and an elapsed-time/kill-count
indicator, shown in the bottom right in Image 5 (p. 319) . At any point in time, this indicator displays the
elapsed time in milliseconds when the most recent prey sh was eaten along with the total number of prey
sh that have been eaten. The two values are separated by a "/" character.
When all of the prey sh have been eaten by the predator, the elapsed time indicator shows the time in
milliseconds required for the predator to catch and eat all of the prey sh. It also shows the number of prey
sh that were eaten, which should match the value that the player entered into the upper-right text eld
before starting the game. (This eld contains 500 in Image 1 (p. 312) and 200 in Image 5 (p. 319) ) .
Not initially in attack mode
When the player clicks the Start button and the game begins, the predator is not in attack mode.
Rather, the predator swims around the school of prey sh encouraging them to bunch up into a smaller and
tighter cluster as shown in Image 5 (p. 319) . The purpose of this behavior is to increase the number of sh
that will be eaten when an attack is made.
The attack will be more or less successful
This circling behavior on the part of the predator continues until the player clicks the Attack button,
at which time the predator enters the attack mode and makes an attack on the cluster as shown in Image 1
(p. 312) . If the player clicks the Attack button too early, or doesn't wait long enough between attacks,
the prey sh will be in a loose cluster and the predator will eat very few sh during the attack.
The predator always has an impact
Even when the predator is not in attack mode, its presence has a signicant eect on the behavior of the
school of prey sh. As the predator swims around the prey sh, they tend to bunch up into a smaller and
tighter cluster, but when the predator swims too close, the prey sh tend to panic and scatter, breaking up
the tight cluster as shown in Image 6 (p. 321) .
Therefore, if the player waits too long to click the Attack button or waits too long between attacks, the
predator will have spiraled in so close to the prey sh that they will break formation and begin to scatter,
making it dicult for the predator to eat a large number of sh during the next attack. This is the other
disadvantage of waiting too long to attack that I mentioned earlier (p. 320) .
Formation starting to break up due to closeness of the predator
Image 6 (p. 321) shows the formation starting to break up because the predator has strayed too close
to the cluster of prey sh. (The sh in the upper right of the formation have pulled out of the cluster and
have started to ee the predator.)
1.224
note: Cleaning up the leftovers: The nal three or four prey sh are often the most dicult
to catch because they have more room to run without colliding with another sh.
Portions of this program are very similar to programs that I have explained in earlier modules in this
series. I won't repeat those explanations here. Rather, I will concentrate mostly on the code that is new
and dierent in this module.
Abbreviated constructor for the GUI class
Listing 1 (p. 323) shows an abbreviated constructor for the GUI class. (Much of the code in the
constructor has been explained before, and was deleted from Listing 1 for brevity.)
GUI(){//constructor
}//end constructor
1.225
If you examine Listing 31 (p. 355) , you will see that the GUI class implements the ActionListener
interface. Therefore, an object of the GUI class can be registered as an action listener on a button. Listing
1 (p. 323) registers the object of the GUI class as a listener on all three of the buttons shown in Image 6
(p. 321) .
Beginning of the actionPerformed method
The actionPerformed method that begins in Listing 2 (p. 324) is called whenever the player clicks
any of the three buttons shown in Image 6 (p. 321) .
if(drawPointsBox.getState()){
drawPoints = true;
}else{
drawPoints = false;
}//end else
if(drawVectorsBox.getState()){
drawVectors = true;
}else{
drawVectors = false;
}//end else
1.226
button. The second statement (at the end) instantiates a new object of the Thread class named
Animate and causes the run method of the animation thread to be executed. I will explain the
animation thread later.
Code that services the Attack button
The code in Listing 3 (p. 325) is executed when the player clicks the Attack button after it is enabled
by the code in Listing 2 (p. 324) .
attack = true;
predatorVec =
predator.getDisplacementVector(preyCenter).
scale(1.0);
1.227
Listing 3 (p. 325) begins by setting the value of the variable named attack to true. As you will see
later, this causes the predator to attack the prey sh in the animation loop.
Control the speed and direction of the predator attack
Then Listing 3 (p. 325) calls the getDisplacementVector method and the scale method of the
game-math library to set the value of the variable named predatorVec to a direction that will be used to
point the predator toward the center of the prey-sh cluster. In Listing 3 (p. 325) , the scale factor is 1.0,
so the application of the scale factor does nothing. However, you can modify this value to control the speed
of the predator during the upcoming attack. If you increase the scale factor, the predator will move faster.
If you decrease the scale factor, the predator will move more slowly.
Temporarily disable the Attack button
Finally, Listing 3 (p. 325) temporarily disables the Attack button so that it will have no eect if the
player clicks it again during the attack. You could also remove this statement, slow down the attack, and
experiment with multiple clicks on the Attack button during the course of an attack to see what happens.
Code that services the Stop button
The code in Listing 4 (p. 326) is executed when the player clicks the Stop button.
}//end actionPerformed
1.228
No explanation beyond the embedded comment should be required for this code.
Beginning of the Animate class and the run method
When the Start button is clicked, the code in Listing 2 (p. 324) instantiates a new object of the
Thread class named Animate and causes the run method belonging to that object to be executed.
Listing 5 (p. 327) shows the beginning of the Animate class and its run method.
1.229
1.230
In addition, Listing 6 (p. 328) populates a container named displayVectors that was also created in
Listing 5 (p. 327) to store a direction vector belonging to each prey sh. This container is populated with
dummy vectors in Listing 6 (p. 328) , simply to set the size of the container to be the same as the size of
the container containing references to the prey sh objects. (There is probably a more ecient way to set
the size of that container.)
Note that each prey sh object is actually represented by an object of the game-math library class named
GM01.Point3D .
Create and position the predator object
Listing 7 (p. 328) creates an object of the GM01.Point3D class that will represent the predator in
the game.
1.231
The initial position given to the predator in Listing 7 (p. 328) causes it to appear in the game near the
top center of the screen when the user clicks the Start button. You could also make the initial position of
the predator random if you think that would improve the game.
A few more housekeeping details
Listing 8 (p. 329) takes care of a few more housekeeping details before the animation actually begins.
1.232
while(animate){
//Compute and save the average position of all the
// prey objects at the beginning of the loop. Save
// the average position in the Point3D object
// referred to by preyCenter.
xSum = 0;
ySum = 0;
zSum = 0;
1.233
The value of animate is set to true by clicking the Start button and is set to false by clicking
the Stop button. Setting the value to false causes the run method to terminate, thereby stopping the
animation.
Attack toward the geometric center
When the predator attacks, it will move to and through the geometric center of the cluster of prey sh,
eating prey sh all along the way. The geometric center of the cluster of prey sh is computed and saved by
the code in Listing 9 (p. 330) as the average location of all the prey sh in the population.
Note that a vector that points to the geometric center may or may not be a good indicator of the best
direction for eating large numbers of prey sh during an attack. In Image 1 (p. 312) , for example, a predator
attacking from the 11:00 o'clock position and heading toward the center would encounter quite a few prey
sh. However, a predator attacking from the 8:00 o'clock position and heading toward the center would
encounter far fewer prey sh.
You will also learn that although the predator will always attack in a direction pointing toward this
geometric center, the positions of the prey sh can change after the center is computed and before the attack
begins, causing the position of the actual geometric center to change, before the predator has an opportunity
to attack. That can decrease the probability of a successful attack by the predator.
These issues form part of the strategy of the game that must be mastered by the player in order to earn
a good score.
Cause all of the prey sh to spiral toward the center
Listing 10 (p. 331) shows the beginning of a fairly complicated algorithm that causes all of the prey sh
to have a tendency to spiral toward the center of the cluster of prey sh.
Listing 10: Cause all of the prey sh to spiral toward the center.
1.234
The code in the body of the for loop that begins in Listing 10 (p. 331) is executed once during each
animation cycle for each of the prey sh in the population of prey sh.
To begin with, the if statement prevents the tendency to spiral toward the geometric center from being
applied when there is only one prey sh remaining in the population. I will leave it as an exercise for the
student to think about this and to decide whether or not this is a good decision.
The code in Listing 10 (p. 331) gets a reference to the next prey sh object in the population and then
gets and saves a reference to a displacement vector pointing from the prey sh to the geometric center.
Create a rotated vector.
Listing 11 (p. 331) creates, scales, and saves a new GM01.Vector3D object having the same component
values as the displacement vector from Listing 11 (p. 331) , but assigning those values to dierent axes.
1.235
Once again, I will leave it as an exercise for the student to think about the length and direction of such
a vector in relation to the original displacement vector. It might help to begin by drawing some vectors in
2D that swap components and then extending the same thinking to 3D. One thing is for certain, unless all
of the components have the same value, the new vector created in Listing 11 (p. 331) has a dierent length
and direction than the displacement vector created in Listing 10 (p. 331) , and that would be true even if
the vector from Listing 11 (p. 331) had not been scaled.
Move the prey sh object based on the sum of the vectors
Listing 12 (p. 332) begins by adding the two vectors that were created in Listing 10 (p. 331) and Listing
11 (p. 331) , scaling the vector from Listing 10 (p. 331) before performing the addition. Note that the scale
factors applied to the rotated vector in Listing 11 is dierent from the scale factor applied to the original
displacement vector in Listing 12 (p. 332) . The ratio of these two scale factors inuences the tendency of
the prey sh object to move toward the center relative to its tendency to move around the center.
Listing 12: Move the prey sh object based on the sum of the vectors.
tempVectorA =
tempVectorA.scale(0.9).add(tempVectorB);
tempPrey = tempPrey.addVectorToPoint(
tempVectorA.scale(0.1));
1.236
Then Listing 12 (p. 332) calls the GM01.Point3D.addVectorToPoint method to relocate the prey
sh object to a new position based on the scaled sum of the two vectors. The bottom line is that this will
cause the prey sh object to spiral toward the geometric center that was computed in Listing 9 (p. 330) as
the animation progresses.
Another scale factor is applied to the sum vector before using it to relocate the prey sh object. This
scale factor controls the overall speed of the prey sh. Increasing the scale factor causes the prey sh to
spiral faster. (Increasing the scale factor also causes some interesting patterns to appear and if you increase
it too much, the prey sh will all leave the playing eld.)
Save a clone of the relocated prey sh object
Listing 13 (p. 332) creates a clone of the relocated prey sh object and uses it to replace the original
prey sh object in the container.
preyObjects.set(cnt,tempPrey.clone());
1.237
Creating and saving a reference to a clone instead of saving a reference to the relocated prey sh object
may be overkill. However, I simply wanted to guard against the possibility of ending up with a corrupted
object later due to the repeated use of the reference variable. I will leave it up to the student to think about
this and to decide if this was a good or a bad decision.
Save a normalized direction vector
Listing 14 (p. 333) calls the GM01.Vector3D.normalize method to create a vector having a length
of 15 units and the same direction as the vector that was used to relocate the prey sh object.
displayVectors.set(
cnt,tempVectorA.normalize().scale(15.0));
1.238
This vector is saved and used for drawing later. Drawing this vector in conjunction with the point that
represents the prey sh object produces the tails shown on the prey sh objects in Image 1 (p. 312) .
Code for when the population contains only one prey sh
Listing 15 (p. 333) shows the else clause that matches up with the if statement in Listing 10 (p.
331) . This code is executed when the population has been reduced to only one prey sh object.
Listing 15: Code for when the population contains only one prey sh.
}else{
displayVectors.set(
cnt,new GM01.Vector3D(
new GM01.ColMatrix3D(10,10,0)));
}//end else
1.239
Listing 15 (p. 333) saves a dummy direction vector for drawing later. This is necessary to prevent a null
pointer exception when the user species only one prey sh object and then clicks the Start button.
Not the end of the story
Listing 15 (p. 333) also signals the end of the for loop that causes the prey sh to spiral toward the
center. The code in this for loop is sometimes referred to as a cohesion algorithm in ocking terminology.
It causes the prey sh to stay together as a group.
This is not the end of the story, however. If the code in this cohesion algorithm were the only code
controlling the behavior of the prey sh in this animation, they would simply continue spiraling toward the
center, eventually producing a cluster that looks something like that shown in Image 7 (p. 334) where 100
prey sh are trying to occupy the same location in 3D space.
Image 7: 100 prey sh trying to occupy the same location in 3D space.
1.240
For example, Image 8 (p. 335) shows the result of temporarily making each prey sh immune to the
presence of the predator, telling each prey sh to spiral toward the center, and also telling each prey sh to
maintain a separation of ten units (pixels) between itself and all of the other prey sh.
1.241
A 3D world
Remember, Image 8 (p. 335) is a 3D world projected onto on a 2D screen display. Even if every prey
sh is separated from every other prey sh by at least ten pixels (which is probably not the case as I will
explain later) , the projection of the 3D world onto the 2D display can make it appear that two or more
prey sh occupy the same location.
Separate the prey sh
Listing 16 (p. 336) shows the beginning of a pair of nested for loops that attempt to keep the prey sh
from colliding with one another by moving each prey sh object away from its close neighbors if necessary.
In ocking terminology, this is often referred to as a separation algorithm.
1.242
This algorithm gets a reference to each prey sh object (primary object) and compares its position with
the positions of all the other prey sh objects (secondary objects) . If the primary object is too close to a
secondary object, the primary object is moved away from the secondary object.
Not a perfect algorithm
This is not a perfect algorithm however. A primary object can be moved away from all of its neighbors
early in the execution of the algorithm, but a neighbor could be moved closer to the primary object later in
the execution of the algorithm. While not perfect, the algorithm does a pretty respectable job of keeping
the prey sh separated as evidenced by comparing the positions of the prey sh in Image 7 (p. 334) with
the positions of the prey sh in Image 8 (p. 335) . This separation algorithm was disabled in Image 7 (p.
334) and was enabled in Image 8 (p. 335) .
Gets two objects that will be compared
Listing 16 (p. 336) gets a reference to a primary prey sh object in the outer loop that iterates on the
counter named row and gets a reference to one of the secondary prey sh objects to which it will be
compared in the inner loop that iterates on the counter named col .
The remainder of the inner loop
Listing 17 (p. 337) shows the remainder of the inner loop.
1.243
It wouldn't make any sense to compare the position of a prey sh with itself, so the if statement in
Listing 17 (p. 337) prevents that from happening.
Code is relatively straightforward
Since you already know how to use most of the methods in the game-math library, you should have no
diculty understanding the code in Listing 17 (p. 337) . This code:
• gets the displacement vector that denes the separation between the primary object and the secondary
object,
• compares the length of that vector with 10 units, and
• moves the primary prey sh object in the opposite direction by 20-percent of the length of the separation
vector if the separation is less than 10 units.
As mentioned earlier, however, moving the primary sh object away from one prey sh could cause it to be
moved closer to a dierent prey sh object, so the separation algorithm is far from perfect.
Listing 17 (p. 337) signals the end of the inner loop that began in Listing 16 (p. 336) .
Save the primary prey sh object and do another iteration
The primary prey sh object may or may not have been moved. Regardless, a clone of that object is
created and saved in the container that contains the prey-sh population in Listing 18 (p. 338) .
Listing 18: Save the primary prey sh object and do another iteration.
preyObjects.set(row,refPrey.clone());
}//end loop on row
1.244
After the object is saved in Listing 18 (p. 338) , control is transferred back to the top of the outer for
loop in Listing 16 (p. 336) and the next prey sh object in the population is compared with all of the other
prey-sh objects in the population, making corrections to the position of the prey sh as necessary.
Prey sh objects react to the predator
As I mentioned earlier, each prey sh object has a reasonably good defense mechanism to avoid being
eaten by the predator. However, in the nal analysis, whether or not a prey sh will escape when it encounters
the predator face to face is a random process. To some extent, success or failure to escape depends on how
quickly the prey sh senses the presence of the predator.
Listing 19 (p. 338) is the beginning of a for loop in which the proximity of each prey sh to the predator
is tested and evasive action on the part of the prey sh is taken if the distance between the two is less than
50 units.
1.245
The code in Listing 19 (p. 338) gets the next prey sh in the population and gets a displacement vector
describing the separation of the prey sh from the predator.
Prey sh object takes evasive action
If the prey sh is at least 50 units away from the predator, the prey sh simply goes on swimming without
concern for the predator. However, if the prey sh is less than 50 units away from the predator, the prey
sh takes evasive action in an attempt to escape the predator. The evasive action is accomplished in Listing
20 (p. 339) , and this is where some of the random behavior comes into play.
1.246
tempVectorA =
tempPrey.getDisplacementVector(predator);
1.247
If the new separation is at least 25 units, the escape attempt is deemed successful and the prey sh will
continue to live. (You can decrease or increase the threshold distance used in the test in Listing 21 (p. 339)
to cause the prey sh object to be more or less successful in the escape attempt. If you make the threshold
distance small enough, the prey sh will almost always escape.)
When the escape attempt is not successful...
When the escape attempt is not successful, the remaining code in Listing 21 (p. 339) is executed. The
prey sh is deemed to have been eaten by the predator. Therefore, the prey sh and its direction vector are
removed from the containers that contain them. This causes the prey sh to be removed from the population.
In addition, the program sounds a beep to notify the user of the successful attack by the predator and
the kill count that is displayed in the bottom right of Image 1 (p. 312) is incremented by one.
Display elapsed time and number of sh eaten
Finally, the code in Listing 21 (p. 339) displays the elapsed time in milliseconds since the Start button
was clicked along with the number of sh that have been eaten. Note that the value that is displayed is the
elapsed time when the most recent prey sh was eaten by the predator and is not the total elapsed time
since the Start button was clicked. (The elapsed time value won't change again until another prey sh
is eaten.)
When all of the prey sh have been eaten, the nal time that is displayed is the time that was required
for the predator to eat all of the sh in the population and the nal kill count that is displayed is the same of
the original number of prey sh in the population. (Also note that the player must click the Stop button
before starting a new game. Fixing this inconvenience will be a good exercise for the student.)
When the escape attempt is successful...
When the escape attempt is successful, a clone of the prey sh in its new location is stored in the prey-
Objects container and a normalized version of the sh's direction vector is stored in the displayVectors
container as shown in Listing 22 (p. 340) .
}else{
//The escape attempt was successful. Restore
// a clone of the prey object in its new
// location along with its direction vector
// to the population.
preyObjects.set(cnt,tempPrey.clone());
//Save a normalized version of the direction
// vector for drawing later. It will
// overwrite the previously saved vector and
// if you watch closely it will show the
// prey object running away from the
// predator.
displayVectors.set(
cnt,tempVectorA.normalize().scale(15.0));
}//end else
}//end if distance < 50
}//end for loop on population
1.248
Listing 22 (p. 340) also signals the end of the for loop that began in Listing 19 (p. 338) .
Keep the prey sh in the playing eld
I have one more section of code to explain that deals with the behavior of the prey sh during each
iteration of the animation loop. The code in Listing 23 (p. 341) causes prey sh that stray outside the
playing eld to return to the playing eld.
if(tempPrey.getDisplacementVector(origin).
getLength() > 0.5*osiHeight){
tempVectorA =
tempPrey.getDisplacementVector(origin);
tempPrey = tempPrey.addVectorToPoint(
tempVectorA.scale(0.1));
preyObjects.set(cnt,tempPrey.clone());
}//end if prey object is out of bounds
}//end for loop to process each prey object
1.249
Listing 24: Erase the o-screen image and draw the large circle.
1.250
Although somewhat tedious, the code in Listing 24 (p. 342) is straightforward and shouldn't require an
explanation beyond the embedded comments.
Draw the prey sh on the o-screen image
Depending on the states of the two check boxes in Image 1 (p. 312) , Listing 25 (p. 343) draws the
GM01.Point3D objects that represent the prey sh or GM01.Vector3D objects that represent the
direction vectors for the prey sh, or both, on the o-screen image. (Note that only the vectors were drawn
on the o-screen image in Image 1 (p. 312) .)
g2D.setColor(Color.RED);
for(int cnt = 0;cnt < preyObjects.size();cnt++){
tempPrey = preyObjects.get(cnt);
if(drawPoints){
tempPrey.draw(g2D);//draw circle around point
}//end if
if(drawVectors){
//Draw the vector with its tail at the point.
displayVectors.get(cnt).draw(g2D,tempPrey);
}//end if
}//end for loop
1.251
There is nothing new in Listing 25 (p. 343) , so I won't bore you with a detailed explanation of the code.
It's time to deal with the predator
So far, we have been dealing exclusively with code that controls the behavior of the prey sh. The time
has come to deal with the code that controls the behavior of the predator.
Cause the predator to slowly circle the cluster of prey sh
When the player clicks the Attack button, a boolean variable named attack is set to true ,
causing the predator to enter attack mode during the next iteration of the animation loop. However, when
the value of this variable is false , the predator is not in attack mode and its behavior is to swim slowly
around the cluster of prey sh encouraging them to bunch up into a smaller and tighter cluster.
The code that accomplishes this circling behavior is shown in Listing 26 (p. 344) .
Listing 26: Cause the predator to slowly circle the cluster of prey sh.
predator = predator.addVectorToPoint(
predatorVec.scale(1.0));
1.252
The code in Listing 26 (p. 344) is very similar to code that I explained earlier in conjunction with the
behavior of the prey sh. Therefore, no explanation beyond the embedded comments should be required.
Execute the attack
When the user clicks the Attack button, the value of the variable named attack is set to true ,
causing the code in Listing 27 (p. 345) to be executed during subsequent iterations of the animation loop.
}else{//attack is true
predator = predator.addVectorToPoint(
predatorVec.scale(0.25));
1.253
g2D.setColor(Color.BLUE);
//Enable the following statement to draw a circle
// around the point that represents the predator.
//predator.draw(g2D);
1.254
1.255
Listing 29 (p. 346) also signals the end of the animation loop, the end of the run method, and the end
of the inner class named Animate .
That is all of the code that I will explain for this program. You can view the remainder of the code in
Listing 31 (p. 355) near the end of the module.
Not a graphics program
Even though this program produces quite a lot of 3D graphics, and those graphics are important in
the playing of the game, this is not a graphics program. Rather, it is a 3D data-processing program that
produces graphics as a side eect.
That is not to say that the graphics are unimportant. To the contrary, the graphics provide visual
feedback to the player, which allows the player to implement a strategy for success. Without graphics, the
game would be very boring. However, the programming eort to produce the graphics represents an almost
trivial part of the total programming eort for this game.
An almost trivial part of the programming eort
Exclusive of the code required to draw the large circle shown in Image 1 (p. 312) , all of the graphics
shown in Image 1 (p. 312) , Image 5 (p. 319) , Image 6 (p. 321) , Image 7 (p. 334) , and Image 8 (p. 335)
are produced by only two calls to game-math library methods named draw . In other words, all of the
required graphics are produced by only two statements in the program code. (One additional statement is
required if you want to display the small circles that represent the locations of the prey sh.)
If those two statements are removed, the program will still compile and run, and the game can still be
played. However, without visual feedback, the game isn't much fun. The lack of visual feedback eliminates
the strategy aspect of the game, causing it to be solely a game of chance. Be that as it may, with or without
visual feedback, the player can still click the Start button and then repetitively click the Attack button
until the display in the bottom-right of Image 1 (p. 312) shows that all of the prey sh have been eaten.
Why am I telling you this?
I'm telling you this to emphasize that the essential skills required to program this game (and probably
most games for that matter) consist of skills in mathematics, programming logic, and several other technical
areas. The ability to produce on-screen graphics is necessary for an enjoyable game, but, (given a good
game-math library that supports graphics) , producing on-screen graphics is almost a trivial part of the pro-
gramming eort. In this collection of modules, you need to be mainly concentrating on learning mathematics
and programming logic and treating the production of on-screen graphics almost as an afterthought.
1.256
1.257
Once you understand the code in the program named GM01test08 that I explained earlier in this
module, you should have no diculty understanding the code in this program. Therefore, I won't explain
the code in this program. I included this program in this module mainly to illustrate the dierences between
2D and 3D from both a visual and programming viewpoint.
A complete listing of this program is provided in Listing 32 (p. 357) near the end of the module.
Visual output
When viewing the output, remember that the program executes the rotations around the axes sequentially
in the following order:
• z-axis
• x-axis
• y-axis
The homework assignment for this module was to study the Kjell tutorial through Chapter6 - Scaling and
Unit Vectors .
The homework assignment for the next module is to study the Kjell tutorial through Chapter 10, Angle
between 3D Vectors .
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 96 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.
I encourage you to copy the code from Listing 30 (p. 353) through Listing 34 (p. 361) . Compile the code
and execute it in conjunction with the game-math library named GM01 provided in Listing 30 (p. 353)
. Experiment with the code, making changes, and observing the results of your changes. Make certain that
you can explain why your changes behave as they do.
1.18.7 Summary
In this module, you learned how to write your rst interactive 3D game using the game-math library named
GM01 . You also learned how to write a Java program that simulates ocking behavior such as that
exhibited by birds and sh and you learned how to incorporate that behavior into the game. Finally,
you examined three other programs that illustrate various aspects of both 2D and 3D animation using the
game-math library.
In the next module, you will learn the fundamentals of the vector dot product in both 2D and 3D. You
will learn how to update the game-math library to support various aspects of the vector dot product, and
you will learn how to write 2D and 3D programs that use the vector dot product methods in the game-math
library.
1.18.9 Miscellaneous
• Revised: 12/31/12
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 30 (p. 353) through Listing
34 (p. 361) below.
Listing 30: Source code for the game-math library named GM01.
/*GM01.java
Copyright 2008, R.G.Baldwin
Revised 02/24/08
http://local.wasp.uwa.edu.au/∼pbourke/geometry/
classification/
Listing 31: Source code for the game program named GM01test08.
/*GM01test08.java
Copyright 2008, R.G.Baldwin
Revised 02/28/08.
When all of the prey fish have been caught and eaten by
the predator, the elapsed time indicator shows the time
in milliseconds required to catch and eat all of the prey
fish. It also shows the number of prey fish that were
Availableshould
caught and eaten, which for free match
at Connexions
one of <http://cnx.org/content/col11450/1.29>
the player
input values.
/*GM01test04.java
Copyright 2008, R.G.Baldwin
Revised 02/25/08.
Available
Tested using JDK 1.6 underforWinXP.
free at Connexions <http://cnx.org/content/col11450/1.29>
*********************************************************/
import java.awt.*;
import javax.swing.*;
358 CHAPTER 1. MATH
/*GM01test03.java
Copyright 2008, R.G.Baldwin
Revised 02/25/08.
/*StringArt04.java
Copyright 2008, R.G.Baldwin
Revised 03/03/08
class StringArt04{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class StringArt04
//======================================================//
1.18.11 Exercises
1.18.11.1 Exercise 1
Using Java and the game-math library named GM01 , or using a dierent programming environment of
your choice, write a program that creates the wireframe drawing of half of a sphere protruding upward from
the x-z plane as shown in Image 11 (p. 363) . The north and south poles of the sphere lie on the y-axis.
The x-z plane intersects the sphere at the equator and only the northern hemisphere is visible.
Cause your name to appear in the screen output in some manner.
1.263
1.18.11.2 Exercise 2
Using Java and the game-math library named GM01 , or using a dierent programming environment of
your choice, write a program that demonstrates your ability to animate two or more objects and have them
moving around in a 3D world.
Cause your name to appear in the screen output in some manner.
1.18.11.3 Exercise 3
Beginning with a 3D world similar to the one that you created in Exercise 2 (p. 363) , demonstrate your
ability to cause your program to recognize when two of your animated objects collide and to do something
that can be noticed by a human observer when the collision occurs.
Cause your name to appear in the screen output in some manner.
1.18.11.4 Exercise 4
Beginning with a program similar to the one that you wrote in Exercise 1 (p. 362) , create a wireframe
drawing of a complete sphere as shown in Image 12 (p. 365) . The north and south poles of the sphere lie on
the y-axis. As before, the x-z plane intersects the sphere at the equator, but in this case, the entire sphere
is visible.
1.264
1.18.11.5 Exercise 5
Beginning with a program similar to the one that you wrote in Exercise 1 (p. 362) , create a wireframe
drawing of one-eighth of a sphere as shown in Image 13 (p. 366) . The north and south poles of the sphere
lie on the y-axis. As before, the x-z plane intersects the sphere at the equator. In this case, only that portion
of the sphere described by positive coordinate values is visible.
1.265
-end-
1.19.2 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.
What you have learned
In the previous module, you learned how to write your rst interactive 3D game using the game-math
library. You also learned how to write a Java program that simulates ocking behavior such as that exhibited
by birds and sh and how to incorporate that behavior into a game. Finally, you examined three other
programs that illustrate various aspects of both 2D and 3D animation using the game-math library.
What you will learn
This module is the rst part of a two-part mini-series on the vector dot product . By the time you
nish both parts, you will have learned
1.266
1.267
1.19.2.1.1 Images
• Image 1 (p. 368) . A 3D image before back-face culling.
• Image 2 (p. 369) . The 3D image after back-face culling.
• Image 3 (p. 371) . Two vectors with their tails at the origin, program DotProd2D02.
• Image 4 (p. 373) . Dot product of two vectors with the same orientation in 2D.
• Image 5 (p. 374) . Dot product of two vectors with the same orientation in 3D.
• Image 6 (p. 375) . Dot product of a 3D vector with an identical vector.
• Image 7 (p. 376) . Dot product of vectors with opposite orientations.
• Image 8 (p. 378) . The dot product of perpendicular vectors in 2D.
• Image 9 (p. 379) . A general formulation of 2D vector perpendicularity.
• Image 10 (p. 380) . Another interesting 2D case of perpendicular vectors.
• Image 11 (p. 382) . A general formulation of 3D vector perpendicularity.
• Image 12 (p. 383) . A pair of perpendicular 3D vectors.
• Image 13 (p. 384) . Another pair of perpendicular 3D vectors.
• Image 14 (p. 388) . GUI for the program named DotProd2D01.
• Image 15 (p. 393) . A screen shot of the output from the program named DotProd3D01.
• Image 16 (p. 396) . Six (magenta) vectors that are perpendicular to a given (black) vector.
• Image 17 (p. 408) . Output from Exercise 1.
• Image 18 (p. 410) . Output from Exercise 2.
• Image 19 (p. 412) . Output from Exercise 3.
1.19.2.1.2 Listings
• Listing 1 (p. 386) . Source code for the method named GM02.ColMatrix3D.dot.
• Listing 2 (p. 386) . Source code for the method named GM02.Vector3D.dot.
• Listing 3 (p. 387) . Source code for the method named GM02.Vector3D.angle.
• Listing 4 (p. 389) . The actionPerformed method in the program named DotProd2D01.
• Listing 5 (p. 390) . Format the dot product value for display in the GUI.
• Listing 6 (p. 391) . Beginning of the actionPerformed method in the program named DotProd2D02.
• Listing 7 (p. 392) . Compute the dot product and the angle between the two vectors.
• Listing 8 (p. 398) . Source code for the game-math library named GM02.
• Listing 9 (p. 400) . Source code for the program named DotProd2D01.
• Listing 10 (p. 402) . Source code for the program named DotProd2D02.
• Listing 11 (p. 404) . Source code for the program named DotProd3D01.
• Listing 12 (p. 406) . Source code for the program named DotProd3D02.
1.19.3 Preview
The homework assignment for this module was to study the Kjell tutorial through Chapter 10, Angle
between 3D Vectors .
I won't repeat everything that Dr. Kjell has to say. However, there are a few points that I will summarize
in this section.
Basic denition of the vector dot product
The vector dot product is a special way to multiply two vectors to produce a real result. A description
of the vector dot product follows.
note: The vector dot product: the vector dot product of two vectors is the product of the
lengths of the vectors multiplied by the cosine of the angle between them
By the angle between them , I mean the angle that would be formed if you were to draw the two vectors
with their tails in the same location.
For example, Image 3 (p. 371) shows a black vector and a magenta vector drawn with their tails at the
origin. Eyeballing the picture suggests that the angle between the two vectors is forty or fty degrees.
Image 3: Two vectors with their tails at the origin, program DotProd2D02.
1.268
eld, and the angle between the two vectors is computed and displayed in the bottom right text eld.
Don't need to know the angle between the vectors
Upon seeing the description of the dot product given above (p. 370) , you may reasonably be concerned
about needing to know the angle between the vectors before you can compute the dot product. Fortunately,
as you will see later (p. 377) , it is possible to compute the dot product of two vectors without knowing
the angle. In fact, being able to compute the dot product is one way to determine the angle between two
vectors.
As you can see, the value of the dot product of the two vectors shown in Image 3 (p. 371) is 6000 and
the angle between the vectors is 49.3987 degrees. You will learn how those values were computed shortly.
Major properties of the dot product
Here are some of the major properties of the dot product of two vectors:
1. The dot product of two vectors with the same orientation is the product of their lengths.
2. The length of a vector is the square root of the dot product of the vector with itself.
3. The dot product of two vectors having opposite orientations is the negative of the product of their
lengths.
4. The dot product of perpendicular vectors is zero.
5. The angle between two vectors is the same as the angle between normalized versions of the vectors,
which is equal to the arc cosine of the dot product of the normalized vectors.
As you will see later, these properties apply to both 2D and 3D vectors. In many cases, they also apply to
vectors having more than three dimensions as well.
Dot product of two vectors with the same orientation in 2D
Image 4 (p. 373) illustrates the rst property in the above list: The dot product of two vectors with
the same orientation is the product of their lengths.
Image 4: Dot product of two vectors with the same orientation in 2D.
1.269
You may recall from some earlier experience that when a right triangle has sides with lengths of 30 and
40, the length of the hypotenuse is 50. That is the case for the magenta vector shown in Image 4 (p. 373)
. Similarly, when the sides of the triangle are 60 and 80, the length of the hypotenuse is 100, as is the case
for the black vector in Image 4 (p. 373) .
From the property given above, we know that the dot product of the black and magenta vectors shown
in Image 4 (p. 373) is 5000, which agrees with the value shown in the Dot Prod output eld in Image 4
(p. 373) .
Dot product of two vectors with the same orientation in 3D
Image 5 (p. 374) shows the dot product of two vectors with the same orientation in 3D. The image in
Image 5: Dot product of two vectors with the same orientation in 3D.
1.270
Rounding the product of the two lengths gives the dot product value of 10000, which matches the value
shown in the bottom left output eld in Image 5 (p. 374) .
The length of a vector
Image 6 (p. 375) illustrates the second property in the above list (p. 372) : The length of a vector is
the square root of the dot product of the vector with itself .
1.271
Image 6 (p. 375) displays two vectors having the same coordinate values as the black vector in Image 5
(p. 374) . (The black vector is hidden by the magenta vector in Image 6 (p. 375) .) Because these two
vectors have identical coordinate values, the dot product of these two vectors is the same as the dot product
1.272
The two vectors shown in Image 7 (p. 376) have the same absolute coordinates as the two vectors shown
in Image 5 (p. 374) . However, the algebraic signs of the coordinates of the magenta vector in Image 7
(p. 376) were reversed relative to Image 4 (p. 373) , causing the magenta vector to point in the opposite
direction from the black vector. (Note that the angle between the two vectors, as reported by the program
is zero degrees in Image 5 (p. 374) and is 180 degrees in Image 7 (p. 376) .)
The point here is that the dot product of the two vectors in Image 7 (p. 376) is the negative of the dot
product of the two vectors in Image 5 (p. 374) . This property will be used in another program in the second
part of this two-part miniseries to achieve the back-face culling shown in Image 1 (p. 368) .
The computational simplicity of the vector dot product
If you have studied the Kjell tutorial through Chapter 10, Angle between 3D Vectors you have learned
that the dot product of two vectors can be computed as the sum of products of the corresponding x, y, and
z components of the two vectors. In particular, in the 2D case , the dot product is given by:
2D dot product = x1*x2 + y1*y2
Similarly, in the 3D case , the dot product is given by:
3D dot product = x1*x2 + y1*y2 + z1*z2
Note that these two formulations don't require the program to know anything about the angle between
the two vectors, as is the case in the earlie (p. 370) r denition.
The dot product of perpendicular vectors in 2D
The dot product has many uses in game programming, not the least of which is determining if two vectors
are perpendicular.
Image 8 (p. 378) illustrates the fourth property in the above list (p. 372) : The dot product of
perpendicular vectors is zero . This is an extremely important property in that it allows game programs
to easily determine if two vectors are perpendicular. I will begin with a 2D discussion because the topic of
perpendicularly of vectors is less complicated in 2D than in 3D .
1.273
By eyeballing Image 8 (p. 378) , you can see that the magenta vector is probably perpendicular to the
black vector. Looking at the output elds at the bottom left and the bottom right in Image 8 (p. 378) , you
will see that the dot product of the two vectors is zero and the angle between the two vectors is 90 degrees.
Restating the perpendicularity property
Most of us learned in our earlier mathematics classes that the angle between perpendicular lines is 90
degrees. Therefore, the angle between perpendicular vectors must be 90 degrees. (See a denition of
perpendicularity 98 .)
98 http://www.thefreedictionary.com/perpendicularity
Most of us also learned in our trigonometry classes that the cosine of 90 degrees is 0.0. Since, by denition
(p. 370) , the value of the dot product of two vectors is the product of the lengths of the vectors multiplied by
the cosine of the angle between them , and the angle must be 90 degrees for two vectors to be perpendicular,
then the dot product of perpendicular vectors must be zero as stated by the fourth property in the above
list of properties (p. 372) .
An innite number of perpendicular vectors
By observing Image 8 (p. 378) , it shouldn't be too much of a stretch for you to recognize that there
are an innite number of dierent vectors that could replace the magenta vector in Image 8 (p. 378) and
be perpendicular to the black vector. However, since we are discussing the 2D case here, all of those vectors
must lie in the same plane and must have the same orientation (or the reverse orientation) as the magenta
vector. In other words, all of the vectors in the innite set of vectors that are perpendicular to the black
vector must lie on the line dened by the magenta vector, pointing in either the same direction or in the
opposite direction. However, those vectors can be any length and still lie on that same line.
A general formulation of 2D vector perpendicularity
By performing some algebraic manipulations on the earlier (p. 377) 2D formulation of the dot product,
we can formulate the equations shown in Image 9 (p. 379) that dene the innite set of perpendicular vectors
described above.
1.274
As you can see from Image 9 (p. 379) , we can assume any values for y1, y2, and x1 and compute a value
for x2 that will cause the two vectors to be perpendicular.
A very interesting case
One very interesting 2D case is the case shown in Image 8 (p. 378) . In this case, I initially specied
one of the vectors to be given by the coordinate values (50,100). Then I assumed that y2 is equal to x1 and
computed the value for x2. The result is that the required value of x2 is the negative of the value of y1.
Thus, in the 2D case, we can easily dene two vectors that are perpendicular by
The actual direction that the second vector points will depend on which value you negate in the second
vector.
Another interesting 2D case of perpendicular vectors
Another interesting 2D case is shown in Image 10 (p. 380) .
1.275
In Image 10 (p. 380) , I assumed the same coordinate values for the black vector as in Image 8 (p. 378) .
Then I assumed that the values of the y-coordinates for both vectors are the same. Using those values along
with the equation in Image 8 (p. 378) , I manually computed a required value of -200 for the x-coordinate
of the magenta vector. I entered that value into the eld labeled VectorBx = in Image 10 (p. 380) and
clicked the OK button.
And the result was...
You can see that the value of the dot product of the two vectors in Image 10 (p. 380) is 0.0, and the
angle between the two vectors is 90 degrees. Therefore, although the magenta vector in Image 10 (p. 380) is
much longer than the magenta vector in Image 8 (p. 378) , the magenta vector in Image 10 (p. 380) is still
perpendicular to the black vector. Thus, Image 8 (p. 378) and Image 10 (p. 380) show two of the innite
number of magenta vectors that are perpendicular to the black vector in those images.
The dot product of perpendicular vectors in 3D
As I mentioned earlier, the topic of perpendicularity in 3D is more complicated (p. 377) than is the case
in 2D. As is the case in 2D, there are an innite number of vectors that are perpendicular to a given vector
in 3D. In 2D, the innite set of perpendicular vectors must have dierent lengths taken in pairs, and the
vectors in each pair must point in opposite directions.
An innite number of perpendicular vectors having the same length
However, in 3D there are an innite number of vectors having the same length that are perpendicular
to a given vector. All of the perpendicular vectors having the same length must point in dierent directions
and they must all lie in a plane that is perpendicular to the given vector.
Perpendicular vectors having dierent lengths may point in the same or in dierent directions but they
also must lie in a plane that is perpendicular to the given vector.
A wagon-wheel analogy
Kjell explains the situation of an innite set of 3D vectors that are perpendicular to a given vector by
describing an old-fashioned wagon wheel with spokes that emanate directly from the hub and extend to the
rim of the wheel. The hub surrounds the axle and each of the spokes is perpendicular to the axle. Depending
on the thickness of the spokes, a large (but probably not innite) number of spokes can be used in the
construction of the wagon wheel.
Another wheel at the other end of the axle
In this case, the wagon wheel lies in a plane that is perpendicular to the axle. There is normally another
wheel at the other end of the axle. Assuming that the axle is straight, the second wheel is in a dierent plane
but that plane is also perpendicular to the axle. Thus, the spokes in the second wheel are also perpendicular
to the axle.
If there were two identical wheels at each end of the axle for a total of four wheels (the predecessor to
the modern 18-wheel tractor trailer) , the spokes in all four of the wheels would be perpendicular to the
axle. Again, the point is that there are an innite number of vectors that are perpendicular to a given vector
in 3D.
A general formulation of 3D vector perpendicularity
By performing some algebraic manipulations on the earlier (p. 377) 3D formulation of the dot product,
we can develop the equations shown in Image 11 (p. 382) that describe an innite set of vectors that are
perpendicular to a given vector.
x2 = -(y1*y2 + z1*z2)/x1
or
y2 = -(x1*x2 + z1*z2)/y1
or
z2 = -(x1*x2 + y1*y2)/z1
1.276
(Although I didn't do so in Image 11 (p. 382) , I could have written three more equations that could be
used to solve for x1, y1, and z1 if the given vector is notated as x2, y2, and z2.)
No simple case
Unlike with 2D vectors, (to my knowledge) , there is no case that simply allows you to swap coordinate
values and change the sign on one of them to produce a vector that is perpendicular to another vector.
However, given the equations in Image 11 (p. 382) , and given values for x1, y1, and z1, we can assume
values for y2 and z2 and determine the value for x2 that will cause the two vectors to be perpendicular.
While this is a fairly tedious computation with a hand calculator, it is very easy to write Java code to
perform the computation. Therefore, given a 3D vector, it is fairly easy to write Java code that will compute
an innite number of vectors that are perpendicular to the given vector.
A pair of perpendicular 3D vectors
Image 12 (p. 383) and Image 13 (p. 384) each show a magenta 3D vector that is part of the innite set
of vectors that are all perpendicular to the black 3D vector. In Image 12 (p. 383) , y1 was assumed to be
equal to y2, and z1 was assumed to be equal to z2. For an x1 value of 25, a value of -125 was required to
cause the magenta vector to be perpendicular to the black vector.
1.277
1.278
For a y1 value of 50, a y2 value of - 25 was required to cause the magenta vector to be perpendicular to
the black vector.
The black vector didn't change
Note that the black vector is the same in Image 12 (p. 383) and Image 13 (p. 384) . However, the
magenta vectors are dierent in Image 12 (p. 383) and Image 13 (p. 384) . They represent just two of the
innite set of vectors that are perpendicular to the black vector. (They are two of the vectors in the innite
set of perpendicular vectors that are relatively easy to compute using program code.)
Computing the angle between two vectors
The fth property in the previous list (p. 372) reads: The angle between two vectors is the same as the
angle between normalized versions of the vectors, which is equal to the arc cosine of the dot product of the
normalized vectors.
In other words, given two vectors, we can compute the angle between the two vectors by rst normalizing
each vector and then computing the dot product of the two normalized vectors.
(By normalizing, I mean to change the coordinate values such that the direction of the vector remains
the same but the length of the vector is converted to 1.0.)
The dot product is equal to the cosine of the angle. The actual angle can be obtained by using one of
the methods of the Math class to compute the arc cosine of the value of the dot product.
Used to compute the output angle in the programs
This is the procedure that is used by the programs in this module to compute and display the angle
between two vectors as illustrated by the contents of the output elds labeled Ang(deg) or Angle (deg)
= in many of the images in this module.
I will have more to say about this topic as I explain the code in the upgraded game-math library named
GM02 as well as the following four programs that demonstrate the use of the upgraded game-math library:
• DotProd2D01
• DotProd2D02
• DotProd3D01
• DotProd3D02
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this module and previous modules.
1.279
This is one of those cases where it is very easy to write the code once you understand the code that you
need to write. Listing 1 (p. 386) implements the equation for the 3D dot product that I provided earlier (p.
377) and returns the result of the computation as type double .
Source code for the method named GM02.Vector3D.dot
Listing 2 (p. 386) shows the source code for the method named GM02.Vector3D.dot . This method
computes the dot product of two Vector3D objects and returns the result as type double .
1.280
Once again, the code is straightforward. All Vector3D objects instantiated from classes in the game-
math library are represented by objects of the ColMatrix3D class. Listing 2 (p. 386) gets a reference to
the two ColMatrix3D objects that represent the two vectors for which the dot product is needed. Then
it calls the GM02.ColMatrix3D.dot method shown earlier in Listing 1 (p. 386) to get and return the
value of the dot product of the two vectors.
Source code for the method named GM02.Vector3D.angle
Listing 3 (p. 387) shows the source code for the method named GM02.Vector3D.angle . This method
computes and returns the angle between two Vector3D objects. The angle is returned in degrees as type
double .
1.281
1.282
1.283
Listing 4 (p. 389) begins by instantiating a pair of GM02.ColMatrix2D objects using data provided
by the user in the top four elds shown in Image 14 (p. 388) .
Then Listing 4 (p. 389) calls the dot method on the object referred to by matrixA , passing the
object referred to by matrixB as a parameter. The dot method computes the dot product of the two
column matrix objects, returning the result as type double .
Format the dot product value for display in the GUI
In some cases, the format of the returned value is not very suitable for display in the lower-left eld
in Image 14 (p. 388) . For example, if the value is very small, it is returned in an exponential notation
requiring a large number of digits for display. Similarly, sometimes the dot-product value is returned in a
format something like 0.33333333 requiring a large number of digits to display.
Listing 5 (p. 390) formats the dot product value to make it suitable for display in the text eld in Image
14 (p. 388) . (There may be an easier way to do this, but I didn't want to take the time to gure out what
it is.)
Listing 5: Format the dot product value for display in the GUI.
}//end actionPerformed
1.284
g2D.setColor(Color.MAGENTA);
vecB.draw(
g2D,new GM02.Point2D(new GM02.ColMatrix2D(0,0)));
1.285
Listing 6 (p. 391) gets the four user input values that dene the two vectors and draws them in black
and magenta on the GUI shown in Image 3 (p. 371) . There is nothing new in the code in Listing 6 (p. 391)
.
Compute the dot product and the angle between the two vectors
Listing 7 (p. 392) computes the dot product and the angle between the two vectors by rst calling the
dot method and then the angle method on the object referred to by vecA , passing the object referred
to by vecB as a parameter.
Listing 7: Compute the dot product and the angle between the two vectors.
1.286
In both cases, the code in Listing 7 (p. 392) formats the returned double values to make them
appropriate for display in the bottom two text elds in Image 3 (p. 371) . This code was deleted from
Listing 7 (p. 392) for brevity.
Conrm that the results are correct
Because this is a 2D display, it is easy to make an eyeball comparison between the drawing of the two
vectors and the reported angle between the two vectors to conrm agreement. However, I recommend that
you use this program to dene several vectors and then use your scientic calculator to conrm that the
results shown are correct.
That concludes the explanation of the program named DotProd2D02 .
Image 15: A screen shot of the output from the program named DotProd3D01.
1.287
library. Therefore, you should have no diculty understanding this program without further explanation
from me.
That concludes the explanation of the program named DotProd3D02 .
Click here 101 to download a zip le containing standard javadoc documentation for the library named
GM02 . Extract the contents of the zip le into an empty folder and open the le 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 8 (p. 398)
and the explanations given above) , the documentation does provide a good overview of the organization
and structure of the library. You may nd it helpful in that regard.
100 http://www.developer.com/java/other/article.php/3484591/Convolution-and-Frequency-Filtering-in-Java.htm
101 http://cnx.org/content/m45018/latest/GM02docs.zip
The homework assignment for this module was to study the Kjell tutorial through Chapter 10, Angle
between 3D Vectors .
The homework assignment for the next module is to continue studying that same material.
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 102 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.
I encourage you to copy the code from Listing 8 (p. 398) through Listing 12 (p. 406) . Compile the code
and execute it in conjunction with the game-math library named GM02 provided in Listing 8 (p. 398) .
Experiment with the code, making changes, and observing the results of your changes. Make certain that
you can explain why your changes behave as they do.
1.19.8 Summary
In this module, you learned the fundamentals of the vector dot product in both 2D and 3D. You learned
how to update the game-math library to support various aspects of the vector dot product, and you learned
how to write 2D and 3D programs that use the vector dot product methods in the game-math library.
In the next module, which will be the second part of this two-part miniseries on the vector dot product, you
will learn how to use the dot product to compute nine dierent angles of interest that a vector makes with
various elements in 3D space.
You will learn how to use the dot product to nd six of the innite set of vectors that are perpendicular
to a given vector as shown in Image 16 (p. 396) .
102 http://cnx.org/content/m44992/latest/
Image 16: Six (magenta) vectors that are perpendicular to a given (black) vector.
1.288
You will also learn how to use the dot product to perform back-face culling as shown in Image 1 (p. 368)
and Image 2 (p. 369) .
1.19.10 Miscellaneous
• File: Game0145.htm
• Published: 10/21/12
• Revised: 12/31/12
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 8 (p. 398) through Listing
12 (p. 406) below
/*GM02.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
/*DotProd2D01.java
Copyright 2008, R.G.Baldwin
Revised 03/04/08
class DotProd2D01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class DotProd2D01
//======================================================//
//----------------------------------------------------//
GUI(){//constructor
/*DotProd2D02.java
Copyright 2008, R.G.Baldwin
Revised 03/07/08
When the user clicks the OK button, the program draws the
two vectors, one in black and the other in magenta, on
the output screen with the tail of each vector located at
the origin in 2D space.
class DotProd2D02{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class DotProd2D02
//======================================================//
/*DotProd3D01.java
Copyright 2008, R.G.Baldwin
Revised 03/04/08
class DotProd3D01{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class DotProd3D01
//======================================================//
//----------------------------------------------------//
Available for free at Connexions <http://cnx.org/content/col11450/1.29>
GUI(){//constructor
/*DotProd3D02.java
Copyright 2008, R.G.Baldwin
Revised 03/07/08
When the user clicks the OK button, the program draws the
two vectors, one black and the other in magenta, on the
output screen with the tail of each vector located at the
origin in 3D space.
class DotProd3D02{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class DotProd3D02
//======================================================//
1.19.12 Exercises
1.19.12.1 Exercise 1
Using Java and the game-math library named GM02 , or using a dierent programming environment of
your choice, write a program that behaves as follows.
When the program starts running, an image similar to Image 17 (p. 408) appears on the screen. Each of
the text elds is blank and the drawing area at the top is also blank.
Each time you click the Replot button, the program generates three random values in the general
range of -128 to 127. The rst two values are used as the x and y values for a vector. The two values are
displayed in the elds labeled VectorAx and VectorAy . Also, the two values are used to create and
draw a black vector with its tail at the origin as shown in Image 17 (p. 408) .
The third random value is used as the x-value for a second vector. It is displayed in the eld labeled
VectorBx . A y-value is computed that will cause that vector to be perpendicular to the black vector.
That value is displayed in the eld labeled VectorBy and the two values are used to draw the magenta
vector shown in Image 17 (p. 408) .
The dot product between the two vectors is computed and displayed in the eld labeled Dot Prod .
The angle between the two vectors is computed and displayed in the eld labeled Angle (deg) .
If the two vectors are perpendicular, the dot product should be close to zero and the angle should be
very close to 90 degrees.
Cause your name to appear in the screen output in some manner.
1.294
1.19.12.2 Exercise 2
Using Java and the game-math library named GM02 , or using a dierent programming environment of
your choice, write a program that behaves as follows.
When the program starts running, an image similar to Image 18 (p. 410) appears on the screen. Each of
the text elds is blank and the drawing area at the top is also blank.
Each time you click the Plot button, the program generates three random values in the general range
of -128 to 127. The rst two values are used as the x and y values for a 3D vector. (Set the z-value for the
vector to 0.0.) The three values are displayed in the elds labeled VecAx , VecAy , and VecAz .
Also, the three values are used to create and draw a black 3D vector with its tail at the origin as shown in
Image 18 (p. 410) .
The third random value is used as the x value for a second 3D vector. (Set the z-value for the vector to
0.0.) Those two values are displayed in the elds labeled VecBx and VecBz . A y-value is computed that
will cause that vector to be perpendicular to the black vector. That value is displayed in the eld labeled
VecBy and the three values are used to draw the magenta vector shown in Image 18 (p. 410) .
The dot product between the two vectors is computed and displayed in the eld labeled Dot Prod .
The angle between the two vectors is computed and displayed in the eld labeled Angle (deg) .
If the two vectors are perpendicular, the dot product should be close to zero and the angle should be
very close to 90 degrees.
Cause your name to appear in the screen output in some manner.
1.295
1.19.12.3 Exercise 3
Using Java and the game-math library named GM02 , or using a dierent programming environment of
your choice, write a program that behaves as follows.
When the program starts running, an image similar to Image 19 (p. 412) appears on the screen. Each of
the text elds is blank and the drawing area at the top is also blank.
Each time you click the Plot button, the program generates ve random values in the general range
of -128 to 127. The rst three values are used as the x, y, and z values for a vector. The three values are
displayed in the elds labeled VecAx , VecAy , and VecAz . Also, the three values are used to create
and draw a black vector with its tail at the origin as shown in Image 19 (p. 412) .
The fourth and fth random values are used as the x and y values for a second vector. They are
displayed in the elds labeled VecBx and VecBy . A z-value is computed that will cause that vector
to be perpendicular to the black vector. That value is displayed in the eld labeled VecBz and the three
values are used to draw the magenta vector shown in Image 19 (p. 412) .
The dot product between the two vectors is computed and displayed in the eld labeled Dot Prod .
The angle between the two vectors is computed and displayed in the eld labeled Angle (deg) .
If the two vectors are perpendicular, the dot product should be close to zero and the angle should be
very close to 90 degrees.
Cause your name to appear in the screen output in some manner.
1.296
-end-
1.20.2 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.
What you have learned
In the previous module, which was the rst part of a two-part miniseries on the vector dot product, you
learned the fundamentals of the vector dot product in both 2D and 3D. You learned how to update the
game-math library to support various aspects of the vector dot product, and you learned how to write 2D
and 3D programs that use the vector dot product methods in the game-math library.
What you will learn
In this module, you will learn how to apply the vector dot product to three dierent applications. You
will learn
• how to use the dot product to compute nine dierent angles of interest that a vector makes with various
elements in 3D space,
• how to use the dot product to nd six somewhat unique vectors of the innite set of vectors that are
perpendicular to a given vector as shown in Image 4 (p. 424) , and
• how to use the dot product to perform back-face culling to convert the image shown in Image 1 (p.
414) to the image shown in Image 2 (p. 415) .
1.297
1.298
1.20.2.1.1 Images
• Image 1 (p. 414) . A 3D image before back-face culling.
• Image 2 (p. 415) . The 3D image after back-face culling.
• Image 3 (p. 417) . Screen shot of the output from the program named DotProd3D05.
• Image 4 (p. 424) . Six (magenta) vectors that are perpendicular to a given (black) vector.
• Image 5 (p. 425) . Screen output when one coordinate has a value of zero.
• Image 6 (p. 426) . A general formulation of 3D vector perpendicularity.
• Image 7 (p. 442) . Output from Exercise 1.
• Image 8 (p. 443) . Output from Exercise 2.
1.20.2.1.2 Listings
• Listing 1 (p. 419) . Beginning of the actionPerformed method in the program named DotProd3D05.
• Listing 2 (p. 420) . Create ColMatrix3D objects that represent projections.
• Listing 3 (p. 421) . Create and draw vectors.
1.20.3 Preview
This module will build on what you learned about the vector dot product in the earlier module titled GAME
2302-0145: Getting Started with the Vector Dot Product 104 . In that module, you learned some of the
theory behind the dot product. In this module, you will learn how to use the dot-product methods of the
game-math library to write several applications. I will present and explain the following four programs:
• DotProd3D05 - Demonstrates how the dot product can be used to compute nine dierent angles
of interest that a vector makes with various elements in 3D space.
• DotProd3D06 - Demonstrates the use of the dot product to nd six somewhat unique vectors of
the innite set of vectors that are perpendicular to a given vector. (See Image 4 (p. 424) .)
• DotProd3D04 - Draws the same 3D object as the one drawn in DotProd3D03 but without the
benet of back-face culling. (See Image 1 (p. 414) .)
• DotProd3D03 - Demonstrates use of the vector dot product for back-face culling. (See Image 2
(p. 415) .)
I will also provide exercises for you to complete on your own at the end of the module. The exercises will
concentrate on the material that you have learned in this module and previous modules.
Image 3: Screen shot of the output from the program named DotProd3D05.
1.299
• Projection onto the XY plane relative to the x-axis, displayed with the label Angle PX .
• Projection onto the YZ plane relative to the y-axis, displayed with the label Angle PY .
• Projection onto the ZX plane relative to the z-axis, displayed with the label Angle PZ .
1.300
You have seen code similar to that in Listing 1 (p. 419) many times before. Therefore, this code should
not require further explanation beyond the embedded comments.
Create ColMatrix3D objects that represent projections
Listing 2 (p. 420) creates ColMatrix3D objects that represent the projection of the user-specied
vector onto each of the three planes.
1.301
Although the actual code in Listing 2 (p. 420) should be familiar to you, the application may be new.
The important thing to note is that the projection onto each of the three planes in Listing 2 (p. 420) is
accomplished by setting one of the coordinate values to zero for each projection. For example, in order to
project the vector onto the XY plane, the value for the z-axis coordinate is set to zero as shown in Listing
2 (p. 420) .
Create and draw vectors
Listing 3 (p. 421) uses the ColMatrix3D objects created in Listing 1 (p. 419) and Listing 2 (p. 420)
to create and draw vectors based on those ColMatrix3D objects.
1.302
Once the ColMatrix3D objects have been created to serve each specic purpose, there is nothing new
in Listing 3 (p. 421) . Therefore, no explanation of the code beyond the embedded comments should be
necessary.
Compute and display the nine angles
Listing 4 (p. 422) calls the angle method of the GM02.Vector3D class nine times in succession,
using references to the vectors created in Listing 3 (p. 421) , to compute and display the nine angle values
shown in Image 3 (p. 417) .
1.303
423
Once the required vectors had been created in Listing 3 (p. 421) , there is nothing new in the code in
Listing 4 (p. 422) . Therefore, no explanation of Listing 4 (p. 422) should be required beyond the comments
embedded in the code.
The bottom line on the program named DotProd3D05
The bottom line is that because the methods in the game-math library named GM02 were designed
to do most of the hard work, writing application programs such as DotProd3D05 using the game-math
library is not dicult at all. You simply need to understand how to organize your code to accomplish the
things that you need to accomplish.
That concludes the explanation of the program named DotProd3D05 .
Image 4: Six (magenta) vectors that are perpendicular to a given (black) vector.
1.304
case, the orientation of two of the vectors will overlay the orientation of the other two. Because the vectors
are normalized to the same length and occupy the same space, you will only see two vectors instead of four.
This is illustrated in Image 5 (p. 425) where the value of the z-axis coordinate value was set to zero relative
to the value used in Image 4 (p. 424) .
1.305
line screen.
The graphical user interface
The GUI shown in Image 4 (p. 424) is provided to allow the user to enter three double values that
dene a GM02.Vector3D object. The GUI also provides an OK button in addition to a 3D drawing
area.
When the user clicks the OK button, the program draws the user-specied vector in black with the tail
located at the origin in 3D space. It draws normalized versions of the perpendicular vectors in magenta with
their tails also located at the origin. Each normalized vector is scaled by a factor of 50 before it is drawn to
cause it to be long enough to be seen.
A short review
Before getting into the programming details, we need to review some material from the previous module.
Recall that I did some algebraic manipulations in the previous module and produced the equations shown
in Image 6 (p. 426) .
x2 = -(y1*y2 + z1*z2)/x1
or
y2 = -(x1*x2 + z1*z2)/y1
or
z2 = -(x1*x2 + y1*y2)/z1
1.306
this program in Listing 11 (p. 436) near the end of the module.
The actionPerformed method begins in Listing 5 (p. 427) . Note that I deleted some of the code
early in the method because it is very similar to code that I have explained before.
Listing 5: Beginning of the actionPerformed method for the program named DotProd3D06.
1.307
1.308
Listing 6 (p. 428) also causes the o-screen image to be displayed on the canvas.
That concludes the explanation of the program named DotProd3D06 .
of the object. The object in Image 2 (p. 415) does incorporate backface culling. The dierence is easy to
see.
This program draws a 3D circular cylinder by stacking 20 circular disks on the x-z plane as shown in
Image 1 (p. 414) . The disks are centered on the y-axis and are parallel to the x-z plane. The thickness of
each disk is 5 vertical units. As mentioned above, there is no backface culling in this program, so all of the
lines that should be hidden show through.
Will discuss in fragments
A complete listing of this program is provided in Listing 12 (p. 438) near the end of the module. I will
explain portions of the program using code fragments. However, I won't repeat explanations of code that I
have already explained in this or in earlier modules.
The method named drawTheCylinder
All of the interesting code in this program is contained in the method named drawTheCylinder ,
which is shown in Listing 7 (p. 429) . (Note that some of the code was deleted from Listing 7 (p. 429)
for brevity.) This method is used to set the axes to the center of the o-screen image and to draw a 3D
cylinder that is centered on the y-axis.
1.309
(p. 430) for brevity.) This method is used to set the axes to the center of the o-screen image and to draw
a 3D cylinder that is centered on the y-axis.
1.310
The homework assignment for this module was to study the Kjell tutorial through Chapter 10, Angle
between 3D Vectors.
The homework assignment for the next module is to study the Kjell tutorial through Chapter 11,
Projections.
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 106 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.
I encourage you to copy the code from Listing 9 (p. 432) through Listing 13 (p. 440) . Compile the code and
execute it in conjunction with the game-math library named GM02 in Listing 9 (p. 432) . Experiment
with the code, making changes, and observing the results of your changes. Make certain that you can explain
why your changes behave as they do.
1.20.7 Summary
In this module, you learned how to apply the vector dot product to three dierent applications. You learned:
• how to use the dot product to compute nine dierent angles of interest that a vector makes with various
elements in 3D space,
• you learned how to use the dot product to nd six of the innite set of vectors that are perpendicular
to a given vector as shown in Image 4 (p. 424) , and
• you learned how to use the dot product to perform back-face culling to convert the image in Image 1
(p. 414) to the image in Image 2 (p. 415) .
106 http://cnx.org/content/m44992/latest/
In the next module, you will learn about rst-person computer games in general, and how to use the game-
math library to write a rst-person game in a 3D world using the game math library.
1.20.9 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
Complete listings of the programs discussed in this module are shown in Listing 9 (p. 432) through Listing
13 (p. 440) below.
/*GM02.java
Copyright 2008, R.G.Baldwin
Revised 02/08/08
/*DotProd3D05.java
Copyright 2008, R.G.Baldwin
Revised 03/06/08
Available
When the user clicks the OK for free at Connexions
button, <http://cnx.org/content/col11450/1.29>
the program draws the
user-specified vector in black with the tail located at
the origin in 3D space. It also draws the projection of
that vector in magenta on each of the XY, YZ, AND ZX
435
/*DotProd3D06.java
Copyright 2008, R.G.Baldwin
Revised 03/09/08
When the user clicks the OK button, the program draws the
user-specified vector in black with the tail located at
the origin in 3D space. It also draws normalized versions
of the perpendicular vectors in magenta with their tails
located at the origin. Each normalized vector is scaled
by a factor of 50 before it is drawn.
/*DotProd3D04.java
Copyright 2008, R.G.Baldwin
Revised 03/07/08
class DotProd3D04{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class DotProd3D04
//======================================================//
GUI(){//constructor
/*DotProd3D03.java
Copyright 2008, R.G.Baldwin
Revised 03/07/08
class DotProd3D03{
public static void main(String[] args){
GUI guiObj = new GUI();
}//end main
}//end controlling class DotProd3D03
//======================================================//
GUI(){//constructor
Available
//Set JFrame size, for freeand
title, at Connexions <http://cnx.org/content/col11450/1.29>
close operation.
setSize(hSize,vSize);
setTitle("Copyright 2008,R.G.Baldwin");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
441
1.20.11 Exercises
1.20.11.1 Exercise 1
Using Java and the game-math library named GM02 , or using a dierent programming environment of
your choice, write a program that creates the drawing of half of a 3D sphere protruding upward from the
x-z plane as shown in Image 7 (p. 442) . The north and south poles of the sphere lie on the y-axis, but only
the northern hemisphere is visible.
Cause your name to appear in the screen output in some manner.
1.316
1.20.11.2 Exercise 2
Beginning with a program similar to the one that you wrote in Exercise 1 (p. 441) , create a drawing of a
3D sphere as shown in Image 8 (p. 443) . The north and south poles of the sphere lie on the y-axis.
1.317
-end-
Physics
2.1.2 Preface
This module is the rst in a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 2 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
2.1.3 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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
1 This content is available online at <http://cnx.org/content/m44992/1.2/>.
2 http://cnx.org/content/m44983/latest
445
446 CHAPTER 2. PHYSICS
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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.2.2 Preface
2.2.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 4 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
3 This content is available online at <http://cnx.org/content/m45001/1.2/>.
4 http://cnx.org/content/m44983/latest
2.2.2.2.1 Images
• Image 1 (p. 449) . Output from script in Listing 1.
• Image 2 (p. 453) . Output from script in Listing 2.
• Image 3 (p. 454) . Binary arithmetic operators.
• Image 4 (p. 455) . General syntax for selection statement.
• Image 5 (p. 455) . Real-world analogy of a selection statement.
• Image 6 (p. 456) . Output from script in Listing 3.
• Image 7 (p. 457) . Relational operators.
• Image 8 (p. 459) . Output from script in Listing 4.
• Image 9 (p. 460) . General syntax for a while loop.
• Image 10 (p. 461) . Output from script in Listing 5.
2.2.2.2.2 Listings
• Listing 1 (p. 448) . A minimal JavaScript script.
• Listing 2 (p. 452) . An example function named getHalf.
• Listing 3 (p. 456) . A selection script example.
• Listing 4 (p. 458) . A sample script that uses variables.
• Listing 5 (p. 461) . A simple while loop.
2.2.3 Discussion
The goal of this module is to provide an introductory JavaScript programming tutorial for students with no
programming experience.
JavaScript encompasses modern programming concepts. For example, JavaScript is based on the concept
of objects. Object-Oriented Programming (OOP) is here to stay. (For an extensive discussion of OOP, see
the early lessons in my online programming tutorials at http://www.dickbaldwin.com/toc.htm 7 .)
A free audible, tactile scientic calculator
I also chose JavaScript because you will be able to use it to create your own scientic calculator. You
can use JavaScript to create solutions to many of the exercises in the modules in this collection of physics
concepts.
</script>
</body></html>
2.1
• Copy all of the text from the body of Listing 1 (p. 448) into your plain text editor and save the le
with an extension of .html (test.html for example).
• Open that le in your browser. (In most cases, you should be able to simply drag the le and drop it
onto an open browser page to open it. If that doesn't work, open it from the browser's File menu.)
2.2
• Copy the text (often referred to as code or source code) from Listing 1 (p. 448) into your plain text
editor.
• Replace the code between the two lines containing the word script with the code for your new script,
leaving the two lines containing the word script intact.
• Save the le with an extension of .html. (The le can have any legal le name so long as the extension
is .html.)
• Open the new html le in your browser.
2.2.3.4 Strings
In programming, we often refer to a group of sequential characters (such as your rst name) as a string .
In JavaScript format (often called syntax), such groups of characters are surrounded by matching quotation
marks to cause the group to be recognized as a single string.
The following strings appear in the JavaScript code in Listing 1 (p. 448) :
1. "Insert JavaScript between script tags."
2.
"<br/>"
3. "Hello from JavaScript"
The rst two strings appear, separated by a comma, inside the matching parentheses following the rst
occurrence of document.write . (We often call the items inside the matching parentheses the argument
list.)
The last item in the above list appears in the argument list following the second occurrence of docu-
ment.write in Listing 1 (p. 448) .
Purpose of document.write
Although this is a simplication, for purposes of the modules in this collection, it will suce to say that
the purpose of the document.write command is to cause the items in its argument list to be displayed in
the browser window. You can place one or more items in the argument list. If there is more than one item
in the argument list, the items must be separated by a comma as shown in Listing 1 (p. 448) .
Displaying strings
With some exceptions, items that appear in the argument list surrounded by matching quotation marks
(strings) will be displayed in the browser window.
The exceptions include the second item in the above list (p. 449) . This item is a special command to
the browser, commonly known as a break tag. The occurrence of a break tag tells the browser to go
down to the next line before displaying any additional material.
Such browser commands usually begin with a left angle bracket as shown in Listing 1 (p. 448) . Because
of this, it is usually wise to avoid displaying strings that begin with left angle brackets unless you know for
sure that your string won't be interpreted as a command to the browser.
Displaying material other than strings
I will show you how to display material other than strings in a later section titled The string concatenation
operator (p. 459) . Before getting into that, however, I will discuss several other topics.
I also expect them to know how to use variables and how to use operators (add, subtract, multiply, divide,
etc.).
You will need to have an introductory knowledge of these topics to understand the JavaScript scripts
that I will use to explain physics concepts in later modules. I will briey explain these topics in this module
and will discuss them further in later modules where they are used.
2.2.3.6.1 Functions
Functions, or procedures as they are called in some languages, provide a fundamental building block for
virtually every programming language. The purpose of a function is to encapsulate the ability to perform a
task into a single set of code and to be able to execute that code from a variety of dierent locations within
the script. This can eliminate the requirement to repeat the same code over and over when the same task is
required at multiple points in the script.
The surface area of a sphere
For example, if you write a script that frequently needs to calculate the surface area of a sphere, you can
encapsulate those calculations in a function. Then, whenever your script needs to know the surface area of
a sphere, it can simply call the function and provide the radius of the sphere as a parameter. The function
will perform the calculation and return the answer to be used by the script at that point.
A JavaScript function denition
A JavaScript function denition has the following basic parts as shown in Listing 2 (p. 452) :
3. A comma-separated list of arguments enclosed in parentheses. (If there are no arguments, which is
perfectly legal, the parentheses must still follow the function name but they will be empty.)
4. The statements in the body of the function enclosed in curly brackets.
The denition names the function and species how it will behave when it is called.
The call to the function temporarily passes control to the statements in the function causing them to
behave as previously dened.
Once the statements have been executed, control is returned to the point in the script where the call was
made. The function may, or may not return a value when it returns control.
The argument list
As in the sphere example discussed above, it is often useful to pass information to the function for it to
use in doing whatever it is supposed to do (but this is not always required). When we call the function, we
include parameters in the call to the function that match up with the argument list mentioned above. That
is the mechanism used to pass information to a function. (This will probably make more sense when you see
an example. Again, in some cases, no arguments are required.)
The purpose of a function
Usually (but not always), the purpose of a function is to calculate or otherwise determine some value
and return it. In the sphere example mentioned earlier, the purpose of the function would be to calculate
and return the surface area of the sphere. Returning a value is accomplished using the return keyword in
the body of the function.
Sometimes, the purpose of a function is not to return a value, but instead to cause some action to occur,
such as displaying information in the browser window. In that case, a return statement is not required.
However, it doesn't cause any problem to put a return statement at the end of the function's body with
nothing to the right of the word return .
An example function named getHalf
The code in Listing 2 (p. 452) denes a function named getHalf and then calls that function from two
dierent locations in a script, passing a dierent parameter value with each call.
</script>
</body></html>
2.3
Each call to the function named getHalf is embedded as one of the elements in the argument list
following document.write .
write is also a function
Although I didn't mention this earlier because you weren't ready for it yet, write is also the name of a
function. However, the write function is predened in JavaScript and we can use it to display information
in the browser window without having to dene it rst.
(Actually, write is a special kind of a function that we call a method , but you don't need to worry
about that unless you want to dig much deeper into the object-oriented aspects of JavaScript.)
Two calls to the getHalf function
The script in Listing 2 (p. 452) calls the function named getHalf twice in two dierent locations,
each of which is embedded in the argument list of a call to the write method. Each call passes a dierent
parameter value to the getHalf function.
The order of operations
When a call to a function or method (such as the call to the write method) includes a call to another
function or method in its argument list, the call to the function in the argument list must be completed
before the call can be made to the function having the argument list. Therefore in each of these two cases,
the call to the getHalf function must be completed before the call to the write method can be executed.
Output from script in Listing 2 (p. 452)
Each call to the getHalf function returns a value that is half the value of its incoming parameter.
As I mentioned earlier, when the function returns, the returned value replaces the call to the function.
Therefore, in each case, the returned value from the call to the getHalf function becomes part of the
argument list for the write method before that method is called. This causes the two calls to the write
method in Listing 2 (p. 452) to display the values returned from the calls to the getHalf function as
shown in Image 2 (p. 453) .
2.4
The operators that we will use in the modules in this collection will usually be restricted to those that
have two operands, a left operand and a right operand . (Operators with two operands are commonly
called binary operators .)
In the function named getHalf in Listing 2 (p. 452) , the "/" character is the division operator.
The left operand is incomingParameter and the right operand is 2 . The result is that the incoming
parameter is divided by the right operand (2).
Binary arithmetic operators
The binary arithmetic operators supported by JavaScript are shown in Image 3 (p. 454) .
2.5
We will use these operators extensively as we work through the physics exercises in future modules.
2.2.3.6.3 Sequence
Of the four items listed under Structured programming (p. 450) earlier, the simplest one is sequence .
The concept of sequence in structured programming simply means that code statements can be executed
in sequential order. Listing 2 (p. 452) provides a good example of the sequential execution of statements.
The code in Listing 2 (p. 452) shows four sequential statements that begin with document.write.
2.2.3.6.4 Selection
The next item that we will discuss from the list under Structured programming (p. 450) is selection .
While not as simple as sequence , selection is something that you probably do many times each day
without even thinking about it. Therefore, once you understand it, it isn't complicated.
General syntax for selection statement
The general syntax for a selection statement (often called an if-else statement) is shown in Image 4
(p. 455) .
2.6
A selection statement performs a logical test that returns either true or false. Depending on the result,
specic code is executed to control the behavior of the script.
A real-world analogy
Image 5 (p. 455) shows a real-world analogy of a selection statement that you might make on your day
o.
2.7
In this analogy, you would check outside to conrm that it is not raining. If the condition is true (meaning
that it isn't raining), you would play tennis, go for a walk, and then relax on the beach. If it is raining,
(meaning that the test condition is false), you would make some popcorn and relax in front of the TV.
The else clause is optional
Note that when writing JavaScript code, the else clause shown in Image 5 (p. 455) is optional. In
other words, you might choose to direct the script to take some specic action if the condition is true, but
simply transfer control to the next sequential statement in the script if the condition is false.
A selection script example
Listing 3 (p. 456) shows a sample script containing two selection statements (commonly called if-else
statements) in sequence.
</script>
</body></html>
2.8
3 is greater than 2.
3 is not less than 2.
2.9
Since 3 isn't less than 2, the statement in the line immediately following the second test in Listing 3
(p. 456) is skipped and the statement in the line immediately following the second word else is executed
producing the second line of output text shown in Image 6 (p. 456) .
2.10
As with the arithmetic operators discussed earlier, we will use these operators extensively as we work
through the physics exercises in future modules.
2.2.3.6.6 Variables
The next item in the list under Structured programming (p. 450) is repetition . Before I can explain
repetition, however, I need to explain the use of variables.
What is a variable?
You can think of a variable as the symbolic name for a pigeonhole in memory where the script can store
a value. The script can change the values stored in that pigeonhole during the execution of the script. Once
a value has been stored in a variable, that value can be accessed by calling out the name of the variable.
Variable names
Variable names must conform to the naming rules for identiers. A JavaScript identier must start with
a letter or underscore "_". Following this, you can use either letters or the symbols for the digits (0-9) in
the variable name.
JavaScript is case sensitive. Therefore letters include the characters "A" through "Z" (uppercase) and
the characters "a" through "z" (lowercase).
Declaring a variable
In many languages, including JavaScript, you must declare a variable before you can use it. However,
JavaScript is very loose in this regard. There are two ways to declare a variable in JavaScript:
Scope
When working with variables in JavaScript and other languages as well, you must always be concerned
about an issue known as scope. Among other things, scope determines which statements in a script have
access to a variable.
Two kinds of variables
JavaScript recognizes two kinds of variables:
• local
• global
Local variables are variables that are declared inside a function. Global variables are variables that are
declared outside a function.
Scope
Local variables may only be accessed by other code within the same function following the declaration of
the variable. Hence, the scope of local variables is limited to the function or method in which it is declared.
Global variables may be accessed by any code within the script following the declaration of the variable.
Hence, the scope of global variables is the entire script.
Use of the keyword var
Using var to declare a global variable is optional. However, you must use var to declare a variable
inside a function (a local variable).
A sample script that uses variables
A sample script that uses variables to store data is shown in Listing 4 (p. 458) .
</script>
</body></html>
2.11
2.12
2.2.3.6.8 Repetition
The last item in the list under Structured programming (p. 450) is repetition , and that will be the topic
of this section.
Repetition (also referred to as looping) means the act of causing something to repeat.
A repetition or loop is a set of commands that executes repeatedly until a specied condition is met.
JavaScript supports three loop statements:
• while
• for
• do-while
while(condition is true){
//Execute statements in body of loop.
}//end while statement
2.13
document.write("The End.");
</script>
</body></html>
2.14
A counting loop
This script initializes the value of a counter variable named cnt to 4. Control continues to loop (iterate)
for as long as the value of the counter is greater than or equal to zero. During each iteration of the loop, the
current value of cnt is displayed and then the value of cnt is reduced by a value of 1.
Repeat the test
At that point, control returns to the top of the loop where the test is repeated. This process produces
the rst ve lines of output text shown in Image 10 (p. 461) .
cnt = 4
cnt = 3
cnt = 2
cnt = 1
cnt = 0
The End.
2.15
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.2.5 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.3.2 Preface
2.3.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 11 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
2.3.2.2.1 Images
• Image 1 (p. 467) . Output for script in Listing 1.
• Image 2 (p. 469) . A 3-4-5 triangle.
• Image 3 (p. 472) . Output for script in Listing 2.
• Image 4 (p. 474) . Output for script in Listing 3.
• Image 5 (p. 474) . Interesting sine equations.
• Image 6 (p. 477) . Interesting cosine equations.
• Image 7 (p. 479) . Output for script in Listing 5
• Image 8 (p. 479) . Two very important equations.
• Image 9 (p. 482) . Interesting tangent equations.
• Image 10 (p. 483) . Output for script in Listing 7.
• Image 11 (p. 486) . Sinusoidal values at 90-degree increments.
• Image 12 (p. 487) . Sinusoidal values at 45-degree increments.
• Image 13 (p. 488) . Sinusoidal values at 22.5-degree increments.
• Image 14 (p. 490) . Plot of cosine and sine curves.
• Image 15 (p. 492) . Algebraic signs versus quadrants.
• Image 16 (p. 494) . Output from the code in Listing 9.
11 http://cnx.org/content/m44983/latest
2.3.2.2.2 Listings
• Listing 1 (p. 466) . Conversions between radians and degrees.
• Listing 2 (p. 471) . Arcsin of 3-4-5 triangle.
• Listing 3 (p. 473) . Finding length of the opposite side.
• Listing 4 (p. 476) . Arccosine of 3-4-5 triangle.
• Listing 5 (p. 478) . Finding the length of the adjacent side.
• Listing 6 (p. 481) . Arctan of 3-4-5 triangle.
• Listing 7 (p. 483) . Finding the length of the opposite side.
• Listing 8 (p. 485) . Sinusoidal amplitude versus angle.
• Listing 9 (p. 493) . A function to deal with quadrants.
Many of the computational requirements for an introductory physics course involve trigonometry. This
module provides a brief tutorial on trigonometry fundamentals.
Sine, cosine, and tangent
There are many topics, such as identities, that are covered in an introductory trigonometry course that
won't be covered in this module. Instead, this module will concentrate mainly on performing computations
on right angles using the sine, cosine, and tangent of an angle.
If I nd it necessary to deal with identities in a later module, I will come back and update this module
accordingly.
2.3.4 Discussion
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var degrees = 90
var radians = toRadians(degrees)
document.write("degrees = " + degrees +
" : radians = " + radians + "<br/>")
radians = 1
degrees = toDegrees(radians)
document.write("radians = " + radians +
" : degrees = " + degrees + "<br/>")
radians = Math.PI
degrees = toDegrees(radians)
document.write("radians = " + radians +
" : degrees = " + degrees)
</script>
</body></html>
2.16
2.17
A template
You might want to save your html le as a template for use with future exercises that require conversions
between radians and degrees. This will be particularly useful when we write scripts that use JavaScript's
built-in trigonometric methods. Those methods deal with angles almost exclusively in radians while we tend
to think of angles in degrees. We will use these two functions to perform conversions between degrees and
radians when required.
• The origin
• x=3, y=0
• x=3, y=4
2.18
Available for free at Connexions <http://cnx.org/content/col11450/1.29>
470 CHAPTER 2. PHYSICS
We can also write a JavaScript script to perform the calculation, which we will do shortly.
Getting the angle for a known sine value
If you have access to a protractor, use it to measure and record the angle at the origin on your triangle.
Then create an html le containing the code shown in Listing 2 (p. 471) and open it in your browser.
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var opp = 4
var hyp = 5
var ratio = opp/hyp
var angRad = Math.asin(ratio)
var angDeg = toDegrees(angRad)
</script>
</body></html>
2.19
radians = 0.9272952180016123
degrees = 53.13010235415598
2.20
Did you measure the angle to be 53 degrees with your protractor. If so, congratulations. If not, you
should probably take another look at it.
Dene conversion functions
The code in Listing 2 (p. 471) begins by dening the functions named toRadians and toDegrees
that we developed earlier in Listing 1 (p. 466) . (In this case, we will only need the function named
toDegrees so I could have omitted the code for the function named toRadians .)
Declare and initialize variables
Then the code in Listing 2 (p. 471) declares and initializes variables to represent the lengths of the
opposite side and the hypotenuse for the triangle ( opp and hyp ). Then it computes and saves the ratio
of the two. (We learned earlier that the ratio is the value of the sine of the angle at the origin even though
we don't know the value of the angle.)
The built-in Math.asin method
JavaScript has a built-in method named Math.asin that receives the sine value for an unknown angle
and returns the value of the corresponding angle in radians. (The Math.asin method has the same purpose
at the word arcsin in the Google calculator.)
The returned value is an angle between -PI/2 and PI/2 radians. (I will have more to say about this
later.)
Listing 2 (p. 471) calls the Math.asin method, passing the ratio (sine of the angle) as a parameter,
and stores the returned value in a variable named angRad .
Then Listing 2 (p. 471) calls the toDegrees method, passing the value of angRad as a parameter
and stores the returned value in a variable named angDeg .
Finally, Listing 2 (p. 471) calls the document.write method twice in success to display the angle
values shown in Image 3 (p. 472) .
Another exercise with a dierent viewpoint
Now let's approach things from a dierent viewpoint. Assume that
Assume also that for some reason you can't simply measure the length of the opposite side. Therefore, you
must calculate it. This is a common situation in physics, so let's see if we can write a script that will perform
that calculation for us.
Create an html le containing the code shown in Listing 3 (p. 473) and open the le in your browser.
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var hyp = 5
var angDeg = 53.13
var angRad = toRadians(angDeg)
var sine = Math.sin(angRad)
hyp = opp/sine
</script>
</body></html>
2.21
opposite = 3.999994640742543
hypotenuse = 5
2.22
Interesting equations
We learned earlier that the sine of the angle is equal to the ratio of the opposite side and the hypotenuse.
We also learned that the angle is the arcsine of that ratio.
If we know any two of those values ( angle , opp , hyp ), we can nd the third (with a little
algebraic manipulation) as shown in Image 5 (p. 474) .
sine(angle) = opp/hyp
angle = arcsine(opp/hyp)
opp = hyp * sine(angle)
hyp = opp/sine(angle)
2.23
The value for the sine of the angle is then used in an algebraic equation to compute the length of the
opposite side, which is displayed in Image 4 (p. 474) . (This equation is one of the equations shown in Image
5 (p. 474) .)
Looks very close to me
As you can see, the computed value for the opposite side shown in Image 4 (p. 474) is extremely close
to the known value of 4 units.
Re-compute the length of the hypotenuse
After that, the value of the hypotenuse is re-computed (as though it were the unknown in the problem)
using the value of the sine and the recently computed value of the opposite side. (Once again, one of the
equations from Image 5 (p. 474) is used to perform the computation.) The output length for the hypotenuse
is shown in Image 4 (p. 474) , and it matches the known value.
Example usage of Math.asin and Math.sin methods
Listing 2 (p. 471) and Listing 3 (p. 473) provide examples of how to use the JavaScript Math.asin
and Math.sin methods to nd the angle, the opposite side, or the hypotenuse of a right triangle when the
other two are known as shown by the equations in Image 5 (p. 474) .
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var adj = 3
var hyp = 5
var ratio = adj/hyp
var angRad = Math.acos(ratio)
var angDeg = toDegrees(angRad)
</script>
</body></html>
2.24
• The call to the Math.asin method was replaced by a call to the Math.acos method.
The output
When you load your html le into your browser, it should produce the output shown earlier in Image
3 (p. 472) . In other words, we know that the angle at the origin didn't change. What changed was the
manner in which we computed the value of that angle.
Dierent approaches to the same solution
In Listing 2 (p. 471) , we used the length of the hypotenuse and the length of the opposite side, along
with the arcsine method to compute the angle.
In Listing 4 (p. 476) , we used the length of the hypotenuse and the length of the adjacent side, along
with the arccosine method to compute the angle.
Which approach should you use?
As would be expected, since the angle didn't change, both approaches produced the same result. Deciding
which approach to use often depends on the values that are available to use in the computation.
Sometimes you only have the lengths of the hypotenuse and the opposite side available, in which case
you could use the arcsine. Sometimes you only have the lengths of the hypotenuse and the adjacent side
available, in which case you could use the arccosine. Sometimes you have the lengths of both the opposite
side and the adjacent side in addition to the length of the hypotenuse, in which case you can use either
approach.
Both approaches use the length of the hypotenuse
It is important to note however that both of these approaches require you to have the length of the
hypotenuse. Later in this module we will discuss the tangent and arctangent for an angle, which allows us to
work with the opposite side and the adjacent side devoid of the length of the hypotenuse. (Of course, if you
have the lengths of the opposite side and the adjacent side, you can always nd the length of the hypotenuse
using the Pythagorean theorem.)
Interesting cosine equations
The equations in Image 6 (p. 477) are similar to equations in Image 5 (p. 474) . The dierence is that
the equations in Image 5 (p. 474) are based on the use of the sine of the angle and the opposite side whereas
the equations in Image 6 (p. 477) are based on the use of the cosine of the angle and the adjacent side.
As you can see in Image 6 (p. 477) , if you know any two of the values for angle , adj , and hyp ,
you can nd the other value. This is illustrated in the script shown in Listing 5 (p. 478) , which produces
the output shown in Image 7 (p. 479) .
cosine(angle) = adj/hyp
angle = arccosine(adj/hyp)
adj = hyp * cosine(angle)
hyp = adj/cosine(angle)
2.25
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var hyp = 5
var angDeg = 53.13
var angRad = toRadians(angDeg)
var cosine = Math.cos(angRad)
hyp = adj/cosine
</script>
</body></html>
2.26
adjacent = 3.0000071456633126
hypotenuse = 5
2.27
2.28
These two equations are so important that it might be worth your while to memorize them. Of course,
you will occasionally need most of the equations in Image 5 (p. 474) and Image 6 (p. 477) , so you should
try to remember them, or at least know where to nd them when you need them.
Vectors
As you will see later in the module that deals with vectors, you are often presented with something that
resembles the hypotenuse of a right triangle whose adjacent side is on the horizontal axis and whose opposite
side is parallel to the vertical axis.
The thing that looks like the hypotenuse of a right triangle is called a vector . It has a length and it
has a direction. Typically, the direction is stated as the angle between the vector and the horizontal axis.
Thus, the direction is analogous to the angle at the origin in your triangle.
Horizontal and vertical components
For reasons that I won't explain until we get to that module, you will often need to compute the horizontal
and vertical components of the vector. The horizontal component is essentially the adjacent side of our
current right triangle. Thus, the value of the horizontal component can be computed using the second
equation in Image 8 (p. 479) .
The vertical component is essentially the opposite side of our current right triangle, and its value can be
computed using the rst equation in Image 8 (p. 479) .
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var opp = 4
var adj = 3
var ratio = opp/adj
var angRad = Math.atan(ratio)
var angDeg = toDegrees(angRad)
</script>
</body></html>
2.29
tangent(angle) = opp/adj
angle = arctangent(opp/adj)
opp = tangent(angle) * adj
adj = opp/tangent(angle)
2.30
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var adj = 3
var angDeg = 53.13
var angRad = toRadians(angDeg)
var tangent = Math.tan(angRad)
adj = opp/tangent
</script>
</body></html>
2.31
When you open your html le in your browser, the output shown in Image 10 (p. 483) should appear in
your browser window. We can see that the values in Image 10 (p. 483) are correct for our 3-4-5 triangle.
opposite = 3.9999851132269173
adjacent = 3
2.32
• Listing 3 (p. 473) uses the sine along with the opposite side and the hypotenuse.
• Listing 5 (p. 478) uses the cosine along with the adjacent side and the hypotenuse.
• Listing 7 (p. 483) uses the tangent along with the opposite side and the adjacent side.
You should be able to work through those dierences without further explanation from me.
The cotangent of an angle
There is also something called the cotangent of an angle, which is simply the ratio of the adjacent side to
the opposite side. If you know how to work with the tangent, you don't ordinarily need to use the cotangent,
so I won't discuss it further.
Computing length of opposite side with the Google calculator
We could also compute the length of the opposite side using the Google calculator.
function toRadians(degrees){
return degrees*Math.PI/180
}//end function toRadians
//============================================//
function toDegrees(radians){
return radians*180/Math.PI
}//end function toDegrees
//============================================//
var angInc = 90
var angStart = -360
var ang = angStart
var angEnd = 360
var sine
var cosine
<;/script>
<;/body><;/html>
2.33
2.34
Image 11 (p. 486) contains the data for two dierent curves. One is a sine curve and the other is a cosine
curve.
Plot the points
You should be able to plots these data values as two separate curves on your graph paper.
Remember, the angle values from -360 degrees (-2*PI radians) to +360 degrees (+2*PI radians) are
horizontal coordinates while the corresponding values for the sine and cosine are vertical coordinates.
Saw tooth curves
Once you have plotted the points, you should be able to discern two curves, each of which is a saw tooth.
The two curves have exactly the same shape, but one is shifted horizontally relative to the other. For
example, the sine curve has a value of zero at an angle of zero (the origin) and it is asymmetric about the
vertical axis.
The cosine curve, on the other hand has a value of 1 at an angle of zero and it is symmetric about the
vertical axis.
Periodic curves
These are periodic curves. For example, the shape of the sine curve between -360 and 0 is the same as
the shape of the sine curve between 0 and +360. Each of those ranges represents one cycle of the periodic
curve.
We only computed the values from -360 to +360. However, if we had computed the values from -3600 to
+ 3600, the overall shape of the curve would not dier from what we have here. The shape of each cycle of
the curve would be identical to the shape of the cycle to the left and the cycle to the right.
Not really a saw tooth
The sine and cosine curves don't really have a saw tooth shape. That is an artifact of the fact that we
didn't compute enough points to reliably describe the shape of the curves. Let's improve on that.
Modify the script
Modify the code in your script to initialize the value of the variable named angInc to 45 degrees instead
of 90 degrees and then load the revised version into your browser. This will cause the script to ll in data
points between the points that we already have producing the output shown in Image 16 (p. 487) .
2.35
2.36
2.37
Grid lines
The image in Image 14 (p. 490) contains 7 vertical grid lines. The vertical grid line in the center
represents an angle of zero degrees. The space between each grid line on either side of the center represents
an angle of 90 degrees or PI/2 radians.
There are two horizontal grid lines. One is one-fourth of the way down from the top. The other is
one-fourth of the way up from the bottom.
The curves
A cosine curve is plotted with vertical values relative to the top grid line. It extends from -360 degrees
on the left to +360 degrees on the right.
A sine curve is plotted with vertical values relative to the bottom grid line. It also extends from -360
degrees on the left to +360 degrees on the right.
Return values for the Math.asin, Math.acos, and Math.atan methods
I told you earlier that the Math.asin method returns a value between -PI/2 and PI/2. However, I
didn't tell you that the Math.acos method returns a value between 0 and PI, or that the Math.atan
method returns a value between -PI/2 and PI/2. You now have enough information to understand why this
is true.
Smooth curves
If you examine the two curves in Image 14 (p. 490) and the data in Image 13 (p. 488) , you can surmise
that the sine and cosine functions are smooth curves whose values range between -1 and +1 inclusive. For
every possible value between -1 and +1, there is an angle in the range -PI/2 and PI/2 whose sine value
matches that value. There is also an angle in the range 0 and PI whose cosine value matches that value.
(Although you haven't plotted the curve for the tangent, a similar situation holds there also, but the
maximum value is not limited to 1.0.)
An innite number of angles
Therefore, given a specic numeric value between -1 and +1, there are an innite number of angles whose
sine and cosine values match that numeric value and the method has no way of distinguishing between them.
Therefore, the Math.asin method returns the matching angle that is closest to zero and the Math.acos
method returns the matching positive angle that is closest to zero.
What can we learn from this?
One important thing that we can learn is there is no dierence between the sine or cosine of an angle
and the sine or cosine of a dierent angle that diers from the original angle by 360 degrees. Thus, the
Math.asin and Math.acos methods cannot be used to distinguish between angles that dier by 360
degrees. (As you learned above, the situation involving the Math.asin and Math.acos methods is even
more stringent than that.)
One-quarter cycle contains all of the information
Another thing that we can learn is that once you know the shape of the cosine curve from 0 degrees to
90 degrees, you have enough information to construct the entire cosine curve and the entire sine curve across
any range of angles. Every possible value or the negative of every possible value that can occur in a sine or
cosine curve occurs in the cosine curve between 0 degrees and 90 degrees. Furthermore, the order of those
values is also well dened.
Think about these relationships
You should think about these kinds of relationships. As I mentioned earlier, as long as we are working with
angles between 0 and 90 degrees, everything is relatively straightforward. However, once we start working
with angles between 90 degrees and 360 degrees (or greater), things become a little less straightforward.
If you have a good picture in your mind of the shape of the two curves between -360 degrees and +360
degrees, you may be able to avoid errors once you start working on physics problems that involve angles
outside the range of 0 to 90 degrees.
Quadrants
We often think of a two-dimensional space with horizontal and vertical axes and the origin at the center
in quadrants. Each quadrant is bounded by half the horizontal axis and half the vertical axis.
It is common practice to number the quadrants in counter-clockwise order with the upper-right quadrant
being quadrant 1, the upper-left quadrant being quadrant 2, the bottom-left quadrant being quadrant 3, and
the bottom-right quadrant being quadrant 4.
Angles fall in quadrants
If you measure the angle between the positive horizontal axis and a line segment that emanates from the
origin, quadrant 1 contains angles between 0 and PI/2, quadrant 2 contains the angles between PI/2 and PI,
quadrant 3 contains the angles between PI and 3*PI/2, and quadrant 4 contains the angles between 3*PI/2
and 2*PI (or zero). (Note that I didn't attempt to reconcile the inclusion of each axis in the two quadrants
on either side of the axis.)
Algebraic signs versus quadrant number
It is sometimes useful to consider how the algebraic sign of the sine, cosine, and tangent values varies
among the four quadrants. Image 15 (p. 492) contains a table that shows the sign of the sine, cosine, and
tangent values for each of the four quadrants
1 2 3 4
sine + + - -
cosine + - - +
tangent + - + -
2.38
The code in Listing 9 (p. 493) begins by dening a function named getAngle that accepts the signed values
of the adjacent side and the opposite side of the right triangle and returns the angle that the hypotenuse
makes with the positive horizontal axis.
Then the code in Listing 9 (p. 493) tests the result for four dierent triangles situated in each of the four
quadrants.
Image 16 (p. 494) shows the output produced by this script.
Start Script
adj = 3.00 opp = 4.00 units
angle = 53.13 units
adj = -3.00 opp = 4.00 units
angle = 126.87 units
adj = -3.00 opp = -4.00 units
angle = 233.13 units
adj = 3.00 opp = -4.00 units
angle = -53.13 units
2.40
This is an issue that will become important when we reach the module that deals with vectors in all four
quadrants.
Structure of the script
The script shown in Listing 9 (p. 493) begins by dening a function named getAngle . The purpose
of this function is to return an angle in degrees in the correct quadrant based on the lengths of the adjacent
and opposite sides of an enclosing right triangle. As mentioned above, the returned angle is the angle that
the hypotenuse makes with the positive horizontal axis.
An indeterminate result
The getAngle function calls the Math.atan method to compute the angle whose tangent is the ratio of
the opposite side to the adjacent side of a right triangle.
If the lengths of both the opposite and adjacent sides are zero, the ratio opposite/adjacent is indeterminate
and the value of the angle cannot be computed. In fact there is no angle corresponding to the ratio 0/0.
However, the function must either return the value of an angle, or must return some sort of ag indicating
that computation of the angle is not possible.
In this case, the function simply returns the value zero for the angle.
Avoiding division by zero
If the length of adjacent side is zero and the length of opposite side is not zero, the ratio opposite/adjacent
is innite. Therefore, the value of the angle cannot be computed. However, in this case, the angle is known
to be 90 degrees (for opposite greater than zero) or 270 degrees (-90 degrees, for opposite less than zero).
The getAngle function traps both of those cases and returns the correct angle in each case.
Correcting for the quadrant
The Math.atan method receives one parameter and it is either a positive or negative value. If the
value is positive, the method returns an angle between 0 and 90 degrees. If the value is negative, the method
returns an angle between 0 and -90 degrees. Thus, the angles returned by the Math.atan method always
lie in the rst or fourth quadrants.
(Actually, as I mentioned earlier, +90 degrees and -90 degrees are not possible because the tangent of
+90 degrees or -90 degrees is an innitely large positive or negative value. However, the method can handle
angles that are very close to +90 or -90 degrees.)
A negative opposite/adjacent ratio
If the opposite/adjacent ratio is negative, this doesn't necessarily mean that the angle lies in the fourth
quadrant. That negative ratio could result from a positive value for opposite and a negative value for
adjacent. In that case, the angle would lie in the second quadrant between 90 degrees and 180 degrees.
The getAngle function tests the signs of the values for opposite and adjacent. If the signs indicate
that the angle lies in the second quadrant, the value returned from the Math.atan method is corrected
to place the angle in the second quadrant. The corrected angle is returned by the getAngle function.
A positive opposite/adjacent ratio
Similarly, if the opposite/adjacent ratio is positive, this doesn't necessarily mean that the angle lies in
the rst quadrant. That positive ratio could result from a negative opposite value and a negative adjacent
value. In that case, the angle would lie in the third quadrant between 180 degrees and 270 degrees.
Again, the getAngle function tests the signs of the values for opposite and adjacent. If both values are
negative, the value returned from the Math.atan method is corrected to place the angle in the third quadrant.
No corrections required...
Finally, if no corrections are required for the quadrant, the getAngle function returns the value returned
by the Math.atan method. Note however, that in all cases, the Math.atan method returns the angle in
radians. That value is converted to degrees by the getAngle function and the returned value is in degrees.
Positive and negative angles
As you can see from the results of the test shown in Image 16 (p. 494) , angles in the rst, second,
and third quadrants are returned as positive angles in degrees. However, angles in the fourth quadrant are
returned as negative angles in degrees.
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.3.6 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.4.2 Preface
2.4.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 17 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
The module provides a brief tutorial on scale factors, ratios, and proportions.
2.4.2.2.1 Images
• Image 1 (p. 499) . Screen output for Listing #1.
• Image 2 (p. 500) . Screen output for Listing #2.
• Image 3 (p. 503) . Screen output for Listing #3.
2.4.2.2.2 Listings
• Listing 1 (p. 498) . Exercise on scale factors
• Listing 2 (p. 500) . Circumference is proportional to radius.
• Listing 3 (p. 502) . Area is proportional to radius squared.
Mathematical expressions are used in physics to describe relationships that are dicult to express in words.
The expressions use algebraic symbols to represent quantities that consist of numbers and units.
Measurements are important
Conclusions that are drawn in physics and other sciences ranging from chemistry to the social sciences
are often based on measurements such as length, width, weight, salinity, population, density, etc.
Each number in an equation often represents the results of a measurement, which is made in terms of a
standard. The units indicate which standard was used to make the measurements.
Knowledge of units is critical
A number that is used to indicate the result of a measurement is of little value unless we know the units
in which the measurement was made. For example, it isn't very useful to know that the length of an object
is 125 unless we know whether the units are meters, centimeters, millimeters, or miles.
The Google calculator
Although I won't go into detail in this module, I will tell you that the Google calculator is very good at
helping you to keep track of units. For example, if you enter the following expression in the Google search
box,
3 ft + 1 yd + 36 inches
The following result will be displayed immediately below the search box:
(3 ft) + (1 yd) + (36 inches) = 2.7432 meters
2.4.4 Discussion
We often express the relationship between two items using a scale factor.
2.4.4.2 Ratios
The factor is the ratio of the new value to the old value. Regarding the colt mentioned above, we might
write:
NewWeight / BirthWeight = 2
where the slash character "/" indicates division.
Percentage increases
It is also common for us to talk about something increasing or decreasing by a given percentage value.
For example, we might say that a colt increased its weight by 50-percent in one year. This is equivalent to
saying:
NewWeight = BirthWeight * (1 + 50/100)
This assumes that when evaluating a mathematical expression:
• Computations begin inside of the inner-most pair of matching parentheses and work outward from
there.
• Multiplication and division are performed before addition and subtraction are performed.
This is typical behavior for computer programs and spreadsheets, but not necessarily for hand calculators.
Percentage decreases
In my dreams, I might say that I went on a diet and my weight decreased by 25-percent in one year.
This would be equivalent to saying:
NewWeight = OldWeight * (1 - 25/100)
Exercise on scale factors
Write a script that has the following behavior. Given a chalk line that is 100 inches long, draw other
chalk lines that are:
• A. Twice the length of the original line.
• B. Twenty-ve percent of the length of the original line.
• C. Twenty-ve percent greater than the length of the original line.
• D. Twenty-ve percent less than the length of the original line.
My version of the script is shown in Listing 1 (p. 498) .
</script>
</body></html>
2.41
Screen output
When you copy the code from Listing 1 (p. 498) into an html le and open the le in your web browser,
the output text shown in Image 1 (p. 499) should appear in your browser window.
2.42
Note that although they sound similar, specications B and D above (p. 498) don't mean the same thing.
2.4.4.3 Proportions
We talk about increasing or changing a value by some factor because we can often simplify a problem by
thinking in terms of proportions.
var r = 10
var C = 2 * Math.PI * r
document.write("r =" + r +
", C = " + C + "<br/>")
</script>
</body></html>
2.43
r =10, C = 62.83185307179586
r =20, C = 125.66370614359172
r =15, C = 94.24777960769379
2.44
Image 2 (p. 500) shows the value of the circumference for three dierent values for the radius. You
should be able to conrm that the combination of the three lines of output text satisfy the proportionality
rules stated earlier (p. 499) .
For example, you can conrm these results by entering the following three expressions in the Google
search box and recording the results that appear immediately below the search box:
2*pi*10
2*pi*20
2*pi*15
Area of a circle
Before I can discuss the area of a circle, I need to dene a symbol that we can use to indicate exponen-
tiation.
• A is the area.
• PI is the mathematical constant 3.14159...
• r is the radius of the circle.
var r = 10
var A = Math.PI * Math.pow(r,2)
document.write("r =" + r +
", A = " + A + "<br/>")
</script>
</body></html>
2.45
r =10, A = 314.1592653589793
r =20, A = 1256.6370614359173
r =15, A = 706.8583470577034
Cube root of 8 = 2
2.46
An examination of the rst three lines of text in Image 3 (p. 503) should conrm that they satisfy the
proportionality rules for the square of the radius described earlier (p. 501) .
The last line of text in Image 3 (p. 503) conrms that the Math.pow method can be used to compute
roots by specifying fractional exponents as the second parameter.
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.4.6 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.5.2 Preface
2.5.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 19 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
The purpose of this module is to explain the use of scientic notation and signicant gures.
2.5.2.2.1 Images
• Image 1 (p. 508) . Examples of signicant gures.
• Image 2 (p. 509) . Screen output from Listing #1.
• Image 3 (p. 511) . Screen output from Listing #2.
• Image 4 (p. 512) . Behavior of the toPrecision method.
• Image 5 (p. 515) . Screen output from Listing #3.
2.5.2.2.2 Listings
• Listing 1 (p. 509) . An exercise involving addition.
• Listing 2 (p. 511) . An exercise involving multiplication.
• Listing 3 (p. 514) . An exercise involving combined operations.
This section will contain a discussion of accuracy, precision, scientic notation, and signicant gures.
A hypothetical experiment
Consider an experiment where a rearm is clamped into a xture, very carefully aimed at a bulls eye
on a downrange target, and red six times. (Although you may never have seen or touched a rearm, you
probably have a pretty good idea of how they behave.)
If the six holes produced by the bullets in the target fall in a tight cluster in the bulls eye, the system
can be considered to be both accurate and precise.
If all of the holes fall in the general area of the bulls eye but the cluster is not very tight, the system can
be considered to be accurate but not precise.
If all of the holes fall in a tight cluster but the cluster is some distance from the bulls eye, the system
can be considered to be precise but not accurate.
If the holes are scattered across a wide area of the target, the system can be considered to be neither
accurate nor precise.
Another use of the word precision
Another use of the word precision, which will be important in this module, is based on the concept that
the precision of a measurement describes the units that you use to measure something.
How tall are you?
For example, if you tell someone that you are about ve feet tall, that wouldn't be very precise. If you
told someone that you are 62 inches tall, that would be more precise. If you told someone that you are 62.3
inches tall, that would be even more precise, and if you told someone that you are 62.37 inches tall, that
would be very precise for a measurement of that nature.
The smaller the unit...
The smaller the unit you use to measure with, the more precise the measurement can be. For example,
assume that you measure someone's height with a measuring stick that is longer than the person is tall.
Assume also that the measuring stick is graduated only in feet. In that case, the best that you could hope
for would be to get the measurement correct to the nearest foot and perhaps estimate a second digit to the
nearest tenth of a foot.
One-inch graduations
On the other hand, if the measuring stick is graduated in inches and you are careful, you should be able
to get the measurement correct to the nearest inch and perhaps estimate another digit to the nearest tenth
of an inch. The second measurement using the one-inch graduations would be more precise than the rst
using the one-foot graduations.
Diminishing returns
If the measuring stick were graduated in tenth-inch units, however, that may or may not lead to a more
precise measurement. That would be approaching the point of diminishing returns where your inability to
take full advantage of the more precise graduations and the inability of the subject to always stand with the
same degree of rigidity might come into play.
• -6.57 * 10^4
• -65.7 * 10^3
• -657 * 10^2
20 http://en.wikipedia.org/wiki/Scientic_notation
In normalized scientic notation, the exponent is chosen such that the absolute value of the mantissa is at
least one but less than ten. For example, -65700 is written:
-6.57 * 10^4
In normalized notation the exponent is negative for a number with absolute value between 0 and 1. For
example, the value 0.00657 would be written:
6.57 * 10^(-3)
The 10 and the exponent are usually omitted when the exponent is 0.
• Leading zeros where they serve merely as placeholders to indicate the scale of the number (.00356 for
example).
• Spurious digits introduced, for example, by calculations carried out to greater accuracy than that of
the original data, or measurements reported to a greater precision than the equipment supports.
A popular physics textbook provides a more complete set of rules for identifying the signicant gures in a
number:
1. 409.8 4 4.098e+2
2. 0.058700 5 5.87e-2
3. 9500 ambiguous 9.5e+3
4. 950.0 * 10^1 4 9.5e+3
2.47
Note that the default JavaScript exponential representation fails to display the signicant trailing zeros for
the numbers on row 2 and row 5. I will show you some ways that you may be able to deal with this issue
later but you may not nd them to be very straightforward.
Beyond knowing about scientic notation and signicant gures from a formatting viewpoint, you need to
know how to perform arithmetic while satisfying the rules for scientic notation and signicant gures.
Performing arithmetic involves three main rules :
1. For addition and subtraction, the nal result should be rounded so as to have the same number of
decimal places as the number that was included in the sum that has the smallest number of decimal
places. In accordance with the discussion early in this module, this is the least precise number.
2. For multiplication and division, the nal result should be rounded to have the same number of signif-
icant gures as the number that was included in the product with the smallest number of signicant
gures.
3. The two rules listed above should not be applied to intermediate calculations. For intermediate cal-
culations, keep as many digits as practical. Round to the correct number of signicant gures or the
correct number of decimal places in the nal result.
</script>
</body></html>
2.48
Screen output
When you open the html le in your browser, the text shown in Image 2 (p. 509) should appear in your
browser.
sum = 554.30656
round = 554.31
The End
2.49
The code in Listing 1 (p. 509) begins by declaring three variables named a , b , and c , adding
them together, and displaying the sum in the JavaScript default format in the browser window.
Too many decimal digits
As you can see from the rst line in Image 2 (p. 509) , the result is computed and displayed with eight
decimal digits, ve of which are to the right of the decimal point. We know, however, from rule #1 (p. 508)
, that we should present the result rounded to a precision of two digits to the right of the decimal point in
order to match the least precise of the numbers included in the sum. In this case, the value stored in the
variable named a is the least precise.
Correct the problem
The code in Listing 1 (p. 509) calls a method named toFixed on the value stored in the variable sum
passing a value of 2 as a parameter to the method. This method returns the value from sum rounded to
two decimal digits. The returned value is stored in the variable named round . Then the script displays
that value as the second line of text in Image 2 (p. 509) .
The output text that reads "The End"
There is a downside to using JavaScript (as opposed to other programming languages such as Java).
By default, if there is a coding error in your script, there is no indication of the error in the output in the
main browser window. Instead, the browser simply refuses to display some or all of the output that you are
expecting to see.
Put a marker at the end
Writing the script in such a way that a known line of text, such as "The End" will appear following all
of the other output won't solve coding errors. However, if it doesn't appear, you will know that there is a
coding error and some or all of the output text may be missing.
JavaScript and error consoles
I explained how you can open a JavaScript console in the Google Chrome browser or an error console
in the Firefox browser in an earlier module. While the diagnostic information provided in those consoles
is limited, it will usually indicate the line number in the source code where the programming error was
detected. Knowing the line number will help you examine the code and x the error.
An exercise involving multiplication
Please copy the code shown in Listing 2 (p. 511) into an html le and open it in your browser.
</script>
</body></html>
2.50
product = 232.39900552679998
rounded = 232.40
The End
2.51
The code in Listing 2 (p. 511) begins by declaring three variables named a , b , and c , multiplying
them together, and displaying the product in the browser window. Each of the factors in the product have
a dierent number of signicant gures, with the factor of value 169.01 having the least number (5) of
signicant gures. We know from rule #2 (p. 508) , therefore, that we need to present the result rounded
to ve signicant gures.
The toPrecision method
Listing 2 (p. 511) calls a method named toPrecision on the variable named product , passing the
desired number of signicant gures (5) as a parameter. The method rounds the value stored in product
to the desired number of digits and returns the result, which is stored in the variable named rounded .
Then the contents of the variable named rounded are displayed, producing the second line of text in
Image 3 (p. 511) .
What about other parameter values
Note that the method named toPrecision knows nothing about signicant gures. It was up to me to
gure out the desired number of signicant gures in advance and to pass that value as a parameter to the
method.
Although this has nothing to do with signicant gures, it may be instructive to examine the behavior
of the method named toPrecision for several dierent parameter values.
Image 4 (p. 512) shows the result of replacing the parameter value of 5 in the call to the toPrecision
method with the values in the rst column of Image 4 (p. 512) and displaying the value returned by the
method.
1 rounded = 2e+2
2 rounded = 2.3e+2
3 rounded = 232
4 rounded = 232.4
5 rounded = 232.40
6 rounded = 232.399
7 rounded = 232.3990
10 rounded = 232.3990055
15 rounded = 232.399005526800
20 rounded = 232.39900552679998214
2.52
I have found two procedures documented on the web that seem to be somewhat contradictory. Both
sources seem to say that you should perform the addition and/or subtraction rst and that you should apply
rule #1 (p. 508) to the results. However, they dier with regard to how stringently you apply that rule
before moving on to the multiplication and/or division.
The more stringent procedure
One source seems to suggest that you should round the results of the addition and/or subtraction ac-
cording to rule #1 (p. 508) and replace the addition or subtraction expression in your overall expression
with the rounded result. Using that approach, you simply create one the factors that will be used later in
the multiplication and/or division. That factor has a well-dened number of signicant gures.
Then you proceed with the multiplication and/or division and adjust the number of signicant gures in
the nal result according to rule #2 (p. 508) .
The less stringent procedure
The other source seems to suggest that you mentally round the results of the addition and/or subtraction
according to rule #1 (p. 508) and make a note of the number of signicant gures that would result if you
were to actually round the result. However, you should not actually round the result at that point in time.
In other words, you should use the raw result of the addition and/or subtraction as a factor in the upcoming
multiplication and/or division knowing that you may be carrying excess precision according to rule #1 (p.
508) .
Then you proceed with the multiplication and/or division and adjust the number of signicant gures in
the nal result according to rule #2 (p. 508) . However, when you adjust the number of signicant gures,
you should include the number of signicant gures from your note in the decision process. If that is the
smallest number of signicant gures of all the factors, you should use it as the number of signicant gures
for the nal result.
An exercise involving combined operations
Evaluate the following expression and display the nal result with the correct number of signicant
gures.
(169.01 + 3294.6372) * (0.00365 - 29.333)
Please copy the code from Listing 3 (p. 514) into an html le and open it in your browser.
</script>
</body></html>
2.53
When you open your html le in your browser, the text shown in Image 5 (p. 515) should appear in the
browser window.
aSum = 3463.65
bDiff = -29.329
product = -101585.39085000001
final = -1.0159e+5
The End
2.54
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.5.6 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.6.2 Preface
2.6.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
23 This content is available online at <http://cnx.org/content/m45005/1.2/>.
GAME 2302-0100: Introduction 24 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
The purpose of this module is to explain units and dimensional analysis.
2.6.2.2.1 Images
• Image 1 (p. 518) . Single-line format.
• Image 2 (p. 519) . SI base units.
• Image 3 (p. 520) . Examples of SI derived units.
• Image 4 (p. 520) . A sampling of SI prexes.
• Image 5 (p. 525) . Screen output for Listing #1.
• Image 6 (p. 529) . Screen output for Listing #2.
• Image 7 (p. 531) . Screen output for Listing #3.
• Image 8 (p. 532) . The trajectory of the falling rock.
2.6.2.2.2 Listings
• Listing 1 (p. 524) . Convert from paces to miles.
• Listing 2 (p. 528) . Free fall exercise.
• Listing 3 (p. 530) . A plotting exercise.
As a young engineering student many years ago, I was told that when evaluating mathematical expressions,
I should always embed the units in the expression, manipulate them algebraically, and conrm that the units
that survive until the end of the evaluation are correct relative to the problem specications.
Three good reasons
There are at least three good reasons for following this procedure:
• It shows what the units of the result are. A common mistake is to get the correct numerical result of
a calculation but to write it with the wrong units.
• It shows where unit conversions must be performed. If units that should have canceled do not cancel,
we need to go back and perform the necessary conversions. For example, when a speed in miles per
hour is being calculated and the result comes out with units of miles per second, we should convert
seconds to hours.
• It helps to locate mistakes. If a velocity (meters per second) is being calculated and the units come
out as seconds per meter, we know to look for an error.
Single-line format
Image 1 (p. 518) shows multiplication and division of fractions in a single-line format similar to how we
write expressions in computer programs.
2.55
Expressions in this format may be more dicult for people to work with than the multiple line format
described above. With enough time and practice, I might become almost as procient in evaluating expres-
sions as shown in Image 1 (p. 518) as in evaluating expressions in a multiple-line format, but I'm afraid that
I would need a lot of time and a lot of practice to achieve that prociency.
We must work with what we are given
However, we must work with what we are given so the mathematical expressions in this module (and
most of the other modules as well) will mostly be presented in a single-line format. The good news is that
the single-line format can usually be easily translated into a format that is suitable for evaluation using
JavaScript and other programming languages.
2.6.3.3 SI units
The discrepancy between the pronunciation of the unit foot and its plural feet is an example of the need
for more consistency in the use of units. Many physics books use a system of units called SI units . SI is
an abbreviation for a French name, which I am unable to pronounce.
I won't attempt to explain much about SI units. You can probably Google SI units and nd hundreds of
web pages that explain the system in varying levels of detail.
Tables of SI units
Most of those references will probably also provide tables for the units. I will also attempt to provide
tables in Image 2 (p. 519) and Image 3 (p. 520) .
Don't ignore the details
Note, however, that you should not ignore the online SI-unit tables altogether. They are likely to contain
important information that I won't reproduce here, such as the fact that the meter is a unit of length and
its value is the length of the path travelled by light in a vacuum during a time interval of 1/299792458 of a
second .
Base units and derived units
When reading about SI units, you will nd that they are often divided into base units and derived units.
I will put the base units in Image 2 (p. 519) and some sample derived units in Image 3 (p. 520) .
length meter m
mass kilogram kg
time second s
electric current ampere A
thermodynamic temperature kelvin K
amount of substance mole mol
luminous intensity candela cd
2.56
Note that the list of derived units in Image 3 (p. 520) is only a sampling of dierent units that can be
derived from the base units.
The exponentiation indicator
As is the case throughout these modules, the character "^" that you see used extensively in Image 3
(p. 520) indicates that the character following the ^ is an exponent. Note also that when the exponent is
negative, it is enclosed along with its minus sign in parentheses for clarity.
2.57
peta-(P) 10^15
tera-(T) 10^12
giga-(G) 10^9
mega-(M) 10^6
kilo-(k) 10^3
deci-(d) 10^(-1)
centi-(c) 10^(-2)
milli-(m) 10^(-3)
micro-(Greek letter mu) 10^(-6)
nano-(n) 10^(-9)
pico-(p) 10^(-12)
femto-(f) 10^(-15)
2.58
There are many dierent units that are used to express length, for example, such as foot, mile, meter,
inch, etc.
Because they all have dimensions of length, you can convert from one to another. For example one mile
is equal to 5280 feet.
Cannot convert between units of dierent dimensions
When evaluating mathematical expressions, we can add, subtract, or equate quantities only if they have
the same dimensions (although they may not necessarily be given in the same units). For example, it is
possible to add 3 meters to 2 inches (after converting units), but it is not possible to add 3 meters to 2
kilograms.
To analyze dimensions, you should treat them as algebraic quantities using the same procedures that we
will use in the upcoming exercise on manually converting units.
Let's work through an exercise manually to determine the distance from your home to your school in miles
given that we know the distance in paces. (I will convert this to a JavaScript script later in the module.)
As we discussed earlier, you have already determined that the distance from your home to your school
is 2112 paces. We have also recognized that the length of one of your paces is likely to be dierent from the
length of someone else's paces.
So now we know that on the average, each time you execute one pace, you have moved your body forward
by 30 inches. The next task is to determine how far you have moved your body when you have executed
2112 paces (the distance from home to school measured in paces).
Convert from paces to inches
We can begin by determining the distance from home to school in inches as follows:
distance = (2112*pace) * (30*inch/pace)
A review of algebra
At this point, let's review a little algebra:
Given the expression: ((w/x)*(y/z))
we can rewrite this as
(w*y)/(x*z)
Given this expression, we can reverse the process by rearranging and factoring out the terms producing
our original expression:
((w/x)*(y/z))
An algebraic manipulation
We determined earlier that
distance = (2112*pace) * (30*inch/pace)
Applying the algebraic process shown above to the problem at hand, we can rearrange terms and factor
our expression to produce
distance = (2112 * 30 * pace * inch)/pace
The distance in inches
At this point, we have a fraction that contains the unit pace in both the numerator and the denominator.
We can cancel those two terms leaving us with
distance = (2112 * 30 * inch) = 63360 * inch
So good so far. We now know the distance from home to school as expressed in units of inches (even
though the original measurement was made in paces and not in inches). The distance hasn't changed. What
has changed is the units in which we are expressing that distance.
Still not what we are looking for
While this is interesting, it still isn't what we are looking for. We want to know the distance in miles.
Therefore, we need to convert the distance in inches to the distance in miles.
How many inches are in a mile?
At this point, we don't know how many inches are in a mile (but we could calculate it if we wanted to).
However, we do know how many inches are in a foot and we know how many feet are in a mile.
A conversion factor for inches to feet
For starters, lets calculate a factor that we can use to convert from inches to feet. We know that
12*inches = 1*foot
If we divide each side by 12*inches, we get
1 = 1*foot/12*inches
Let's refer to this as a conversion factor
Multiplication by 1
Since the expression on the right side is equal to 1, we can multiply any expression in an equation with
the conversion factor
1*foot/12*inches
without changing the intrinsic value of that expression. (Once again, although we won't be changing the
intrinsic value of the expression, we may cause that intrinsic value to be expressed in dierent units.)
We can use this conversion factor to convert a distance value expressed in inches into the value for the
same distance expressed in feet.
A conversion factor for feet to inches
We could also use the reciprocal of the expression to convert a distance value expressed in feet into the
value for the same distance expressed in inches. I will have more to say on this later.
A conversion factor for feet to miles
Please copy the code from Listing 1 (p. 524) into an html le and open the le in your browser.
document.write(
"d = " + d + " paces" + "<br/>")
//pace*inch/pace = inch
var d = d *f1 //distance, units = inches
document.write(
"d = " + d + " inches" + "<br/>")
//inch*feet/inch = feet
var d = d *f2 //distance, units = feet
document.write(
"d = " + d + " feet" + "<br/>")
//feet*mile/feet = mile
var d = d *f3 //distance, units = miles
document.write(
"d = " + d + " mile" + "<br/>")
//miles*paces/mile = paces
var d = d *f4 //distance, units = paces
document.write(
"d = " + d + " paces" + "<br/>")
document.write("TheAvailable
End") for free at Connexions <http://cnx.org/content/col11450/1.29>
>/script >
>/body /html >
525
Screen output
When you open the html le in your browser, the text shown in Image 5 (p. 525) should appear in your
browser window.
d = 2112 paces
f1 =30 inches/pace
d = 63360 inches
f2 = 0.08333333333333333 feet/inch
d = 5280 feet
f3 = 0.0001893939393939394 miles/foot
d = 1 mile
f4 = 2112 paces/mile
d = 2112 paces
The End
2.60
That conversion factor was applied to the distance expressed in miles to produce the same distance
expressed in paces. As you might have guessed, this value of 2112 paces shown near the end of Image 5 (p.
525) matches the value shown at the beginning of Image 5 (p. 525) .
Analysis of the script
Now lets analyze the script code in Listing 1 (p. 524) that produced the text output shown in Image 5
(p. 525) .
Listing 1 (p. 524) begins by declaring and initializing the variables d , d2 , and d3 , which are
respectively,
Various values are displayed as the script executes using calls to the document.write method. You should
have no diculty identify the code that displays the values, so I will skip over that code in this discussion.
Compute, save, and apply the conversion factor f1
Then Listing 1 (p. 524) declares a variable named f1 and populates it with the value of a conversion
factor that can be used to convert paces to inches. This conversion factor is computed from the known
relationship between paces and inches mentioned earlier.
The conversion factor named f1 is applied to the distance in paces converting it to a value that represents
the same distance in inches (63360 inches).
Analysis of the units
The comment that reads
//pace*inch/pace = inch
is an analysis that shows the units that will result from applying the conversion factor to the distance at
this point. As you can see, the pace terms will cancel and the result will be in inches.
Compute, save, and apply the conversion factor f2
Following that, a conversion factor named f2 is computed that can be used to convert a value expressed
in inches to the same value expressed in feet. This conversion factor is based on the known fact that there
are 12 inches in a foot.
The factor named f2 is applied to the distance that is now expressed in inches converting it to a new
value that expresses the same distance in feet (5280 feet).
Analysis of the units
The comment that reads
//inch*feet/inch = feet
is an analysis that shows the units that will result from applying the conversion factor to the distance at
this point. As you can see, the inch terms will cancel and the result will be in feet.
Compute, save, and apply the conversion factor f3
Following that, a conversion factor named f3 is computed that can be used to convert a value expressed
in feet to the same value expressed in miles. This conversion factor is based on the known fact that there
are 5280 feet in a mile.
The factor named f3 is applied to the distance that is now expressed in feet converting it to a new value
that expresses the same distance in miles (1 mile).
Analysis of the units
The comment that reads
//feet*mile/feet = mile
is an analysis that shows the units that will result from applying the conversion factor to the distance at
this point. As you can see, the feet terms will cancel and the result will be in miles.
That satises the specications
That satises the original program specication. However, I mentioned earlier that if a conversion factor
X can be used to convert from A-units to B-units, the reciprocal of X can be used to convert from B-units
back to A-units.
Reversing the process
document.write("<br/>The End")
>/script<>/body<>/html<
2.61
Screen output
When you open the html le in your browser, the text shown in Image 6 (p. 529) should appear in your
browser window.
At 10 seconds:
distance traveled = -1609 feet
height = 8391 feet
At 20 seconds:
distance traveled = -6435 feet
height = 3565 feet
The End
2.62
As you can see from Image 6 (p. 529) , after ten seconds, the rock will have traveled a distance of -1609
feet. (The minus sign indicates downward motion.)
Adding this value to the initial height of 10000 feet produces a value of 8391 for the height of the rock
at the end of 10 seconds.
Similarly, Image 6 (p. 529) gives us 3565 for the height of the rock at 20 seconds.
Analysis of the code
The code in Listing 2 (p. 528) begins by dening a function that computes and returns the distance
traveled for a rock falling toward the earth for a given time interval since release assuming that the initial
velocity was zero (the rock was simply dropped).
This function implements the equation (p. 527) shown earlier, and expects to receive the time as an
input parameter. It returns the distance traveled during that time interval.
Note that the interaction of units is shown in the comments with the result that the returned value is in
feet.
Call the function twice in succession
Then the code calls that function twice in succession for two dierent time intervals (10 seconds and 20
seconds) to determine the distance traveled during each time interval.
In both cases, the distance traveled is added to the initial height of 10000 feet to determine the height of
the rock at the end of the time interval.
Also, in both cases, the time interval, the distance traveled, and the resulting height of the rock above
the ground are displayed as shown in Image 6 (p. 529) .
Note again that in all cases, the interactions of the various units are shown in the comments.
document.write("<br/>The End")
</script/body/html<
2.63
The End
2.64
2.65
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.6.6 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.7.2 Preface
2.7.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 26 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
The purpose of this module is to introduce motion and to explain displacement and vector analysis.
2.7.2.2.1 Images
• Image 1 (p. 537) . A graphic showing displacement.
• Image 2 (p. 539) . Vector diagram for a familiar example.
• Image 3 (p. 542) . A triangle with sides of 30, 40, and ?.
• Image 4 (p. 544) . Vector diagram for the sum of six vectors.
• Image 5 (p. 546) . Illustration of the parallelogram law.
• Image 6 (p. 550) . Screen output for Listing #1.
• Image 7 (p. 553) . Screen output for Listing #2.
• Image 8 (p. 556) . Screen output for Listing #3.
2.7.2.2.2 Listings
• Listing 1 (p. 549) . Using the Math.atan method.
• Listing 2 (p. 552) . The sum of two vectors.
• Listing 3 (p. 555) . The sum of four vectors.
2.7.4.1 Displacement
As mentioned above, if one body is moved with respect to another body, either one of them may be said to
have experienced a displacement .
Displacement is not the same as distance
Assume, for example, that you go to the local high school and run ve laps around the track, stopping
exactly where you started. The distance that you have run will be the length of the path that you followed
while running. However, while you may be completely out of breath by that point in time, the magnitude
of your displacement will have been zero.
Scalars versus vectors
Distance is a scalar quantity, while displacement is a vector quantity. Scalar quantities have only
magnitude, such as three kilometers.
Vector quantities have two parts: magnitude and direction . For example, you might describe a
vector quantity as having a magnitude of three kilometers and a direction of northwest.
Magnitude and direction
A displacement vector must have both magnitude and direction. For example, if you were to run about
three-fourths of the way around the track, the distance that you ran would be the length of your path.
However, the magnitude of your displacement would be the straight-line distance from your starting point
to your stopping point.
The direction of your displacement would be an angle measured between some reference (such as due
east, for example) and an imaginary line connecting your starting point and your stopping point.
If you stop where you start...
Getting back to the original proposition, if your stopping point is exactly the same as your starting point,
the magnitude of your displacement vector will be zero and the angle of your displacement vector will be
indeterminate.
Vector notation
Assume that there are three spots marked on the top of a table as A, B, and C. If an object is moved
from A to B and then from B to C, using vectors, it may be stated that:
vecAC = vecAB + vecBC
where vecAB, vecBC, and vecAC represent vectors.
Typical notation
A typical notation for a vector in a physics textbook is something like AB, possibly in boldface and/or
italics, with a small arrow drawn above the two letters. However, there is no such small arrow on a QWERTY
keyboard, making it very dicult for me to reproduce in these modules.
My alternative notation
Therefore, in these physics modules, I will use the following notation
vecAB
to indicate a vector extending from the spot labeled A to the spot labeled B.
In order to determine direction in an unambiguous way, you often need to know where the vector starts
(the tail) and where it ends (the head). The notation used above indicates that the tail of the vector is at
A and the head is at B.
In some cases, particularly in JavaScript code where a vector is dened by magnitude and direction
instead of by a starting point and an ending point, I will refer to a vector simply as
vecA, vecB, etc.
A graphic illustrating displacement
Image 1 (p. 537) is a graphic that illustrates displacement.
2.66
The triangle shown in Image 1 (p. 537) is a physical representation of the vector equation
vecAC = vecAB + vecBC
As usual, please ignore the lower-case letters scattered throughout the image, which were placed there
for a purpose other than for use in this module.
What does this mean?
This vector equation does not mean that the algebraic sum of two sides of the triangle are equal to the
third side. However, it does mean that the displacement vecAB together with the displacement vecBC, have
an eect that is equivalent to the single displacement vector vecAC.
Scalar addition and subtraction
When adding or subtracting scalars, you only need to take the magnitude values of the scalars into
account and perform normal arithmetic using those magnitude values. An example would be to add 6 birds
and 5 birds to produce a sum of 11 birds.
Vector addition and subtraction
However, when adding or subtracting vectors, you not only need to take the magnitude of the vectors
into account, you also need to take the directions of the vectors into account.
A thought exercise
Image 2 (p. 539) shows the vector diagram for a familiar example.
2.67
Pretend that you are standing at point A in Image 2 (p. 539) . Then pretend that you walk 30 meters
due east and designate that location as point B.
Up to this point, your displacement can be represented by vecAB with a magnitude of 30 and an angle
of zero (assuming that due east represents an angle of zero).
Walk 40 meters due north
Now pretend that you walk 40 meters due north and mentally designate the stopping point as C. Your
displacement relative to point B can be represented as vecBC with a magnitude of 40 meters and a direction
of north or 90 degrees.
Displacement relative to point A
The interesting question is, what is your displacement relative to your starting point at A?
The displacement vector vecAC is the straight line from point A to point C, pointing in a direction from
A to C. This vector is shown in the vector equation
vecAC = vecAB + vecBC
as the sum of the two vectors that describe the two segments of your journey from A to C.
Graphical addition of vectors
This process of connecting two or more vectors tail-to-head in sequence and then measuring the distance
and direction from the tail of the rst vector to the head of the last vector is known as the graphical addition
of vectors . The resulting vector (in this case vecAC) is known as the sum of the vectors that make up the
sequence. (The resulting vector is often called the resultant.)
A 3-4-5 triangle
Recalling what we learned in an earlier module where I discussed a 3-4-5 triangle, the magnitude of the
vector from A to C (the hypotenuse of a right triangle with sides of 30 and 40) is 50 meters. You may also
recall that the angle is approximately 53 degrees relative to the horizontal (east-west) line.
You should be able to measure the length of vecAC as well as the angle between that vector and the
horizontal in Image 2 (p. 539) and get reasonable agreement with the above.
No requirement for a right triangle
While this example is based on a right triangle, that is not a requirement for adding vectors. I chose a
3-4-5 right triangle for the example because I knew what the answer would be in advance and also because
it should have been familiar to you.
Graphic representation of vectors
Many problems in kinematics and kinetics can be solved graphically using a graphical representation of
vectors.
Vectors are typically drawn as a heavy line between two points with an arrow head at one end and nothing
in particular at the other end. The end with the arrow head is commonly called the head of the vector and
the other end is commonly called the tail.
Somewhat inconvenient
Drawing vectors on graph paper can be inconvenient, particularly if you don't have graph paper available.
Fortunately, as you will soon learn, it isn't necessary to use graphics to solve vector problems. You can also
solve such problems mathematically, which will often be the better choice.
and assume that the magnitude of vecAB is 30 and the magnitude of vecBC is 40. The sum of those two
vectors (vecAC) can have a magnitude ranging anywhere from 10 to 70 depending on the relative angles of
vecAB and vecBC.
A triangle with sides of 30, 4 0, and ?
Consider the triangle shown in Image 3 (p. 542) .
2.68
Pretend that instead of walking due north from point B as shown in Image 2 (p. 539) , you change
direction and walk northwest (135 degrees relative to the east-west horizontal line with east being zero
degrees) keeping the length at 40 meters.
What happened to the displacement?
What is the displacement of the point C relative to the point A? I can't do the arithmetic in my head
for this problem, but I can measure the length of vecAC to be about 28 meters and the angle of vecAC to
be a little less than 90 degrees. (I will show you how to write a script to solve this problem mathematically
later.)
Any number of displacements can be added
There is no limit to the number of displacement vectors that can be added in this manner. For example,
pretend that you walk from point A,
2.69
The displacement in Image 4 (p. 544) is the vector with its tail at A and its head at G, which you could
measure with a measuring stick and a protractor.
Can be extended to three (or more) dimensions
The physics textbook titled College Physics by Mendenhall, Eve, Keys, and Sutton contains the following
example.
"If a man climbs up the mast of a ship sailing east while the tide caries it south, then that sailor may
have three displacements at right angles, vecAB 30 feet upward, vecBC 100 feet eastward, vecCD 20 feet
southward, all with respect to the bed of the ocean. The three displacements vecAB, vecBC, and vecCD
are equivalent to the single displacement vecAD; and in the same way, any number of displacements may be
added together."
Dicult to draw
Of course, we can't easily draw that 3D vector diagram on a at sheet of paper or construct it on a at
computer monitor, but we can solve for the displacement vecAD if we are familiar with computations in
three dimensions. (An explanation of 3D computations is beyond the scope of this module.)
The parallelogram law
There is a law that states:
The sum of two vectors in a plane is represented by the diagonal of a parallelogram whose adjacent sides
represent the two vector quantities.
The resultant
As I mentioned earlier, the sum of two or more vectors is called their resultant .
In general, the resultant is not simply the algebraic or arithmetic sum of the vector magnitudes. Instead,
in our original vector equation
vecAC = vecAB + vecBC
vecAC is the resultant of the sum of vecAB and vecBC in the sense that a single vector vecAC would
have the same eect as vecAB and vecAD acting jointly.
Geometrical addition
The parallelogram law is a form of geometrical addition. In engineering and physics, it is often used to
nd graphical solutions to problems involving forces, velocities, displacements, accelerations, electric elds,
and other directed quantities. (Directed quantities have both magnitude and direction.)
Solving a vector problem with a parallelogram
Pretend that you walk from point A
Let's use a vector diagram and the parallelogram law to nd the resultant displacement vector vecAC.
Image 5 (p. 546) illustrates the use of the parallelogram law to nd a graphical solution to this problem.
2.70
where
• angle is the angle that the vector makes relative to the horizontal axis.
• vecABh, vecABv, and vecABmag are respectively the horizontal component, the vertical component,
and the magnitude of the vector vecAB
The angle that the resultant vector makes with the horizontal axis is the arctangent (corrected for
quadrant) of the ratio of the vertical component to the horizontal component.
document.write("The End")
</script>
</body></html>
2.71
angle = 0.0
angle = 30.0
angle = 60.0
angle = 90.0
angle = 120.0
angle = 150.0
angle = 180.0
angle = 210.0
angle = 240.0
angle = 270.0
angle = -60.0
angle = -30.0
angle = -0.0
The End
2.72
+90 degrees or -90 degrees is an innitely large positive or negative value. However, the method can handle
angles that are very close to +90 or -90 degrees.)
A negative y/x ratio
If the y/x ratio is negative, this doesn't necessarily mean that the angle lies in the fourth quadrant. That
negative ratio could result from a positive value for y and a negative value for x. In that case, the angle
would lie in the second quadrant between 90 degrees and 180 degrees.
The getAngle function tests the signs of the values for y and x. If the signs indicate that the angle lies
in the second quadrant, the value returned from the Math.atan method is corrected to place the angle in
the second quadrant. The corrected angle is returned by the getAngle function.
A positive y/x ratio
Similarly, if the y/x ratio is positive, this doesn't necessarily mean that the angle lies in the rst quadrant.
That positive ratio could result from a negative y value and a negative x value. In that case, the angle would
lie in the third quadrant between 180 degrees and 270 degrees.
Again, the getAngle function tests the signs of the values for y and x. If both values are negative, the
value returned from the Math.atan method is corrected to place the angle in the third quadrant.
No corrections required...
Finally, if no corrections are required for the quadrant, the getAngle function returns the value returned
by the Math.atan method. Note however, that in all cases, the Math.atan method returns the angle in
radians. That value is converted to degrees by the getAngle function and the returned value is in degrees.
Positive and negative angles
As you can see from the results of the test shown in Image 6 (p. 550) , angles in the rst, second,
and third quadrants are returned as positive angles in degrees. However, angles in the fourth quadrant are
returned as negative angles in degrees.
Screen output
When you open the html le in your browser, the text shown in Image 7 (p. 553) should appear in your
browser window.
2.74
• Add the horizontal components of all the vectors to get the horizontal component of the resultant
vector.
• Add the vertical components of all the vectors to get the vertical component of the resultant vector.
• Compute the magnitude (if needed) of the resultant vector as the square root of the sum of the
squares of the horizontal and vertical components.
• Compute the angle (if needed) of the resultant vector as the arctangent of the ratio of the vertical
component and the horizontal component.
Listing 2 (p. 552) computes the sum of the horizontal components from each of the vectors and saves the
result in the variable named vecResultH . Then it computes the sum of the vertical components and
saves the result in the variable named vecResultV .
Compute the magnitude of the resultant
In many cases, simply knowing the horizontal and vertical components is the solution to the problem.
However, in some cases, it is necessary to convert those components into a magnitude and an angle.
There are a couple of ways to compute the magnitude. One way is to use the Pythagorean theorem as
described above (p. 553) to compute the square root of the sum of the squares of the horizontal and vertical
components.
• 12 meters at 20 degrees
• 8 meters at 120 degrees
• 10.5 meters at -74 degrees
• 12.5 meters at 145 degrees
var vecBmag = 8;
var vecBang = 120*Math.PI/180;//degrees*radians/degrees=radians
Screen output
The text shown in Image 8 (p. 556) should appear in your browser when you open the html le in your
browser.
2.76
As you can see, the displacement vector is just a little over eight meters at an angle of about 90.5 degrees.
In other words, your ending position was approximately 8 meters north of your starting position. Hopefully
you were able to arrive at a very similar answer using vector diagram.
Explanation of the code
The code in Listing 3 (p. 555) is very similar to the code in Listing 2 (p. 552) . However, there is more
of it because the code is adding four vectors instead of only 2.
As before, Listing 3 (p. 555) begins with the getAngle method that we developed earlier.
Magnitude and angle for each vector
Then Listing 3 (p. 555) denes eight variables containing the magnitudes and angles of the four segments
of the walk.
(Note that the names that I used for the variables in this script are somewhat simpler than the names
that I used in Listing 2 (p. 552) .)
Horizontal and vertical components
Following that, Listing 3 (p. 555) computes the horizontal and vertical components for each of the four
vectors and saves those values in eight dierent variables.
Sums of components
Then Listing 3 (p. 555) computes and saves the sum of all four horizontal components and computes
and saves the sum of all four vertical components.
After that, there is essentially no dierence between the script in Listing 3 (p. 555) and the script in
Listing 2 (p. 552) .
Other vector operations
In addition to the addition and subtraction of vectors, there are other operations that can be performed
using vectors, such as the dot product and the cross product. However, those operations are beyond the
scope of this module.
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.7.6 Miscellaneous
note: Financial : Although the Connexions site makes it possible for you to download a
PDF le for this module at no charge, and also makes it possible for you to purchase a pre-printed
version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.8.2 Preface
2.8.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 28 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
The purpose of this module is to explain uniform velocity and relative velocity.
2.8.2.2.1 Images
• Image 1 (p. 560) . Screen output for Listing #1.
• Image 2 (p. 562) . Vector diagram for the hockey puck.
• Image 3 (p. 565) . Screen output for Listing #2.
• Image 4 (p. 567) . Vector diagram for a man on a train.
• Image 5 (p. 569) . Screen output for Listing #3.
• Image 6 (p. 572) . Another vector diagram for a man on a train
• Image 7 (p. 573) . Screen output for Exercise #2 for a man on a train.
• Image 8 (p. 574) . Vector diagram for man on aircraft carrier.
• Image 9 (p. 576) . Screen output for Listing #4.
2.8.2.2.2 Listings
• Listing 1 (p. 560) . A simple exercise on uniform velocity.
• Listing 2 (p. 564) . An exercise on average velocity.
• Listing 3 (p. 568) . Exercise #1 for a man on a train.
• Listing 4 (p. 575) . An exercise with three vectors in a plane.
What is velocity?
Velocity is the time rate of change of position . Since displacement is the change of position, velocity
is also the rate of displacement . Since displacement is a vector quantity, velocity is also a vector quantity
it has magnitude and direction.
An airplane may traverse 350 miles in a northeasterly direction in one hour. This statement describes a
vector quantity (velocity) because it has both magnitude and direction.
The same airplane may traverse 350 miles in a southwesterly direction in one hour. This statement
describes a dierent velocity. Even though the magnitude is the same in both cases, the direction is dierent.
Hence, the velocity is dierent.
What is speed?
Speed is distance covered in a unit of time without reference to direction. Since there is no reference to
direction, speed is a scalar quantity.
A car may traverse 60 miles in one hour. An airplane may traverse 350 miles in one hour. An excellent
runner may traverse one mile in three minutes. All of these statements describe scalar quantities (speed)
since there is no reference to direction.
28 http://cnx.org/content/m44983/latest
A person in a seat on a Ferris wheel may travel around the axle in the center of the wheel at a constant
rotational speed. However, that person's velocity is not constant. The velocity is continually changing
because the direction of motion is continually changing.
Uniform velocity
Velocity is uniform when equal distances along a straight line are traversed in equal intervals of time. In
this case
v = s/t
where
• v is uniform velocity
• s is the distance traveled (displacement)
• t is an interval of time
Units of velocity
The units of velocity are units of distance (such as meters) divided by units of time (such as seconds).
</script>
</body></html>
Screen output
The text shown in Image 1 (p. 560) should appear in your browser window when you open the html le
in your browser.
Start Script
speed = 350 miles/hour
distance = 700 miles
time = 2 hours
End Script
• v is uniform velocity
• s is the distance traveled
• t is an interval of time
• What is the time required for the puck to complete each leg of its journey?
• What is the average velocity of the puck from the start to the end of its journey?
Screen output
The text shown in Image 3 (p. 565) should appear in your browser window when the html le is opened
in your browser.
Start Script
Time for leg A = 0.30 seconds
Time for leg B = 0.33 seconds
Displacement magnitude = 25.00 feet
Displacement angle = 98.13 degrees
Total time = 0.63 seconds
Average velocity magnitude = 39.47 feet/second
Average velocity angle = 98.13 degrees
End Script
• Compute and display the time required to traverse each leg of the trip based on the given information.
• Compute and display the magnitude and the angle of the displacement from start to nish.
• Compute and display the time required to complete the entire trip, which is the sum of the times from
both legs.
• Compute and display the magnitude of the average velocity as the magnitude of the displacement
divided by the total time.
• Recognize that the angle of the average velocity is the same as the angle of the displacement.
The magnitude and angle of the overall displacement for the two-leg trip (identied by the variables
named vecResultMag and vecResultAng respectively) are computed using procedures that were
explained in an earlier module. Therefore, I won't repeat that explanation in this module.
The magnitude of the overall displacement is stored in the variable named vecResultMag , and the
angle for the overall displacement is stored in the variable named vecResultAng .
The total time
The total time for the trip, identied by the variable named totalTime , is computed as the sum of
the times for the individual legs.
Magnitude of the average velocity vector
The magnitude of the average velocity vector, identied by the variable named vecVelMag , is compute
by dividing the magnitude of the displacement vector by the total time. This results in a value having units
of feet/second as shown by the comments.
The direction of the average velocity vector
The direction of the average velocity vector, identied by the variable named vecVelAng , is recognized
as being the same as the direction of the overall displacement vector with units of degrees.
Display the results
Finally, the document.write method is called several times in succession to display the output text
shown in Image 3 (p. 565) .
JavaScript code
Please copy the code shown in Listing 3 (p. 568) into an html le and open the le in your browser.
Screen output
The text shown in Image 5 (p. 569) should appear in your browser window when you open the html le
in your browser.
Start Script
Velocity magnitude = 3.00 miles/hour
Velocity angle = 0.00 degrees
End Script
This array object will be used as a container to return the magnitude and angle values for the resultant
vector.
Can only return one item
A JavaScript function can only return one item. Up to this point in these modules, that item has consisted
of a single numeric value, such as the angle value that is returned from the getAngle function.
However, the vectorSum function needs to return two dierent values. One way to do that is to put
those two values in the pigeon holes of an array object and return that array object as the one item that
can be returned.
Store the resulting magnitude in the array object
Once the array object is created, the code in the function shown in Listing 3 (p. 568) is essentially the
same as the code used earlier to add two vectors, down to the statement that begins with:
vecResult[0] = Math.sqrt(Math.pow(vecResultH,2) +...
That statement computes the magnitude of the resultant vector the same way as before, but instead of
storing the value of the magnitude in a variable, it is stored in the rst pigeon hole of the array object.
The value is directed into the rst pigeon hole (technically called element) by the "[0]" that you see
following the name of the array object in that statement.
Store the resulting angle in the array object
Immediately thereafter, the statement in Listing 3 (p. 568) that reads
vecResult[1] = getAngle(vecResultH,vecResultV);
computes the angle for the resultant vector and stores it in the second element in the array object (the
element identied by the index value 1).
Return the array object for use later
These same index values along with the square brackets "[ ]" will be used later to retrieve the magnitude
and angle values from the array object.
Finally, the function returns the array object to the calling script by executing the statement that reads
return vecResult;
The main script body
The main script body begins where indicated by the comment in Listing 3 (p. 568) .
The rst four statements establish values for the magnitude and direction of the two vectors that represent
the train and the man. There is nothing in those statements that you haven't seen before.
Note the treatment of the units
However, I encourage you to pay attention to the treatment of units in the comments for the value stored
in the variable named vecManMag . The arithmetic in that statement uses two dierent conversion
factors to convert the value from feet per second to miles per hour.
Once again, working through the units in this fashion can help you to organize your arithmetic correctly.
Call the vectorSum function
The statement that begins
var resultant = vectorSum(vecTrainMag...
calls the new vectorSum function to add the two vectors, passing the magnitude and angle for each
vector as parameters.
Store the returned array object in a variable
This statement also declares a new variable named resultant . The array object that is returned from
the vectorSum function is stored in this variable.
Once this statement nishes executing, the magnitude and angle of the resultant vector have been com-
puted and saved for later use. (In this script, the only use of those two values is to display them later.
However, they will be used in a more signicant way in another exercise later.)
Code to display the results
The call to the vectorSum function is followed by three calls to the document.write method. The
rst two calls display magnitude and angle values, and the third call simply displays some text to indicate
that the script has nished executing.
Displaying the magnitude value
If you examine the statement containing the rst call to the document.write method, you will see
that the argument list contains the following expression:
resultant[0].toFixed(2)
In this case, the "[0]" means to retrieve the value stored in the array element identied by the index value
0.
Once that value has been retrieved, the built-in toFixed method is called, passing the literal value 2
as a parameter, to format the value so that it will be displayed with two digits to the right of the decimal
point.
Image 5 (p. 569) shows that value displayed in the line of text that reads:
Velocity magnitude = 3.00 miles/hour
(Note that very few of the values that I display in these modules comply with the rules for decimal digits
and signicant gures that I explained in an earlier module.)
A partial solution to the problem
A partial answer to the question posed for this exercise is that the magnitude of the man's overall velocity
with respect to the ground is 3 miles per hour as shown in Image 5 (p. 569) .
The rest of the solution
The next statement in Listing 3 (p. 568) uses a similar syntax to retrieve the value from the second
element in the array object (the element with an index value of 1) and to display it as
Velocity angle = 0.00 degrees
as shown in Image 5 (p. 569) .
This means that the man is moving due east (the same direction that the train is moving) with a velocity
of 3 miles per hour with reference to the ground.
Analysis of the results
Now I will tell you why I used a strange walking speed (2.933 feet per second) for the man. As it turns
out, this is very close to 2 miles per hour, and I wanted the man to have a walking speed that would result
in simple numeric results.
Let's review the problem
The train is moving east with a uniform velocity of 1 mile per hour relative to the ground.
The man is moving east with a uniform velocity of 2 miles per hour (2.933 feet per second) relative to
the train.
What is the man's velocity relative to the ground?
The algebraic sum of the magnitudes
Because the man and the train are both moving along the same straight line, and the man's velocity is
stated relative to the train, the magnitude of the man's velocity relative to the ground is the algebraic sum
of the magnitudes of the two velocities. Because they are both moving in the same direction, that algebraic
sum is additive.
An analysis of the velocities
The train is moving 1 mile per hour with reference to the ground, and the man is moving 2 miles per
hour with reference to the train (along the same line and in the same direction as the train). Therefore, the
man is moving 1+2=3 miles per hour with reference to the ground.
This means that an observer standing on the ground at a point on a line perpendicular to the train would
perceive the man to be moving to the to the right with a velocity of 3 miles per hour (assuming that the
train is moving to the right).
A zero-degree angle is not required
Note that it isn't necessary that the train and the man be moving at an angle of zero degrees (east). The
magnitude of the result would be the same regardless of the direction that they are moving provided they
are moving along the same straight line.
We will specify a dierent common direction for the train and the man in the next exercise.
(Because of the small dierences between this script and the previous script, I won't publish a copy of this
new script here.)
Screen output
The text shown in Image 7 (p. 573) should appear in your browser window when you open the le in
your browser.
Start Script
Velocity magnitude = 1.00 miles/hour
Velocity angle = 225.00 degrees
End Script
Figure 2.86: Image 7: Screen output for Exercise #2 for a man on a train.
Screen output
The text shown in Image 9 (p. 576) should appear in your browser window when the html le is opened
in your browser.
Start Script
Platform velocity magnitude = 3.70 miles/hour
Platform velocity angle = 22.50 degrees
Man velocity magnitude = 4.83 miles/hour
Man velocity angle = 45.00 degrees
End Script
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.8.6 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
2.9.2 Preface
2.9.2.1 General
This module is part of a series of modules designed for teaching the physics component of GAME2302
Mathematical Applications for Game Development at Austin Community College in Austin, TX. (See
GAME 2302-0100: Introduction 30 for the rst module in the course along with a description of the course,
course resources, homework assignments, etc.)
The purpose of this module is to explain variable velocity and acceleration.
2.9.2.2.1 Images
• Image 1 (p. 582) . Graph for variable velocity exercise #1.
• Image 2 (p. 585) . Screen output for Listing #1.
• Image 3 (p. 586) . Displacement versus time for rst ve time intervals.
• Image 4 (p. 590) . Screen output for Listing #2.
• Image 5 (p. 594) . Screen output for Listing #3.
• Image 6 (p. 598) . Screen output for Listing #4 at 45 degrees.
• Image 7 (p. 599) . Trajectory for two dierent ring angles.
• Image 8 (p. 600) . Screen output for Listing #4 at 60 degrees.
• Image 9 (p. 604) . Screen output for Listing #5.
• Image 10 (p. 606) . Screen output for Listing #6.
• Image 11 (p. 609) . Screen output for Listing #7.
2.9.2.2.2 Listings
• Listing 1 (p. 584) . Variable velocity exercise #1.
• Listing 2 (p. 589) . Variable velocity exercise #2.
• Listing 3 (p. 593) . Acceleration of gravity exercise #1.
• Listing 4 (p. 597) . Acceleration of gravity exercise #2.
• Listing 5 (p. 603) . Acceleration of gravity exercise #3.
• Listing 6 (p. 606) . Exercise to nd the velocity.
• Listing 7 (p. 608) . Exercise to nd the height.
I will provide an introduction to variable velocity, acceleration, and the acceleration of gravity in this section.
I will provide exercises on those topics in the next section.
30 http://cnx.org/content/m44983/latest
2.9.3.2 Acceleration
Everyone is familiar with the acceleration that occurs when a motor vehicle speeds up or slows down. When
the vehicle speeds up very rapidly, the positive acceleration forces us against the back of the seat. (This
involves the relationship among force, mass, and acceleration, which will be the subject of a future module.)
If the vehicle slows down very rapidly or stops suddenly, the negative acceleration may cause us to crash
into the windshield, the dashboard, or a deployed airbag.
The accelerator pedal
A common name for the pedal that causes gasoline to be fed to the engine is often called the accelerator
pedal because it causes the vehicle to speed up. (However, I have never heard anyone refer to the pedal that
causes the vehicle to slow down as the deceleration pedal. Instead, it is commonly called the brake pedal.)
Denitions
Displacement is a change in position.
Velocity is the rate of change of position or the rate of displacement .
Acceleration is the rate of change of velocity .
Jerk is the rate of change of acceleration (not covered in this module).
According to this author 31 , there is no universally accepted name for the rate of change of jerk .
The algebraic sign of acceleration
When the velocity of a moving object increases, that is viewed as positive acceleration. When the velocity
of the object decreases, that is viewed as negative acceleration.
Uniform or variable acceleration
Acceleration may be uniform or variable. It is uniform only if equal changes in velocity occur in equal
intervals of time.
A vector quantity
Acceleration has both direction and magnitude. Therefore, acceleration is a vector quantity.
The units for acceleration
31 http://math.ucr.edu/home/baez/physics/General/jerk.html
The above denition (p. 579) for acceleration leads to some interesting units for acceleration. For
example, consider a situation in which the velocity of an object changes by 5 feet/second in a one-second
time interval. Writing this as an algebraic expression gives us
(5 feet/second)/second
Multiplying the numerator and the denominator of the fraction by 1/second gives us
5 feet/(second*second)
This is often written as
5 feet/second^2
which is pronounced ve feet per second squared.
• For practical purposes, the eect of the acceleration of gravity is the same regardless of the height of
an object above the surface of the earth, provided that the distance above the surface of the earth is
small relative to the radius of the earth.
• In the absence of an atmosphere, all objects fall toward the earth with the same acceleration regardless
of their masses.
By multiplying both sides of the equation by m, we get a more common presentation of this relationship,
which is
f = m*a
where the symbols mean the same as listed above (p. 580) .
A ratio of two dierent forces of gravity
Now let's use the equation from above (p. 580) to form a ratio of the forces exerted on two dierent
masses by the earth, assuming that both masses are the same distance from the center of the earth.
f1/f2 =(E*m1/d^2)/(E*m2/d^2)
Cancel like terms to simplify
If we cancel like terms from the numerator and denominator of the expression on the right, we can
simplify the ratio to
f1/f2 = m1/m2
Replacing the forces on the left by the expression from above (p. 581) , we get
m1*a1/m2*a2 = m1/m2
Multiplying both sides by m2/m1 we get
a1/a2 = 1
or
a1 = a2
This shows that the acceleration resulting from the gravitational force exerted on two objects that are
equally distant from the center of mass of the earth is the same regardless of the dierences in mass of the
two objects.
I will present and explain several dierent scenarios based on the above assumptions in this section.
2.90
Create a script
Let's analyze this situation using a script. Copy the code shown in Listing 1 (p. 584) into an html le
and open the le in your browser.
document.write("End Script");
</script>
</body></html>
2.91
Screen output
The text shown in Image 2 (p. 585) should appear in your browser window when you open the html le
in your browser.
Start Script
t = 0.00 seconds h = 6.0 feet
t = 0.25 seconds h = 30.0 feet
t = 0.50 seconds h = 52.0 feet
t = 0.75 seconds h = 72.0 feet
t = 1.00 seconds h = 89.9 feet
t = 1.25 seconds h = 105.8 feet
t = 1.50 seconds h = 119.8 feet
t = 1.75 seconds h = 131.7 feet
t = 2.00 seconds h = 141.6 feet
t = 2.25 seconds h = 149.5 feet
t = 2.50 seconds h = 155.4 feet
t = 2.75 seconds h = 159.2 feet
t = 3.00 seconds h = 161.1 feet
t = 3.25 seconds h = 160.9 feet
t = 3.50 seconds h = 158.8 feet
t = 3.75 seconds h = 154.6 feet
t = 4.00 seconds h = 148.4 feet
t = 4.25 seconds h = 140.2 feet
t = 4.50 seconds h = 130.0 feet
t = 4.75 seconds h = 117.7 feet
t = 5.00 seconds h = 103.5 feet
t = 5.25 seconds h = 87.2 feet
t = 5.50 seconds h = 69.0 feet
t = 5.75 seconds h = 48.7 feet
t = 6.00 seconds h = 26.4 feet
t = 6.25 seconds h = 2.1 feet
t = 6.50 seconds h = -24.2 feet
End Script
2.92
velocity until it strikes the earth and stops. That is the message conveyed by the plot of height in Image 1
(p. 582) and the output from the script shown in Image 2 (p. 585) .
The maximum height
At about 3 seconds and a height of about 161 feet, the kinetic energy provided by the initial velocity
will have been dissipated by the gravitational attraction of the earth. At that point, the arrow won't go any
higher. Instead, it will start falling back toward the earth. Somewhere around 6.25 seconds, it will strike
the earth.
The shape of the curve
The shape of this curve is controlled by only two factors: the initial velocity of the arrow and the
gravitational attraction of the earth. The archer has some degree of control over the initial velocity, but has
no control over the gravitational attraction of the earth.
In theory, in the absence of an atmosphere, if the arrow is shot straight up, the arrow should land in the
same place from which it was shot. In practice in the real world, wind and other factors would probably
prevent that from happening.
Variable velocity
We learned in an earlier module that if velocity is uniform, the displacement should be the same during
each successive equal interval of time. However, we can see from Image 2 (p. 585) that is not true in this
case. For example, Image 3 (p. 586) shows the displacement versus time for the rst ve time intervals and
we can see that it is anything but uniform.
Interval Displacement
1 24
2 22
3 20
4 17.9
5 15.9
2.93
Assuming that you are able to create a plot of displacement versus time at closely-spaced points, you can
estimate the variable velocity curve by connecting each pair of points with a straight line and measuring the
slope of each such straight line segment. An estimate of the velocity during the interval dened by a pair of
points is the slope of the line that connects those points. The closer the points are, the better will be the
estimate of the velocity at a point half way between those two points.
In the situation where you are able to collect enough data to draw a smooth curve of displacement versus
time, the instantaneous velocity at any point on that curve is the slope of a line that is tangent to the curve
at that point. Note, however, that the construction of such a tangent line is dicult.
Units of velocity
If may recall from your high school geometry course that the slope of a line is given by the "rise over
run." In other words, the slope of the line is the ratio of the height to the base of a right triangle for which
the hypotenuse is on or parallel to the line.
Estimate some variable velocity values
At this point, I encourage you to use an object with a straight edge, place it rmly on two points that
dene a time interval on your graph, estimate the slope of the edge, and record that slope as your estimate
of the velocity at the center of that time interval. We will do something similar in our script.
Explanation of the code
The code in Listing 1 (p. 584) begins by declaring and initializing values to contain the parameters of
the problem:
• The acceleration of gravity in feet/sec^2. Note that this value is negative indicating that the gravita-
tional attraction is toward the center of the earth (down).
• The initial velocity of the arrow in feet/sec. This value is positive because the direction of velocity is
away from the center of the earth (up).
• The height of the arrow when it is released, positive values meaning up from the ground.
• The time interval at which successive estimates of the height of the arrow will be computed.
Working variables
Following that, the code in Listing 1 (p. 584) declares and initializes two working variables for time and
distance that will change as the program progresses.
Then Listing 1 (p. 584) declares and initializes a variable named sp that is used solely to insert spaces
between the columns in the output display.
A while loop
A while loop is used to evaluate the equation given earlier (p. 579) , to compute and display the height
of the arrow every 0.25 seconds for as long as the arrow is above the ground (height is positive). The loop
continues to iterate and display time and height values in two separate columns (see Image 2 (p. 585) ) until
the computation produces one negative height value.
When the test at the top of the while loop determines that the previously-computed value for height
was negative,
This is not a complicated script in comparison with some of the scripts that were presented in earlier modules.
Given the output shown in Image 2 (p. 585) , you should be able to estimate and plot the velocity of the
arrow on the same graph by dividing the displacement during each time interval by the value of the time
interval.
Copy the code from Listing 2 (p. 589) into an html le and open the le in your browser.
Screen output
The text shown in Image 4 (p. 590) should appear in your browser window when the html le opens in
your browser.
Start Script
t = 0.00 seconds h = 6.0 feet v = 100.00 feet/second
t = 0.25 seconds h = 30.0 feet v = 95.97 feet/second
t = 0.50 seconds h = 52.0 feet v = 87.92 feet/second
t = 0.75 seconds h = 72.0 feet v = 79.87 feet/second
t = 1.00 seconds h = 89.9 feet v = 71.82 feet/second
t = 1.25 seconds h = 105.8 feet v = 63.77 feet/second
t = 1.50 seconds h = 119.8 feet v = 55.72 feet/second
t = 1.75 seconds h = 131.7 feet v = 47.67 feet/second
t = 2.00 seconds h = 141.6 feet v = 39.62 feet/second
t = 2.25 seconds h = 149.5 feet v = 31.57 feet/second
t = 2.50 seconds h = 155.4 feet v = 23.52 feet/second
t = 2.75 seconds h = 159.2 feet v = 15.47 feet/second
t = 3.00 seconds h = 161.1 feet v = 7.42 feet/second
t = 3.25 seconds h = 160.9 feet v = -0.63 feet/second
t = 3.50 seconds h = 158.8 feet v = -8.68 feet/second
t = 3.75 seconds h = 154.6 feet v = -16.73 feet/second
t = 4.00 seconds h = 148.4 feet v = -24.78 feet/second
t = 4.25 seconds h = 140.2 feet v = -32.83 feet/second
t = 4.50 seconds h = 130.0 feet v = -40.88 feet/second
t = 4.75 seconds h = 117.7 feet v = -48.93 feet/second
t = 5.00 seconds h = 103.5 feet v = -56.98 feet/second
t = 5.25 seconds h = 87.2 feet v = -65.03 feet/second
t = 5.50 seconds h = 69.0 feet v = -73.08 feet/second
t = 5.75 seconds h = 48.7 feet v = -81.13 feet/second
t = 6.00 seconds h = 26.4 feet v = -89.18 feet/second
t = 6.25 seconds h = 2.1 feet v = -97.23 feet/second
t = 6.50 seconds h = -24.2 feet v = -105.28 feet/second
End Script
2.95
At 3.25 seconds, the velocity switches from positive to negative meaning that the arrow begins falling
back toward the earth. The velocity reaches -100 feet/second somewhere between 6.25 and 6.5 seconds,
which is about the same time that the arrow hits the ground.
Hopefully you have recognized that the velocity curve for this particular situation is a straight line with
a negative slope. That straight line crosses the horizontal axis going from positive territory into negative
territory about half way between the original release of the arrow and the point where the arrow strikes the
ground.
Analysis of the code
A comparison of Listing 2 (p. 589) with Listing 1 (p. 584) shows the addition of the following variables:
We can extend that procedure to estimate the acceleration of a moving object at a point in time by
determining the slope of a curve that plots the velocity of the object versus time at that particular point in
time. Positive slopes indicate positive acceleration and negative slopes indicate negative acceleration.
Estimate some velocity values graphically
If you have the velocity curve from Image 4 (p. 590) plotted on your graph, I recommend that you
estimate and record the slope and hence the acceleration at a few points. That should be easy to do in this
case, because the velocity curve should be a straight line with a negative slope.
A constant acceleration value
If the velocity curve is a straight line with a negative slope, and if the acceleration at any point in
time is equal to the slope of the velocity curve, that means that the acceleration has a constant negative
value throughout the time interval of interest. In fact, you should nd that the value of the acceleration is
approximately -32.2 feet/second^2, which is known as the acceleration of gravity .
Create a script
Copy the code from Listing 3 (p. 593) into an html le and open that le in your browser.
Screen output
The text shown in Image 5 (p. 594) should appear in your browser window when the html le is opened
in your browser.
Start Script
t = 0.00 sec h = 6 ft v = 100.00 ft/sec a = 0.00 ft/(sec*sec)
t = 0.25 sec h = 30 ft v = 95.97 ft/sec a = 0.00 ft/(sec*sec)
t = 0.50 sec h = 52 ft v = 87.92 ft/sec a = -32.20 ft/(sec*sec)
t = 0.75 sec h = 72 ft v = 79.87 ft/sec a = -32.20 ft/(sec*sec)
t = 1.00 sec h = 90 ft v = 71.82 ft/sec a = -32.20 ft/(sec*sec)
t = 1.25 sec h = 106 ft v = 63.77 ft/sec a = -32.20 ft/(sec*sec)
t = 1.50 sec h = 120 ft v = 55.72 ft/sec a = -32.20 ft/(sec*sec)
t = 1.75 sec h = 132 ft v = 47.67 ft/sec a = -32.20 ft/(sec*sec)
t = 2.00 sec h = 142 ft v = 39.62 ft/sec a = -32.20 ft/(sec*sec)
t = 2.25 sec h = 149 ft v = 31.57 ft/sec a = -32.20 ft/(sec*sec)
t = 2.50 sec h = 155 ft v = 23.52 ft/sec a = -32.20 ft/(sec*sec)
t = 2.75 sec h = 159 ft v = 15.47 ft/sec a = -32.20 ft/(sec*sec)
t = 3.00 sec h = 161 ft v = 7.42 ft/sec a = -32.20 ft/(sec*sec)
t = 3.25 sec h = 161 ft v = -0.63 ft/sec a = -32.20 ft/(sec*sec)
t = 3.50 sec h = 159 ft v = -8.68 ft/sec a = -32.20 ft/(sec*sec)
t = 3.75 sec h = 155 ft v = -16.73 ft/sec a = -32.20 ft/(sec*sec)
t = 4.00 sec h = 148 ft v = -24.78 ft/sec a = -32.20 ft/(sec*sec)
t = 4.25 sec h = 140 ft v = -32.83 ft/sec a = -32.20 ft/(sec*sec)
t = 4.50 sec h = 130 ft v = -40.88 ft/sec a = -32.20 ft/(sec*sec)
t = 4.75 sec h = 118 ft v = -48.93 ft/sec a = -32.20 ft/(sec*sec)
t = 5.00 sec h = 103 ft v = -56.98 ft/sec a = -32.20 ft/(sec*sec)
t = 5.25 sec h = 87 ft v = -65.03 ft/sec a = -32.20 ft/(sec*sec)
t = 5.50 sec h = 69 ft v = -73.08 ft/sec a = -32.20 ft/(sec*sec)
t = 5.75 sec h = 49 ft v = -81.13 ft/sec a = -32.20 ft/(sec*sec)
t = 6.00 sec h = 26 ft v = -89.18 ft/sec a = -32.20 ft/(sec*sec)
t = 6.25 sec h = 2 ft v = -97.23 ft/sec a = -32.20 ft/(sec*sec)
t = 6.50 sec h = -24 ft v = -105.28 ft/sec a = -32.20 ft/(sec*sec)
End Script
2.97
with a constant negative slope. (Note that the procedure used to estimate the acceleration did not allow for
an accurate estimate of acceleration for the rst two values in the acceleration column.)
Free fall
According to Wikipedia 33 , free fall is any motion of a body where gravity is the only force acting upon
it.
Since this denition does not specify velocity, it also applies to objects initially moving upward (which is
the case with our arrow that was shot upward).
Free fall was demonstrated on the moon by astronaut David Scott on August 2, 1971. He simultaneously
released a hammer and a feather from the same height above the moon's surface. The hammer and the feather
both fell at the same rate and hit the ground at the same time. This demonstrated Galileo's discovery that
in the absence of air resistance, all objects experience the same acceleration due to gravity.
By the way, it is no accident that the value shown for acceleration in Image 4 (p. 590) matches the value
specied for the acceleration of gravity near the beginning of the code in Listing 3 (p. 593) .
Analysis of the code
The code in Listing 3 (p. 593) is very similar to the code in Listing 2 (p. 589) with the addition of the
code necessary to estimate the acceleration values on the basis of the slope of the velocity curve.
The code that estimates the acceleration in Listing 3 (p. 593) is so similar to the code that estimates the
velocity in Listing 2 (p. 589) that I won't bore you by explaining the code in detail.
However, there is one bit of new code that is worthy of note. Without going into detail as to the reasons
why, this procedure is incapable of accurately estimating the slope of the velocity curve during the rst two
time intervals. Therefore, an if statement was written into the while loop to force the acceleration
estimate to be zero for the rst two time intervals.
As usual, the units for distance, time, velocity, and acceleration must be consistent with one another.
Shooting the arrow straight up
If we shoot an arrow straight up, as was the case in the previous exercises, the initial velocity doesn't have
a horizontal component. Instead, the initial velocity has only a vertical component and the corresponding
motion of the arrow has only a vertical component. In other words, the arrow goes straight up and it comes
down in the same spot.
Shooting the arrow other than straight up
However, if we shoot the arrow in a direction other than straight up or straight down, the initial velocity
has both a vertical component and a horizontal component. Therefore, the resulting motion has both a
vertical component and a horizontal component.
33 http://en.wikipedia.org/wiki/Free_fall#Uniform_gravitational_eld_without_air_resistance
To determine the position of the arrow at some time after it is released, we must determine both the
vertical and the horizontal component of its motion.
Compute vertical and horizontal components independently
The equation given above (p. 595) can be used to compute the vertical and horizontal components of
motion independently of one another. This approach can be used to give us the position as a function of
time along each axis. We can then use that information to determine and plot the position of the arrow in
x-y space at one or more points in time.
Vertical and horizontal motion components are independent
It is important to understand that the vertical and horizontal components of motion are independent of
one another. In other words, changing the vertical component of motion doesn't eect the horizontal motion
and changing the horizontal component of motion doesn't eect the vertical motion. The overall motion
seen by an observer is the superposition of the two.
Create a script
Please copy the code shown in Listing 4 (p. 597) into an html le and open the le in your browser.
document.write("End Script");
598 CHAPTER 2. PHYSICS
Screen output
The text shown in Image 6 (p. 598) should appear in your browser when you open the html le in your
browser.
Start Script
t = 0.00 seconds x = 0.0 feet y = 6.0 feet
t = 0.25 seconds x = 17.7 feet y = 22.7 feet
t = 0.50 seconds x = 35.4 feet y = 37.3 feet
t = 0.75 seconds x = 53.0 feet y = 50.0 feet
t = 1.00 seconds x = 70.7 feet y = 60.6 feet
t = 1.25 seconds x = 88.4 feet y = 69.2 feet
t = 1.50 seconds x = 106.1 feet y = 75.8 feet
t = 1.75 seconds x = 123.8 feet y = 80.4 feet
t = 2.00 seconds x = 141.4 feet y = 83.0 feet
t = 2.25 seconds x = 159.1 feet y = 83.6 feet
t = 2.50 seconds x = 176.8 feet y = 82.2 feet
t = 2.75 seconds x = 194.5 feet y = 78.7 feet
t = 3.00 seconds x = 212.1 feet y = 73.2 feet
t = 3.25 seconds x = 229.8 feet y = 65.8 feet
t = 3.50 seconds x = 247.5 feet y = 56.3 feet
t = 3.75 seconds x = 265.2 feet y = 44.8 feet
t = 4.00 seconds x = 282.8 feet y = 31.2 feet
t = 4.25 seconds x = 300.5 feet y = 15.7 feet
t = 4.50 seconds x = 318.2 feet y = -1.8 feet
End Script
2.99
2.100
Start Script
t = 0.00 seconds x = 0.0 feet y = 6.0 feet
t = 0.25 seconds x = 12.5 feet y = 26.7 feet
t = 0.50 seconds x = 25.0 feet y = 45.3 feet
t = 0.75 seconds x = 37.5 feet y = 61.9 feet
t = 1.00 seconds x = 50.0 feet y = 76.5 feet
t = 1.25 seconds x = 62.5 feet y = 89.1 feet
t = 1.50 seconds x = 75.0 feet y = 99.7 feet
t = 1.75 seconds x = 87.5 feet y = 108.3 feet
t = 2.00 seconds x = 100.0 feet y = 114.8 feet
t = 2.25 seconds x = 112.5 feet y = 119.4 feet
t = 2.50 seconds x = 125.0 feet y = 121.9 feet
t = 2.75 seconds x = 137.5 feet y = 122.4 feet
t = 3.00 seconds x = 150.0 feet y = 120.9 feet
t = 3.25 seconds x = 162.5 feet y = 117.4 feet
t = 3.50 seconds x = 175.0 feet y = 111.9 feet
t = 3.75 seconds x = 187.5 feet y = 104.3 feet
t = 4.00 seconds x = 200.0 feet y = 94.8 feet
t = 4.25 seconds x = 212.5 feet y = 83.2 feet
t = 4.50 seconds x = 225.0 feet y = 69.7 feet
t = 4.75 seconds x = 237.5 feet y = 54.1 feet
t = 5.00 seconds x = 250.0 feet y = 36.5 feet
t = 5.25 seconds x = 262.5 feet y = 16.9 feet
t = 5.50 seconds x = 275.0 feet y = -4.7 feet
End Script
2.101
Perhaps you could do the same thing for some other launch angles and determine which launch angle
provides the greatest horizontal range and which launch angle provides the greatest vertical height.
For example, how far does the arrow y when launched at an angle of 0 degrees from a height of 6 feet?
Analysis of the code
The code in this script treats the horizontal and vertical components of motion independently and uses
the equation given above (p. 595) to determine the position along that axis as a function of time every 0.25
seconds.
Common parameter values
The code in Listing 4 (p. 597) begins by dening common parameter values for the ring angle, the time
increment at which coordinate values will be computed and displayed, and the initial velocity of the arrow
in the ring direction.
Horizontal and vertical parameters
Following that, the code in Listing 4 (p. 597) denes horizontal parameters and vertical parameters that
will be used to compute the horizontal and vertical components of motion respectively.
Horizontal acceleration
The horizontal acceleration is set to zero. In the absence of air resistance, there is nothing to cause the
horizontal component of the arrow to speed up or slow down until it stops suddenly when it hits the ground.
Vertical acceleration
The vertical acceleration is set to the acceleration of gravity at the surface of the earth, which is the same
value used for the previous exercises in this module.
Decompose the initial velocity
The cosine and sine functions are used to decompose the initial velocity into horizontal and vertical
components of velocity.
Initial horizontal and vertical positions
Finally, the horizontal position when the arrow is released is set to 0 and the vertical position is set to 6
feet, approximately the height of the release point for an archer that is six feet tall.
Working variables
After dening the horizontal and vertical parameters, the code in Listing 4 (p. 597) declares working
variables for time, horizontal position (x), and vertical position (y).
A while loop
A while loop is used to iterate for as long as the arrow is above the ground.
During each iteration, the equation given above (p. 595) is evaluated twice, once to determine the height
of the arrow and once to determine the horizontal position of the arrow at the current time.
Time starts at 0, and increments by +0.25 seconds during each iteration.
The document.write method is called inside the while loop to display the results shown in Image 6
(p. 598) .
In this form, you may recognize this as a standard quadratic equation which is often written as
a*t^2 + b*t + c = 0
(Now you know why I replaced the acceleration term a by the acceleration term g earlier. I need to
use the symbol a in the standard quadratic equation.)
Standard solution for a quadratic equation
Given values for a, b, and c, you should know that the solution for determining the values for t is to nd
the roots of the equation.
There are two roots (hence two values for t). You should also know that the two roots can be found by
evaluating the quadratic formula in two forms.
t1 = (-b+Math.sqrt(b*b-4*a*c))/(2*a);
t2 = (-b-Math.sqrt(b*b-4*a*c))/(2*a);
Using the solution
Relating the coecients in the standard motion equation (p. 601) to the coecients in the standard
quadratic equation (p. 601) gives us:
• a = 0.5*g
• b = v0
• c = -d
The scenario
Let's use the scenario posed in the rst exercise (p. 581) in this module. In this scenario, an archer that
is six feet tall shoots an arrow directly upward with a velocity of 100 feet per second. Assume that the arrow
is at a height of 6 feet when it leaves the bow. Also ignore the eects of air resistance.
Referring back to Image 1...
We learned from the table in Image 2 (p. 585) that the arrow was at a height of 89.9 feet at 1 second
on the way up from the surface of the earth, and was at a height of 89.9 feet again on the way down at
approximately 5.2 seconds.
Let's pretend that we don't have the table in Image 1 (p. 585) and write a script that uses the quadratic
form of the standard motion equation (p. 601) along with the quadratic formula (p. 601) to compute the
times that the arrow was at a height of 89.9 feet.
Do it also for the moon
To make the problem even more interesting, let's also cause the script to compute and display the times
that the arrow was at a height of 89.9 feet assuming that the archer was standing on the surface of the moon
instead of the earth.
An issue involving the initial height
The standard motion equation (p. 601) can be used to compute the time that the arrow has traveled to
any specic height, relative to the height from which it was released. Therefore, since the arrow was released
from a height of 6 feet and it initially traveled up, we need to determine the time at which it had traveled
83.9 feet to nd the time that it was actually at 89.9 feet.
The JavaScript code
Please copy the code from Listing 5 (p. 603) into an html le and open the le in your browser.
//Solve the quadratic formula for the two times at which the
// height matches the target height corrected for the
// initial height.
var roots = getRoots(a,b,c);
Screen output
The text shown in Image 9 (p. 604) should appear in the browser window when you open the html le
in the browser.
Start Script
On Earth
Arrow is at 89.9 feet at 1.00 seconds
Arrow is at 89.9 feet at 5.21 seconds
On the Moon
Arrow is at 89.9 feet at 0.86 seconds
Arrow is at 89.9 feet at 36.33 seconds
End Script
2.103
Then Listing 5 (p. 603) sets the value of the coecient named a to reect the acceleration of gravity
on the moon, repeats the process, and displays the results in the lower half of Image 9 (p. 604) .
Note that the arrow reaches the target height somewhat quicker on the moon due to the lower acceleration
of gravity, and takes much longer to arrive at the same height on the way back down to the surface of the
moon. Were we to create a chart similar to Image 2 (p. 585) for the moon, we would see that the arrow
goes much higher before turning around and falling back to the surface of the moon.
Some physics textbooks also list the following equations as being important .
v = v0 + g*t
v^2 = v0^2 + 2*g*h
where v is the velocity of the object and the other terms are the same as described above (p. 605) .
//Given that v = v0 + g * t
//At what time does the velocity go to zero?
document.write("<br/>End Script");
</script>
</body></html>
2.104
Screen output
The text shown in Image 10 (p. 606) should appear in your browser window when you open the html le
in your browser.
Start Script
End Script
2.105
Compared to working through the solutions to the previous exercises, this one seems almost trivial.
After establishing values for the acceleration of gravity and the initial velocity of the arrow, the code in
Listing 6 (p. 606) rearranges the rst equation given above (p. 605) and solves for the value of time at which
the velocity goes to zero. This is the point in time when the arrow turns from moving up and begins falling
back toward the earth.
The results are shown in Image 10 (p. 606) . You should compare this result with Image 1 (p. 582) ,
which shows that the arrow reaches its maximum height at approximately 3 seconds, which agrees very well
with the result shown in Image 10 (p. 606) .
document.write("<br/>End Script");
</script>
</body></html>
2.106
Screen output
The text shown in Image 11 (p. 609) should appear in your browser window when the html le is opened
in your browser.
Start Script
End Script
2.107
I encourage you to run the scripts that I have presented in this lesson to conrm that you get the same
results. Copy the code for each script into a text le with an extension of html. Then open that le in
your browser. Experiment with the code, making changes, and observing the results of your changes. Make
certain that you can explain why your changes behave as they do.
2.9.6 Miscellaneous
note: Disclaimers: Financial : Although the Connexions site makes it possible for you to
download a PDF le for this module at no charge, and also makes it possible for you to purchase a
pre-printed version of the PDF le, 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 nancial 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.
Aliation : I am a professor of Computer Information Technology at Austin Community College
in Austin, TX.
-end-
Attributions
Collection: GAME 2302 - Mathematical Applications for Game Development
Edited by: Richard Baldwin
URL: http://cnx.org/content/col11450/1.29/
License: http://creativecommons.org/licenses/by/3.0/
Module: "GAME 2302-0095: Preface to GAME 2302"
By: Richard Baldwin
URL: http://cnx.org/content/m45315/1.3/
Pages: 1-2
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "GAME 2302-0100: Introduction"
By: Richard Baldwin
URL: http://cnx.org/content/m44983/1.5/
Pages: 3-5
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0100s Slides"
By: Richard Baldwin
URL: http://cnx.org/content/m45611/1.2/
Page: 6
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "GAME 2302-0105: Getting Started"
By: Richard Baldwin
URL: http://cnx.org/content/m44990/1.4/
Pages: 7-38
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0105r Review"
By: Richard Baldwin
URL: http://cnx.org/content/m45585/1.3/
Pages: 39-52
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0105s Slides"
By: Richard Baldwin
URL: http://cnx.org/content/m45610/1.2/
Pages: 52-53
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "GAME 2302-0110: Updating the Game Math Library for Graphics"
By: Richard Baldwin
URL: http://cnx.org/content/m45009/1.4/
Pages: 53-92
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0110r Review"
By: Richard Baldwin
URL: http://cnx.org/content/m45586/1.3/
Pages: 93-102
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0110s Slides"
By: Richard Baldwin
URL: http://cnx.org/content/m45613/1.2/
Pages: 102-103
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "GAME 2302-0115: Working with Column Matrices, Points, and Vectors"
By: Richard Baldwin
URL: http://cnx.org/content/m45010/1.3/
Pages: 103-123
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0115r Review"
By: Richard Baldwin
URL: http://cnx.org/content/m45587/1.4/
Pages: 124-129
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0115s Slides"
By: Richard Baldwin
URL: http://cnx.org/content/m45619/1.3/
Pages: 129-130
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "GAME 2302-0120: Visualizing Column Matrices"
By: Richard Baldwin
URL: http://cnx.org/content/m45011/1.5/
Pages: 130-144
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
Module: "Game0120s Slides"
By: Richard Baldwin
URL: http://cnx.org/content/m45615/1.2/
Page: 145
Copyright: Richard Baldwin
License: http://creativecommons.org/licenses/by/3.0/
About Connexions
Since 1999, Connexions has been pioneering a global system where anyone can create course materials and
make them fully accessible and easily reusable free of charge. We are a Web-based authoring, teaching and
learning environment open to anyone interested in education, including students, teachers, professors and
lifelong learners. We connect ideas and facilitate educational communities.
Connexions's modular, interactive courses are in use worldwide by universities, community colleges, K-12
schools, distance learners, and lifelong learners. Connexions materials are in many languages, including
English, Spanish, Chinese, Japanese, Italian, Vietnamese, French, Portuguese, and Thai. Connexions is part
of an exciting new information distribution system that allows for Print on Demand Books. Connexions
has partnered with innovative on-demand publisher QOOP to accelerate the delivery of printed course
materials and textbooks into classrooms worldwide at lower prices than traditional academic publishers.