0% found this document useful (0 votes)
8 views31 pages

Module 2 & 3

The document covers collision detection in Unity, detailing the role of colliders, types of colliders, and how to implement collision detection using C# scripts. It explains the use of trigger colliders, the setup for floor object collision, and the creation of characters and floors in Unity. Additionally, it provides sample scripts for handling collisions and interactions between GameObjects.

Uploaded by

Kamalin Dany
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

Module 2 & 3

The document covers collision detection in Unity, detailing the role of colliders, types of colliders, and how to implement collision detection using C# scripts. It explains the use of trigger colliders, the setup for floor object collision, and the creation of characters and floors in Unity. Additionally, it provides sample scripts for handling collisions and interactions between GameObjects.

Uploaded by

Kamalin Dany
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

MODULE 2

Collision theory
Collision detection is an essential element in game development. In Unity,
whenever two objects interact, a collision occurs. The UnityEngine offers
various ways of responding to collision events, whether by the use of Physics
or by the custom C# scripts.

To detect the collision between two GameObjects, Unity offers components


called Colliders.

GameObjects are the fundamental objects that represent characters, props,


and all the objects inside a scene – every object in your game is
a GameObject.

What are colliders?

Colliders are components which define the shape of a GameObject for


physical collisions.

Colliders define the objects' physical boundaries to calculate collisions


accurately.

Types of colliders

Unity offers different types of colliders each of which are given below.

 Sphere Collider: It is a simple collider in the shape of a ball which is


suitable for spherical objects.

 Box Collider: It is a simple cuboid shape collider which is suitable for


objects with box shapes.

 Capsule Collider: This is a cylindrical shaped collider which has


hemispherical ends. It is mostly used for character controllers.

 Mesh Collider: It is a collider that matches the shape of the game


object's mesh exactly. This collider type is useful for more complex
shapes but comes at the expense of performance.

 Terrain Collider: It is a collider which is specifically designed for the


terrain objects.

Collision detection in Unity


Collision occurs whenever the two colliders interact. To detect this collision,
you can either use Physics to control the objects' motion or scripts to call the
functions related to the collision.

Key aspects of collision

Here are some of the key features of the collision system in Unity.

Collision response: The physics engine determines how the objects should
respond when they collide. It usually involves a change in the speed and
direction.
Bouncing back of a ball whenever it hits the wall is an example of collision
response.

Collision events: There are many event functions in Unity which


automatically get called whenever a collision occurs. These functions
include onCollisionEnter(), OnCollisionStay(), and OnCollisionExit(). You can
use these functions whenever the corresponding events happen.

Note: OnCollisionEnter can be used to decrease the player's health


whenever the player collides with the enemy.

Collision layers and matrix: Unity offers different layers


for GameObjects which you can set up to specify which layers can interact
with each other. It helps to make sure that only the relevant collisions are
detected.

How to detect collision

To detect collision between two colliders, you can make use of the collision
detection functions mainly OnCollisionEnter(). It gets called as soon as the
two GameObjects collide with each other.

A sample C# script is given below which outputs to the console as soon as


the OnCollisionEnter() function is called.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour

// Gets called at the start of the collision


void OnCollisionEnter(Collision collision)

Debug.Log("Entered collision with " + collision.gameObject.name);

// Gets called during the collision

void OnCollisionStay(Collision collision)

Debug.Log("Colliding with " + collision.gameObject.name);

// Gets called when the object exits the collision

void OnCollisionExit(Collision collision)

Debug.Log("Exited collision with " + collision.gameObject.name);

Sample C# script for collision detection

Explanation

 Lines 1–3: These lines make all the necessary imports.

 Line 5: A class named NewBehaviourScript is declared here which


inherits from the MonoBehaviour class.

 Lines 8–11: OnCollisionEnter() function is called whenever


the GameObject enters the scene. It takes the collision object and
returns the name of the GameObject it enters in collision with.

 Lines 14–17: OnCollisionStay() function is called during the stay of


