0% found this document useful (0 votes)
122 views

Welcome To Processing 2019 An Introduction Into Programming - Michael Q

This document provides an introduction to Processing, a programming language for creating interactive graphics and video games. It outlines the instructor's background and goals for the class, which is focused on teaching lines, shapes, colors, and basic programming concepts. The first lesson covers drawing lines, rectangles, ellipses and using RGB and HSB color modes. It demonstrates various drawing functions and encourages students to practice the concepts.

Uploaded by

api-463572654
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

Welcome To Processing 2019 An Introduction Into Programming - Michael Q

This document provides an introduction to Processing, a programming language for creating interactive graphics and video games. It outlines the instructor's background and goals for the class, which is focused on teaching lines, shapes, colors, and basic programming concepts. The first lesson covers drawing lines, rectangles, ellipses and using RGB and HSB color modes. It demonstrates various drawing functions and encourages students to practice the concepts.

Uploaded by

api-463572654
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 204

Welcome to Processing!

An introduction into programming


and video game design!
My name is Michael Quinn!
I am a junior at the high school High Tech High North
County.

Experience: Robotics club, Java Programming, & Unity

My dream is to become a video game developer!


Introduction of yourself!
What experiences do you have with coding?

What are your expectations for this class?

What are you most excited to learn about?

What are you planning to do with what you learned?


What are your goals?
Lesson One:
Lines, Shapes, and Colors!
Comments
● Uses a Double Forward slash

● Important to take notes with.

● It can hide commands that you don’t want to run at a


particular time.
Background
● The background function sets the color of the
background for your window.

● background (grayscale);

● background(red, green, blue);


Size Command
● Defines the dimensions of the window that your game
is running on!

● size(screenWidth, screenHeight);

● You can also use fullScreen();


Lines
● Draws a straight line between two points on a screen.

● line( x1, y1, x2, y2);

● Colors the line using the stroke() function while


determining the width of the line with strokeWeight();
Example 1:
Example 2:
Example 3:
Example 4:
Create your own
example?
Rectangles!
● Draws a rectangle starting with the upper left point
and the top of the rectangle.

● rect(x, y, width, height)

● X is the upper left point while Y is the top of the


rectangle.
Examples:
Fill Command
● Set the color to be used in fill in shapes!

● fill(red, green, blue)

● Using RGB, putting the amount of color between red,


green, and blue to make a different color is liking
mixing the color of paint together to make something
new!
Examples:

fill(150,200,150); fill(240,200,200);
Why is 255 the maximum number?
● It is used because 255 is a number that is important to
binary. Early developers of the binary computers used
bytes as a standard unit.

● A byte is defined as 8 bits and for binary, 2 was a very


important number. 2^8 = 256.

● Since 0 is a number that is included, you would


subtract 256 by 1 to get the maximum number of 255.
Ellipses
● Draws an ellipse (oval) on the screen. The coordinates
are now located in the middle of the oval.

● ellipse(x, y, width, height)

● An ellipse with an equal width and height will make a


perfect circle.
Examples:
RGB vs HSB
HSB Color Wheel for 8 Bit
Save your program!
● Click File > Save As...

● Make a new folder on your flash drive and make a


name for it.

● Save the name of your program to something


meaningful and click File > Quit to close Processing.
Review One?
Lines, Shapes, and Colors!
Lines:
Rectangles:
Ellipses:
RGB vs HSB

HUE = The pure color.


Saturation = The Intensity of the HUE color. Basically the transparency of the
color.
Brightness = Determines how bright or dark the color is.
HSB Color Wheel
Lesson Two:
Shape Modes, Precise Coordinates,
Void Functions, & Introduction into Text.
rectMode()
● Modifies where the program draws the
rectangle.

● Using rectMode(CORNER) uses the upper left


corner to set the location of where the
program draws.

● Using rectMode(CENTER) uses the shape’s


center point to set the location of where the
program draws.
ellipseMode()
● Modifies where the program draws the
rectangle.

● Using ellipseMode(CENTER) uses the shape’s


center point to set the location of where the
program draws.

● Using ellipseMode(CORNER) uses the upper


left corner to set the location of where the
program draws.
Coordinates
When you choose a window size for your program. Have you noticed
something about your game is off? Can you notice the difference
between the two programs when only the window size is different?
Precise Coordinates
● There is a solution to this… SYSTEM VARIABLES!
● System variables are variables that are built into the program to know
the function of that variable.
● For example, there are two system variables for the function, size()

Say hello to...

width & height!


Precise Coordinates For example if divide the width and
height by two… the shape will be
width and height account for the centered!
width and height of the window
size.

No matter how you change the


window size, as long as you use
the width and height variables,
the coordinates will stay the
same for all your objects.

Find out more ways that using


precise coordinates can help!

Why is this important?


Precise Coordinates
Precise Coordinates
Precise Coordinates Test
Precise Coordinates Test & Answer
Void Functions
These functions are used to tell the program when to operate
the commands you put in at what point of the “animation.”

These functions are important to declare when they occur so


that the order of events are organized and the program
understands when to play them.

These functions will have two brackets, ( { & } ), which will


contain each command for that period of time.
void setup()
void setup() tells Processing that all the commands within the
two brackets will be executed at the very beginning and the
commands will only run once.

void setup() //This is an example of what the function


{ // looks like.
size(500,500)
} // This function is used to define the initial
// environment with things like size, background, etc.
void draw()
void draw() tells Processing that all the commands within the two brackets
will be executed 60 times per second while the program is running.

void draw() //This is an example of what the function looks like.


{
fill(50,50,50);
ellipse(width/2, height/2, 100, 100);
line(width/2-50, height/2, width/2+50, height/2);
line(width/2, height/2-50, width/2, height/2+50);

}
text()
● Draws some text on the screen!

● text(“text example”, x, y)

● Use textSize() to determine the


font size!
Processing Class Survey

https://forms.gle/tHreweCxS7fXsGq68
Review Two
Shape Modes, Precise Coordinates,
Void Functions, & Introduction into
Text.
Precise Coordinates, void Functions,
and text() review!
● Draw three ellipses and one Hi there!
rectangle to make a person.
Attempt to make two people!

● Draw some text on the screen!

● Make it look like two people


are having a conversation!
Void Functions Review
● Tells the program when to operate the commands you put
in at what point of the “animation.”

● These functions will have two brackets, ( { & } ), which will


contain each command for that period of time.

● void functions will be crucial when we have lots of lines of


code that used for different functions.
void setup()
&
void draw()
text()
● Draws some text on the screen!

● text(“text example”, x, y)

● Use textSize() to determine the


font size!
Lesson Three:
Finishing Text, Creating Variables,
& Introduction to Movement
createFont()
● Searches for fonts on
your computer and
creates it in your
program.

● Depending on how many


fonts the computer has,
it could have 400+ fonts
to choose from.
textAlign()
● Sets the alignment of x coordinate for the text to be
either LEFT, RIGHT, OR CENTER for the formula
textAlign([x-coordinate])

● However, if you want to change the alignment for the y


coordinate, you would write either TOP, BOTTOM,
CENTER, or BASELINE.

textAlign([x-coordinate],[y-coordinate])
[34] "Berlin Sans FB" [69] "Californian FB" [102] "Consolas" [195] "Javanese Text" [367] "Symbol"

Example Fonts: [35] "Berlin Sans FB Bold" [70] "Californian FB Bold" [106] "Constantia" [196] "Jokerman" [371] "Times New Roman"

[0] "Agency FB"


[14] "Bahnschrift Bold" [71] "Californian FB Italic" [110] "Cooper Black" [281] "Onyx" [386] "Verdana"

[1] "Agency FB Bold"


[21] "Bahnschrift Regular" [72] "Calisto MT" [113] "Corbel" [288] "Papyrus" [395] "Wingdings"

[2] "Algerian"
[22] "Bahnschrift SemiBold" [76] "Cambria" [117] "Courier New" [289] "Parchment" [396] "Wingdings 2"

[3] "Arial"
[39] "Bodoni MT" [81] "Candara" [130] "Ebrima" [290] "Perpetua" [397] "Wingdings 3"

[4] "Arial Black"


[50] "Book Antiqua" [85] "Castellar" [133] "Elephant" [296] "Playbill"

[5] "Arial Bold"


[51] "Book Antiqua Bold" [88] "Century Gothic" [140] "Felix Titling" [297] "Poor Richard" You can find more with these

[7] "Arial Italic"


