Unity 3D Slides - Project Boost
Unity 3D Slides - Project Boost
Rick Davidson
Unity 2020.1
Rick Davidson
Game Screen
B
Moving
A obstacles
Level 1
Level X
Game Theme (ie. Story & Visuals)
● Experimental early generation spacecraft.
● On an unknown planet, trying to escape.
What’s Your Theme?
● Think of a central theme for your game.
● Decide on a starting name for your game.
● Share with the community!
Unity 2020.1
Onion Design
Rick Davidson
Common Development Questions
● What features should I include in my game?
● Where should I start development?
● What are my priorities?
● What if I run out of time?
● When should I stop?
Onion Design
Most important feature
2. World collision
Core
Feature
3. Level progression
Unity 2020.1
Unity Units
Rick Davidson
Building Our Starting Pieces
Rocket
Launch Landing
Pad Pad
Ground
Which Axis Is Which...
+x = right
+y = up
+z = forward
Build Our Starting Pieces
● Create the items from just 1 primitive each (later
we’ll make them more complex if need be):
○ Ground
○ Launch pad
○ Landing pad
○ Rocket
Unity 2020.1
Introducing Classes
Rick Davidson
How C# Is Broadly Organised
namespace UnityEngine
class OurClass
SomeMethod()
statementA;
statementB;
What Are Classes?
● Classes are used to organise our code
● Classes are “containers” for variables and methods
that allow us to group similar things together
● Usually we aim for a class to do one main thing and
not multiple things
○ Easier to read our code
○ Easier to fix issues
○ Easier to have multiple people work on a project
Classes We Create
● We tend to create a new class each time we create
a new script and have that script responsible for
one thing. Eg:
○ Movement
○ CollisionHandler
○ Shooting
○ Score
○ EnemyAI
Too Much In One Class Is A Mess
● Cluttered
code is like a
cluttered
desktop
Too Much In One Class Is A Mess
● Also risky
because
everything
can access
everything
else
Encapsulating Our Code
● Where possible we Encapsulate our code:
○ En-capsule-ating - putting in a capsule.
● Think of the different parts of your code as having a
“need to know basis” level of access.
○ Ie. Don’t let everything access everything else.
● For example, only the Methods in our Movement
Class can alter our player’s movement speed.
Classes Already Built For Us
● Unity has many Classes (containing useful methods
and variables) already created for us.
○ By accessing the class, we access its content.
● In our code we write the class name then use the
dot operator to access things in the class:
ClassName.MethodName()
Unity 2020.1
Rick Davidson
Finish Our Code
● Replace the “somethings” with code
● When we push “A” then print “rotate left”
● When we push “D” then print “rotate right”
● BONUS:
○ Identify the bug / issue with our logic
Unity 2020.1
Using AddRelativeForce()
Rick Davidson
Unity 2020.1
Rick Davidson
Tuning Our Rocket
● Add a variable so we can tune the main rocket
thrust
● Make the force applied frame rate independent
Unity 2020.1
Rick Davidson
Tuning Our Rocket’s Rotation
● Add a variable so we can tune the rotation speed
● Make the rotation speed frame rate independent
Unity 2020.1
Rigidbody Constraints
Rick Davidson
Tidy Up Our Movement
● Apply changes to prefab
● Add an obstacle
● Freeze constraints for our rocket
● Fix our obstacle-hitting bug
● Set our drag value
Unity 2020.1
Rick Davidson
Some Terminology
● Source Control: a system for tracking and managing
changes to your code and your project
● Git: A type of version control system that tracks
changes to files
● Gitlab (also, Github): Repository hosting service
● Repository (Repo): Directory or storage space for your
project
● SourceTree: Desktop client to help view your repo
Why Use Source Control?
● As a backup to save your project
● To allow you to safely make changes to your
project knowing you can go back to a previous
version
● To explore multiple ideas at the same time
● To more easily collaborate on projects
Setting Up Your Own Repo
● Now is a good time to
investigate how to set up
your own repo
● Google “set up git repo”
● Check out Ben’s Git Smart
course at GameDev.tv
Accessing My Project Changes
● After every lecture, I commit my project changes to
source control
○ Every lecture will have a link to my project changes
● You can easily access my project to see what has
changed or compare my code to yours
● You can also download my entire project to explore
it
Unity 2020.1
Rick Davidson
3 Main Things We Need
Audio
Listener The “sounds”
To “hear”
Audio that get played
Audio Source
We can add a reference to our Component
audio file directly into the Audio
Source component
Assets On Disk
SoundEffect.ogg
Unity 2020.1
Rick Davidson
Play SFX When Thrusting
● Cache a reference to AudioSource called audioSource
● Use audioSource.Play() to play when we are thrusting
● Use !audioSource.isPlaying to make sure we only
play if we aren’t already playing (Note: ! = not true)
● Use an else condition and audioSource.Stop() to
stop our SFX when we aren’t thrusting.
Unity 2020.1
Switch Statements
Rick Davidson
Switch Statements
● Switch Statements are a Conditional like If / Else
Statements.
● Allow us to compare a single variable (variables can
change or “vary”) to a series of constants (ie. things
that don’t change or have a “constant” value).
Switch Syntax
switch (variableToCompare)
{
case valueA:
ActionToTake();
break;
case valueB:
OtherAction();
break;
default:
YetAnotherAction();
break;
}
Print Different Collision Situations
● Using a Switch Statement, print to the console
different messages based upon what we collide
into.
● Remember that our collision tag returns a “string”.
● Our variable will be: other.gameObject.tag
● A reminder of the Switch syntax...
Switch Syntax
switch (variableToCompare)
{
case valueA:
ActionToTake();
break;
case valueB:
OtherAction();
break;
default:
YetAnotherAction();
break;
}
Unity 2020.1
Rick Davidson
Reload Current Scene
● Use SceneManager.LoadScene() to load the
current scene and therefore respawn our rocket
ship when it collides with the ground
● You’ll need to use the
UnityEngine.SceneManagement namespace
Unity 2020.1
Rick Davidson
Load Next Level
● When we reach the Landing Pad, load the next
level.
● Hint: our scene index is an integer, therefore we
can add a number to it.
Unity 2020.1
Using Invoke
Rick Davidson
Using Invoke
● Using Invoke() allows us to call a method so it
executes after a delay of x seconds.
● Syntax:
Invoke(“MethodName”, delayInSeconds);
● Pros: Quick and easy to use
● Cons: String reference; not as performant as using
a Coroutine
Use Invoke To Delay Next Level
● Parameterise our delay (ie. make a variable which
we can tune in the inspector)
● When we reach the Landing Pad, make sure we
have a delay before loading the next level
● Stop player controls during the delay
Unity 2020.1
Rick Davidson
Play Audio On Collision
● Trigger for audio to be played for these situations:
○ When the player crashes into an obstacle
○ When the player successfully reaches landing pad
● HINTS:
○ Get and cache the audio component
○ Create variables for each clip
○ Play the clip at the appropriate time
Unity 2020.1
Rick Davidson
Finish Our Logic
● We want to stop additional things happening after
we have a collision event.
● Use our isTransitioning bool and an if
statement.
Unity 2020.1
Rick Davidson
Make Your Rocket Look Different
● Using basic shapes, update your rocket prefab to
look interesting.
● Add a splash of colour.
● Consider the pivot point so that the rotation feels
right.
Unity 2020.1
Rick Davidson
Particles System Component
Rick Davidson
Get Ourselves Ready To Trigger
● Set up your rocket so that it has 3 particle systems,
ready for us to trigger in code:
○ Main booster
○ Left booster
○ Right booster
● Add them in your prefab and create variables for
each
Unity 2020.1
Rick Davidson
Tidy Up Our Code
● Using the extract method approach, refactor
ProcessThrust() and ProcessRotation() to
make them read as clearly as possible.
Unity 2020.1
Rick Davidson
Tricky Advanced Challenge!
● When the user pushes the ‘L’ key, load the next
level
● When the user pushes the ‘C’ key, disable
collisions
Unity 2020.1
Rick Davidson
Make Your Levels Look Interesting
● Using just cubes or other primitives, add some
depth to the look of your level.
● Try to frame your world so the player can’t fly off
where they shouldn’t.
Unity 2020.1
Rick Davidson
Main Directional Light (Sun)
Environment Lighting
Scene Lights
Light Your Scene
● Add at least one point light and one spotlight to
your scene.
● Experiment with a lighting setup that you’re happy
with.
● Share a screenshot!
Unity 2020.1
Rick Davidson
To Move In A Consistent Direction
Starting position
(x, y, z)
Movement Vector
(x, y, z)
To Move In A Consistent Direction
Starting position
(0, 0, 0)
Movement Vector
(10, 0, 0)
Move 10 on x axis
To Oscillate (Back & Forth)
Starting position
(0, 0, 0)
Movement Vector
(10, 0, 0)
0 1
Movement Factor
(between 0 and 1)
To Oscillate (Back & Forth)
Eg.
Starting position Offset = Movement Factor
(0, 0, 0) is currently 0.5,
Movement Vector Offset is?...
(10, 0, 0) 5, 0, 0
*
0 1
Movement Factor
(between 0 and 1)
Finish The Last Line
● Add one more line that defines the new position of
the object that is offset from its original position.
Unity 2020.1
Rick Davidson
Make Something Move
● Oscillate something in your level so that it provides
an interesting challenge for your player.
Unity 2020.1
Rick Davidson
Try And Protect Zero Period
● Try and put some protection code in.
● The goal is to eliminate the NaN error when period
is 0.
Rick Davidson
Useful Game Design Approach
● Design “moments” and then expand them into a
level. Moments that use the environment:
○ Fly under
○ Fly over
○ Fly through a gap
○ Time your flight through moving obstacle
○ Land on moving platform
○ Fly through narrow tunnel
Useful Game Design Approach
● Moments that use tuning of our existing game:
○ Slower rocket (eg. it got damaged)
○ Faster rocket (eg. got a boost)
○ Darker level
○ Closer camera
○ Bigger rocket (carrying something)
○ Reversed controls
○ And so on...
Level Design Challenge (If Interested)
● Create 5 (or more) different levels, each with a
unique game moment
● Add the levels to the build settings so they are
playable
● Share a video with us of your one best moment
(OBS is a free recording package)
Unity 2020.1
Quit Application
Rick Davidson
Hit Escape To Quit
● Create a new script called QuitApplication.cs
● Create logic so that if the player hits escape on
their keyboard we call Application.Quit()
● Add a debug line to make sure that hitting escape
works.
Unity 2020.1
Rick Davidson
Make A WebGL Build
● Make a WebGL build of your game
● Publish to sharemygame.com
● Tell our community about your game and where to
find it
● Play at least one other person’s game (good karma)
Unity 2020.1
Rick Davidson
Unity 2020.1
+x = right
+y = up
+z = forward
Setup Your World
● Your ground level is at y = 0.
● The launchpad is centered on x = 0, z = 0.
● You have an initial camera view you like.
● Everything in the Hierarchy is “prefabbed”.
● You have assigned terrain colour.
● You’ve modified the directional light rotation.
● You have shared a screenshot.
Unity 2020.1
rigidBody = GetComponent<RigidBody>();
Using Time.deltaTime
Frame-rate Independence
● The time each frame takes can vary wildly.
● Time.deltaTime tells you the last frame time.
● This is a good predictor of the current frame time.
● We can use this to adjust our movement.
● Longer frames lead to more movement.
● Shorter frames lead to less movement.
● e.g. rotation = rcsThrust * Time.deltaTime;
Words For Parts Of A Transform
Audio Source
Component
Assets On Disk
SoundEffect.ogg
Start And Stop Audio
● The audio should start when you thrust.
● It should stop immediately you stop thrusting.
● There should be no weird audio artifacts.
● Why not make a little video and share it?
Unity 2020.1
Pros Cons
Just one per game object Is based on a string
Very simple to use in Inspector Have to rename in 2 places
Makes for clear code Nothing “keeps you honest”
Write Collision Logic
● Your collisions should log either “dead” or “OK”.
● Allow for future tags (e.g. Fuel).
● We suggest opt-in to Friendly tag.
Unity 2020.1
Prefabs In Detail
Create Object
Level 1
If die
Level 2
Unity 2020.1
Dying or
Alive
Transcending
Timer
Expired?
void Start()
{
startingPos = transform.position;
}
void Update()
{
Vector3 offset = movementVector * movementFactor;
transform.position = startingPos + offset;
}
Make It Shake!
● At least one obstacle should oscillate manually.
● You should feel comfortable with how it works.
● Enjoy your new creative tool!
Unity 2020.1
period (s)
Setup An Oscillator
● Setup at least one game object to oscillate.
● Have fun!
Unity 2020.1
Environment Lighting
Scene Lights
Add Scene Lighting
● Alter your scene’s main directional light to make
your scene feel different.
● Add at least one scene light.
● Share a screenshot.
Unity 2020.1
Instantiate at runtime
Unity 2020.1
Tuning: Visuals:
- Player Movement - Lighting
- Camera Position - Particle Effects
- Timing (eg. level load) - Materials / Colours
Level Flow And Variety
● We need to keep our players engaged for as long
as we can
● Two options with our current game:
1. Randomised levels of similar challenge level
2. Sequential levels of increasing challenge level
Share Your Best Game Moment
● Refine your Tuning, Visuals, Levels and Audio.
● Create at least 5 levels.
● Find what you think is the best 10-15 second
moment.
● Capture video of that moment.
● Share on our Facebook group or Forum.
Unity 2020.1
Section 3 Wrap-Up