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

Final Lecture 3

The document discusses various Unity concepts and components: 1) Awake(), Start(), Update(), and FixedUpdate() are initialization and game loop methods that scripts can use. Awake() and Start() initialize objects, while Update() and FixedUpdate() are called each frame for periodic calculations. 2) Vector2 and Vector3 classes represent 2D and 3D vectors with common operations. Transform stores an object's position, rotation, and scale. 3) SpriteRenderer displays sprite images. Materials apply textures. Parent-child relationships affect how object transforms are inherited. 4) Name and tag properties help retrieve GameObjects. Components can be accessed via GetComponent. Time.deltaTime makes movement frame-
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Final Lecture 3

The document discusses various Unity concepts and components: 1) Awake(), Start(), Update(), and FixedUpdate() are initialization and game loop methods that scripts can use. Awake() and Start() initialize objects, while Update() and FixedUpdate() are called each frame for periodic calculations. 2) Vector2 and Vector3 classes represent 2D and 3D vectors with common operations. Transform stores an object's position, rotation, and scale. 3) SpriteRenderer displays sprite images. Materials apply textures. Parent-child relationships affect how object transforms are inherited. 4) Name and tag properties help retrieve GameObjects. Components can be accessed via GetComponent. Time.deltaTime makes movement frame-
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Unity

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:

Vector2.up: shorthand for writing Vector2(0, 1).

Vector2.down: shorthand for writing Vector2(0, -1).

Vector2.left: shorthand for writing Vector2(-1, 0).

Vector2.right: shorthand for writing Vector2(1, 0).

Vector2.zero: shorthand for writing Vector2(0, 0).

Vector2.one: shorthand for writing Vector2(1, 1). 5


Vector3 Class – Scripting
● Vector3 class represents 3D vectors.

● Main Constants: Vector3.up: shorthand for writing Vector3(0, 1, 0).

Vector3.down: shorthand for writing Vector3(0, -1, 0).

Vector3.left: shorthand for writing Vector3(-1, 0, 0).

Vector3.right: shorthand for writing Vector3(1, 0, 0).

Vector3.forward: shorthand for writing Vector3(0, 0, 1).

Vector3.back: shorthand for writing Vector3(0, 0, -1).

Vector3.zero: shorthand for writing Vector3(0, 0, 0).

Vector3.one: shorthand for writing Vector3(1, 1, 1).


6
Transform Component – Scripting

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.

● Using Time.deltaTime, the speed will be the same on all computers.


12
Name and Tag – Scripting
● We can retrieve and find GameObject/GameObjects by Name or Tag.

● Find(“Name”)  returns the object having the given name.

● 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

Retrieving a Collection of GameObjects by Tag

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.

● To access a component of the GameObject, we use the command GetComponent as


follows:

ComponentType Name = GetComponent < ComponentType >();

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.

● Tiling: controls how many times


the texture is duplicated across the
GameObject.

● Offset: sets the placement offset of


a given texture. In other words, it
translates/shifts the texture in the
𝑥𝑦 space. It controls where the tiles
start. 17
Texture Material – Scripting
Changing Offset Values

18
Texture Material – Scripting
Changing Tiling Values

19
SpriteRenderer Component
● Sprites are 2D Graphic objects. They are a type of Asset in
Unity projects.

● Importing Sprites into Unity project: from Assets menu 


select Import New Asset  choose the image and Unity puts it
in the Project view.

● Setting imported image as a Sprite: if the project mode is set to


2D, the image is automatically set as a Sprite. However, if the
project mode is set to 3D, the image is set as a Texture.

● To change the asset’s Texture Type: select the asset in the


Project window  set the Texture Type in the Inspector panel
to Sprite (2D and UI).
20
SpriteRenderer Component
● The Sprite Renderer component displays images as Sprites for
use in both 2D and 3D scenes.

● For adding Sprite Renderer component to a GameObject:


select the GameObject in the Hierarchy window  press Add
Component button in the Inspector panel  choose
SpriteRender.

● Sprite: sets the sprite object to render.

● Color: defines the color that tints this Sprite object (default is
white for no tint).

● Flip: flips the sprite in the 𝑥 or 𝑦 planes. 21


SpriteRenderer Component – Scripting

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.

● ObjectToDestroy is destroyed immediately after the current Update loop, or after


TimeInSeconds from now if a time is specified.

● If ObjectToDestroy is a Component, this method removes the component from


the GameObject.

● If ObjectToDestroy is a GameObject, it destroys the GameObject and all its


components and all transform children of the GameObject.

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.

● User input will include any events triggered by a mouse or keyboard.

● 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.

● An expandable list called


Axes will appear.

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.

● The button name "Jump" in the game actually


means spacebar (Positive Button "space") and this
is what defines the mapping.

● If you decide to use the mouse button to jump, all