[54] "Bookman Old Style" [96] "Chiller" [142] "Forte" [298] "Pristina" commands:

[8] "Arial Narrow"


[59] "Bradley Hand ITC" [97] "Colonna MT" [153] "Freestyle Script" [299] "Rage Italic"

[13] "Bahnschrift"
[60] "Britannic Bold" [98] "Comic Sans MS" [154] "French Script MT" [300] "Ravie"

[29] "Baskerville Old Face"


[61] "Broadway" [99] "Comic Sans MS Bold" [161] "Georgia" [301] "Rockwell"

[30] "Bauhaus 93"


[62] "Brush Script MT Italic" [100] "Comic Sans MS Bold Italic" [191] "Impact" [311] "SansSerif.plain"

[31] "Bell MT"


[63] "Calibri" [101] "Comic Sans MS Italic" [194] "Ink Free" [336] "Serif.plain"
Creating Variables
● Declaring a variable is a key component of programming.
Variables allows programmers to put a “name” for a data
type.

● One type of variables is called a “float.” A float is a


variable that can hold numbers that contain decimals.

● The formula for a float is: float [insert variable name];


Creating Variables
Know that you know how to create a variable, let’s make
variables for the x-coordinates and the y-coordinates for your
objects.

A good thing to know about variables is that you have to place


them somewhere that your commands for the program are
able to read it. Be careful to where you put your float variable.
Creating Variables
Here is an example of
how to set up your float
variable…

This works because the


program registers the
float variable and the
ellipse function
recognizes and uses it.
void random()
void random() tells Processing that all the commands within the two
brackets will be executed at random while the program is running.

The random() function can not only be used as a void but can be used in
other voids to generate random numbers. Every time the function is
called, an unexpected value gets generated between 0 and the highest
function you put into there.

For example, if you put random(5), it will choose a number between 0 and
5. If you put random(-10, 15), it will return values starting at -10 and up to
15. (However, not equal to 15.) Basically, -10 < x < 15.
random()
Consider this function:

What do you believe will occur when


you change the x-coordinates and the
y-coordinates to a random() function?
Creating a new void function:
Make a new void function to call your design.
You can name it whatever you’d like.

Include the shapes and objects that will become a new


design.

This is an example of how to do this:

------------------------------------------------>
Making a object have its own function:

Once you made your new void function, you


are ready to import all your information into
it. Take your object from void draw() and
port it over!

This is an example of how to do this:

------------------------------------------------>
How the function should look:

After you make those changes, then you should


add the “displayicon();” function into void
draw().

This is an example on how all of this should look:

------------------------------------------------>
Creating a new void move function:
Make a new void move function by naming it what fits best with you. Add
the name of this function to draw() above displayicon().

Then, copy and paste your definitions of xLoc and yLoc. Example, xLoc =
width/2, etc. Then comment those out.

It should look similar to this example:


Example: void moveicon()

{
// xLoc = width/2
//yLoc = height/2
}
Moving your icon / object
To move your object, you simply need to add something the x-coordinates
and the y-coordinates while the program is running. To do this, you will
write a formula in the moveicon() function using xLoc and yLoc.

For example:

xLoc = xLoc + 1 //This is why commenting out the other xLoc


yLoc = yLoc +1 // functions is important.

Test it out and see how it goes!


void move() function
When you tested the move function, you noticed the black blur behind it
right? This is fixable.

To fix this, go back to the void draw() function add the following:

void draw()
{
background(255);
...
}
Delete background from void setup()
Since void draw() makes the background every 60 frames,
void setup() doesn’t need the background function so you may remove it!

void setup()
{
size(500,500);
colorMode(HSB);
b̶̶a̶c̶k̶g̶r̶o̶u̶n̶d̶(̶2̶5̶5̶)̶;̶
}
Practice with movement!
Now that you’ve learned how to move your objects with the moveicon()
function using xLoc and yLoc, test out how the object moves by editing
your code this far.

For example, what happens when you change what is being added or
subtracted by xLoc and yLoc.

xLoc = xLoc + 1
yLoc = yLoc +1
Review Three
Finishing Text, Creating Variables,
& Introduction to Movement
Before we start...
● Find the Processing file stored into your computer and
move it into your flash drive.

● This flash drive will store your processing files for


convenience and will ensure the security of the files.

● Double check to make sure the files in your flash drive


are up to date and from now on, save your files on
your flash drive.
1) Challenge Approaching...
Create a variable for a random()
function that makes your object
move on screen while the object
randomize its colors for 60 frames
per second.
This task will include the following
concepts…
● float variables
● random();
● void functions
● Movement
Challenge Approaching Examples
You can make interesting things happen. These interesting
effects can happen to shapes, text, background, and various
other things.

Try limiting the amount of colors that


are randomized and customize it to
your liking.

Have fun with the effects that occur!


Reminder 01
● void setup()

● void draw()
text review!
Float Variables
● Variables allows programmers to put a “name” for a data
type. This variable is called a “float” which holds
numbers.

● We made two variables called xLoc and yLoc which refer


to the x coordinates and y coordinates.

● Be careful where you put the float variables!


void Design Function
Create a new void function to call for
your design. Make sure the name of the
void function makes it clear what the
purpose of the function is.

Import your design / object into your // Add displayicon() into


void design function between the two void draw() and run your
program.
brackets.
void Movement Function
Create a void function for your object’s Example: void moveicon()

movement. Move your definitions of {


// xLoc = width/2
xLoc and yLoc to your movement //yLoc = height/2
}
function and comment them out.

Define xLoc and yLoc by using a new // Add moveicon() into void
formula, for example: draw() but make sure to put
it above your design
“xLoc = xLoc + 1; function!
yLoc = yLoc + 1;”
Fixing background issue void setup()
{
size(500,500);
To fix your “black blur” issue with their colorMode(HSB);
object. All you would need to do is move rectMode(CENTER);
your background command from void b̶̶a̶c̶k̶g̶r̶o̶u̶n̶d̶(̶2̶5̶5̶)̶;̶
setup() and move that over to void draw() }

void draw()
This fixes the issue because the object {
was being made every 60 frames per background(255);
second, with the background command moveObject();
occuring at the same speed, the drawObject();
background basically restores itself. }
Lesson Four:
Explanations, Object Movement,
& a brief introduction into Controls!
Global Variables
Pfont myFont;
The reason that PFont, xLoc, and yLoc
float xLoc;
are all on the top of the program is float yLoc;
because they are being used as Global
Variables. void setup()
{
size(500,500);
So the difference between Global
colorMode(HSB);
Variables and normal variables is that rectMode(CENTER);
they are available throughout the }
program.
Movement Explanation
void moveObject()
The assignment statement of xLoc states {
that the statement is taking the current xLoc = xLoc + 1
xLoc value and adds it by 1. yLoc = yLoc + 1
}

However, it’s not just adding one pixel to


// Essentially, it’s
xLoc because it’s being called by void moving 60 pixels per
draw(). By being in void draw, it’s adding second instead of one
1 to xLoc by 60 frames per second. pixel per second.
Starting Position for Coordinates
To set the initial value of a variable, you void setup()
would have to set it up in the very {
beginning. This is where void functions size(500,500);
become crucial. colorMode(HSB);
rectMode(CENTER);
Declare the initial values of the x
xLoc = width/2;
coordinate and the y coordinates in void yLoc = height/2;
setup(). }
Using random coordinates
Since the object goes off screen in // For example...
its current state, a solution is
needed to keep your object on void moveObject()
screen. {
xLoc = xLoc + random(-10, 10);
yLoc = yLoc + random(-10, 10);
Using the random() function, you }
can make your object stay in a
certain range of coordinates while
still being randomized.
Using random coordinates

While editing the random // Try this also…


coordinate on your own. Have you void moveObject()
tried to make the random values be {
anything other than a negative? xLoc = xLoc + random(0, 10);
yLoc = yLoc + random(0, 10);
What will happen when you do so? }
More Global Variables PFont myFont;
float xLoc;
More global variables! Now you are float yLoc;
going to make global variables for float diam;
the sides of your shapes. This will be float rad;
float widthSide;
important for later! float heightSide;

Here is an example of implementing void setup()