the GameObject in the scene. It takes the collision object and returns
the name of the GameObject it is colliding with.

 Lines 20–24: OnCollisionExit() function is called whenever


the GameObject exits the scene. It takes the collision object and
returns the name of the GameObject it exited in collision with.
For Demonstration

https://www.educative.io/answers/introduction-to-collision-
detection-in-unity

GameObjects with all OnCollision methods

Using Colliders as Triggers

The scripts in Unity can detect whether collision occurs and returns the
response actions using the OnCollisionEnter function. However, the physics
engine can be used to detect whenever one collider enters the space of
another collider without creating a collision.

A collider (on which the Is Trigger property is set) does not behave as a
solid GameObject. It allows other colliders to pass through it. Whenever a
collider enters the space of other GameObjects,
the OnTriggerEnter() function gets called on the object.

Trigger response and events: Unity engine also offers trigger colliders
which are used whenever a GameObject enters or exits the specified area.
The main functions associated with the trigger events
are OnTriggerEnter(), OnTriggerStay(), and OnTriggerExit(). These functions
can be used whenever the corresponding events happen.

Note:

 You will have to configure the Is Trigger property if you want


the GameObjects to collide.

 If you want your colliders to interact physically with the world, Is


Trigger property should be unchecked.

 If you want your collider to act as a trigger for an event when


something enters it, Is Trigger property should be checked.

Example

You can define a response, such as increasing the player’s score, playing a
sound, or displaying a message, whenever a trigger detects that the player
has entered the specified area.
These responses can be implemented using C# scripts attached to
the GameObjects.

A sample C# script is given below.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour

// Gets called when the object enters the collider area

void OnTriggerEnter(Collider objectName)

Debug.Log("Entered collision with " + objectName.gameObject.name);

// Gets called during the stay of object inside the collider area

void OnTriggerStay(Collider objectName)

Debug.Log("Colliding with " + objectName.gameObject.name);

// Gets called when the object exits the collider area

void OnTriggerExit(Collider objectName)

Debug.Log("Exited collision with " + objectName.gameObject.name);

Sample C# script for Collider as Trigger

Explanation

 Lines 1–3: These lines make all the necessary imports.


 Line 5: A class named NewBehaviourScript is declared here which
inherits from the MonoBehaviour class.

 Lines 8–11: OnTriggerEnter() function is called whenever the collider


enters the specified area.

 Lines 14–17: OnTriggerStay() function is called if the colliders are


currently interacting.

 Lines 20–24: OnTriggerExit() function is called whenever


the Collider exits the scene. It takes the collider object and returns the
name of the GameObject it exited colliding with.

For Demonstration

https://www.educative.io/answers/introduction-to-collision-
detection-in-unity

Floor object collision


In Unity, to handle floor object collision, you typically work with colliders
and rigidbodies. Here’s a step-by-step guide to set up collision detection
between an object (like a player or an object falling) and the floor:

1. Add Colliders to the Floor

 Ensure that your floor object (such as a terrain or platform) has a


Collider component attached. The most common collider for a flat
floor would be a BoxCollider.

 If your floor is a terrain, it will have a TerrainCollider component by


default.

2. Add a Rigidbody to the Falling Object (if needed)

 If you want the object to react to physics (e.g., falling or moving with
gravity), you should add a Rigidbody component to the object.

 To add a Rigidbody:

o Select your object in the Unity editor.

o Click Add Component.

o Search for and add a Rigidbody component.


 You can modify the Rigidbody properties to control mass, drag, or other
physics-related settings.

3. Collision Detection

 BoxCollider, SphereCollider, CapsuleCollider: These are the most


common colliders for static objects (like the floor) and dynamic objects
(like a player or a box). Unity will automatically handle collision
detection and response when colliders are properly set up.

 If you use a Rigidbody on your object, Unity will automatically handle


collisions for you, as long as the other object (in this case, the floor)
has a collider too.