you would have to do is change that in the
Positive Button field and the change would apply
33
to everything in the game.
Input Manager
● There are two main types of buttons that are predefined:
1) Button: a single button like "Jump" (spacebar)
would return either true or false, it’s either being
pressed or not. There are variations of the
functions:
■ GetButton: returns true if the button is currently being pressed down, false otherwise.

■ 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

■ W/S or Up arrow/Down arrow—Vertical axis

● To get a specific key directly:

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.

■ 2D physics: Box2D engine integration.

■ 3D physics: Nvidia PhysX engine integration.


● They are similar, with most of the major components having analogous components in both
versions, but the two systems are not compatible with one another.

● 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.

1) Dynamic: makes the object entirely driven by the


physical engine. This causes the motion of the game
object affected by gravity, force, velocity, etc. The
physics engine takes responsibility for resolving their
collisions with static, kinematic, and other dynamic
objects and rebounding them as needed. It can be used
for game characters, moving game objects, etc.

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.

● Linear Drag: it affects the positional movement.

● Angular Drag: it can be used to slow down the rotation of


an object. The higher the drag the more the rotation slows
down.

● Gravity Scale: set the degree to which the object is affected


by gravity. Increasing the Gravity Scale makes an object
fall faster through the air.
42
Rigidbody2D Component
● Collision Detection: used to prevent fast moving objects from
passing through other objects without detecting collisions. If
the object is moving very fast, it’s possible for this object to
move through an object that they’re supposed to land on. To
prevent this from happening, change the Collision
Detection setting on the Rigidbody2D component from
Discrete to Continuous.

● Constraints: set restrictions on the rigidbody’s motion


1) Freeze Position  Stops the rigidbody moving in the
world 𝑥 & 𝑦 axes selectively.

2) Freeze Rotation  Stops the rigidbody rotating around


the 𝑧 axes selectively. 43
Rigidbody2D Component – Scripting
● The GetComponent function is used to access components attached to the GameObject
from a C# script. Thus, we can set/change all properties.

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.

● Unity has eight inbuilt kinds of 2D colliders:

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

● The simplest colliders are primitive collider types which are:

In 2D, BoxCollider2D and CircleCollider2D.

In 3D, BoxCollider, SphereCollider, and CapsuleCollider.

● We can add any number of colliders to a single GameObject to create compound


colliders.
53
Colliders
● Static Colliders: Colliders that are added to an object without a Rigidbody component
and used to create floors, walls and other motionless elements of a scene. We should not
reposition static colliders by changing the Transform position since this will impact
heavily on the performance of the physics engine.

● 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.

● Every 2D collider in Unity inherits from a


common class called Collider2D. As a
result, they share common properties.

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.

● Offset: it can be used to shift the local origin of any 2D collider


geometry.

● Size: defines the width and height of the rectangle. The 𝑥


coordinate of the vector represents the width while the 𝑦
represents the height. These values are specified relative to a center
point, so the distance from the center to the left edge is actually
width/2.
56
Collider2D Component
● Material: defines the PhysicsMaterial2D that can be used by the
collider and determines properties of collisions, such as friction and
bounciness.

● “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.

● It is used to add effects to the game object (e.g., bouncing)


when it collides with another object.

● To create a Physics Material 2D, go to Assets  Create 


2D  Physics Material 2D.

● Bounciness sets the degree to which collisions


rebound from the surface. A value of 0 indicates no
bounce while a value of 1 indicates a perfect bounce with
no loss of energy.
59
2D Physics Events – Collisions
● OnCollisionEnter2D(Collision collision): called when the object's collider has begun
touching another object's collider.

● OnCollisionStay2D(Collision collision): called each frame when a collider on another


object is touching this object's collider.

● OnCollisionExit2D(Collision collision): called when a collider on another object stops


touching this object's collider.

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.

● OnTriggerStay2D(Collider collider): called each frame where another object is within a


trigger collider attached to this object.

● OnTriggerExit2D(Collider collider): called when another object leaves 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

Static Collider yes

Rigidbody Collider yes yes yes

Kinematic Rigidbody Collider yes

Static Trigger Collider

Rigidbody Trigger Collider

Kinematic Rigidbody Trigger


Collider
68
Trigger messages are sent upon collision

Kinematic
Kinematic Static Rigidbody
Static Rigidbody Rigidbody
Rigidbody Trigger Trigger
Collider Collider Trigger
Collider Collider Collider
Collider

Static Collider yes yes

Rigidbody Collider yes yes yes

Kinematic Rigidbody Collider yes yes yes

Static Trigger Collider yes yes yes yes

Rigidbody Trigger Collider yes yes yes yes yes yes

Kinematic Rigidbody Trigger


yes yes yes yes yes yes
Collider
69
Adding/Removing Component – Scripting
● Function AddComponent is used to add a component of type componentType to the game
object.

● 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

You might also like