your new variables into your code! {
...
diam = 100; //Don’t copy this directly! Put it in its }
ellipse(xLoc, yLoc, diam, diam) //proper places.
Define the xVel variable PFont myFont;
float xLoc;
float yLoc;
Now we are going to make a new float xVel;
float diam;
float variable and call it “xVel”. float rad = diam * 0.5;
float widthSide;
float heightSide;
By making this new variable we
void setup()
need to make sure we update a few {
xVel = 1;
things. }

void moveObject()
Update both void setup() and void {
xLoc = xLoc + xVel;
moveObject() to include xVel. }
Brief Introduction into controls.
Now that you’ve learned how to void moveObject()
define the x location, y location, {
and the x velocity. How about xLoc = mouseX;
you take a break and get a brief yLoc = mouseY;
introduction into controls. println(xLoc, yLoc);
// The println() function
Use the built-in system variables: prints the coordinates of the
mouseX & mouseY! Make sure object which will be helpful
you print information on this in later.
the console log! }
Lesson Five:
if Statements & Wall Collision
EJECT YOUR FLASH DRIVES
Remember to press eject on your flash drives before you
remove them from your computer! This is crucial for the
security of your flash drives so that all your files don’t become
corrupted!
// Look for your flash drives in these two locations!
The flash drive should appear in both places!
if Statements
Like this…
if Statements are used to determine the condition
of which the code is to be executed. if Statements if (x > 180)
are used when a condition needs a true function {
when present or a false function when the [Something happens]
condition isn’t present. }

An if statement is a conditional statement, which //Basically, the


statement is like this…
is a set of rules that are executed if certain
conditions are met. A if example could be that if [this] occurs, then
something will occur when a value is over 180. [this] will happen.
xLoc > width Expression xLoc = xLoc + xVel;
//yLoc = yLoc + 1;
Now that you know about if statements, let’s use
this knowledge to benefit our code. For now, let’s if (xLoc > width)
comment out the y coordinates so that we can {
focus on the x values. [Something happens]
}
Let’s make an if statement for the condition of the
x coordinates being beyond the amount of the //The statement above occurs
when the condition is true!
width of the window size.
This statement is what is called a “Boolean Expression.” This
expression allows us to compare two number values in the statement.
Knock it back into the negatives!
Now let’s put the commands for what occurs when xLoc = xLoc + xVel;
the xLoc is more than the width of the screen. //yLoc = yLoc + 1;
To make the object bounce off the window screen, if (xLoc > width)
we want to make the object move in the opposite
{
direction. xVel = xVel * -1;
}
In order to do this, we want to make the xVel
negative so that the object will be pushed in the //The statement above tells the
program to knock the object
other direction. (Negative means it’ll subtract from back in the opposite direction!
Zero.)
xLoc = xLoc + xVel;
else if statements //yLoc = yLoc + 1;

Now let’s learn about else if statements. Think of if (xLoc > width)
else if statements as the opposite of if statements! {
xVel = xVel * -1;
if statements look for when the condition is true, }
else if looks for when the condition is false.
else if (xLoc < 0)
We want to use this boolean expression to make {
sure that when our object reaches below 0, we can xVel = xVel * -1;
make our object bounce back onto the screen! }
//We are just changing
the direction with this!
yLoc > height Expression xLoc = xLoc + xVel;
yLoc = yLoc + yVel;
Now uncomment the yLoc and add the float
variable, yVel! if (yLoc > height)
{
yVel = yVel * -1;
After you do that, use the Boolean Expression to
make your object go on the opposite y location! } //changes direction

Instead of using xLoc > width, we are using else if (yLoc < 0)
yLoc > height because the yLoc uses the height of {
yVel = yVel * -1;
the screen.
} //changes direction
Everything else should be the same for this boolean expression.
A radical part of Wall Collision
Now onto the float variable that everyone is float diam;
asking about! float rad;

void setup()
Say hello to the rad float variable! {

This variable is crucial for a precise collision, diam = [Circle Size]
rad = diam * 0.5
either with two objects or with the collision of a
//Define here so you can
wall or surface. give the initial value at the
start every time.
Make sure you set up the rad variable }
appropriately!
Including rad into Wall Collision
After you define the rad variable, we
get to use it for our code! if ([Loc] > [Width or Height] - rad)
{
Input rad into our wall collision code [Vel] = [Vel] * -1;
to make the program take the radius } //changes direction
or your half length of your shape into
else if ([Loc] < rad)
consideration before bouncing your
{
ball back onto screen.
[Vel] = [Vel] * -1;
} //changes direction
This allows your program to keep
your object on screen!
Test out your new Wall Collision Code!
Does your object collide with the walls and bounce off of
them perfectly?

Why does your code provide this outcome?

Why does the velocity of your object have to be multiplied by


negative one to be pushed into the opposite direction?

What if you changed the negative value to the velocity?


Lesson Six:
Object Classes!
How to make a Class
Today, we will go over the basics of
object-oriented programming. We’ll
make something called a “class” that
will hold all the code for an object.

Press new tab and name your tab


“Character” or whatever you want to
// Click the arrow to reveal the
name your object. “new tab” option. Clicking “new
tab” will create a new data type
Make sure it’s capitalized! for the program to use.
Why Classes?
● Using classes helps developers to break up the program
into useful parts, creating useful custom data types to be
used in our program.

● Classes allows the program to have multiple objects that


have the similar behaviors. (Object 1, Object 2, ..., etc.)

● Classes helps developers deal with the complexity of the


code.
Creating a class & Class Variables
When the Character tab is made, the next thing to do is tell
the program that the tab is being used as a class. Declare the
class by writing “class” and write the name of the tab after it.
class Character //class is known to start the class function and create your character’s initial state.
{ //Character is known as a custom data type and since the program knows it, it has become orange.

} class Character
{
Since you declared your class for your character, float xLoc;
float yLoc;
now you need to put your global variables for your
float diam;
character inside this class. Cut them from the main …
program and put them into the class. }
Class Constructor
class Character
{ Now that you declared your class and
float xLoc;
float yLoc;
moved all your global variables from the
... main program to your class, you can set up
Character()
{ the initial setup of your character.
xLoc = width/2;
yLoc = height/2;
... Think of this as your void setup() for your
} character!
// When an object is created,
it runs a constructor that
constructs the object. The
constructor is similar than a
Import all your void setup() code from your
function. main program and put in inside your class.
}
Class Methods
Character() After you added the constructor of your Character
{
... Class, now you’ll insert the Methods of your class!
}

Cut your void drawCharacter() function and your
//Methods void movementCharacter() function from your main
void drawCharacter()
{...}
program and insert it into your class below the
constructor.
void moveCharacter()
{...}
The Methods of your class acts includes the custom
} void functions of the main program!
Defining your Class!
Character Char; Let’s go back to our main program because our
void setup() program hasn’t defined our new tab yet!
{...}
In order to do that, we need to define the class in
void draw()
{...} the main program so that the program can run our
class when the program is running!
}

Next, we’ll treat our new class like a global variable


where we write the name of our tab and then make
an abbreviation for it. (Insert a name for it!)
Setup your Class!
Character Char; After we define our new class, we want to make
void setup() sure we let our program know that “Char” will
{ be a new object named “Character”.

Char = new Character();
//Tells program to make a Using this command, the main program will
new object from the class.
} acknowledge that the variable, “Char” will
void draw()
become the variable for your character.
{

}
...
Now onto the final part!

}
Draw your Class!
Character Char;
After we setup our class, we’ll have to make
void setup()
{ sure that our program actually runs the
… commands and functions inside the Character
Char = new Character(); Class.
}
void draw()
To do that, make sure you put the name of your
{
… variable, add a period, and then include the
Char.moveCharacter(); void functions of your character to allow your
Char.drawCharacter();
}
program to run the functions needed for your
character.
}
Making a new similar object
Character Char;
Character Char2;
Now that your original object is finished, now
void setup() you can make a duplicate of your object!
{
Char = new Character();
Char 2 = new Character();
}
By making a new variable for your second
void draw()
object and including the initial setup and
{ drawing of said object, now you can have two

Char.moveCharacter();
object with identical code on your program at
Char.drawCharacter(); the same time.
Char2.moveCharacter();
Char2.drawCharacter();
} How about you run your program to test it?
}
The Second Object Problem
Character Char;
Character Char2; The problem is that now we have two exact
void setup() same objects being overlapped by each other.
{
Char = new Character(xVel, yVel);
We just want objects with similar behavior
Char 2 = new Character(xVel, yVel); but having them in the exact same location
}
won’t help.
void draw()
{
… So instead, we’ll change the velocity of which
Char.moveCharacter();
Char.drawCharacter();
the circles are moving by changing the
Char2.moveCharacter(); parameters of the objects.
Char2.drawCharacter();
}
Unfortunately, we have to edit the class first!
}
Parameters for your class!
The parameters are the numerical factors
// Constructor for Character
class Character(float xV, float yV, float di)
that set the conditions of a operation.
{
xLoc = width/2; In this case, we are making three float
yLoc = height/2;
variables as parameters for the class. We
xVel = xV; //Definition of xVel
yVel = yV; //Definition of yVel can use these to set the conditions for each
diam = di; //Definition of diam object we create.
rad = diam * 0.5;
hue = 160;
} Make sure you match the definitions of
... each of the variables you use with the new
variables you added.
Fixing the problem
Character Char;
Character Char2; Now plug in your values for your characters!
void setup()
{
Char = new Character(xVel, yVel, di); An example for values you can put is:
Char2 = new Character(xVel, yVel, di); Char = new Character(1, -2, 100);
} Char2 = new Character(random(-5,5), random(5,-5), 100);
void draw()
Char3 = new Character(20, 40, 50);
{

Char.moveCharacter(); Feel free to mess around with values! You
Char.drawCharacter(); can make as much objects as you’d like!
Char2.moveCharacter();
Char2.drawCharacter();
}
Make new parameters or new objects?
}
Processing Class Survey 2