4. Scripting (Optional)

If you want to customize behavior on collision, such as triggering an event


when an object hits the floor, you can use Unity's collision detection methods
in scripts.

Here’s an example script that detects when an object collides with the floor:

csharp

Copy

using UnityEngine;

public class CollisionHandler : MonoBehaviour

private void OnCollisionEnter(Collision collision)

if (collision.gameObject.CompareTag("Floor"))

// Handle collision with the floor

Debug.Log("Object collided with the floor!");

}
}

In this script:

 The OnCollisionEnter method is triggered when the object with this


script collides with any other collider.

 The CompareTag("Floor") checks if the object collided with something


tagged as "Floor" (make sure to tag your floor object in Unity with the
"Floor" tag).

5. Testing

 Play the scene in Unity.

 Ensure that the object (e.g., a player or falling object) is moving and
reacts with the floor when they collide.

Creating characters and floors

Creating characters and floors in Unity involves several steps, from designing
the assets to setting up the necessary components to make them interact
properly. Here’s a step-by-step guide to creating characters and floors in
Unity.

1. Creating the Floor

Option A: Using a Simple Plane

1. Create a Plane:

o Right-click in the Hierarchy window and select 3D Object >


Plane.

o This will create a flat plane to serve as your floor.

o You can resize the plane by adjusting its Scale in the Inspector
window to make it bigger if needed (e.g., set X and Z to 10, 10
for a larger area).

2. Add a Collider (if not added by default):

o By default, Unity adds a MeshCollider to the plane, which is


enough for simple floor interactions.

o If it’s not there, add a BoxCollider or MeshCollider by selecting


the plane and clicking Add Component > BoxCollider or
MeshCollider.
3. Optional: Add a Material or Texture:

o You can make your floor look more realistic by applying a


material or texture. Create a new material, then drag and drop it
onto the floor object in the scene.

Option B: Using a Terrain (For Larger, More Complex Floors)

1. Create a Terrain:

o Right-click in the Hierarchy window and select 3D Object >


Terrain.

o This will create a large, editable terrain where you can shape and
texture the floor.

2. Modify the Terrain:

o In the Inspector, use the Terrain tools to sculpt the terrain. You
can raise, lower, and smooth the ground as you like.

3. Add Textures:

o You can paint textures onto the terrain using the Paint Texture
tool in the Terrain component. Add materials like grass, dirt, or
rocks to create a more detailed floor.

2. Creating a Character

Option A: Using a Simple Cube (Basic Character)

1. Create a Cube:

o Right-click in the Hierarchy window and select 3D Object >


Cube. This will be your basic character for now.

2. Add a Rigidbody (for Physics-based Movement):

o Select the Cube and add a Rigidbody component by clicking


Add Component > Rigidbody in the Inspector.

o This will allow the cube to interact with gravity and other
physics-based elements like the floor.

3. Add a Collider:

o A BoxCollider will be added automatically to the Cube (you can


adjust its size in the Inspector if necessary).
4. Add Movement Script:

o To move the cube, you can create a basic movement script in


C#:

csharp

Copy

using UnityEngine;

public class PlayerMovement : MonoBehaviour

public float speed = 5f;

private void Update()

float horizontal = Input.GetAxis("Horizontal");

float vertical = Input.GetAxis("Vertical");

Vector3 movement = new Vector3(horizontal, 0, vertical) * speed *


Time.deltaTime;

transform.Translate(movement);

o Attach this script to your Cube (or any other object you want to
act as your character).

o You can now move the cube around using the arrow keys or
WASD.

Option B: Using a Pre-made Character (e.g., Capsule or 3D Model)

1. Create a Capsule (for a Simple Character):


o Right-click in the Hierarchy window and select 3D Object >
Capsule.

o A capsule is often used as a simple player character since it is


more humanoid than a cube.

2. Add a Rigidbody (for Physics-based Movement):

o As with the Cube, add a Rigidbody to the Capsule so that


