Final Lecture 3
Final Lecture 3
Lecture 3
Awake()–Start()–Update()–FixedUpdate()
● In scripts, Unity has many built-in methods inherit from the superclass “MonoBehaviour”.
● There are two special methods automatically included: Start() and Update() and two other
methods can be added to a script: Awake() and FixedUpdate().
● Awake() vs Sart() Start and Awake are initialization methods. When the game starts, it
will execute its Awake method and then its Start method, always in that order. If we are
creating multiple GameObjects at the same time, Unity will execute each of the Awake
methods of all GameObjects and then all Start methods. In particular, Awake is used to
guarantee a value is initialized before other GameObjects use it and Start() is used for basic
initialization. Generally, both are not needed except for specific cases where order is
crucial.
2
Awake()–Start()–Update()–FixedUpdate()
● The two main game loops are Update() and FixedUpdate(). The frequency of these two
methods differ.
● FixedUpdate() is called at regular and fixed intervals. It is running very periodically (t=0.02,
t=0.04, t=0.06, etc). It is closely linked to the physics system and is called in sync with the
Physics calculations.
● Update() is called whenever it is ready. It is closely linked to the rendering system and is
called in sync with when the screen is being redrawn. Periodic calculations that do not
require fixed intervals
● Generally, FixedUpdate() is used for periodic calculations that need to be regular (for
example, object motion), and Update() is used for periodic calculations that do not require
fixed intervals. 3
Awake()–Start()–Update()–FixedUpdate()
4
Vector2 Class – Scripting
● Vector2 class represents 2D vectors. It contains functions and properties for common vector
operations (e.g., Angle, Distance, Dot, etc.)
● Main Constants:
7
Transform Component – Scripting
8
Transform Component – Scripting
9
Transform Component – Scripting
10
Transform Component – Scripting
11
Frame-rate Independent Movement
● To make the movement frame-rate independent, the speed value must be multiplied by
another value called deltaTime.
● Time is a class that has properties and methods, and one of those properties is deltaTime
which represents the amount of change in time.
● Specifically, deltaTime is the amount of time between frames. The time between frames
varies at different frame rates (for example, 30 fps has a deltaTime of 1/30th of a second).
● Thus, multiplying the speed value by Time.deltaTime is important because the game
may be run on varying hardware when deployed, and it would be odd if time slowed
down on slower computers and was faster when better computers ran it.
● FindWithTag(“Tag") assumes that there is just one object with the given tag (If there
is none, then null is returned. If there is more than one, it returns one of them).
● FindGameObjectsWithTag(“Tag") returns all objects having the given tag in the form
of an array.
13
Name and Tag – Scripting
Retrieving a GameObject by Name
14
Accessing Components
● Each GameObject is associated with a number of defining entities called its
components.
● Unity defines class types for each of the possible components, and we can access and
modify this information from a script.
15
Texture Material
● For creating a new material,
right click in the Project panel
Create Material.
● Select the created material on
Project panel and go to
Inspector panel choose Unlit
from Shader Texture.
● For applying texture to the
created material, RIGHT CLICK
on Project panel and choose
Import New Asset to insert the
texture image to project.
16
Texture Material
● Select the Material, press the select
button in the Inspector panel and
choose the imported texture.
18
Texture Material – Scripting
Changing Tiling Values
19
SpriteRenderer Component
● Sprites are 2D Graphic objects. They are a type of Asset in
Unity projects.
● Color: defines the color that tints this Sprite object (default is
white for no tint).
22
Parent-Child GameObjects
● A GameObject is capable of storing any number of other GameObjects “inside it.” This
system is called parenting: one GameObject is the parent of many others, and those
GameObjects stored inside it are called its children.
● Unity looks at this as the Transform components being attached to each other.
● Any Transform changes (movement, rotation, or scaling) applied to the parent will
affect the children, but the opposite is not true.
● To make a GameObject child of another object, click and drag this object in the
Hierarchy panel, and drop it over the “Parent” object.
23
Parent-Child GameObjects
● The position of a child object can be depicted in two ways: world position and local
position. The world position is its absolute position in the scene. The local position is its
position relative to its parent.
● A position of (5, 0, 0) in world coordinates is “5 units to the right of the center of the
world.” But in local coordinates, that same position instead means “5 units to the right
side of the parent object.”
● The local positions are affected by the scale of the parent. So, if the parent doesn’t have
(1, 1, 1) for its scale, then adding 1 unit to the X means that the local position is
multiplied by the scale of the parent.
24
Parent-Child GameObjects – Scripting
25
Parent-Child GameObjects – Scripting
26
Parent-Child GameObjects – Scripting
27
Parent-Child GameObjects – Scripting
28
Destroying GameObjects – Scripting
● Destroy(Object ObjectToDestroy, float TimeInSeconds): removes a GameObject,
component or asset.
29
Destroying GameObjects – Scripting
Destroy game object from script attached to it Destroy game object from script of another game object
Or
or
or
30
Getting User Input
● An important part of writing game scripts is to get user input and use it to do
interesting things in our game, like move the player around, attack enemies, etc.
● To get user input, there are several static methods built into the predefined Input class,
and these will be called in the same fashion (Input.SOMETHING ).
● A key refers to a particular key (for example the ’H’ key, or the spacebar),
● A button is simply a name that is associated with a particular key in the project settings.
31
Input Manager
● To see all of the
predefined Buttons
currently in the project: go
to edit ProjectSettings
InputManager.
32
Input Manager
● If you open one of the predefined Buttons, let’s
say "Jump", you will see several properties that
define what "Jump" means when you call it in a
script.
■ GetButtonDown: returns true if the button was pressed down THIS FRAME (only
called once each time the button is pressed), false otherwise.
■ GetButtonUp: returns true if the button was released THIS FRAME (also once each
time the button is pressed), false otherwise.
34
Input Manager
2) Axis: a pair of buttons that represents a positive
and negative direction. It returns a float between
-1 and 1, depending on which direction it is being
pressed. The two predefined axes are
"Horizontal" and "Vertical", which by default are:
■ A/D or Left arrow/Right arrow—Horizontal axis
35
Physics
● Unity has 2D and 3D mode. The only difference between the two modes is that 2D mode
completely ignored the z axis (depth). Thus, working with only two dimensions makes
programming the game much much simpler.
● Unity has a 2D and a 3D Physics systems to ensure that objects correctly accelerate and
respond to collisions, gravity, and various other forces.
● The three main components in the Physics system are Rigidbodies, Colliders, and
PhysicsMaterials. 36
Rigidbodies
● A rigid body component specifies how the object moves physically in space by defining
elements like the object’s mass, drag (air resistance), and whether the object is affected
by gravity.
● Adding a rigid body component to a GameObject forces that GameObject to obey the
laws of physics.
● This means that the GameObject will be affected by gravity, it can be moved using
physics forces, when used with a Collider, it will collide into other objects that also have
Collider components attached.
37
Rigidbody2D Component
● Select the GameObject and go to the Inspector panel Add Component Physics 2D
Rigidbody 2D.
38
Rigidbody2D Component
● When dealing with Rigidbody2D, there are three key
body types which determines how a game object move
and react to collision.
39
Rigidbody2D Component
2) Kinematic: switches off the physical behavior of the
Rigidbody2D so that the game object will not be
affected by gravity or forces. A Kinematic
Rigidbody2D does not collide with other Kinematic
Rigidbody2Ds or with Static Rigidbody2Ds and will
only collide with Dynamic Rigidbody2Ds. It is used
for game objects that are entirely moved by the script
code instead.
40
Rigidbody2D Component
3) Static: no real Rigidbody component attached to them,
so physics engine does not consider them to be
moving (objects that will not move at all). No collision
can be applied to them. It is used for ground, walls,
any other game object we don’t want the character
collide with.
41
Rigidbody2D Component
● Mass: set the mass of the rigidbody (the weight of the
object in kilograms). Higher mass objects push lower mass
objects more when colliding.
44
Rigidbody2D Component – Scripting
● AddForce(Vector2 Force, ForceMode2D Mode): Apply an amount of force to the object
to make it jump or move using physics.
Force Components of the force in the X and Y axes.
Mode The method used to apply the specified force. There are two mods:
ForceMode2D.Force This is used for continuous changes (a gradual force over time)
that are affected by mass.
ForceMode2D.Impulse This is used for instant change that is affected by mass. It is
useful for explosions and collisions.
ForceMode2D.Force is the default force mode when none is provided.
45
or
46
Rigidbody2D Component – Scripting
● Velocity: sets the linear velocity of the Rigidbody in units per second. It is specified as a
vector with components in the X and Y directions.
47
Rigidbody Component
● Select the GameObject and go to the Inspector panel Add Component Physics
Rigidbody .
48
Rigidbody Component – Scripting
49
Rigidbody Component – Scripting
50
Rigidbody Component – Scripting
51
Colliders
● Collider is the way used to manage collisions between GameObjects.
● A collider is a component that attached to a GameObject and define its shape for the
purposes of physical collisions. It is an invisible net that surrounds an object's shape and is
responsible for detecting collisions occur between this object and another GameObject (with
another collider). It does not need to be the exact same shape as the GameObject’s mesh.
1) BoxCollider2D 5) CustomCollider2D
2) CapsuleCollider2D 6) EdgeCollider2D
3) CircleCollider2D 7) CompositeCollider2D
4) PolygonCollider2D 8) TilemapCollider2D
52
Colliders
● 3D colliders are:
1) BoxCollider 4) MeshCollider
2) CapsuleCollider 5) TerrainCollider
3) SphereCollider 6) WheelCollider
● Dynamic Colliders: Colliders that are added to an object that does have a Rigidbody
component.
54
Collider2D Component
● For adding BoxCollider2D to a
GameObject, select the object in
Hierarchy panel press Add
Component in Inspector view select
the BoxCollider2D.
55
Collider2D Component
● Edit collider: each kind of 2D collider has a different shape, but
most of them allow us to change some properties of their shapes,
like the scale and distance of vertices.
● “Is Trigger”: if this box is checked, this will set the collider to act as a
trigger making the physics engine notify the collisions rather than
simulate them. It gives the Colliders the ability to trigger events when
the objects touch each other or overlap. This means that, if the collider
of an object is setup as a Trigger, other colliders will simply pass
through it. When the Trigger event occurs, you can decide how you
wish to set this up depending on the objective of your game. You must
also have a Rigidbody attached to one of the game objects.
57
Collider2D Component – Scripting
58
PhysicsMaterial2D
● PhysicsMaterial2D is an asset that can be added to the
’material’ field of Rigidbodies and Colliders.
60
2D Physics Events – Collisions
61
2D Physics Events – Triggers
● OnTriggerEnter2D(Collider collider): called when another object enters a trigger
collider attached to this object.
62
2D Physics Events – Triggers
63
Collider3D Component
● For adding BoxCollider to a GameObject, select the object in Hierarchy panel press
Add Component in Inspector view select the BoxCollider.
64
3D Physics Events – Collisions
65
3D Physics Events – Triggers
66
3D Physics Events – Triggers
67
Collision detection occurs and messages are sent upon collision
Kinematic
Kinematic Static Rigidbody
Static Rigidbody Rigidbody
Rigidbody Trigger Trigger
Collider Collider Trigger
Collider Collider Collider
Collider
Kinematic
Kinematic Static Rigidbody
Static Rigidbody Rigidbody
Rigidbody Trigger Trigger
Collider Collider Trigger
Collider Collider Collider
Collider
● Unity does not have a remove component function. Destroy function can be used for this
purpose.
Adding a Rigidbody Component Removing a BoxCollider Component
or
70