https://forms.gle/Xktcz9E4LHFVTbVu6
https://docs.google.com/forms/d/e/1FAIpQLSdWM0SdNLaWTNG206lM_eKefwGe5RTque8Ic6g4ho9rOvSyiQ/
viewform?usp=sf_link
Lesson Seven:
Ping Pong - Introduction to
Collision Detection
Review of Parameters!
Remember that the parameters are
// Constructor for Character the numerical factors that set the
class Character(float xV, float yV, float di, float _ )
{
conditions of a operation.
xLoc = width/2;
yLoc = height/2; These are the parameters that we
xVel = xV; //Definition of xVel
yVel = yV; //Definition of yVel
made yesterday for our lesson.
diam = di; //Definition of diam
rad = diam * 0.5; Now to test what we learned, how
hue = 160;
}
about you make one more
... parameter for the color of each
object! (Or three if using RGB!)
Setup two new objects!
First, comment out all your characters that you’ve made for now.
(Comment the global variable, the setup, and the methods for the Char.)

Afterwards, make two new objects called the “Ball” and the “Paddle” to
proceed with our plan to make a single player pong game today!

The next thing to do is to make the class, constructor, and methods for
each of the objects.

//An alternative route to take is to make a new Processing program


instead of commenting out what you already have!
Ball Setup
class Ball
{
float xLoc;
float yLoc; This is an example of the set up for
float xVel;
float yVel; the Ball. You should have mostly
float diam;
float rad;
everything set up but you have to
float hue; make a few changes to match the
Ball(float xL, float yL, float xV, float yV, float diam, float h) code to the object.
{
xLoc = xL;
yLoc = yL; Feel free to make your own
xVel = xV;
yVel = yV; changes to the setup of the ball.
Diam = di
rad = diam * 0.5
hue = h;
Paddle Setup
class Paddle
{
This is an example of the set up for the
float xLoc; Paddle. You should have mostly
float yLoc;
float paddleLength;
everything set up but you have to make
float halfLength; a few changes to match the code to the
float randomhue;
float hue; object.
Paddle(float xL, float h, float padLength)
{ Since the Paddle will become a line, the
xLoc = xL;
yLoc = height/2; variables will be different from the ball.
paddleLength = padLength;
halfLength = paddleLength/2;
hue = h; Feel free to make your own changes to
}
the setup of this paddle!
Description for Collision Detection
For collision detection, there is many ways to accomplish a
successful collision. However, many of the methods are
complicated and complex because of the preciseness needed for
the collision.

Though, today we are going to work on a basic collision which


includes a paddle and a ball. With the paddle, we are going to hit
the ball back. The paddle will only move vertically to simplify the
equation needed for the collision.
boolean collide()
We are going to start with the Paddle’s code first. For the paddle,
we are going to make a collide() method. This method will tell the
conditions of the collison.

We only want a true or false response for our collide method so


we’ll make it a boolean expression. When we make a boolean
expression, we’ll need to include two values into the expression.
Instead of what we did last time, we’ll just put the ball’s tab name
and then the name of the variable between the parentheses.
Using the boolean collide()
boolean collide(Ball ball) //The collide method only needed is the ball’s location and radius.
{
if ( ball.xLoc - this.xLoc < ball.rad && //The x location between the two objects is less than the ball’s radius.
ball.yLoc > this.yLoc - halfLength && // if the ball’s y coordinates are below the highest point of the paddle.
ball.yLoc < this.yLoc + halfLength ) // if the ball’s y coordinates are above the lowest point of the paddle..
{
return true;
}
else
{
return false;
}

If the ball collides with the paddle, the collision will be reported as true, otherwise it
will be reported as false. This will be important for the program to note later on!
What’s up with “this”?
We are going to be using something called “this”. But what does
this do or what does this mean?

this can be used to make the program refer to itself essentially. In


this case, this would refer to the class.

For example, if the program says, “this.xLoc”... the program is


referring to the class’s x coordinate.
Ball detecting paddle collision!
if (xLoc+rad > width) For the final step for your collision
{
xVel = xVel * - 1;
detection, we want to use the ball tab
} and go to the movement function of the
else if (pad.collide(this) ) ball.
{
xVel = xVel * -1;
} We want to have the ball detect the
paddle’s collision and if the ball collides
... with paddle, we want the code to push
// The ball is going to focus on the the ball in the opposite direction.
paddle’s collision and vise versa.
Fixing the main program
Make sure you update the
declaration of the classes and
make sure your main program
runs both your paddle and your
ball.

Here’s an example of what it


can look like and after you are
done, run your program to see
your changes!
Lesson Eight:
Ping Pong - Clean Code,
Acceleration, & Game Over Screen
Processing Class Survey 3

https://forms.gle/vszsvQ63aErcZYkw5
https://docs.google.com/forms/d/e/1FAIpQLSd-to2_EuCu_5AqPBVfWN-H0
4hotUciedRUfc_utINdzTBGTw/viewform
Removing the left-side barrier!
if (xLoc+rad > width) First things first, you want to comment out the code
{
concerning the expression: xLoc is less than the radius!
xVel = xVel * - 1;
}
else if (pad.collide(this) )
This code will keep the ball inside the window by
{ knocking it back inside by having a barrier on the left. For
xVel = xVel * -1; the left, we want to use the paddle to knock it back
} instead. Comment out what causes the ball to bounce
// else if (xLoc < rad) off the left side of the window.
{
xVel = xVel * -1; Next, print the coordinates of the x location and the y
} location to know where the ball is at while the program
println(xLoc, yLoc); is running.
The use of “&&”
To access the “&” symbol, all you need to do is hold down the shift button
and press the number 7. To use the operator, “&&” you need to press the
number 7 twice while holding down shift.

This operator will allow you to include two or more conditions in one
statement, however all the conditions included in the statement must be
true conditions. If two conditions end up with the same result but they
aren’t both true, using “&&” won’t work for the statement.

A good example of using the “&&” is by looking at the if statement made


in the Paddle’s collision detection code.
The use of “||”
To access the “||” symbol, you need to hold down the shift button and
press the forward slash button that is right under the backspace button.
When you press the forward slash button while holding down shift, you
should make this symbol, “||” which is a logical operator.

This operator will let you manipulate two boolean values. Consider “||”
to be like the word “OR”. If [this] happens OR [this] happens, then
[something command] will occur. Now, think of “||” instead of OR.

A good example to use this in is with your movement code for your ball.
if(xLoc + rad > width || xLoc < rad) {xVel = xVel * -1;}
if(yLoc > height-rad || yLoc < rad) {yVel = yVel * -1;}
Acceleration
float xLoc;
float yLoc; To make and edit the acceleration of
float xVel;
float yVel; your ball so that the ball moves faster
float Accel;
… over time, all you need to do is make
Ball(float xL, float yL, float xV, float yV, ...) another float!
{ //You can also make a float for Accel!
xLoc = xL;
yLoc = yL;
xVel = xV; Once you make another float, you can
yVel = yV;
Accel = -1.01; write a negative value for the
}
… acceleration and then change the
else if (pad.collide(this) )
{ value from one.
xVel = xVel * Accel;
}
Adding a “Game Over” Situation
else if (xLoc < rad) Let’s make our game an actual game!
{
x̶V̶e̶l̶ ̶=̶ ̶x̶V̶e̶l̶ ̶*̶ ̶-̶1̶;̶ The first thing to do is edit your code
println("Game Over!"); by editing your former code to make
} a barrier for the left side of the
screen.

For now, let’s remove what was


currently there and let the console log
print the words, “Game over!”
Changing the void move() into boolean move()
boolean move() However, we want a proper game over screen
{ rather than the console telling the developer that
the game’s over.

So what we need to do is to change the void
else if (xLoc < rad) function into a boolean function. The void function
{ doesn’t return anything while the boolean function
return false; can return two values. In this case, boolean will be
used to state that something is either true or false.
}
… If the game is over, the function will tell the
program to stop running. If the game is still playing,
return true; it will return as true.
boolean playOn!
PFont myFont;

Ball ball;
boolean playOn; //Determines if the program is running, true or false.
Paddle pad;

Now we are going to make a new variable called the boolean


variable!

With this, we can use this variable to determine if the program


is running!
Gameover Screen
So now all we need to do is to put our new
void draw() boolean variable to use!
{
if (playOn)
{ Since boolean variables need a false and true
background(100); statement, we need to add those in our code. In
pad.move();
pad.drawPaddle(); void setup(), set the variable to true.
if ( ball.move() ) // playOn = true;
{
ball.drawBall();
}
For void draw(), make sure you include if
else statements to play out your code. You’ll need to
{ tell the program to use the variable, playOn, to
playOn = false;
println("Game Over!");
start your program. When the program stops
} playing, you’ll need to tell it to return the variable
} as false.
}
Adding text to your Game Over Screen
… Now that you’ve finished your code
else
{ for your Game Over screen, now all
playOn = false; you need to do is create what appears
myFont = createFont("Impact", 30);
textFont(myFont); for your Game Over screen!
fill(190,255,255);
textAlign(CENTER,CENTER);
text("Game Over!", width/2, Feel free to make your own text or
height/2); special effects to occur when the
println("Game Over!");
} game finishes!
}
}
Please enjoy your game!
Lesson Nine:
Ping Pong - Scores,
Sound Effects, & Music
Integers
We’ve used float variables in the past that had the capabilities
to use number values that can include decimals in them.

Now we are going to use a int variable which only uses number
values that are integers. Integers are numbers that are full
numbers like 1, 2, 3, 4, etc. Decimal numbers are not integers.

For our first int variable, make a new global variable that is a int
variable for scores in your game. Then, set that variable to zero
in the void setup().
Scores to FrameCount
This is one way of using the score
variable in your code.

With this method, you are


making the score equal to the
frameCount.

Then, you print the gameover


screen and when doing so, you’ll
add some text explaining the
score along with the score value
frameCount counts all the frames that has been
being added to it as well. The
runned since the program started.
score is divided by 60 because
the program runs at 60 frames.
//The program runs at 60 frames per second.
Scores to HitCount
The other method would be
setting the score variable to the
collision between the ball and
the paddle.

With this method, you wouldn’t


need to divide the score by 60 in
the main program.

Instead, all you need to do is


// This works because every time a collision make the score variable equal to
occurs, a point gets added to the score. itself plus one.
Adding a
data folder!

This will be helpful for


allowing you to store files
that you can import into
your program!
Sound Effects and Music!
Now we are moving onto sound effects! Sound effects and
music is an important part of video games after all.

We’ll add some sound effects to the collisions that occur to the
objects in our game.

First before we set up the code for our sound effects and music,
we need to make a library for them!
Importing sound code!
Now that we’ve made our data folder, we can move onto the next
step! So before we actually start coding, we need to important
the classes and variables for our code with sound!

In fact, Processing already has this done and all we need to do is


important the library including the built-in system variables for
sound and music!

Import the sound library by pressing: Sketch -> Import Library ->
Sound. (You might have to add and download it if it isn’t already!
Sound Effect Variables
After we imported the
sound library, all we need
to do is use the SoundFile
method and make three
variables for our three
sound files.

Next, we will declare the


sound files to be the
same as the wav files in
our data folder.
Incorporating the Sound Effects
Now that we set up our
variables for the Sound
Effects, now all we need
to do is put them into
action!

Using the play() method,


put the name of your file
and you can play the file
during any point in your
// Test out your code to see your results!
code!
Adding Music Now onto adding music for
your game!

SoundFile Music;
void setup() To add music, you need to
{
... use the SoundFile variable
collideWall = new SoundFile(this, "collideWall.wav");
collidePaddle = new SoundFile (this, "collidePaddle.wav");
but instead of using play(),
missBall = new SoundFile(this, "missBall.wav"); you would use loop()
Music = new SoundFile(this, "Music.mp3");
Music.loop(); instead!

else
{ Then, you need to make
Music.stop();
playOn = false; sure the music stops after
... the game is done!
Lesson 10:
Finishing our Ping Pong Game!
Keys, controls, and more!
2) Challenge Approaching...
Make your ball or paddle change
color overtime at a slow pace (not
using the random() function).

Then, figure out how to pick a


specific color range.
This task will include the following
concepts…
● float variables
● if statements
● Paddle’s Initial Parameters
Challenge Option - Answer
Paddle(float xL, float h, float padLength) All we are doing with the hue (pure
{
color) is adding more to the color
… //Set the parameter for what the hue starts at.
} which changes the color overtime.

hue = hue + 0.5; After it reaches 255, it’ll be stuck at


red so to prevent this, make an if
strokeWeight(10);
stroke(hue,255,200);
statement to set the hue to 0.
line(xLoc,yLoc - halfLength,xLoc,yLoc + halfLength);
If you want a specific color range,
if (hue > 220) //Ends with purple all you would need to do is change
{
hue = 180; //Starts at dark blue
the initial hue (using the object’s
} parameters) and the if statement.
Game Over Music
else Now it is time for your game over
{ music!
Music.stop();
GameOver.loop();
playOn = false; Instead of putting your Game Over
... music command in the void setup(),
}
}
you will have to put it in the else
} command.

Unlike your background music, it


doesn’t start at the beginning.
Play again!
else Now that you have a game and a
{
... game over screen, perhaps it is
text("Game Over! Your score is: " + Score, width/2, height/3); time to give our players a chance
fill(randomhue, 255, 255); //Makes the text a random color.
text("Play again?", width/2, height/2); to replay the game.
println("Game Over!");
}
} //Feel free to add text explaining how the player needs to If you want players to press a key
} // press a key to continue! This is an example! to continue, you need a void
void keyPressed()
keyPressed() function!
{
Music.stop();
GameOver.stop();
Make sure you make both the
setup(); // Calls the start of the game again! music stop before you call setup()!
}
Setting a key to Play Again!
void keyPressed()
{ If you want to the game to start
println("Key code pressed: " + keyCode);
// Tells you what key is pressed (With a numeric code!) in
over using a key, here is how to
// the console log! Give it a try! do so!
if (key == ENTER || key == RETURN) // ENTER for PCs,
{ // RETURN for Macs! Make your code accessible for both! We want to make an if
Music.stop(); statement for when the
GameOver.stop();
setup(); program registers the key being
} pressed in the program!
void keyReleased()
{ Using this, we’ll be able to press
println("Key has been released! ^u^");
//Tells you when the key has been released! The key pressed a key to restart the game! Isn’t
// console commands multiple at a time! This tells us when it ends! that pretty neat?
}
keyPressed(), key, & keyCode
The keyPressed() function is used to detect when a key is pressed during the
program. void functions determine when the event occurs in the program so
the void keyPressed() function deals with all the key press events throughout
your code!

When holding a key down, it’ll make multiple calls to that key as the action is
being repeated multiple times. The action will stop when the key button is let
go. That’s a key piece of info isn’t it?

Now the system variable, key, contains the value of the key when pressed or
released. keyCode does something similar, however, it specializes in special
keys.
key vs keyCode
key is useful for defining a key’s purpose in your program. Since most of the keys
you use for the system variable are used pretty often, the program isn’t required to
check what the key is. You just need to tell the program which key to use and what
the command is for that key. Pretty simple if you ask me.

keyCode is used to detect “special keys” that aren’t commonly used in the program
so we would need to define them. These special keys include the arrow keys, “UP,
DOWN, LEFT, RIGHT”, and also “ALT, CONTROL, and SHIFT.”
// keyCode also lists the keys in the console log as numbers!
keyCode is required to have the program check to see if the key is coded. To do
this, we need to add this conditional, “if (key == CODED)” to use special keys.

key can use all the letter keys and also “BACKSPACE, TAB, ENTER, RETURN, ESC,
and DELETE.”
Setting Movement to keys!
void move()
Now the first step with using keys for
{ your paddle’s movement is to comment
//yLoc = mouseY; out the movement code we already
//Comment this out so you can use keys to move!
have.
}

void PaddleUp() Next, we need to make two new void


{ functions representing the movement
yLoc = yLoc - Accel; that our paddle is going to make!
} //You can make a acceleration variable!
Make sure you use the coordinates to
void PaddleDown()
{
move so that you aren’t constantly
yLoc = yLoc + Accel; moving! You only want to move when
} //Name the accel variable whatever you’d like! the key is pressed!
Calling key Movement via keys
void keyPressed()
{
Now that you are done with your paddle
println("Key code pressed: " + keyCode); movement, we just need to declare the key we are
if (key == ENTER || key == RETURN) going to use for the movement!
{
… //Added earlier.
} We are going to use the class variable’s name to let
if (key == 'w') the program look within that class and then you’ll
{
pad.PaddleUp(); put the name of your void movement classes
} afterwards.
else if (key == 's')
{
pad.PaddleDown(); Make a if statement and then an else if statement
}
} to accomplish this. Afterwards, run your program
to test if you can use the keys to move!
Calling key Movement via keyCode
void keyPressed()
{
If you want to use arrow keys instead,
println("Key code pressed: " + keyCode); you’ll need to use keyCode!
if (key == ENTER || key == RETURN)
{ Remember, using special keys requires
… //Added earlier.
} to check what the keys are so that they
if (key == CODED) //Using keyCode for the arrow keys. can properly be used in code!
{
if (keyCode == UP)
{ Write the if statement for if the key is
}
pad.PaddleUp(); coded and make sure you replace key
with keyCode since we are using
else if (keyCode == DOWN)
{ special keys.
pad.PaddleDown();
}
} Run your code to see your results!
}
GAME CLEAR!
You’ve completed your pong
game!

Now comment on every


programming concept and
make finishing touches so we
can create a new game next
time!
Lesson 11:
Point & Click Game: Images, Mouse
Presses, Enemies, and more!
New Game / PImage
PImage Cursor; Click File > New to make a new game!
float xLoc;
float yLoc;
Next, click File > Save As… to create the next
void setup() game we are going to create!
{
Next, set up your code and include our new
} variable, PImage!
void draw()
{
With this new variable, you’ll be able to name
the image that you are going to add into the
} game!
Add image to data folder
Now make a data folder for your new
project and make sure you include the file
of your image in here.

You can either copy and paste your image


from your computer or you can use
“Sketch > Add File…” to search
throughout your computer to find the file.

Processing will then put the file into the


folder.
loadImage / image()
PImage Cursor;
float xLoc; Next, we want to add our essential code
float yLoc; to our program and then we’ll use our
void setup() loadImage function!
{
fullScreen(); //Makes the game fullscreen.
Cursor = loadImage("pointer-cursor.png"); loadImage can load four types of images
xLoc = width/2; (.gif, .jpg, .tga, & .png) from PImage. Use
yLoc = height/2;
} loadImage in setup()!
void draw()
{
The image() function is used to draw an
background(200); //Clears blurs. image in the program. The equation for
image(Cursor, xLoc, yLoc, 32, 32);
} //Cursors are usually 16x16 or 32x32;
this function is: (variable, xLoc, yloc, w, h)
An alternative to using images for
Alternative - Urls your game requires you to acquire a
url that has an image you would like
PImage webImage; to have from that site.
...

void setup() Right click the picture from the


{ website to get the image onto
fullScreen(); //Makes the game fullscreen.
another tab to copy the url from.
String url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
webImage = loadImage(url, "png");
Then, use a String method to spell
...
} out the url as a variable. Using this
variable, you can take the image on
void draw()
{ the site and define it as a png file.
background(200); //Clears blurs.
image(webImage, xLoc, yLoc, 100, 50); Finally, you’ll be able to load your
}
file. Try it out!
imageMode()
There is three imageModes for images.
PImage Cursor;
float xLoc;
float yLoc; CORNER is the default option which uses the last two
parameters of your image as the width and the
void setup() height.
{
...
} CORNERS uses two corners as points (kinda like a line)
and two parameters of your image would count for
void draw() the upper left corner and two parameters would
{
background(200); //Clears blurs. count for the lower right corner.
imageMode(CORNERS);
image(Cursor, xLoc, yLoc, 32, 32); CENTER uses the last two parameters of the image as
} //Cursors are usually 16x16 or 32x32;
the image’s center point.
void imageMovement
PImage Cursor;
float xLoc; Now the next step is to make a void
float yLoc;
function for the image movement.
void setup()
{
...
} Make the xLoc and yLoc equal to your
void draw() mouse and test your code out!
{
cursorMovement();
}
Include your imageMode and attempt to
void cursorMovement()
{
use all the different modes. See what
xLoc = mouseX;
yLoc = mouseY;
works for the program the best!
}
Character Class
class Character
{
Since you already know the steps, make
float xLoc; sure you make a character class so that
float yLoc;
float widthLength; you can have a character that moves.
float heightLength;

Character() For now, create your character so that


{
xLoc = width/2; we get to creating our movement with
yLoc = height/2;
widthLength = 20; the mouse.
heightLength = 20;
}
Since your character is a square or
void display()
{ rectangle, we are making two variables
fill(0, 10, 50);
rect(xLoc, yLoc, widthLength, heightLength);
for the width length and height length of
} our character.
}
Easing Easing is useful to create a distance between two
class Character
{
objects. In this case, we want a distance between
float xLoc; the cursor and the object.
float yLoc;
float easing = 0.005;
Easing will allow the object to follow the cursor
Character()
{ so that eventually the object can reach the
... location of the cursor eventually.
}

void display() We want distance between the two so that the


{
... object can move instead of staying in one
} location.
Movement with Easing
class Character The movement for our character is different this
{
float easing = 0.005;
time because we are using a mouse to move our
… character. The character should move when the
mouse is pressed.
void move()
{ //Name simplified because it’s a class.
if (mousePressed) For the character to move we need to set a target
{ for the movement. We’ll set the target for our
float targetX = mouseX;
float distx = targetX - xLoc;
object to be mouseX, aka the cursor.
xLoc += distx * easing;
Next, we want to subtract the distance between the
float targetY = mouseY; object and our target. After that, we just need to
float disty = targetY - yLoc;
yLoc += disty * easing; multiple the distance with easing to create the
} movement for our object.
Creating an enemy
class Enemy
{
float xELoc; Now that we’ve made our player, we can
float yELoc;
float hue; create our enemy!
float widthLength;
float heightLength;
// Remember to make two variables for
// the width and height of your character! Make sure you create a new class and
Enemy(float h)
{ define it in your main program.
xELoc = width/3;
yELoc = height/3;
hue = h;
widthLength = 20; Make your own variables for your enemy
heightLength = 20;
} class (name them differently from your
void display()
{
character class) and make your display
fill(hue, 255, 150);
rect(xELoc, yELoc, widthLength, heightLength);
code to show your enemy.
}
}
Movement for the Enemy
class Enemy
{
float xELoc;
First, create a new variable called “Easing” or
float yELoc; “Enemy easing”. Name it something you can
float hue;
float Length; make different from your character easing
float Easing;
variable.
Enemy(float h, float E)
{
Easing = E; Easing for an enemy is a little different for your
}
character. The target for your movement is
void move()
{ now the coordinates of your character object.
float TargetX = character.xLoc;
float TargetY = character.yLoc;

float distx = TargetX - xELoc;


After the movement is done, make the Easing
float disty = TargetY - yELoc; variable a parameter for your Enemy. This will
xELoc = xELoc + distx * Easing; allow you to change the speed of each enemy
yELoc = yELoc + disty * Easing;
}
in the future.
Set up the main program with your classes!
Character character;
Enemy enemy1;
... Now the final step is to add your
void setup()
{
classes to the main program and
...
size(700,700); make sure all the functions of your
character = new Character();
enemy1 = new Enemy(10, 0.01);
classes are included in your main
}
program.
void draw()
{
background(200);
... Then, you can run to see if all your
character.display();
character.move(); functions are running in your
enemy1.display();
enemy1.move(); program. Have fun!
}
...
Appeartime for your enemy!
class Enemy The next thing to do with our enemy
{
... is to add an appearance time for
float AppearTime;
when the enemy shows up in your
Enemy(float h, float E, float AT)
{
code!
AppearTime = AT;
}
For this, we need a new variable to
void display()
{
use when the frameCount is over the
if (frameCount/60 > AppearTime) Appearance time. Add an if
{
… //Add everything in here. statement to reflect this and test our
}
} your code!
Including AppearTime with Movement
void move()
{ As you could see, the object moved
println(frameCount/60);
//Prints the seconds in the before the appearance time
program. occurred.
if (frameCount/60 > AppearTime)
{
float TargetX = character.xLoc; To fix this issue, we needed to make
float TargetY = character.yLoc;
an if statement stating the same
float distx = TargetX - xELoc;
float disty = TargetY - yELoc;
thing to make the object’s
appearance and movement start
xELoc = xELoc + distx * Easing;
yELoc = yELoc + disty * Easing; when their appearance time occurs.
}
Collision with Rectangles Pt.1 (Enemies)
boolean collide(Character character) Now onto the collision with rectangles.
{
if ( this.xELoc < character.xLoc + character.widthLength && First we need to go into our enemy class!
this.xELoc + this.widthLength > character.xLoc &&
this.yELoc < character.yLoc + character.heightLength &&
this.yELoc + this.heightLength > character.yLoc) Collision with rectangles are different
{ because you need to take into
return true;
} else consideration on all the sides of the
{ rectangles. An example of this is on the
return false;
right.
}
}
Then if the collision occurred, it must
} //End of Enemy Class. return as true to tell the program it
occured. Else, the collision is false.
Collision with Rectangles Pt.2 (Enemies)
boolean noCollision()
{
If (enemy1.collide(this) || enemy2.collide(this) || enemy3.collide(this) ) Now onto our Character class!
{
return false;
} We need to make a new boolean
function for our collision code.
return true;
This will take the collision info
} from enemy and put it to use!

} //End of Character Class.

We need to use a new boolean function because we don’t want it to interfere with our display and movement
code. (If we do it in character movement, it won’t count the collision when holding down the mouse.)
We’ll name this boolean function, “no Collision.”

We want to make a if statement in our collision code to tell our boolean function if there isn’t a collision or if there
is a collision. If it collides, then the function is false.
Collision with Rectangles Pt.3 (Enemies)
void draw()
{ And finally, we can finish things up in the main program. We
if (PlayOn)
{
want to create a game over screen for when the collision occurs.
background(200);
if (character.noCollision() )
{
Now we want to create the variable PlayOn again but this time,
... we want to use the noCollision boolean that we used earlier.
character.display();
character.move();
Insert your noCollision boolean into your if statement
enemy1.display(); conditional.
enemy1.move();
… // You can add more enemies here!
} Then, you want to include all your display and movement code
else
{ into the if statement.
PlayOn = false;
textAlign(CENTER,CENTER);
text("Game Over!", width/2, height/2); After that, make an else and include the gameover screen that
} you desire to create! Have fun with your gameover screen and
}
} run your program to test the results.
Finishing things up!
Enemy enemy1;
Enemy enemy2; Now we are pretty much
Enemy enemy3; finished with the code that we
void setup() intended to create!
{
size(700,700);
colorMode(HSB); You want to create more
...
PlayOn = true;
enemies to make the game
harder!
character = new Character();
enemy1 = new Enemy(0, 5, random(0.001,0.01)); //Hue, Easing, Appearance Time.
enemy2 = new Enemy(170, 15, random(0.008, 0.02)); Also make sure you add the
enemy3 = new Enemy(100, 30, random(0.02, 0.06));
music and sound effects you
} want because we are making a
new game soon!
GAME CLEAR!
You’ve completed your point
and click game!

Now comment on every


programming concept and
make finishing touches so we
can create a new game next
time!
Lesson 12:
Air Hockey: Ball Collision, Points,
and Multiplayer
New Game / Classes
Puck puck; Click File > New to make a new game!
Player p1;
Player p2;
int P1Score; Next, click File > Save As… to create the next
int P2Score; game we are going to create!
void setup()
{ Next, set up your code and include the new
classes for our new game. Make a player class
} and a puck class!
void draw()
{ Then you can make a score for your first player
and a score for your second player!
}
Creating your player!
class Player Next, we want to create our player class.
{
… // Include variables
Player(float __) //Include parameters Since we are using a class for each of our
// for player 1 and player 2
{ players, we are going to include variables
… // Include declarations for each and with the differences
}
between them, we’ll make some
void display() parameters for our class.
{
strokeWeight(0); //No outline
fill(hue,255,200); //Actual Player Afterwards, we’ll move onto the display
ellipse(xLoc,yLoc,diam,diam);
strokeWeight(2); //Handle outline of our players. Since this is air hockey, we
ellipse(xLoc,yLoc,diam/2,diam/2); //Handle are including another circle as the handle.
}
Moving your player!
class Player
{ After you successfully displayed your
... character, you can start to create your
void display()
{ code to move your character!
...
}
void Up() Like we did with our pong code, create an
{ up and down void function to later
yLoc = yLoc - yAccel;
}
connect with keys.
void Down()
{
Make sure you make the appropriate
yLoc = yLoc + yAccel; variables to accomplish this!
}
keyPressed() for player Movement!
void keyPressed()
{
if (key == 'w') //Using keys w & s to move.
Now onto keyPressed()!
{
p1.Up();
}
else if (key == 's')
If you remember the previous lesson,
{
p1.Down();
keyPressed() takes care of all the key
} pressed throughout your code.
if (key == CODED) //Checks if the key is coded.
{
if (keyCode == UP) //Using arrow keys, up and down to move.
{
With keyPressed(), you want to make
}
p2.Up(); sure you make the controls for both of
else if (keyCode == DOWN)
{
your characters to make sure both
}
p2.Down(); characters can move.
}
}
Setting up your players in the program!
void setup()
{
size(500,500);
colorMode(HSB);

p1 = new Player(6, 20, 45); // Paddle(xLoc, hue, diam);


p2 = new Player(width-6, 20, 45); // Paddle(xLoc, hue, diam);
P1Score = 0;
P2Score = 0;
}

Now you might as well set up your void setup() code to test the code you
have this far! Make sure the x coordinates of your players are in their
proper locations and include any differences between your players in your
player class’s parameters as well. Include your class’s functions in the
program as well!
Creating your puck!
class Puck Next, we want to create our puck class.
{
… // Include variables
Puck(float __) // Include parameters Just like with our player class, we are
// for your puck.
{ going to include the variables needed to
… // Include declarations create our puck code!
}

void display() Then, we need to create a circle that is


{
fill(0,0,0); completely black to resemble a puck.
strokeWeight(0);
ellipse(xLoc,yLoc,diam,diam);
} Finish the design of your puck and get
ready to work on moving it!
Moving your puck! Now let’s move onto our code for the
movement of the puck!
void move()
{
xLoc = xLoc + xVel;
We would need to make if statements for
yLoc = yLoc + yVel; each of the walls of the program. The left
if (xLoc+rad > width) side would be where the second player
{
xVel = xVel * -1; makes a point while the right side is when
P1Score = P1Score + 1;
missPuck.play(); //Play sound effect for the paddle missing the ball.
the first player makes a point.
xLoc = width/2;
yLoc = height/2;
xVel = InitalVelocity; Next, we need to make a float for the
} else if (xLoc < rad)
{ Initial Velocity which is the same velocity
P2Score = P2Score + 1;
missPuck.play(); //Play sound effect for the paddle missing the ball.
for the beginning of the game. Once you do
xLoc = width/2; that, you can make the coordinate
yLoc = height/2;
xVel = InitalVelocity; centered because this code will make the
}
if (yLoc > height-rad || yLoc < rad) puck reset when a player gets a point.
{
collideWall.play(); //Play sound effect for wall collision.
yVel = yVel * -1; You can also include your sounds effects as
}
} well!
Setting up your puck in the program!
void setup()
{
size(500,500);
colorMode(HSB);

puck = new Puck(width/2, height/2, random(1,2), random(1,4), 30, 0); //xLoc, yLoc, xVel, yVel, diam, hue
p1 = new Player(6, 20, 45); // Paddle(xLoc, hue, diam);
p2 = new Player(width-6, 20, 45); // Paddle(xLoc, hue, diam);
P1Score = 0;
P2Score = 0;
}

Yeah! Now you can put your puck into the program by declaring the puck
class as a new puck object so that you can test your code!

Don’t forget to include your void functions in your void draw().


Ball Collision Pt. 1 Now back into our player class, we need to
boolean collide(Puck puck) create code for when a collision occurs for
{ either of our players.
float distx = this.xLoc - puck.xLoc;
float disty = this.yLoc - puck.yLoc;
float distance = sqrt(distx * distx + disty * To do this, we need to have the distance
disty); //Makes everything positive. between the players and the pucks and have
variables for it so that we can have a value
if (distance < this.radius + puck.rad)
{ for the distance.
return true;
} else Then, we can use an if statement for when
{
the distance is less the radius of both circles.
return false;
This allows us to tell the program that the
} collision occurred by saying its true.
} Otherwise, it would be false.
Ball Collision Pt. 2
void move()
{
... Next, we can go back to our puck
if (xLoc+rad > width) code and add two more else if
{

}
… // Added already. statements.
else if (p1.collide(this))
{
collidePuck.play(); //Play sound effect for paddle collision.
xVel = xVel * Accel; When we have done so, we need to
}
else if (p2.collide(this)) make the puck know that the collision
{
collidePuck.play(); //Play sound effect for paddle collision.
xVel = xVel * Accel;
had occured. We can do this by
}
else if (xLoc < rad)
making an else if statement stating
{
… // Added already. this. You can also combine the two
}
if (yLoc > height-rad || yLoc < rad)
{
else if statements into one else if by
}
… // Added already. using the || operator!
}
playOn & GameOver
void draw()
{
if (playOn) Now we want to include the boolean
{
background(100);
if(GameContinue() )
playOn as we’ve used a couple times
{
puck.move(); before. Make sure to create, declare,
puck.display();
p1.display();
p2.display();
and add your playOn boolean into
}
else
your code.
{
Music.stop();
playOn = false;
GameOver.play();
playagain = createFont("Impact", 30);
Next, create your playOn if statement
textFont(playagain);
fill(190,255,255); and create the gameover screen to go
textAlign(CENTER,CENTER);
fill(randomhue, 255, 255); //Makes the text a random color.
text("Play again?", width/2, height/2);
with it. If you want, include a name to
fill(randomhue, 255, 255); //Makes the text a random color.
text("Press Enter to continue!", width/2, height/1.7); your font like how my code used
}
} “playagain” as the font name.
Start again and key presses!
void keyPressed()
{ Now that we’ve created our
println("Key code pressed: " + keyCode);
gameover screen, we might as well
if (key == ENTER || key == RETURN) create a method to start over the
{
Music.stop();
game with a key!
GameOver.stop();
setup();
} Include an if statement for what key
} should be pressed for the method.

void keyReleased()
{
Also if you choose to, you can print
println("Key has been released!"); what key is being pressed and when!
}
boolean GameContinue()
boolean GameContinue()
{
if(P1Score > 9)
Now that we completed our playOn and
{ gameover code, we can create the
Gameover = createFont("Arial", 20);
textFont(Gameover); condition of when the game should
fill(180,255,200);
textAlign(CENTER,CENTER); continue or not.
text("Player 1 wins!", width/2, height/3);
text("P1 Score: " + P1Score + " P2 Score: " + P2Score, width/2, height/2.5);

}
return false; We want to make an if statement for
if(P2Score > 9) when the score becomes big enough to
{
Gameover = createFont("Arial", 20); end the game. You can choose the score
textFont(Gameover);
fill(180,255,200); to end the game.
textAlign(CENTER,CENTER);
text("Player 2 wins!", width/2, height/3);
text("P1 Score: " + P1Score + " P2 Score: " + P2Score, width/2, height/2.5);
return false;
Create your game over text explaining
} who won and how many points each
return true; //If either player doesn't have over 9 points.
} player got.
Finishing our program code!
void draw() Now you can include your
{
if (playOn) GameContinue() condition into your void
{
background(100);
draw() code and make sure you put the
if (GameContinue() ) background on top to prevent the classes
{
puck.move();
being displayed when the game is over.
puck.display();
p1.display();
p2.display();
Be careful where you put your brackets
} and make sure your condition holds all
else
{ your display and move functions that you
Music.stop(); need for your game.
playOn = false;
GameOver.play();
… // Game over screen text. Include your own music and sound effects
}
} to personalize your game! Have fun with
} the game you create!
GAME CLEAR!
You’ve completed your air
hockey game!

Now comment on every


programming concept and
make finishing touches so we
can create a new game next
time!
Lesson 13:
Platforming: Gravity, Surface
Collision, and more!
New Game
Character character; Click File > New to make a new game!
Ground ground;

void setup() Next, click File > Save As… to create the next
{ game we are going to create!
}
Then, add all your code you want into your
void draw() character class. We’ll get to the ground in a
{ second.
}
Set up your void setup() and void draw() as well!
Character Class!
class Character
{
Next we need to include out global variables for
float xLoc; your character class!
float yLoc;
float xVel;
float yVel;
float Speedx; We are going to include xVel and yVel for future
float widthLength; use and make sure you define xVel and yVel in the
float heightLength;
declarations. yVel will start at 0 for reasons that
Character()
{ will be explained later.
xLoc = width/3;
yLoc = height/2;
xVel = 20; We’ll also need to have a speed for x which can be
yVel = 0;
Speedx = 1.5; whatever speed you want.
widthLength = 20;
heightLength = 20;
} After that, create your display() function!
Ground Class!
class Ground
{ Next we need to create your ground class and
float xLoc1;
float xLoc2; make the global variables for your ground class!
float yLoc;
float hue;
If we are using a line, we’ll need at least to x values
Ground(float x1, float x2, float y, float h)
{ to make the length of the platform. However, since
xLoc1 = x1;
xLoc2 = x2;
the platform is horizontal, we don’t need another y
yLoc = y; value because the y value will stay the same!
hue = h;
}

void display()
Make sure you include two x values and one y
{ value to your ground class and make the void
stroke(hue, 55, 155);
strokeWeight(0); display() as well.
line(xLoc1, yLoc, xLoc2, yLoc);
}
Ground Collision
// If there is a collision with the platform. Now for ground collision. We need to make a
void groundCollision()
{ void function for when the collision occurs
if (character.yLoc + character.heightLength > this.yLoc)
{
between your ground and your character.
character.yLoc = this.yLoc - character.heightLength;
//Keeps character at ground position.
Then, make an if statement for when the
character.yVel = 0; character reaches the ground and make the
//Stops falling.
character fall onto the ground. You can make
Jumping = false; the character fall to the ground by subtracting
//Allows Jumping
} the distance between them.
else {
character.yVel ++;
} // Increment = increase. Include a method to stop your character from
falling and make your character able to jump
}
when they reach the floor.
Character: Platform Movement
void Up()
{ Now we just need to create your movement code in your
if(!Jumping) { character class. We can do this by including the three directions
yVel = -15;
Jumping = true; that the character will move in.
}
} With up, we’ll use an if statement to see when you aren’t able
void Left()
{ to jump. This allows you to not jump over and over again. The
xLoc = xLoc - xVel * Speedx; “!” is a operator that means “Not”. So when you aren’t able to
}
jump, you are telling the program that you are still in the air.
void Right() You won’t gain the ability to jump again until you reach the
{ floor.
xLoc = xLoc + xVel * Speedx;
}
Next, we will include some movement using xVel and Speedx.
xVel is the amount of space we move and Speedx is how quickly
you move that amount of space.
Update program!
Character character;
Ground ground; Include the boolean for jumping to
boolean Jumping = false; //Allows Jumping allow the character to jump at the
void setup() beginning of the game.
{
// Include class declarations.
}
Also include the declarations,
void draw() functions, and key presses for your
{
// Include functions. classes to finish up your code.
}

void keyPressed()
{
With all of this, you should be able
// Include character movement. to successfully jump with gravity.
}
Save your program!
● Click File > Save...

● Save on your flash drive to keep your files secure!

● Click File > Quit to close Processing.

● Eject your flash drive.


Processing Resources!

Go to Help > Reference if


you want to be sent to a
page for references.

This will be helpful to


review commands that you
may want to add.
Extras!
To be added onto at a later date.
Shh, don’t spoil the students on their future!
Create your own character?
... {To Be Added} ...
Character Example?

You might also like