gravity and collision work properly.

3. Add a Collider:

o A CapsuleCollider is automatically added to the Capsule, but


you can adjust the collider size if necessary to match the shape
of the character more closely.

4. Optional: Add a Character Controller

o If you want more advanced control (such as walking, jumping,


and crouching), you can use Unity’s built-in
CharacterController component:

 Select the Capsule, and click Add Component >


CharacterController.

 The CharacterController provides better control over


movement, especially for humanoid characters.

5. Create a Movement Script (using CharacterController):

o Here's an example script for using the CharacterController:

csharp

Copy

using UnityEngine;

public class PlayerMovement : MonoBehaviour

public float speed = 5f;

public float jumpHeight = 2f;

private CharacterController controller;


private Vector3 velocity;

private void Start()

controller = GetComponent<CharacterController>();

private void Update()

float horizontal = Input.GetAxis("Horizontal");

float vertical = Input.GetAxis("Vertical");

Vector3 move = transform.right * horizontal + transform.forward *


vertical;

controller.Move(move * speed * Time.deltaTime);

if (controller.isGrounded && velocity.y < 0)

velocity.y = -2f;

if (Input.GetButtonDown("Jump") && controller.isGrounded)

velocity.y = Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y);

velocity.y += Physics.gravity.y * Time.deltaTime;

controller.Move(velocity * Time.deltaTime);

6. Custom Characters (Using Models):


o If you want to use a 3D model as your character, you’ll need to
import the model (e.g., an .fbx or .obj file).

o You can then attach a Rigidbody, Collider, and a


CharacterController to the imported character object.

o Ensure that the model’s root object is placed at the character's


feet (adjust the height of the CharacterController collider
accordingly).

3. Interaction between Character and Floor

1. Ensure Proper Collisions:

o The character (whether a cube, capsule, or model) should have a


Collider and a Rigidbody attached.

o The floor should also have a Collider (either a BoxCollider,


MeshCollider, or TerrainCollider).

o Unity’s physics engine will automatically handle interactions and


collisions between the character and the floor.

2. Add Gravity (if needed):

o By default, Unity applies gravity to any object with a Rigidbody.


You can control the gravity strength in the Physics settings
(under Edit > Project Settings > Physics), or you can adjust
the Rigidbody’s useGravity property.

3. Testing the Interaction:

o Ensure your character is on the floor. You can add a script to


make the character move, jump, and interact with the floor by
applying physics or directly moving it with transform
manipulation.

MODULE 3
In Unity, you can apply a color filter to a camera by using
post-processing effects or by modifying the camera's
image through scripts. Here's how you can do both:
1. Using Post-Processing (Recommended)
Post-processing is a powerful tool in Unity that allows you
to apply various effects, including color filters, to your
camera.
Steps to apply a color filter using Post-Processing:
1. Install Post-Processing Package:
o Open Unity's Package Manager (Window >
Package Manager).
o Search for "Post Processing" and install it.
2. Add Post-Processing Volume:
o In the hierarchy, right-click and choose Create
> Volume > Global Volume (or local volume if
needed).
o In the Inspector window, click Add Component,
and add the Post Process Volume component.
o Make sure Is Global is checked if you want the
effect applied globally.
3. Create or Use a Post-Processing Profile:
o Click the New button next to the Profile field in
the Post Process Volume component.
o A new Post-Processing profile will be created. You
can modify this profile later.
4. Add the Color Grading Effect:
o In the Post-Processing Profile, click Add Effect >
Color Grading.
o In the Color Grading settings, you can adjust
the Post-Processing settings:
 Tone Mapping: Select a tone mapping
algorithm to affect the overall colors.
 Saturation: Increase or decrease saturation
to change how vibrant the colors are.
 Temperature & Tint: Adjust the color
temperature and tint to add a color filter
(e.g., blue, orange).
 Lift, Gamma, Gain: These control
shadows, midtones, and highlights. You can
use these to add more specific color
adjustments.
5. Play the Scene:
o When you run the scene, the camera should
apply the color filter as per the settings you
configured in the Post-Processing Profile.

2. Using a Custom Shader (Advanced)


If you want to apply a custom color filter (for instance,
using specific colors or blending effects), you can use a
shader in Unity. A shader can be written to change the
colors of the camera view.
Example: Simple Color Filter Shader
csharp
Copy
Shader "Custom/ColorFilter"
{
Properties
{
_Color ("Filter Color", Color) = (1, 1, 1, 1)
}
SubShader
{
Tags { "Queue"="Overlay" }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f
{
float4 pos : POSITION;
};

float4 _Color;

v2f vert(appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}

half4 frag(v2f i) : SV_Target


{
return _Color; // Apply the filter color
}
ENDCG
}
}
}
1. Create the Shader:
o Go to the Assets folder, right-click, and select
Create > Shader > Unlit Shader.
o Name it something like ColorFilterShader and
replace the code with the above shader code.
2. Create a Material with this Shader:
o Right-click in the Assets window, go to Create
> Material.
o Apply the newly created ColorFilterShader to this
material.
3. Create a Script to Apply the Shader to the
Camera:
o Create a C# script that will render the color filter
to the camera using the material you just made.
csharp
Copy
using UnityEngine;

[RequireComponent(typeof(Camera))]
public class CameraColorFilter : MonoBehaviour
{
public Material colorFilterMaterial;
private void OnRenderImage(RenderTexture src,
RenderTexture dest)
{
if (colorFilterMaterial != null)
{
Graphics.Blit(src, dest, colorFilterMaterial);
}
else
{
Graphics.Blit(src, dest);
}
}
}
4. Apply the Script to the Camera:
o Create a new Empty GameObject in the scene
and add the CameraColorFilter script to it.
o Assign the material you created earlier to the
colorFilterMaterial field in the script.

3. Using Camera's Background Color (Simple)


If you just need to change the color of the background for
your camera, you can simply change the Camera's
Background Color:
1. Select the camera in the hierarchy.
2. In the Inspector window, under Camera, you'll find
Background.
3. Set the desired color for the background of the
camera.
Camera zoom extend
1. Zooming by Changing Camera’s Field of View
(FOV) (For Perspective Cameras)
If you're using a Perspective Camera, you can zoom in
and out by changing the Field of View (FOV) property of
the camera. This affects how much of the scene is visible
and gives the illusion of zooming in and out.
Script for Zooming by FOV
csharp
Copy
using UnityEngine;

public class CameraZoom : MonoBehaviour


{
public Camera camera;
public float zoomSpeed = 10f;
public float minFOV = 15f;
public float maxFOV = 90f;
void Update()
{
// Get scroll wheel input for zooming
float scrollInput = Input.GetAxis("Mouse
ScrollWheel");

// Change the FOV based on scroll input


camera.fieldOfView -= scrollInput * zoomSpeed;

// Clamp the FOV to be within a certain range


camera.fieldOfView =
Mathf.Clamp(camera.fieldOfView, minFOV, maxFOV);
}
}
Steps:
1. Attach this script to a GameObject (like the Camera).
2. Drag the Camera object into the camera field of the
script in the Inspector.
3. Adjust the zoomSpeed, minFOV, and maxFOV to
get the desired zoom effect.
 zoomSpeed: The speed at which the zoom happens
when you scroll.
 minFOV and maxFOV: These limit the zoom range
(to avoid extreme zooming).
Now when you scroll your mouse wheel, the camera will
zoom in and out based on the FOV.
2. Zooming by Moving the Camera (For
Orthographic and Perspective Cameras)
For Orthographic and Perspective cameras, you can
also zoom by changing the camera's position (for
perspective) or size (for orthographic).
For Perspective Camera (Zoom by Changing
Camera's Z Position)
In perspective mode, you can simulate zooming by
changing the position of the camera along the Z-axis.
csharp
Copy
using UnityEngine;

public class CameraZoom : MonoBehaviour


{
public Camera camera;
public float zoomSpeed = 10f;
public float minDistance = 5f;
public float maxDistance = 50f;

void Update()
{
// Get scroll input
float scrollInput = Input.GetAxis("Mouse
ScrollWheel");

// Change the camera's position along the Z-axis


(camera zoom)
camera.transform.position +=
camera.transform.forward * scrollInput * zoomSpeed;

// Clamp the camera's position to prevent going too


close or too far
float clampedZ =
Mathf.Clamp(camera.transform.position.z, -maxDistance,
-minDistance);
camera.transform.position = new
Vector3(camera.transform.position.x,
camera.transform.position.y, clampedZ);
}
}
For Orthographic Camera (Zoom by Changing
Camera’s Size)
If you're using an Orthographic Camera, you can zoom
by changing the size property of the camera. The size
defines the half-width of the camera's view, so decreasing
it zooms in, and increasing it zooms out.
csharp
Copy
using UnityEngine;

public class CameraZoom : MonoBehaviour


{
public Camera camera;
public float zoomSpeed = 10f;
public float minSize = 5f;
public float maxSize = 50f;

void Update()
{
// Get scroll input
float scrollInput = Input.GetAxis("Mouse
ScrollWheel");

// Change the camera size


camera.orthographicSize -= scrollInput *
zoomSpeed;

// Clamp the size to avoid extreme values


camera.orthographicSize =
Mathf.Clamp(camera.orthographicSize, minSize,
maxSize);
}
}
Steps:
1. Attach this script to a GameObject (e.g., the
Camera).
2. Drag the Camera into the camera field in the
Inspector.
3. Adjust zoomSpeed, minSize, and maxSize.
Now, when you scroll the mouse wheel, the camera will
zoom in or out based on the camera’s size.
3. Zooming Using Input Keys (Example with WASD)
You can also create custom zooming controls by detecting
other input (e.g., arrow keys, WASD).
Here’s an example of zooming in and out by pressing the
W and S keys:
csharp
Copy
using UnityEngine;

public class CameraZoom : MonoBehaviour


{
public Camera camera;
public float zoomSpeed = 10f;
public float minFOV = 15f;
public float maxFOV = 90f;

void Update()
{
// Zoom in with W key
if (Input.GetKey(KeyCode.W))
{
camera.fieldOfView -= zoomSpeed *
Time.deltaTime;
}

// Zoom out with S key


if (Input.GetKey(KeyCode.S))
{
camera.fieldOfView += zoomSpeed *
Time.deltaTime;
}

// Clamp the FOV between min and max values


camera.fieldOfView =
Mathf.Clamp(camera.fieldOfView, minFOV, maxFOV);
}
}
This script allows you to zoom in and out when you press
W or S, and it will automatically clamp the zoom level to
prevent it from going beyond the specified FOV range.

Switching Cameras
We can achieve this by setting different cameras on or off
using SetActive().
We first start by deciding on the condition we use to
change the camera. For now we’ll use Input buttons 1, 2
and 3 to switch between cameras. We go into Project
Settings -> Input Manager and add three new items to
the list, which we’ll label Switch1, Switch2, and Switch3.
Each correspond to the button on the keyboard.
Then we write a C# script called CamSwitch. All we need
is three public GameObjects which we’ll label cam1,
cam2, and cam3 for each of the cameras we’ll be
switching into. Inside the Update function, depending on
which button we press, we’ll turn the corresponding
camera active while setting the other cameras false.
We then need to create two additional camera on the
Scene and place them where we want it to. Only set the
camera you want the players to see first active and the
other camera inactive.
Last we create an empty GameObject called CamManager
to store the script, and link the cameras to the script.

With this when we click on play, and press 1, 2, or 3, we’ll


switch between the different camera and see from a
different angle.

You might also like