Quantcast
Viewing all 1620 articles
Browse latest View live

An Introduction to Teleportation in VR

One of the challenges of virtual reality is locomotion. In room-scale VR users can walk around, but limited space is a problem. Mobile VR users with only three degrees of freedom have to rely on head movement or controllers.

Teleportation is a fun way to get around the limitations of VR. Although not truly natural, users are accustomed to the concept of teleportation from sci-fi and fantasy, and it is not hard to implement.

We will be building a scene for Oculus Go/Gear VR that demonstrates teleportation using the controller as a pointer.

Source Code

The Unity project for this tutorial is available for download here. To save space, Oculus Utilities and VR Sample Scenes are not included, but the source files that were modified are included in the top level of the project. These files are OVRPlugin.cs, VREyeRaycaster.cs, and Reticle.cs.

Setup

To get started, create a new Unity project, Teleporter. Create the folder Assets/Plugins/Android/assets within the project, and copy your phone’s Oculus signature file there. See https://dashboard.oculus.com/tools/osig-generator/ to create a new signature file.

Select File -> Build Settings from the menu and choose Android as the platform. Click on Player Settings to load PlayerSettings in Unity inspector. Add Oculus under Virtual Reality SDK’s and select API Level 19 as the Minimum API Level.

Download Oculus Utilities from https://developer.oculus.com/downloads/package/oculus-utilities-for-unity-5/ and extract the zip file on your computer. Import Oculus Utilities into your project by selecting Assets -> Import Package -> Custom Package within Unity and choosing the location of the package you extracted. If you are prompted to update the package, follow the prompts to install the update and restart Unity.

A folder named Oculus will be created in your project. Oculus/Prefabs contains the OVRCameraRig and TrackedRemote prefabs that we will use to implement controller support. If you expand TrackedRemote in the project view, you’ll see that it contains prefabs for the Gear VR and Oculus Go controllers.

Image may be NSFW.
Clik here to view.

If you get the error message “‘OVRP_1_15_0’ does not exist in the current context,” open Assets/Oculus/VR/Scripts/OVRPlugin.cs and add #if !OVRPLUGIN_UNSUPPORTED_PLATFORM  and

#endif
  around code that checks the OVRPlugin version. You can find a fixed copy of OVRPlugin.cs in the included source. This error probably does not occur on Windows.

We will also need the VR Samples package from the Unity Asset Store. This package includes a number of sample scenes as well as prefabs and scripts that we will customize to add a laser pointer and reticle. Click on the Asset Store tab in Unity, and search for “VR Samples.” When loaded, click the import button and follow the instructions to import this package. The folders VRSampleScenes and VRStandardAssets will be created in your Assets folder.

Preparing Your Headset

If you are using the Gear VR, you will need to activate Developer Mode on your phone to test your app. In your phone settings, go to “About Device” and tap seven times on “Build number.”

You will also need to activate Developer Mode if you are using an Oculus Go. First, you need to create an organization in your Oculus account at https://dashboard.oculus.com/. Then, in the Oculus mobile app, choose the headset you’re using from the Settings menu, select More Settings, and toggle Developer Mode. See https://developer.oculus.com/documentation/mobilesdk/latest/concepts/mobile-device-setup-go/ for details.

Camera and Controller

Let’s start by setting up a VR camera and adding controller support. First, remove the Main Camera object that was created by default. We will be using a custom camera.

Create an instance of the OVRCameraRig prefab included in Oculus Utilities by dragging Assets/Oculus/VR/Prefabs/OVRCameraRig from the project window to the hierarchy window. Expand OVRCameraRig, and you’ll see that it contains a TrackingSpace with anchors for the eyes and hands. Set the position of  OVRCameraRig to (0, 1.8, 0) to approximate the height of a person.

Image may be NSFW.
Clik here to view.

CenterEyeAnchor is the placeholder for our camera that we will replace with the MainCamera prefab included in VR Sample Scenes. Drag Assets/VRSampleScenes/Prefabs/Utils/MainCamera from the project window to the hierarchy. Rename this instance CenterEyeAnchor and nest it under OVRCameraRig -> TrackingSpace. Remove the original CenterEyeAnchor.

Now add the controller using the Assets/Oculus/Prefabs/TrackedRemote prefab. Create instances of TrackedRemote as children of OVRCameraRig->TrackingSpace -> LeftHandAnchor and OVRCameraRig -> TrackingSpace -> RightHandAnchor. TrackedRemote contains models for both the Gear VR controller and the Oculus Go controller. When you run this scene, the correct controller model is displayed depending on which headset you’re using.

Image may be NSFW.
Clik here to view.

Make sure the Controller field of the TrackedRemote instance under LeftHandAnchor is set to “L Tracked Remote.” The instance under RightHandAnchor should be set to “R Tracked Remote.” You can do this in the Unity inspector.

If both hands are set correctly, the controller will automatically be displayed for the correct hand when you run the scene.

Next, add a laser beam that extends from the controller. Add a Line Renderer to CenterEyeAnchor by clicking “Add Component” in the inspector and typing “Line Renderer” in the search box. Disable “Receive Shadows” and set the material to MazeAgentPath, a red material included with the VR Sample Scenes package. If you want a different colored laser, you can easily create a different colored material and use it in the Line Renderer.

Under the Width field, drag the slider down to set a width of about (0.0, 0.02). If the width is too thick, your laser beam will look like a huge block instead of a beam.

Image may be NSFW.
Clik here to view.

Coding a Laser Beam

Our next step will turn the controller into a laser pointer. To do this, we modify the scripts attached to CenterEyeAnchor and VRCameraUI using the steps described in https://developer.oculus.com/blog/adding-gear-vr-controller-support-to-the-unity-vr-samples/. The modified scripts are included in the source code package that comes with this tutorial.

The script Assets/VRStandardAssets/Scripts/VREyeRaycaster.cs is attached to CenterEyeAnchor. Add these fields to the VREyeRaycaster class:

[SerializeField] private LineRenderer m_LineRenderer = null;     
public bool ShowLineRenderer = true;

Add the following accessors to VREyeRaycaster:

/* Accessors for controller */

public bool ControllerIsConnected {
	get {
		OVRInput.Controller controller =OVRInput.GetConnectedControllers () & (OVRInput.Controller.LTrackedRemote | OVRInput.Controller.RTrackedRemote);
		return controller == OVRInput.Controller.LTrackedRemote || controller == OVRInput.Controller.RTrackedRemote;
	}
}

public OVRInput.Controller Controller {
	get {
		OVRInput.Controller controller = OVRInput.GetConnectedControllers ();
		if ((controller & OVRInput.Controller.LTrackedRemote) == OVRInput.Controller.LTrackedRemote) {
			return OVRInput.Controller.LTrackedRemote;
		} else if ((controller & OVRInput.Controller.RTrackedRemote) == OVRInput.Controller.RTrackedRemote) {
			return OVRInput.Controller.RTrackedRemote;
		}
		return OVRInput.GetActiveController ();
	}
}

Controller
  determines which controller is connected, and
ControllerIsConnected
  determines if a controller is connected.

Now look for the EyeRaycast function and find the line:

RaycastHit hit;

After this line, add:

Vector3 worldStartPoint = Vector3.zero;
Vector3 worldEndPoint = Vector3.zero;
if (m_LineRenderer !=null) {
  	m_LineRenderer.enabled = ControllerIsConnected && ShowLineRenderer;
}

This code enables the line renderer, making the laser beam visible, only if a controller is connected.

Add more code after this to convert the controller’s local position and rotation to world coordinates:

if (ControllerIsConnected && m_TrackingSpace != null) {
    Matrix4x4 localToWorld = m_TrackingSpace.localToWorldMatrix;
    Quaternion orientation = OVRInput.GetLocalControllerRotation (Controller);

    Vector3 localStartPoint = OVRInput.GetLocalControllerPosition (Controller);
    Vector3 localEndPoint = localStartPoint + ((orientation * Vector3.forward) * 500.0f);

    worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
    worldEndPoint = localToWorld.MultiplyPoint(localEndPoint);

    // Create new ray
    ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
}

Now find the line:

VRInteractiveItem interactible = hit.collider.GetComponent<VRInteractiveItem>();

and add the following code after it:

if (interactible) {
  	worldEndPoint = hit.point;
}

This sets the end point of the laser beam to the position of any VRInteractiveItem it hits.

At the end of the EyeRaycast function, add:

if (ControllerIsConnected && m_LineRenderer != null) {
  	m_LineRenderer.SetPosition (0, worldStartPoint);
  	m_LineRenderer.SetPosition (1, worldEndPoint);
}

to make the endpoints of the laser beam the same as the endpoints of the ray we’re casting.

Reticle

The end of the laser beam will have a reticle, or a targeting circle. The MainCamera prefab already includes a reticle that is displayed in front of the camera. We’re going to change its code so that the reticle is automatically displayed at the end of the laser beam if a controller is connected, but displayed in front of the camera if there is no controller.

In Assets/VRSampleScenes/Scripts/Utils/Reticle.cs, find the

SetPosition()
  function. Change this function so that it takes two arguments, a position and a direction:

public void SetPosition (Vector3 position, Vector3 forward) {
  	// Set the position of the reticle to the default distance in front of the camera.
  	m_ReticleTransform.position = position + forward * m_DefaultDistance;
  
  	// Set the scale based on the original and the distance from the camera.
  	m_ReticleTransform.localScale = m_OriginalScale * m_DefaultDistance;
  
  	// The rotation should just be the default.
  	m_ReticleTransform.localRotation = m_OriginalRotation;
}

We’ll see a compilation error about

SetPosition()
  until we add the arguments
ray.origin
  and
ray.direction
  to
m_Reticle.SetPosition
  at the end of the
VREyeRayCaster.EyeRaycast
  function:

if (m_Reticle)
    m_Reticle.SetPosition (ray.origin, ray.direction);

To pull everything together in Unity, make sure VREyeRayCaster’s fields in the inspector are filled. You will need to manually add CenterEyeAnchor to the “Line Renderer” field, which populates m_LineRenderer, and TrackingSpace to the “Tracking Space” field.

Image may be NSFW.
Clik here to view.

If you run the scene in a headset, the reticle will appear at the end of the laser beam that extends from the controller.

Image may be NSFW.
Clik here to view.

Teleport Manager and Player

It’s finally time to implement the scripts for teleportation. Create an empty GameObject named TeleportManager. Create a new script, Assets/Scripts/TeleportManager.cs, and attach it to the TeleportManager GameObject.

Open TeleportManager.cs and create the class:

using System;
using UnityEngine;
using VRStandardAssets.Utils;

public class TeleportManager : MonoBehaviour {
    public static event Action<Transform> DoTeleport;
    [SerializeField] VRInteractiveItem[] teleportLocations;
    [SerializeField] Transform reticleTransform;
}

The VRInteractiveItem component, defined in Assets/VRStandardAssets/Scripts/VRInteractiveItem.cs, allows you to interact with objects in VR. VRInteractiveItem provides events that are activated when different types of interactions occur. We will be using the OnClick event.

teleportLocations
  is an array of VRInteractiveItems that, when clicked, cause the user to teleport to the location of the reticle. We will populate
teleportLocations
  from the inspector.

 When the reticle targets a teleport location, and the controller is clicked, the player will be teleported to the position of 

reticleTransform
 .

The actual teleporting will be done by the Player object, which we will create later.

Player
  will contain a method that subscribes to
TeleportManager.DoTeleport
. DoTeleport is an event like
VRInteractiveItem.OnClick
 .

Within TeleportManager, add the following methods:

void OnEnable() {
    foreach (VRInteractiveItem t in teleportLocations) {
        t.OnClick += Teleport;
    }
}

void OnDisable() {
    foreach (VRInteractiveItem t in teleportLocations) {
        t.OnClick -= Teleport;
    }
}

void Teleport() {
    if (DoTeleport != null) {
        DoTeleport(reticleTransform);
    } else {
        Debug.Log("DoTeleport event has no subscribers.");
    }
}

OnEnable is called automatically when the TeleportManager is created. In OnEnable, the Teleport method subscribes to the OnClick event of each teleport location.

TeleportManager.Teleport
is run whenever a teleport location is clicked. OnDisable unsubscribes Teleport when the TeleportManager object is destroyed. Unsubscribing prevents memory leaks.

The Teleport method calls the DoTeleport action, which causes subscribing methods to run.

Now we’ll create a wrapper object for the player. Create an empty GameObject named Player, and attach a new script, Assets/Scripts/Player.cs. Nest OVRCameraRig under Player because the camera is the point of view of the player. Set Player’s position to (0, 1.8, 0), and reset OVRCameraRig’s position to (0, 0, 0). OVRCameraRig’s position is now relative to Player.

Image may be NSFW.
Clik here to view.

Add the code for Player.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

	Vector3 playerPosition;       // Keeps track of where Player will be teleported.
	
	[SerializeField] float playerHeight = 1.8f; 
	
	void OnEnable() {
		TeleportManager.DoTeleport += MoveTo;
	}

	void OnDisable() {
		TeleportManager.DoTeleport -= MoveTo;
	}

	void MoveTo(Transform destTransform) {
		// Set the new position.
		playerPosition = destTransform.position;
		// Player's eye level should be playerHeight above the new position.
		playerPosition.y += playerHeight;  
		// Move Player.
		transform.position = playerPosition;
	}
}

playerPosition
  is a placeholder for the position where the player will be teleported.
playerHeight
  exists because we need to take the player’s eye level into consideration when we teleport.

In

OnEnable
 , the
Player.MoveTo
  method is subscribed to the
TeleportManager.DoTeleport
  event. The unsubscription occurs in OnDisable.

Player.MoveTo   does the work of teleporting a player. We add playerHeight to the y coordinate of the destination Transform’s position to account for eye level. Then we move Player by updating the position of its Transform to the new destination.

Image may be NSFW.
Clik here to view.
The flow of control when the controller clicks a teleport location.

Creating Teleport Locations

Our last step will be creating teleport locations.

In the Unity hierarchy, create a plane named “Ground” and position it at the origin. Enlarge Ground and attach VRStandardAssets/Scripts/VRInteractiveItem.cs. Create a couple of cubes located on the ground to serve as waypoints. As we teleport on the ground, these waypoints will help us tell where we are.

Now create some thinner cubes and form them into the steps of a staircase. Nest the stairs in an empty GameObject named Stairs, and attach VRInteractiveItem.cs to each stair.

Image may be NSFW.
Clik here to view.

Finally, to pull everything together, we will populate the fields of TeleportManager. In the inspector, open the “Teleport Locations” field, and set the size equal to the number of VRInteractiveItems. Fill in the elements by dragging Ground and each of the stairs from the hierarchy window to the fields in the inspector. Fill in the “Reticle Transform” field with GUIReticle.

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

Building the Project

Now we’re ready to test the app. Plug in your Oculus Go headset or your Samsung phone, and select “Build and Run” from the File menu. If everything works, you will be able to teleport to any location on the ground or on the stairs by pointing the controller and clicking the trigger button. You have now successfully implemented teleporting in VR!

Image may be NSFW.
Clik here to view.
Initial view
Image may be NSFW.
Clik here to view.
View after teleporting to the stairs
Image may be NSFW.
Clik here to view.
Standing on the stairs

Teleportation in VR with Unity – Oculus Go and GearVR Tutorial

One of the challenges of virtual reality is locomotion. In room-scale VR users can walk around, but limited space is a problem. Mobile VR users with only three degrees of freedom have to rely on head movement or controllers.

Teleportation is a fun way to get around the limitations of VR. Although not truly natural, users are accustomed to the concept of teleportation from sci-fi and fantasy, and it is not hard to implement.

We will be building a scene for Oculus Go/Gear VR that demonstrates teleportation using the controller as a pointer.

Source Code

The Unity project for this tutorial is available for download here. To save space, Oculus Utilities and VR Sample Scenes are not included, but the source files that were modified are included in the top level of the project. These files are OVRPlugin.cs, VREyeRaycaster.cs, and Reticle.cs.

Setup

To get started, create a new Unity project, Teleporter. Create the folder Assets/Plugins/Android/assets within the project, and copy your phone’s Oculus signature file there. See https://dashboard.oculus.com/tools/osig-generator/ to create a new signature file.

Select File -> Build Settings from the menu and choose Android as the platform. Click on Player Settings to load PlayerSettings in Unity inspector. Add Oculus under Virtual Reality SDK’s and select API Level 19 as the Minimum API Level.

Download Oculus Utilities from https://developer.oculus.com/downloads/package/oculus-utilities-for-unity-5/ and extract the zip file on your computer. Import Oculus Utilities into your project by selecting Assets -> Import Package -> Custom Package within Unity and choosing the location of the package you extracted. If you are prompted to update the package, follow the prompts to install the update and restart Unity.

A folder named Oculus will be created in your project. Oculus/Prefabs contains the OVRCameraRig and TrackedRemote prefabs that we will use to implement controller support. If you expand TrackedRemote in the project view, you’ll see that it contains prefabs for the Gear VR and Oculus Go controllers.

Image may be NSFW.
Clik here to view.

If you get the error message “‘OVRP_1_15_0’ does not exist in the current context,” open Assets/Oculus/VR/Scripts/OVRPlugin.cs and add #if !OVRPLUGIN_UNSUPPORTED_PLATFORM  and

#endif
  around code that checks the OVRPlugin version. You can find a fixed copy of OVRPlugin.cs in the included source. This error probably does not occur on Windows.

We will also need the VR Samples package from the Unity Asset Store. This package includes a number of sample scenes as well as prefabs and scripts that we will customize to add a laser pointer and reticle. Click on the Asset Store tab in Unity, and search for “VR Samples.” When loaded, click the import button and follow the instructions to import this package. The folders VRSampleScenes and VRStandardAssets will be created in your Assets folder.

Preparing Your Headset

If you are using the Gear VR, you will need to activate Developer Mode on your phone to test your app. In your phone settings, go to “About Device” and tap seven times on “Build number.”

You will also need to activate Developer Mode if you are using an Oculus Go. First, you need to create an organization in your Oculus account at https://dashboard.oculus.com/. Then, in the Oculus mobile app, choose the headset you’re using from the Settings menu, select More Settings, and toggle Developer Mode. See https://developer.oculus.com/documentation/mobilesdk/latest/concepts/mobile-device-setup-go/ for details.

Camera and Controller

Let’s start by setting up a VR camera and adding controller support. First, remove the Main Camera object that was created by default. We will be using a custom camera.

Create an instance of the OVRCameraRig prefab included in Oculus Utilities by dragging Assets/Oculus/VR/Prefabs/OVRCameraRig from the project window to the hierarchy window. Expand OVRCameraRig, and you’ll see that it contains a TrackingSpace with anchors for the eyes and hands. Set the position of  OVRCameraRig to (0, 1.8, 0) to approximate the height of a person.

Image may be NSFW.
Clik here to view.

CenterEyeAnchor is the placeholder for our camera that we will replace with the MainCamera prefab included in VR Sample Scenes. Drag Assets/VRSampleScenes/Prefabs/Utils/MainCamera from the project window to the hierarchy. Rename this instance CenterEyeAnchor and nest it under OVRCameraRig -> TrackingSpace. Remove the original CenterEyeAnchor.

Now add the controller using the Assets/Oculus/Prefabs/TrackedRemote prefab. Create instances of TrackedRemote as children of OVRCameraRig->TrackingSpace -> LeftHandAnchor and OVRCameraRig -> TrackingSpace -> RightHandAnchor. TrackedRemote contains models for both the Gear VR controller and the Oculus Go controller. When you run this scene, the correct controller model is displayed depending on which headset you’re using.

Image may be NSFW.
Clik here to view.

Make sure the Controller field of the TrackedRemote instance under LeftHandAnchor is set to “L Tracked Remote.” The instance under RightHandAnchor should be set to “R Tracked Remote.” You can do this in the Unity inspector.

If both hands are set correctly, the controller will automatically be displayed for the correct hand when you run the scene.

Next, add a laser beam that extends from the controller. Add a Line Renderer to CenterEyeAnchor by clicking “Add Component” in the inspector and typing “Line Renderer” in the search box. Disable “Receive Shadows” and set the material to MazeAgentPath, a red material included with the VR Sample Scenes package. If you want a different colored laser, you can easily create a different colored material and use it in the Line Renderer.

Under the Width field, drag the slider down to set a width of about (0.0, 0.02). If the width is too thick, your laser beam will look like a huge block instead of a beam.

Image may be NSFW.
Clik here to view.

Coding a Laser Beam

Our next step will turn the controller into a laser pointer. To do this, we modify the scripts attached to CenterEyeAnchor and VRCameraUI using the steps described in https://developer.oculus.com/blog/adding-gear-vr-controller-support-to-the-unity-vr-samples/. The modified scripts are included in the source code package that comes with this tutorial.

The script Assets/VRStandardAssets/Scripts/VREyeRaycaster.cs is attached to CenterEyeAnchor. Add these fields to the VREyeRaycaster class:

[SerializeField] private LineRenderer m_LineRenderer = null;     
public bool ShowLineRenderer = true;

Add the following accessors to VREyeRaycaster:

/* Accessors for controller */

public bool ControllerIsConnected {
	get {
		OVRInput.Controller controller =OVRInput.GetConnectedControllers () & (OVRInput.Controller.LTrackedRemote | OVRInput.Controller.RTrackedRemote);
		return controller == OVRInput.Controller.LTrackedRemote || controller == OVRInput.Controller.RTrackedRemote;
	}
}

public OVRInput.Controller Controller {
	get {
		OVRInput.Controller controller = OVRInput.GetConnectedControllers ();
		if ((controller & OVRInput.Controller.LTrackedRemote) == OVRInput.Controller.LTrackedRemote) {
			return OVRInput.Controller.LTrackedRemote;
		} else if ((controller & OVRInput.Controller.RTrackedRemote) == OVRInput.Controller.RTrackedRemote) {
			return OVRInput.Controller.RTrackedRemote;
		}
		return OVRInput.GetActiveController ();
	}
}

Controller
  determines which controller is connected, and
ControllerIsConnected
  determines if a controller is connected.

Now look for the EyeRaycast function and find the line:

RaycastHit hit;

After this line, add:

Vector3 worldStartPoint = Vector3.zero;
Vector3 worldEndPoint = Vector3.zero;
if (m_LineRenderer !=null) {
  	m_LineRenderer.enabled = ControllerIsConnected && ShowLineRenderer;
}

This code enables the line renderer, making the laser beam visible, only if a controller is connected.

Add more code after this to convert the controller’s local position and rotation to world coordinates:

if (ControllerIsConnected && m_TrackingSpace != null) {
    Matrix4x4 localToWorld = m_TrackingSpace.localToWorldMatrix;
    Quaternion orientation = OVRInput.GetLocalControllerRotation (Controller);

    Vector3 localStartPoint = OVRInput.GetLocalControllerPosition (Controller);
    Vector3 localEndPoint = localStartPoint + ((orientation * Vector3.forward) * 500.0f);

    worldStartPoint = localToWorld.MultiplyPoint(localStartPoint);
    worldEndPoint = localToWorld.MultiplyPoint(localEndPoint);

    // Create new ray
    ray = new Ray(worldStartPoint, worldEndPoint - worldStartPoint);
}

Now find the line:

VRInteractiveItem interactible = hit.collider.GetComponent<VRInteractiveItem>();

and add the following code after it:

if (interactible) {
  	worldEndPoint = hit.point;
}

This sets the end point of the laser beam to the position of any VRInteractiveItem it hits.

At the end of the EyeRaycast function, add:

if (ControllerIsConnected && m_LineRenderer != null) {
  	m_LineRenderer.SetPosition (0, worldStartPoint);
  	m_LineRenderer.SetPosition (1, worldEndPoint);
}

to make the endpoints of the laser beam the same as the endpoints of the ray we’re casting.

Reticle

The end of the laser beam will have a reticle, or a targeting circle. The MainCamera prefab already includes a reticle that is displayed in front of the camera. We’re going to change its code so that the reticle is automatically displayed at the end of the laser beam if a controller is connected, but displayed in front of the camera if there is no controller.

In Assets/VRSampleScenes/Scripts/Utils/Reticle.cs, find the

SetPosition()
  function. Change this function so that it takes two arguments, a position and a direction:

public void SetPosition (Vector3 position, Vector3 forward) {
  	// Set the position of the reticle to the default distance in front of the camera.
  	m_ReticleTransform.position = position + forward * m_DefaultDistance;
  
  	// Set the scale based on the original and the distance from the camera.
  	m_ReticleTransform.localScale = m_OriginalScale * m_DefaultDistance;
  
  	// The rotation should just be the default.
  	m_ReticleTransform.localRotation = m_OriginalRotation;
}

We’ll see a compilation error about

SetPosition()
  until we add the arguments
ray.origin
  and
ray.direction
  to
m_Reticle.SetPosition
  at the end of the
VREyeRayCaster.EyeRaycast
  function:

if (m_Reticle)
    m_Reticle.SetPosition (ray.origin, ray.direction);

To pull everything together in Unity, make sure VREyeRayCaster’s fields in the inspector are filled. You will need to manually add CenterEyeAnchor to the “Line Renderer” field, which populates m_LineRenderer, and TrackingSpace to the “Tracking Space” field.

Image may be NSFW.
Clik here to view.

If you run the scene in a headset, the reticle will appear at the end of the laser beam that extends from the controller.

Image may be NSFW.
Clik here to view.

Teleport Manager and Player

It’s finally time to implement the scripts for teleportation. Create an empty GameObject named TeleportManager. Create a new script, Assets/Scripts/TeleportManager.cs, and attach it to the TeleportManager GameObject.

Open TeleportManager.cs and create the class:

using System;
using UnityEngine;
using VRStandardAssets.Utils;

public class TeleportManager : MonoBehaviour {
    public static event Action<Transform> DoTeleport;
    [SerializeField] VRInteractiveItem[] teleportLocations;
    [SerializeField] Transform reticleTransform;
}

The VRInteractiveItem component, defined in Assets/VRStandardAssets/Scripts/VRInteractiveItem.cs, allows you to interact with objects in VR. VRInteractiveItem provides events that are activated when different types of interactions occur. We will be using the OnClick event.

teleportLocations
  is an array of VRInteractiveItems that, when clicked, cause the user to teleport to the location of the reticle. We will populate
teleportLocations
  from the inspector.

 When the reticle targets a teleport location, and the controller is clicked, the player will be teleported to the position of 

reticleTransform
 .

The actual teleporting will be done by the Player object, which we will create later.

Player
  will contain a method that subscribes to
TeleportManager.DoTeleport
. DoTeleport is an event like
VRInteractiveItem.OnClick
 .

Within TeleportManager, add the following methods:

void OnEnable() {
    foreach (VRInteractiveItem t in teleportLocations) {
        t.OnClick += Teleport;
    }
}

void OnDisable() {
    foreach (VRInteractiveItem t in teleportLocations) {
        t.OnClick -= Teleport;
    }
}

void Teleport() {
    if (DoTeleport != null) {
        DoTeleport(reticleTransform);
    } else {
        Debug.Log("DoTeleport event has no subscribers.");
    }
}

OnEnable is called automatically when the TeleportManager is created. In OnEnable, the Teleport method subscribes to the OnClick event of each teleport location.

TeleportManager.Teleport
is run whenever a teleport location is clicked. OnDisable unsubscribes Teleport when the TeleportManager object is destroyed. Unsubscribing prevents memory leaks.

The Teleport method calls the DoTeleport action, which causes subscribing methods to run.

Now we’ll create a wrapper object for the player. Create an empty GameObject named Player, and attach a new script, Assets/Scripts/Player.cs. Nest OVRCameraRig under Player because the camera is the point of view of the player. Set Player’s position to (0, 1.8, 0), and reset OVRCameraRig’s position to (0, 0, 0). OVRCameraRig’s position is now relative to Player.

Image may be NSFW.
Clik here to view.

Add the code for Player.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

	Vector3 playerPosition;       // Keeps track of where Player will be teleported.
	
	[SerializeField] float playerHeight = 1.8f; 
	
	void OnEnable() {
		TeleportManager.DoTeleport += MoveTo;
	}

	void OnDisable() {
		TeleportManager.DoTeleport -= MoveTo;
	}

	void MoveTo(Transform destTransform) {
		// Set the new position.
		playerPosition = destTransform.position;
		// Player's eye level should be playerHeight above the new position.
		playerPosition.y += playerHeight;  
		// Move Player.
		transform.position = playerPosition;
	}
}

playerPosition
  is a placeholder for the position where the player will be teleported.
playerHeight
  exists because we need to take the player’s eye level into consideration when we teleport.

In

OnEnable
 , the
Player.MoveTo
  method is subscribed to the
TeleportManager.DoTeleport
  event. The unsubscription occurs in OnDisable.

Player.MoveTo   does the work of teleporting a player. We add playerHeight to the y coordinate of the destination Transform’s position to account for eye level. Then we move Player by updating the position of its Transform to the new destination.

Image may be NSFW.
Clik here to view.
The flow of control when the controller clicks a teleport location.

Creating Teleport Locations

Our last step will be creating teleport locations.

In the Unity hierarchy, create a plane named “Ground” and position it at the origin. Enlarge Ground and attach VRStandardAssets/Scripts/VRInteractiveItem.cs. Create a couple of cubes located on the ground to serve as waypoints. As we teleport on the ground, these waypoints will help us tell where we are.

Now create some thinner cubes and form them into the steps of a staircase. Nest the stairs in an empty GameObject named Stairs, and attach VRInteractiveItem.cs to each stair.

Image may be NSFW.
Clik here to view.

Finally, to pull everything together, we will populate the fields of TeleportManager. In the inspector, open the “Teleport Locations” field, and set the size equal to the number of VRInteractiveItems. Fill in the elements by dragging Ground and each of the stairs from the hierarchy window to the fields in the inspector. Fill in the “Reticle Transform” field with GUIReticle.

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

Building the Project

Now we’re ready to test the app. Plug in your Oculus Go headset or your Samsung phone, and select “Build and Run” from the File menu. If everything works, you will be able to teleport to any location on the ground or on the stairs by pointing the controller and clicking the trigger button. You have now successfully implemented teleporting in VR!

Image may be NSFW.
Clik here to view.
Initial view
Image may be NSFW.
Clik here to view.
View after teleporting to the stairs
Image may be NSFW.
Clik here to view.
Standing on the stairs

CREDIT: Featured Image from Photo by Martin Sanchez on Unsplash

How to Build a Complete 2D Platformer in Unity

Introduction

Since the release of Unity 2017.1 in the summer of 2017, Unity Technologies has made making 2D games incredibly easy and fast. In this tutorial, we will create a fully-featured 2D platformer. This project will incorporate a number of key topics including how to make cutscenes, how to quickly build and prototype a 2D level, and how to precisely choreograph game objects using the Timeline Editor. This tutorial can also be thought of as the culmination of several tutorials – posted on Game Dev Academy – about these topics. You can check them out here:

Storytelling in Unity – Part 1: Virtual Cameras

Storytelling in Unity – Part 2: Animation Tracks

Cinemachine and Timeline Editor for Unity 2D Game Development

Mastering Unity’s New Tilemap Editor: Building 2D Levels

Project Details

Let’s think about what we will be making. As said in the introduction, it will be a 2D platformer. We will use the 2D character from the Unity Standard Assets pack. Then we will create an environment using tilemaps and Unity’s new Tilemap Editor. Then we will create an enemy that has an Idle/Attack animation (you’ll see). Then we will create a cutscene where the camera views the entire level then zooms on the character: here we will use the Timeline Editorand Cinemachine for 2D.

Tilemap Editor, Timeline, and Cinemachine

When Unity Technologies released the Unity 2017 version cycle, they introduced three pivotal tools designed to make Unity more accessible to artists. These tools were the Tilemap Editor, Timeline, and Cinemachine. The Tilemap Editor, released later in the 2017 cycle, allowed users to “…literally paint directly in Unity” according to Rus Scammell, the project manager of Unity for 2D. The Tilemap Editor gives you the ability to create vast and complicated Tilemaps without having to use a third-party program. The Timeline Editor and Cinemachine were released at the same time, though improvements to Cinemachine were released later. Cinemachine is a suite of cameras that allows you to create cutscenes, specify how the camera tracks a game object, and, in the end, allows you to tell a better story. Combine this with the Timeline Editor, a tool that allows you to choreograph game objects like a movie editor. With these two tools, you can create stunning compositions with having to write any code. Well, that’s a summary of the tools that we will be using! This tutorial is by no means exhaustive, for more information about these tools check out the tutorials linked above.

Setting up our project

The assets for this project you can get here. Then create a new Unity project. Let’s import the 2D Standard Assets package by going to Assets -> Import Package -> 2D.

Image may be NSFW.
Clik here to view.

Next, we need to create two new folders. One called “Animations” and the other called “Tiles”.

Image may be NSFW.
Clik here to view.

In the Tiles folder, create another folder called “Tile Palettes”.

Image may be NSFW.
Clik here to view.

The use of this folder will become apparent later on. Now let’s import Cinemachine by going to the asset store and searching “Cinemachine”. It should be the first option so just select it and import it.

Image may be NSFW.
Clik here to view.

Now we need to import the Tilemap Editor tools. Click this link to take you to the Github download page. Import this into the “Assets” folder of your project.

Image may be NSFW.
Clik here to view.

Now that we have everything imported we can start getting our tools in order. We will start with the Tilemap Editor. Go to Window -> Tile Palette.

Image may be NSFW.
Clik here to view.

Place it in a sensible place on your workspace. I chose to put it in the space between the inspector and the scene view. Next, we need the Timeline Editor. Go to Window -> Timeline Editor.

Image may be NSFW.
Clik here to view.

The position of this tab is not set in stone so be prepared to move it around. We now have our workspace in order! Time to start creating!

Creating our environment

Go to your Tile Palette tab and create a new palette. Call it “Solids” since these are the tiles that the character will not be able to pass through.

Image may be NSFW.
Clik here to view.

A palette works just like you would expect it to based on the name, it is a set of images that we use to “paint” with. Leave all of the settings set to default and save it in the Tile Palettes folder which we created in the Tiles folder.

Image may be NSFW.
Clik here to view.

Now, go to your “Environment Tiles” folder and pick out a set of environment tile images. Once you have selected an environment theme, select all of them and change the Pixels Per Unit value in the import settings.

Image may be NSFW.
Clik here to view.

The reason we do this is so that the tile images correctly fit the tile cells in the grid space. Click “Apply” and your good to go! Next, we are going to create a special type of tile, called a “Rule Tile”, that will drastically speed up level creation. In the Tiles folder, right click and go to Create -> Rule Tile.

Image may be NSFW.
Clik here to view.

Name it “Environment Tiles”.

Image may be NSFW.
Clik here to view.

We have to do one last thing to our tile images and that is to make them into Tiles instead of just images. The easiest way to do this is to drag all of the environment images into the Tile Palette tab.

Image may be NSFW.
Clik here to view.

You will be asked where to save each tile. This can be kind of tedious so just get through it as fast possible and save each tile in the Tiles folder. Now go to your rule tile and create a place for each of your environment tiles. The settings for this rule tile can be kind of complicated and hard to get used to. That is why it is best if you just copy the settings of this rule tile:

Image may be NSFW.
Clik here to view.

Once you are finished, drag your rule tile into the Tile Palette tab.

Image may be NSFW.
Clik here to view.

Now that all of our tiles are in order, let’s create a “canvas” to paint on. In your hierarchy, right-click and got to 2D Object -> Tilemap.

Image may be NSFW.
Clik here to view.

What it has done is created a grid, and inside that grid is our “canvas”, also known as a tilemap. In order to start painting you need to familiarize your self with the toolbar in the Tile Palette tab. With your rule tile selected, start experimenting with the various types of brushes. Once you feel pretty confident with the tools, start creating your level!

Adding the character

The last thing we have to do to our tilemap is to make it have physics interactions. Right now anything we put on it would just fall through the world. To fix this, Unity Technologies released a new collider component called the Tilemap Collider. This behaves just like you would expect it to based on the title, it creates a collider around each tile. Go to your Tilemap and click Add Component.

Image may be NSFW.
Clik here to view.

Search “Tile” and it should appear first. Once you add this, you can drag the character into the scene!

Image may be NSFW.
Clik here to view.

We will be using the default character that came with the 2D standard asset pack. You can find the character by either going to Standard Assets -> 2D -> Prefabs and then dragging in the “CharacterRobotBoy”, or, you can just search “CharacterRobotBoy” and access it from there. Once the character is in the scene, you can hit play and move the character through the arrow keys. You may have to reposition the camera in order to see the robot. Great! On to the next paragraph!

Creating the enemy

In the “Enemies” folder from the asset pack, pick a certain enemy that you think would go well with your scene.

Image may be NSFW.
Clik here to view.

Drag it into your scene and place it in a sensible spot.

Image may be NSFW.
Clik here to view.

Then create a new tag called “Enemy” and assign it to your enemy.

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

Now we are going to animate this enemy. You should already have the Animation tab open in the lower window of your workspace. If not, go to Window -> Animation.

Image may be NSFW.
Clik here to view.

With your enemy selected, click “Create” in the Animation tab.

Image may be NSFW.
Clik here to view.

Name it “Enemy1Controller”.

Image may be NSFW.
Clik here to view.

Save the animator controller in the Animations folder we created earlier. Next, click “Create” again

Image may be NSFW.
Clik here to view.

and give the animation a sensible title.

Image may be NSFW.
Clik here to view.

Hit the record button and change the Sprite field to the other image that was provided (in my case it was called Saw_move, it may be similar if you chose a different enemy).

Image may be NSFW.
Clik here to view.

Then move about four frames ahead and change the image back to what it was before.

Image may be NSFW.
Clik here to view.

Then move a couple frames forward and change it back to the first image.

Image may be NSFW.
Clik here to view.

Now if you hit play you will see that our enemy is animating! Cool!

Scripting our enemy

Let’s make it so that whenever the character touches the enemy the level restarts. The best way to do this is to actually create a new script and box collider on our robot character.

Image may be NSFW.
Clik here to view.

Set the box collider to Trigger and make sure it liberally covers the character. Name the new script “EnemyReaction”.

Image may be NSFW.
Clik here to view.

Let’s create a new folder called “Scripts” to house this component.

Image may be NSFW.
Clik here to view.

Here is the content of the EnemyReaction script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // This is very important if we want to restart the level

public class EnemyReaction : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	// This function is called every time another collider overlaps the trigger collider
	void OnTriggerEnter2D (Collider2D other){
		// Checking if the overlapped collider is an enemy
		if (other.CompareTag ("Enemy")) {
			// This scene HAS TO BE IN THE BUILD SETTINGS!!!
			SceneManager.LoadScene ("scene1");
		}
	}
}

In order for this script to work, we need to do a couple of things. First, we need to have a collider on our enemy.

Image may be NSFW.
Clik here to view.

A simple box collider works best for covering all needs. Then, we need to save this scene as “scene1”.

Image may be NSFW.
Clik here to view.

Just save it in the root folder since we only have one, but if you are planning on having multiple scenes then you should create a new folder. Finally, that scene has to be put in the build settings. To do this, just go to File -> Build Settings

Image may be NSFW.
Clik here to view.

and then click “Add Open Scenes”.

Image may be NSFW.
Clik here to view.

Now everything should work! Hit play and run into the enemy, the level restarts!

Cinemachine and Timeline

We now come to the last part of this tutorial. In this part, we will be using Cinemachine and the Timeline editor. Let’s start with Cinemachine. You’ll notice that our camera isn’t following the character when he moves around. We can fix this by creating what is known as a Virtual Camera. Navigate to your toolbar and go to Cinemachine -> Create 2D Camera.

Image may be NSFW.
Clik here to view.

Then assign the “follow” field on this camera to be the CharacterRobotBoy. Rename this to “PlayerCam”. Set the Aim to “Do Nothing” and set the Body to “Framing Transposer”.

Image may be NSFW.
Clik here to view.

Now, in the game view, you will notice a set of blue and red areas.

Image may be NSFW.
Clik here to view.

You can click and drag these areas to change their shape. The one that is harder to see is the clear zone. It sits right on top of our character. This is known as the Dead Zone. The Camera will not do anything as long as the character is in this zone. The blue zone is the Soft Zone. If the character crosses over into this zone the camera will reposition itself so that the character is back in the Dead Zone. The red zone is known as the Bias. The character will never ever cross into this area. Now that you have this knowledge, change the size of these areas in order to get the right following style that you like. Next, let’s have a look at the Timeline Editor. Create a new, empty game object, named “Timeline”…

Image may be NSFW.
Clik here to view.

…and then click Create in the Timeline Editor. Call it “TheTimeline” and save it in the root folder.

Image may be NSFW.
Clik here to view.

You can have multiple timeline editors in a scene, which just adds to the complexity so we just have one. With this Timeline, we will create a cutscene where the camera views the entire level and then zooms in on the player. This will occur as soon as the scene starts. In order to do this, we need to combine Cinemachine and the Timeline Editor. We can do this through Cinemachine shot clips. In the Timeline, click “Add” and then go to Cinemachine.Timeline -> Cinemachine Track.

Image may be NSFW.
Clik here to view.

Drag the Main Camera into the field.

Image may be NSFW.
Clik here to view.

Then right-click and go to “Add Cinemachine Shot Clip”.

Image may be NSFW.
Clik here to view.

With this track, we can specify how long we want a certain camera to be active. Let’s create a new 2D camera and position it so that we can see the entire level. Name this one “FullLevel”.

Image may be NSFW.
Clik here to view.

This will be our first camera so select the Cinemachine shot clip and drag this camera into the “Virtual Camera” field.

Image may be NSFW.
Clik here to view.

Set how long you want this camera to last. One thing that helps is to set the timescale to be in second and not frames.

Image may be NSFW.
Clik here to view.

Next, we need to create another clip for the player camera.

Image may be NSFW.
Clik here to view.

Place this at the end of the other clip. Drag either one of the clips on top of each other in order to smoothly transition. Now if you hit play, we have a pretty neat cutscene! But notice when the last track ends it goes back to the first camera instead of staying on the player. The easiest way to fix this is by deactivating the first camera after we have transitioned into the second. We can do this by using an Activation Track. As its title implies, the specified game object will stay active as long as the track persists. Create an Activation track…

Image may be NSFW.
Clik here to view.

…and drag the first camera into its field.

Image may be NSFW.
Clik here to view.

Then set the length to be a little after the transition. Now if you hit play, it all looks good and the player camera persists!

Outro

Congratulations on getting to the end of this tutorial. As I said before, this is not meant to be exhaustive. In order to find out more about these tools, you can either read the tutorials linked above, or you can explore them on your own! In either case:

Keep making great games!

A Guide to Using the Facebook Instant Games Plugin for Phaser 3 – Part 1

Phaser is a fantastic HTML5 game framework that works on both desktop and mobile web browsers. Not only this, it is constantly getting updates and new features. One of the newer features is native support for Facebook’s Instant Games. This feature was added in version 3.13 and it is great! With this new addition, it is very easy to take your existing Phaser game and turn it into a Facebook Instant Game.

If you are not familiar with Facebook Instant Games, they are a newer type of game that can be played across Facebook platforms. These types of games are HTML5 games that people can play directly in their news feed or in their Messenger conversations on both desktop and mobile devices. If you are interested, you can read more about it here: Facebook Developers – Instant Games.

In this tutorial, you will learn how to use the Facebook Instant Game Plugin for Phaser 3. We will show you how to access information about the player, how you can store data on Facebook, and how you can use other features like leaderboards.

You can download all of the files associated with the source code here.

Tutorial Requirements

One of the requirements for testing your html5 games with the Facebook Instant Games SDK is you either need to zip and upload your game to Facebook every time you make a change, or you can run a local SSL enabled server and you can embed the game in Facebook’s instant game player. For the purpose of this tutorial, we will be running the SSL enabled server locally.

Another requirement for this tutorial is you must be using at least Phaser 3.13. Earlier versions of Phaser do not support the Facebook Instant games plugin. You should be able to follow along with any version of Phaser after 3.13.

To create our server we will be using Node.js. We will also be using NPM to install the required packages we need for the server to be enabled for SSL. In order to follow along with this tutorial, you will need to have Node.js and NPM installed locally, or you will need access to an environment that already has them installed. We will also be using the Command Prompt (Windows) / Terminal (Mac) to install the required packages, and to start/stop our Node server.

Having a prior experience with these tools is a plus, but it is not required for this tutorial. We will not be covering how to install these tools as the focus of this tutorial is making a game with Phaser. The last thing you will need is an IDE or Text Editor for editing your code.

To install Node.js, click the link here: and choose the LTS version. You can download and use the current version with this tutorial, however, the LTS version is recommended for most users. When you install Node.js, NPM will also be installed on your computer. Once you have these tools installed, you can move on to the next part.

Creating a new Facebook App

The first thing we need to do when creating a new game for Facebook is we need to create an app in their developer portal. To do this, you will need to have a Facebook Developer account. You can access the Facebook Developer website here: Facebook Developers Website.

After you have logged into your account, go ahead and click on “My Apps”  button from the drop-down menu and select the “Add new app” option.

Image may be NSFW.
Clik here to view.

In the popup window that appears, enter your email address and a name for your app, and then click on the “Create App ID” button. You may get a new window asking you to complete a security check. If you do, just complete the reCAPTCHA and hit “submit”.

Image may be NSFW.
Clik here to view.

You should then be taken to the “Add A Product” screen, and from here you will need to “Set Up” button under the Instant Games section.

Image may be NSFW.
Clik here to view.

On the “Instant Games” page, you will want to make sure the “Use Instant Games” toggle is turned on. Next, you will need to fill out the “Tagline” and “Publisher” fields. Lastly, choose a “Category” for your game.

Image may be NSFW.
Clik here to view.

Once you have done this, go ahead and click on the “Save Changes” button at the bottom of the page. Next, we are going to add a “Leaderboard” to our app. To do this, click on the “Leaderboards” option on the left side of the page.

Image may be NSFW.
Clik here to view.

Then, in the “Create Leaderboard” section, enter a name for your leaderboard. For this tutorial, we will call ours phaser_tutorial_board. Next, go ahead and click on the “Save Changes” button to finish setting up your leaderboard.

Image may be NSFW.
Clik here to view.

Before you can publish your game, you will need to add some more information about your app and you will need to go through the Facebook App review process. We will come back to these steps later in the tutorial.

Phaser Template

For this tutorial, we will be using the Phaser 3 Webpack Project Template. To get a copy of this template, you can either download the project from the link above or if you have Git installed on your computer you run the following command to clone the repo:

git clone https://github.com/photonstorm/phaser3-project-template.git

You can also get a copy of the files here

Once you have a copy of the files, open your terminal/command prompt and navigate to the project directory and run the following command: npm install. This command will install all of the dependencies that are needed to use this template.

Now that you have the template, we are going to make a few adjustments to it. The first thing we are going to do is we are going to update the npm start command in our package.json file. First, we are going to update the port to point to 8080 instead of 8000. Then, we will add the --https flag to the command, which will tell the webpack dev server to generate it’s own certificates and to enabled SSL. The start command should now look like the following:

"start": "npm run build && webpack-dev-server --port=8080 --https"

Next, we need to tell webpack to load the Facebook Instant Games plugin. To do this, we just need to update the plugins section in our webpack.config.js file. In this file, add the following code to the existing plugins that are defined for Phaser:

'PLUGIN_FBINSTANT': JSON.stringify(true)

The plugins section should look like this:

plugins: [
        new webpack.DefinePlugin({
            'CANVAS_RENDERER': JSON.stringify(true),
            'WEBGL_RENDERER': JSON.stringify(true),
            'PLUGIN_FBINSTANT': JSON.stringify(true)
        })
    ]

Finally, we are going to split index.js file into a few different files. First, we will move the Phaser config object to its own file. In the src folder, create a new file called config.js, and add the following code to it:

import 'phaser';

export default {
  type: Phaser.AUTO,
  parent: 'phaser-example',
  width: window.innerWidth,
  height: window.innerHeight
};

In the code above, we did the following:

  • Copied the config variable from the index.js file.
  • Updated the width and height variables to use the browser’s width and height.
  • Added the export default line in front of our config object. If you are not familar with webpack, the export default line will allow us to import our variable, class, or function inside another file. This is great since it allows us to separate our code into multiple files without losing any functionality.
  • Lastly, we added the import 'phaser' line at the top of our file. The line allows us to reference phaser in our code even though this code is not present in our current file. When webpack runs, it will bundle all of our code toghether and resolve all of these imports.

Next, we are going to move the code for our Phaser Scene into a new file. In your src folder, create a new folder called scenes and in this folder create a new file called GameScene.js. In this file add the following code:

import 'phaser';

export default class GameScene extends Phaser.Scene {
  constructor() {
    super({ key: 'Game', active: false });
  }

  preload() {
    this.load.image('logo', 'assets/logo.png');
  }

  create() {
    const width = this.game.config.width;
    const height = this.game.config.height;
    this.add.image(width/2, height/2, 'logo');
  }
}

Let’s review the code we just added:

  • We created a new class called GameScene and we had it extend the Phaser.Scene class.
  • Since our new class is extending an existing class, we are required to add a constructor method and have it call super() before anything else. The super() method is used to call the Parent Class’s constructor method.
  • We added the preload and create method’s code from the index.js file and we removed the tween on the logo.
  • Lastly, we updated the position of the image by getting the width and height of our Phaser game, and we divided those by 2 to center our logo image.

Finally, we just need to update our index.js file. In this file, replace all of the existing code with the following:

import 'phaser';
import config from './config';
import GameScene from './scenes/GameScene';

class Game extends Phaser.Game {
  constructor() {
    super(config);
    this.scene.add('Game', GameScene);
    this.scene.start('Game');
  }
}

new Game();

In the code above we:

  • Imported the config object and the GameScene class we just created.
  • We created a new class called Game that extends the Phaser.Game class.
  • We added our existing scenes to our Game class, and we instantiated our new class.

With those last few changes, we have finished setting up our template.

Running the local server

To start our server, switch back to your terminal and run the following command: npm run start

After a few seconds, you should see a message about webpack compiling successfully and that your project is running at https://localhost:8080/.

Image may be NSFW.
Clik here to view.

Once your server is started, navigate to https://localhost:8080/ in your browser. Since we are using self-signed certs, your browser will probably show a privacy error when you visit that page.

Image may be NSFW.
Clik here to view.

To get around this issue, click on the “Advanced” link, and then click on the “Proceed to localhost (unsafe)” link.

Image may be NSFW.
Clik here to view.

Now, when you view the link you should see a blank page and we can start using Facebook’s instant game player to test our game. To view your game, you will need to update the YOUR_GAME_ID text in the following URL with the id of your Facebook App:

https://www.facebook.com/embed/instantgames/YOUR_GAME_ID/player?game_url=https://localhost:8080

You can find your Facebook App Id in your Facebook Developer account at the top of the page when you are viewing your app.

Image may be NSFW.
Clik here to view.

When you visit this URL, you should see a screen similar to this:

Image may be NSFW.
Clik here to view.

With our local server setup and the Facebook Instant Games player working, we will now start building our game.

Setting up Instant Games SDK

In order to fully use the Facebook Instant Games plugin, we need to import the Instant Games SDK in our index.html file. To do this, open index.html and add the following code to the <head> section of our code:

<script src="https://connect.facebook.net/en_US/fbinstant.6.2.js"></script>

While we are here, we will also add some additional code to the <head> section. First, we are going to add a few additional <meta> tags that will help make our a little more responsive. Add the following code below our existing <meta> tag:

<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="full-screen" content="yes" />
<meta name="screen-orientation" content="portrait" />

Next, we will add some additional styling to remove the padding around our game. Add the following code below the code we just added:

<style>
  body {
    padding: 0px;
    margin: 0;
  }
</style>

Your index.html file should now look like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width, user-scalable=no, minimal-ui">
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="full-screen" content="yes" />
        <meta name="screen-orientation" content="portrait" />
        <style>
            body {
                padding: 0px;
                margin: 0;
            }
        </style>
        <script src="https://connect.facebook.net/en_US/fbinstant.6.2.js"></script>
    </head>
    <body>
        <script src="build/project.bundle.js" charset="utf-8"></script>
    </body>
</html>

The last thing we need to do with the Facebook Instant Games SDK is we need to wait for the SDK to be initialized, and then we can start utilizing the SDK. To do this, the SDK offers a initializeAsync method which returns a Promise once the SDK has been initialized.

For our game, we just need to wrap this method around the code that instantiates our Game class. In index.js, update the new Game(); line of code with the following code:

FBInstant.initializeAsync().then(function() {
  new Game();
}).catch(function(error) {
  console.log(error.message);
});

In the code above, we are waiting for the initializeAsync method to return and once it does we create our Phaser game. In case the initializeAsync method throws an error, we added a catch method that will log the error message to our console.

Now, if you save your game and view it in the Facebook Instant Games player, you should just see the loading icon. If you still see the message with the button “Play Now”, go ahead and click on it.

Image may be NSFW.
Clik here to view.

Conclusion

That brings part one of our tutorial to an end. In part two, we will cover the following topics:

  • Adding a Preloader and connecting it to Facebook Instant Game’s preloader.
  • Loading information about the player
  • Loading and saving stats to the cloud storage of the associated player
  • Saving and loading data from a leaderboard
  • Publishing your game

I hoped you enjoyed part one of this tutorial and found it helpful. If you have any questions, or suggestions on what we should cover next, please let us know in the comments below.

Understanding Procedural Dungeon Generation in Unity

There are two ways of building dungeons in your game. The first one is to manually create the dungeon rooms and connect them through the dungeon. The advantage of doing this is that you can manually select what will be in each room of the dungeon.

The second option is to procedurally generate the dungeon rooms. In this way, you don’t have so much control of what is in each room, but you increase the unpredictability of your game, since each dungeon might be different.

In this tutorial, I’m going to show how you can use Unity to procedurally generate a dungeon. We are going to use Unity’s tilemap functionalities to generate multiple rooms and pseudo-randomly connect them. Then we are going to build a demo where you can try multiple configurations of number of rooms, enemies and obstacles inside each room.

To read this tutorial, it is important that you’re familiar with the following concepts:

  • C# programming and object-oriented concepts
  • Basic Unity concepts, such as Sprites, Scenes and Prefabs

Source Code files

You can download the tutorial source code files here.

Creating the tiled maps

The first thing we need to do is creating the tilemaps for the dungeon rooms. Then, we can just load those tilempas later after generating the dungeon.

Unity provides tilemap generation features, so we are going to use them. First, download the sprites for this tutorial and we are going to configure the “terrains” sprite to be used for tilemaps. You need to do two things: (1) setting the Pixels Per Unit to 40 to make sure the tiles will appear in the right size; (2) changing the Sprite Mode to Multiple, and then slicing it to be separated into individual tiles.

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Now, right click on the Object Hierarchy tab, and select 2D object -> Tilemap. You also need to open the Tile Palette window (Window -> 2D -> Tile Palette). We need to create a new tile palette with the “terrains” tileset Unity will ask where you wish to save the palette, I suggest saving it in a separate folder called Tile Palettes. After creating the tile palette, drag and drop the tileset to the Tile Palette window.

Image may be NSFW.
Clik here to view.

Now, we can start creating our room tilemap using this tile palette. Select the brush tool and paint the tilemap with the tiles you wish. In the end, you should have something like this:

Image may be NSFW.
Clik here to view.

The next step is making the walls in the room collidable, while the floor tiles are not. In order to do so, select the Tilemap object and add a Tilemap Collider 2D. However, this will make all tiles collidable. To make the floor tiles not collidable, select the floor tile in the Tile Palettes folder and change the Collider Type to None.

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Player and door prefabs

We created the room for our dungeon, but we still need a player to move in the dungeon, and door to navigate through rooms.

Let’s start by creating the Player. First, select the “player” sprite in the Sprites folder, change the Pixels Per Unit to 30, the Sprite Mode to multiple and slice the prefab. Then, create a new GameObject called player from this sprite, and add a Box Collider 2D and a Rigidbody 2D to this object. Notice that we need to do some changes in the components. First, we don’t want the player to rotate when colliding with things, so we check the Freeze Rotation box of Rigidbody 2D. Also, we need to reduce the size of the collider a little bit, so that the Player can walk through the doors. We do so by changing the size of the Box Collider 2D. You also need to create a Tag called “Player”, and assign it to this object.

Image may be NSFW.
Clik here to view.

Also, since this is a top-view game, we don’t want any gravity force. We can disable gravity in Edit -> Project Settings -> Physics2D and changing the gravity in the Y axis to 0.

Image may be NSFW.
Clik here to view.

Now, create a new script called PlayerMovement and add it to the Player object. This script will be very simple as the only thing we need is being able to move the Player. So, it needs a speed attribute as a SerializeField and we implement the FixedUpdate method to move the player. In order to do so, it gets the values of the Horizontal and Vertical input and update the velocity accordingly.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

	[SerializeField]
	private float speed;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		float horizontal = Input.GetAxis ("Horizontal");
		float vertical = Input.GetAxis ("Vertical");

		GetComponent<Rigidbody2D> ().velocity = new Vector2 (horizontal * speed, vertical * speed);
	}
}

Now that we have the Player object, let’s create the Door prefab as well. So, create a new GameObject called Door. This object will not have a sprite, it will only be an invisible collidable sprite. In order to do so, you need to add a Box Collider 2D and a Rigidbody 2D to the Door. For the Rigidbody 2D, you need to set the Body Type to static. This will make sure the Door will be immovable while still colliding with the Player.

Image may be NSFW.
Clik here to view.

After creating the Door object, let’s create a new script called EnterDoor and add it to the Door object. For now, when the Player touches the door we are only going to restart the game. Later on, we are going to use it to navigate through the Dungeon rooms. Either way, the collision between the Door and Player will be detected by implementing the OnCollisionEnter2D method. In this method, we are going to check if the collision was with the Player. If so, we start the Demo Scene again. Notice that you need to add the SceneManagement namespace to restart the Scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class EnterDoor : MonoBehaviour {

	void OnCollisionEnter2D(Collision2D col) {
		if (col.gameObject.tag == "Player") {
			SceneManager.LoadScene ("Demo");
		}
	}
}

Now, to test it, save the Scene as Demo and you can try playing the game. By now, you should be able to move the player and restart the game when touching the Door.

The dungeon generation algorithm

Now that we have the basic objects to our game (Player and Door), let’s implement the dungeon generation algorithm. In order to do so, strat by creating an empty object called Dungeon and attach a script called DungeonGeneration to it.

The algorithm to generate the dungeon room is as follows:

  1. Create a empty grid where the rooms will be saved.
  2. Create an initial room and save it in a rooms_to_create list.
  3. While the number of rooms is less than a desired number “n”, repeat:
    1. Pick the first room in the rooms_to_create list
    2. Add the room to the grid in the correspondent location
    3. Create a random number of neighbors and add them to rooms_to_create
  4. Connect the neighbor rooms.

This algorithm is implemented in the GenerateDungeon method below. Notice that the first room coordinate is generated in the middle of the grid. Also, the dungeon grid is initialized with three times the number of rooms on each axis. This way, we can make sure that all rooms fit into the grid. Then, the first loop creates the rooms using the steps described above. All the created rooms are stored in a list called “createdRooms”. When all the rooms have been created, it iterates through this list connecting the neighbor rooms. This is done, by iterating through the neighbor coordinates of each room and checking if there is a room in the grid for this coordinate. If so, the algorithm connects both rooms. In the end, we guarantee the desired number of rooms in the dungeon, and we ensure that all rooms are connected, since they are always connected as neighbors of a previous room.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class DungeonGeneration : MonoBehaviour {

	[SerializeField]
	private int numberOfRooms;

	private Room[,] rooms;

	void Start () {
		this.currentRoom = GenerateDungeon ();
	}

	private Room GenerateDungeon() {
		int gridSize = 3 * numberOfRooms;

		rooms = new Room[gridSize, gridSize];

		Vector2Int initialRoomCoordinate = new Vector2Int ((gridSize / 2) - 1, (gridSize / 2) - 1);

		Queue<Room> roomsToCreate = new Queue<Room> ();
		roomsToCreate.Enqueue (new Room(initialRoomCoordinate.x, initialRoomCoordinate.y));
		List<Room> createdRooms = new List<Room> ();
		while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
			Room currentRoom = roomsToCreate.Dequeue ();
			this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
			createdRooms.Add (currentRoom);
			AddNeighbors (currentRoom, roomsToCreate);
		}
			
		foreach (Room room in createdRooms) {
			List<Vector2Int> neighborCoordinates = room.NeighborCoordinates ();
			foreach (Vector2Int coordinate in neighborCoordinates) {
				Room neighbor = this.rooms [coordinate.x, coordinate.y];
				if (neighbor != null) {
					room.Connect (neighbor);
				}
			}
		}

		return this.rooms [initialRoomCoordinate.x, initialRoomCoordinate.y];
	}
		
}

You may have noticed we are using a Room class to create the dungeon grid. Also, we add the neighbors of a room to the “rooms_to_create” list using a method called AddNeighbors, so we need to implement it. This method starts by checking what neighbor coordinates are actually available to be selected as having rooms. A coordinate is available only if there is not any other room occupying its place. After finding the available coordinates, a random number of them is selected to be added to “rooms_to_create”. For each room to be created, one of the neighbors is selected randomly.

private void AddNeighbors(Room currentRoom, Queue<Room> roomsToCreate) {
		List<Vector2Int> neighborCoordinates = currentRoom.NeighborCoordinates ();
		List<Vector2Int> availableNeighbors = new List<Vector2Int> ();
		foreach (Vector2Int coordinate in neighborCoordinates) {
			if (this.rooms[coordinate.x, coordinate.y] == null) {
				availableNeighbors.Add (coordinate);
			}
		}
			
		int numberOfNeighbors = (int)Random.Range (1, availableNeighbors.Count);

		for (int neighborIndex = 0; neighborIndex < numberOfNeighbors; neighborIndex++) {
			float randomNumber = Random.value;
			float roomFrac = 1f / (float)availableNeighbors.Count;
			Vector2Int chosenNeighbor = new Vector2Int(0, 0);
			foreach (Vector2Int coordinate in availableNeighbors) {
				if (randomNumber < roomFrac) {
					chosenNeighbor = coordinate;
					break;
				} else {
					roomFrac += 1f / (float)availableNeighbors.Count;
				}
			}
			roomsToCreate.Enqueue (new Room(chosenNeighbor));
			availableNeighbors.Remove (chosenNeighbor);
		}
	}

Now let’s create the Room class. Notice that this is not a MonoBehaviour, but simply a regular class. So, we need to create its constructor and the methods used in the DungeonGeneration script (NeighborCoordinates and Connect).

First, the constructor is simple, it only needs to initialize the room coordinate and a dictionary with neighbors information. We are going to use a dictionary instead of a list, because we want to associate each neighbor to its direction as well.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class Room
{
	public Vector2Int roomCoordinate;
	public Dictionary<string, Room> neighbors;

	public Room (int xCoordinate, int yCoordinate)
	{
		this.roomCoordinate = new Vector2Int (xCoordinate, yCoordinate);
		this.neighbors = new Dictionary<string, Room> ();
	}

	public Room (Vector2Int roomCoordinate)
	{
		this.roomCoordinate = roomCoordinate;
		this.neighbors = new Dictionary<string, Room> ();
	}

The NeighborCoordinates method will return the coordinates of all neighbors of the current room. Each room has a neighbor in each one of the four directions: North, East, South and West. This order is important, since it will be necessary to instantiate the Rooms in the game later.

public List<Vector2Int> NeighborCoordinates () {
		List<Vector2Int> neighborCoordinates = new List<Vector2Int> ();
		neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x, this.roomCoordinate.y - 1));
		neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x + 1, this.roomCoordinate.y));
		neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x, this.roomCoordinate.y + 1));
		neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x - 1, this.roomCoordinate.y));

		return neighborCoordinates;
	}

Finally, the Connect method will check what is the direction of the room and add it alongside its direction in the neighbors dictionary.

public void Connect (Room neighbor) {
		string direction = "";
		if (neighbor.roomCoordinate.y < this.roomCoordinate.y) {
			direction = "N";
		}
		if (neighbor.roomCoordinate.x > this.roomCoordinate.x) {
			direction = "E";
		}   
		if (neighbor.roomCoordinate.y > this.roomCoordinate.y) {
			direction = "S";
		}
		if (neighbor.roomCoordinate.x < this.roomCoordinate.x) {
			direction = "W";
		}
		this.neighbors.Add (direction, neighbor);
	}

In order to test if the dungeon is being generated correctly, we are going to implement a PrintGrid method that will show the room grid as a string.

private void PrintGrid() {
		for (int rowIndex = 0; rowIndex < this.rooms.GetLength (1); rowIndex++) {
			string row = "";
			for (int columnIndex = 0; columnIndex < this.rooms.GetLength (0); columnIndex++) {
				if (this.rooms [columnIndex, rowIndex] == null) {
					row += "X";
				} else {
					row += "R";
				}
			}
			Debug.Log (row);
		}
	}

Now, back to the DungeonGeneration script, we call the GenerateDungeon method in its Start method. After creating the dungeon we print it for testing.

void Start () {
		GenerateDungeon ();
		PrintGrid ();
	}

By now, you can try running the game with a given number of parameters and checking if it is working correctly.

Image may be NSFW.
Clik here to view.

Navigating through rooms

Now that we are generating the dungeon grid, we need to actually instantiate the room tilemaps in the game. First, we need to create tilemaps for all the possible rooms. Let’s start by saving the room we already have in a folder called Resources. It is very important that it is in the Resources folder, since we need that to instantiate the rooms in runtime.

Now we need to do the same for all rooms. For this, I recommend you download the tutorial source code and copy the rooms from the Resources folder, because it may take some time to make all of them. You need a room for each possible neighborhood configuration, so there are a total of 15 possible rooms. The room names should follow the pattern “Room_NESW”, where “NESW” represents the neighbors of this room (North, East, South, West).

Image may be NSFW.
Clik here to view.

This way, we can add a method in the Room class called PrefabName which returns the name of the Room Prefab of the current room. Notice that, since the NeighborCoordinates method returns the neighbors in the correct order, the name returned by PrefabName matches the name of the prefab we want to instantiate.

public string PrefabName () {
		string name = "Room_";
		foreach (KeyValuePair<string, Room> neighborPair in neighbors) {
			name += neighborPair.Key;
		}
		return name;
	}

Finally, we update the Start method of DungeonGeneration to instantiate this room prefab. After generating the dungeon, it returns the initial room. Then, it loads the prefab from the Resources folder and instantiates the prefab.

void Start () {
		this.currentRoom = GenerateDungeon ();
		string roomPrefabName = this.currentRoom.PrefabName ();
		GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
	}

By now, you can try playing the game again and checking if it is instantiating the correct room. Try playing the game multiple times to see if the initial room is changing.

Image may be NSFW.
Clik here to view.

Now that we can instantiate a Room Prefab from its name, we can make the doors navigate through rooms. We are going to do that by restarting the Demo Scene with another room as the current one. However, we don’t want the dungeon to be generated again. So, we need to make the Dungeon object a persistent one. This way, we can make sure we have always the same dungeon.

We do that in the Awake method by calling DontDestroyOnLoad. This way, the Dungeon object will not be destroyed when we restart the scene. However, Unity will still create a new Dungeon object every time the scene is started. So, we are going to save the first DungeonGeneration instance in a static attribute. This will be set in the Awake method for the first time it is called. We are also going to generate the dungeon in this method. If the instance has already been set, we are only going to instantiate the current room prefab and we are going to delete the newly created Dungeon object.

void Awake () {
		if (instance == null) {
			DontDestroyOnLoad (this.gameObject);
			instance = this;
			this.currentRoom = GenerateDungeon ();
		} else {
			string roomPrefabName = instance.currentRoom.PrefabName ();
			GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
			Destroy (this.gameObject);
		}
	}

	void Start () {
		string roomPrefabName = this.currentRoom.PrefabName ();
		GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
	}

Now, let’s update the EnterDoor script to restart the demo scene with a new current room. For that, we need to save the direction of the door in the script. Then, in the OnCollisionEnter2D method, we get the next room from acessing the neighbors dictionary for the desired direction in the current room. After identifying the next room, we change the current room in the dungeon and restart the demo scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class EnterDoor : MonoBehaviour {

	[SerializeField]
	string direction;

	void OnCollisionEnter2D(Collision2D col) {
		if (col.gameObject.tag == "Player") {
			GameObject dungeon = GameObject.FindGameObjectWithTag ("Dungeon");
			DungeonGeneration dungeonGeneration = dungeon.GetComponent<DungeonGeneration> ();
			Room room = dungeonGeneration.CurrentRoom ();
			dungeonGeneration.MoveToRoom (room.Neighbor (this.direction));
			SceneManager.LoadScene ("Demo");
		}
	}
}

We still need to implement the CurrentRoom and MoveToRoom methods in the DungeonGeneration script, as well as the neighbor getter in the Room object.

public void MoveToRoom(Room room) {
		this.currentRoom = room;
	}

	public Room CurrentRoom() {
		return this.currentRoom;
	}

public Room Neighbor (string direction) {
		return this.neighbors [direction];
	}

Finally, set the direction values of the doors for all rooms. Then, you can try running your game again. By now, you should be able to move between rooms.

Adding obstacles

It’s time to add other elements in our dungeon, starting with the obstacles. The obstacles will be tiles we are going to set in some specific parts of the room. For each room, the number of obstacles and their positions will be randomly chosen.

Let’s start by writing a PopulateObstacles method in the Room class. This method will receive as parameters the number of obstacles and the possible obstacle sizes. Notice that the sizes are a Vector2int, which specifies the dimensions in X and Y coordinates.

For each obstacle to be created, this method chooses a random size among the possible ones and look for a free region on the room with this size. In order to keep track of what coordinates are free in the room, we are going to use a string matrix called population. After choosing the region of the obstacle, we update the population matrix.

private string[,] population;

	public Room (int xCoordinate, int yCoordinate)
	{
		this.roomCoordinate = new Vector2Int (xCoordinate, yCoordinate);
		this.neighbors = new Dictionary<string, Room> ();
		this.population = new string[18, 10];
		for (int xIndex = 0; xIndex < 18; xIndex += 1) {
			for (int yIndex = 0; yIndex < 10; yIndex += 1) {
				this.population [xIndex, yIndex] = "";
			}
		}
		this.population [8, 5] = "Player";
	}

	public Room (Vector2Int roomCoordinate)
	{
		this.roomCoordinate = roomCoordinate;
		this.neighbors = new Dictionary<string, Room> ();
		this.population = new string[18, 10];
		for (int xIndex = 0; xIndex < 18; xIndex += 1) {
			for (int yIndex = 0; yIndex < 10; yIndex += 1) {
				this.population [xIndex, yIndex] = "";
			}
		}
		this.population [8, 5] = "Player";
	}

public void PopulateObstacles (int numberOfObstacles, Vector2Int[] possibleSizes) {
		for (int obstacleIndex = 0; obstacleIndex < numberOfObstacles; obstacleIndex += 1) {
			int sizeIndex = Random.Range (0, possibleSizes.Length);
			Vector2Int regionSize = possibleSizes [sizeIndex];
			List<Vector2Int> region = FindFreeRegion (regionSize);
			foreach (Vector2Int coordinate in region) {
				this.population [coordinate.x, coordinate.y] = "Obstacle";
			}
		}
	}

Now we need to implement the FindFreeRegion method. Basically, this method consists on a loop that looks for random regions until it finds one that is available. In each iteration of the loop, it generates a random center tile between tiles 2 and 15 in the x coordinate and between tiles 2 and 7 in the y coordinate. We are using those coordinates so that the obstacles are not above the walls of our room. After doing that, it calculates the coordinates of the rest of the obstacle, based on its size. Finally, it checks if the region is free in the while loop. If it is not, it iterates again to find another region, until finding a free one.

private List<Vector2Int> FindFreeRegion (Vector2Int sizeInTiles) {
		List<Vector2Int> region = new List<Vector2Int>();
		do {
			region.Clear();

			Vector2Int centerTile = new Vector2Int(UnityEngine.Random.Range(2, 18 - 3), UnityEngine.Random.Range(2, 10 - 3));

			region.Add(centerTile);

			int initialXCoordinate = (centerTile.x - (int)Mathf.Floor(sizeInTiles.x / 2));
			int initialYCoordinate = (centerTile.y - (int)Mathf.Floor(sizeInTiles.y / 2));
			for (int xCoordinate = initialXCoordinate; xCoordinate < initialXCoordinate + sizeInTiles.x; xCoordinate += 1) {
				for (int yCoordinate = initialYCoordinate; yCoordinate < initialYCoordinate + sizeInTiles.y; yCoordinate += 1) {
					region.Add(new Vector2Int(xCoordinate, yCoordinate));
				}
			}
		} while(!IsFree (region));
		return region;
	}

The IsFree method, by its turn, simply iterates through all coordinates of the region and checks if the population matrix is free for all of them.

private bool IsFree (List<Vector2Int> region) {
		foreach (Vector2Int tile in region) {
			if (this.population [tile.x, tile.y] != "") {
				return false;
			}
		}
		return true;
	}

Now, we need to properly call the PopulateObstacles method for each room. We are going to do that after connecting the rooms. Also, after instantiating the room prefab, we need to actually add the obstacle tiles in the tilemap. So, we update the Awake and Start methods accordingly.

[SerializeField]
	private TileBase obstacleTile;

void Awake () {
		if (instance == null) {
			DontDestroyOnLoad (this.gameObject);
			instance = this;
			this.currentRoom = GenerateDungeon ();
		} else {
			string roomPrefabName = instance.currentRoom.PrefabName ();
			GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
			Tilemap tilemap = roomObject.GetComponentInChildren<Tilemap> ();
			instance.currentRoom.AddPopulationToTilemap (tilemap, instance.obstacleTile);
			Destroy (this.gameObject);
		}
	}

	void Start () {
		string roomPrefabName = this.currentRoom.PrefabName ();
		GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
		Tilemap tilemap = roomObject.GetComponentInChildren<Tilemap> ();
		this.currentRoom.AddPopulationToTilemap (tilemap, this.obstacleTile);
	}

We still need to implement the AddPopulationToTilemap method. This method will iterate through all the coordinates in the population matrix and check if it is an obstacle. If so, we set the tile on that coordinate to be an obstacle. Notice that we need to set the tile on coordinate (xIndex – 9, yIndex – 5). That’s because in our population matrix, the (0, 0) index is the lower left corner, while in the tilemap, (0, 0) is actually the center of the map.

public void AddPopulationToTilemap (Tilemap tilemap, TileBase obstacleTile) {
		for (int xIndex = 0; xIndex < 18; xIndex += 1) {
			for (int yIndex = 0; yIndex < 10; yIndex += 1) {
				if (this.population [xIndex, yIndex] == "Obstacle") {
					tilemap.SetTile (new Vector3Int (xIndex - 9, yIndex - 5, 0), obstacleTile);
				} 
			}
		}
	}

Now, update the Dungeon object to set the values for the new attributes, such as the possible obstacle sizes and the obstacle tile. Then, you can try playing the game to see if it is correctly creating the obstacles.

Image may be NSFW.
Clik here to view.

Adding enemies

Adding enemies will be very similar to adding obstacles, except the enemies will be prefabs instead of tiles, and their size will be always of one tile.

Let’s start by adding a PopulatePrefabs method, which will add the enemies to the game given their prefabs. This method will iterate through the number of desired prefabs and, for each one, it will pick a random prefab among the possible ones, find a free region of size one and add it to the population matrix. In the population matrix we are going to use the prefab name to identify it. Later we are going to need to instantiate the prefab from its name. So, we are going to use a dictionary (initialized in the constructor) called name2Prefab. This dictionary will be indexed by the prefab name and it will return its Prefab.

private Dictionary<string, GameObject> name2Prefab;

public Room (int xCoordinate, int yCoordinate)
	{
		this.roomCoordinate = new Vector2Int (xCoordinate, yCoordinate);
		this.neighbors = new Dictionary<string, Room> ();
		this.population = new string[18, 10];
		for (int xIndex = 0; xIndex < 18; xIndex += 1) {
			for (int yIndex = 0; yIndex < 10; yIndex += 1) {
				this.population [xIndex, yIndex] = "";
			}
		}
		this.population [8, 5] = "Player";
		this.name2Prefab = new Dictionary<string, GameObject> ();
	}

	public Room (Vector2Int roomCoordinate)
	{
		this.roomCoordinate = roomCoordinate;
		this.neighbors = new Dictionary<string, Room> ();
		this.population = new string[18, 10];
		for (int xIndex = 0; xIndex < 18; xIndex += 1) {
			for (int yIndex = 0; yIndex < 10; yIndex += 1) {
				this.population [xIndex, yIndex] = "";
			}
		}
		this.population [8, 5] = "Player";
		this.name2Prefab = new Dictionary<string, GameObject> ();
	}

public void PopulatePrefabs (int numberOfPrefabs, GameObject[] possiblePrefabs) {
		for (int prefabIndex = 0; prefabIndex < numberOfPrefabs; prefabIndex += 1) {
			int choiceIndex = Random.Range (0, possiblePrefabs.Length);
			GameObject prefab = possiblePrefabs [choiceIndex];
			List<Vector2Int> region = FindFreeRegion (new Vector2Int(1, 1));

			this.population [region[0].x, region[0].y] = prefab.name;
			this.name2Prefab [prefab.name] = prefab;
		}
	}

This way, we can update the AddPopulationToTilemap to add the prefabs in the map as well. When the coordinate is not an obstacle, but it is also not empty and it is not the player, that means we need to instantiate a prefab for it. We instantiate the prefab by acessing the name2Prefab dictionary.

public void AddPopulationToTilemap (Tilemap tilemap, TileBase obstacleTile) {
		for (int xIndex = 0; xIndex < 18; xIndex += 1) {
			for (int yIndex = 0; yIndex < 10; yIndex += 1) {
				if (this.population [xIndex, yIndex] == "Obstacle") {
					tilemap.SetTile (new Vector3Int (xIndex - 9, yIndex - 5, 0), obstacleTile);
				} else if (this.population [xIndex, yIndex] != "" && this.population [xIndex, yIndex] != "Player") {
					GameObject prefab = GameObject.Instantiate (this.name2Prefab[this.population [xIndex, yIndex]]);
					prefab.transform.position = new Vector2 (xIndex - 9 + 0.5f, yIndex - 5 + 0.5f);
				}
			}
		}
	}

Then, we can call the PopulatePrefabs method from GenerateDungeon, right after adding the obstacles.

[SerializeField]
	private int numberOfEnemies;
	[SerializeField]
	private GameObject[] possibleEnemies;

private Room GenerateDungeon() {
		int gridSize = 3 * numberOfRooms;

		rooms = new Room[gridSize, gridSize];

		Vector2Int initialRoomCoordinate = new Vector2Int ((gridSize / 2) - 1, (gridSize / 2) - 1);

		Queue<Room> roomsToCreate = new Queue<Room> ();
		roomsToCreate.Enqueue (new Room(initialRoomCoordinate.x, initialRoomCoordinate.y));
		List<Room> createdRooms = new List<Room> ();
		while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
			Room currentRoom = roomsToCreate.Dequeue ();
			this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
			createdRooms.Add (currentRoom);
			AddNeighbors (currentRoom, roomsToCreate);
		}
			
		foreach (Room room in createdRooms) {
			List<Vector2Int> neighborCoordinates = room.NeighborCoordinates ();
			foreach (Vector2Int coordinate in neighborCoordinates) {
				Room neighbor = this.rooms [coordinate.x, coordinate.y];
				if (neighbor != null) {
					room.Connect (neighbor);
				}
			}

			room.PopulateObstacles (this.numberOfObstacles, this.possibleObstacleSizes);
			room.PopulatePrefabs (this.numberOfEnemies, this.possibleEnemies);
		}

		return this.rooms [initialRoomCoordinate.x, initialRoomCoordinate.y];
	}

We still need to create the enemy prefab, in order to set the possible enemies in the DungeonGeneration script. First, we need to change the Enemy sprite Pixels Per Unit to 40, so that it is not too big in our map. Now, create a new GameObject from the Enemy sprite, and add a BoxCollider2D to it (you need to set the collider as a trigger). Finally, set the Enemy tag to be “Enemy” and save it as a Prefab.

Image may be NSFW.
Clik here to view.

Now, you can update the Dungeon object to add the number of enemies and enemy prefabs to the DungeonGeneration script. Then, you can try playing the game to check if the enemies are being created.

Image may be NSFW.
Clik here to view.

Adding the goal

We have enemies, but we still need a way to clear our game. What we are going to do in this demo is adding a Goal object, which will always be in the furthest room from the start, and must be found by the player. When the player touches the Goal, they should finish the game.

Let’s start by creating the Goal prefab. We are going to use the Portal sprite for that. So, change the Pixels Per Unit of this sprite to 30, and create a new GameObject from it. As we did with the enemies, we need to add a BoxCollider2D to this object, and set it as a trigger. Finally, save it as a Prefab.

Image may be NSFW.
Clik here to view.

Now, let’s change the DungeonGeneration script to create the Goal inside the furthest room. First, we need to find the furthest room. We do that when iterating through the createdRooms to populate them. For each room, we calculate its distance to the initial one, and save which is the final room. Then, outside this loop, we call PopulatePrefabs again for the final room, but now we are using the Goal prefab instead of the Enemy one, and we only need one Goal object inside the room.

[SerializeField]
	private GameObject goalPrefab;

private Room GenerateDungeon() {
		int gridSize = 3 * numberOfRooms;

		rooms = new Room[gridSize, gridSize];

		Vector2Int initialRoomCoordinate = new Vector2Int ((gridSize / 2) - 1, (gridSize / 2) - 1);

		Queue<Room> roomsToCreate = new Queue<Room> ();
		roomsToCreate.Enqueue (new Room(initialRoomCoordinate.x, initialRoomCoordinate.y));
		List<Room> createdRooms = new List<Room> ();
		while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
			Room currentRoom = roomsToCreate.Dequeue ();
			this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
			createdRooms.Add (currentRoom);
			AddNeighbors (currentRoom, roomsToCreate);
		}

		int maximumDistanceToInitialRoom = 0;
		Room finalRoom = null;
		foreach (Room room in createdRooms) {
			List<Vector2Int> neighborCoordinates = room.NeighborCoordinates ();
			foreach (Vector2Int coordinate in neighborCoordinates) {
				Room neighbor = this.rooms [coordinate.x, coordinate.y];
				if (neighbor != null) {
					room.Connect (neighbor);
				}
			}
			room.PopulateObstacles (this.numberOfObstacles, this.possibleObstacleSizes);
			room.PopulatePrefabs (this.numberOfEnemies, this.possibleEnemies);

			int distanceToInitialRoom = Mathf.Abs (room.roomCoordinate.x - initialRoomCoordinate.x) + Mathf.Abs(room.roomCoordinate.y - initialRoomCoordinate.y);
			if (distanceToInitialRoom > maximumDistanceToInitialRoom) {
				maximumDistanceToInitialRoom = distanceToInitialRoom;
				finalRoom = room;
			}
		}

		GameObject[] goalPrefabs = { this.goalPrefab };
		finalRoom.PopulatePrefabs(1, goalPrefabs);

		return this.rooms [initialRoomCoordinate.x, initialRoomCoordinate.y];
	}

Now, let’s add a new script to the Goal prefab called ReachGoal. In this script, we are only going to implement the OnTriggerEnter2D method and, when the player collides with the goal, we are going to call a method called ResetDungeon inside DungeonGeneration, besides restarting the Demo scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ReachGoal : MonoBehaviour {

	void OnTriggerEnter2D(Collider2D col) {
		if (col.gameObject.tag == "Player") {
			GameObject dungeon = GameObject.FindGameObjectWithTag ("Dungeon");
			DungeonGeneration dungeonGeneration = dungeon.GetComponent<DungeonGeneration> ();
			dungeonGeneration.ResetDungeon ();
			SceneManager.LoadScene ("Demo");
		}
	}
}

Finally, the ResetDungeon method will simply generate the dungeon again.

public void ResetDungeon() {
		this.currentRoom = GenerateDungeon ();
	}

Now, set the Goal prefab value in the DungeonGeneration script and try playing the game again. By now, you should be able to find the Goal in the dungeon and restart the Demo.

Image may be NSFW.
Clik here to view.

Finishing the demo

The last thing we are going to do is allowing the player to leave a room or the dungeon only when all enemies in that room have been defeated. This is actually very simple to do, but first we need a way to defeat the enemies.

So, let’s add a new script called KillEnemy to the Enemy prefab. In this script we implement the OnTriggerEnter2D method. Since this is just a demo, the enemy will be automatically destroyed when the Player touches it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KillEnemy : MonoBehaviour {

	void OnTriggerEnter2D(Collider2D col) {
		if (col.gameObject.tag == "Player") {
			Destroy (this.gameObject);
		}
	}
}

Now, we need to update the EnterDoor and ReachGoal scripts to check the number of remaining enemies before leaving the room or the dunteon. Let’s start by the EnterDoor script. Inside the OnCollisionEnter2D method we are going to find the objects with the “Enemy” tag. This will return an array of GameObjects, and if this array length is 0, this means that all enemies have been defeated. If so, we execute the code we already had. Otherwise, we do nothing.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class EnterDoor : MonoBehaviour {

	[SerializeField]
	string direction;

	void OnCollisionEnter2D(Collision2D col) {
		if (col.gameObject.tag == "Player") {
			GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
			if (enemies.Length == 0) {
				GameObject dungeon = GameObject.FindGameObjectWithTag ("Dungeon");
				DungeonGeneration dungeonGeneration = dungeon.GetComponent<DungeonGeneration> ();
				Room room = dungeonGeneration.CurrentRoom ();
				dungeonGeneration.MoveToRoom (room.Neighbor (this.direction));
				SceneManager.LoadScene ("Demo");
			}
		}
	}
}

Then we do the same checking inside the ReachGoal script, which means we only restart the dungeon if there are no enemies left inside this room.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ReachGoal : MonoBehaviour {

	void OnTriggerEnter2D(Collider2D col) {
		if (col.gameObject.tag == "Player") {
			GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Enemy");
			if (enemies.Length == 0) {
				GameObject dungeon = GameObject.FindGameObjectWithTag ("Dungeon");
				DungeonGeneration dungeonGeneration = dungeon.GetComponent<DungeonGeneration> ();
				dungeonGeneration.ResetDungeon ();
				SceneManager.LoadScene ("Demo");
			}
		}
	}
}

Now try playing the game again, and you should only be able to leave a room or restart the dungeon once you have killed all the enemies in that room.

Image may be NSFW.
Clik here to view.

And that concludes this tutorial on Procedural Dungeon Generation using Unity. I hope you enjoyed this tutorial, and if you have any questions, please let me know in the comments section.

How to Create a Hyper Casual Game for Android in Unity- Part 2

Obstacle setup, Scoring setup using TextMeshPro, and Game Manager implementation

This is Part 2 of a three part tutorial series on how to create a Hyper Casual game. Please make sure you have followed Part 1 of the tutorial and completed it before starting this part. The link to the previous tutorial is here.

Source Code Files

You can download the tutorial source code files here. All the project files are located in the main folder. The asset folder contains additional intermediate files that were used during the process of creating the game sprites.

This part of the tutorial was made in Unity version 2018.2.13f1, which was the same version used in the previous tutorial.

Add a Prefab Folder to the Project

We need to create a new folder in the project and name it “Prefabs.” We will be adding game objects to this folder that we will be instantiating later on in the tutorial.

Obstacle Creation

Begin by creating the first obstacle. This obstacle is going to be a square. Go ahead and create an empty GameObject, and reset the transform component after creation. Rename this GameObject to “SquareObstacle.” We must now create the square sprite we will use for an obstacle for the player to avoid during play. Right click in the Sprites folder and Choose: Create>Sprites>Square.

Image may be NSFW.
Clik here to view.

Make the Square a child of the “SquareObstacle.” Add a 2D box Collider component to the square. Set the Is Trigger checkbox to true on the square.

Image may be NSFW.
Clik here to view.

Create a new tag called “Obstacle” and tag the Square as “Obstacle.”

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

Next up is adding the On trigger function to the player script so that we can detect when the player collides with this square obstacle. Go ahead and open up the Player script, we are going to add the OnTriggerEnter2D function to the Player script for the collision detection. You can add this function under the PlayerInput() function already in the script. We are going to set up a Debug statement as well inside this function so that we can test out the collision detection and make sure the player is indeed entering the trigger of the Square obstacle. It’s common practice to make your debug statements make sense so that when you are testing your projects out and debugging multiple aspects of a project you can easily tell what is exactly going on, this also helps others working on your project too, if you so happen to be working on a project with multiple team members. So for this Debug statement we are going to simply put “I have collided with the Square.”

private void OnTriggerEnter2D(Collider2D other)
    {
      Debug.Log("I have collided with the square!");
        
    }

Once you add this function and debug statement, make sure to save the script and you can go back into the Unity Editor and hit the Play button to test this out. If you see that the Debug statement is firing in the Console then our function is working and collision detection is also working properly.

Game Manager Creation and Setup

Create another empty GameObject and add it to the scene, reset the transform component and name it “Game Manager.” Create and add a new script called “GameManager” to the Game Manager object, move this script into the Scripts folder in the project so we keep our project organized. Open the Player script up, we need to get reference to our GameManager script in the Player script. Create a GameManager variable and name it gameManagerObject. Get reference to the object inside the Awake function, save the script.

GameManager gameManagerObject;

  void Awake()
    {
        PlayerRigi = GetComponent<Rigidbody2D>();
        gameManagerObject = GameObject.Find("Game Manager").GetComponent<GameManager>();
    }

Open the GameManager script and we need to create a public “GameOver” function in this script. This function needs to be public so that we can access it from other scripts. Add a Debug statement to this function and put “Game Over!” Save the script.

public void GameOver()
    {
        Debug.Log("Game Over!");
    }

Create a private PlayerDeath function in the Player script. Call the GameOver function in the PlayerDeath function. We will then be calling the PlayerDeath function inside the OnTriggerEnter2D function; essentially what will be happening is that whenever our Player GameObject collides with an obstacle this will cause the GameOver function to fire.

private void OnTriggerEnter2D(Collider2D other)
    {
        PlayerDeath();
        
    }

void PlayerDeath()
    {
       
        gameManagerObject.GameOver();
    }

You may also now remove the Debug statement “I have collided with the Square” from the OnTriggerEnter2D function if you like: This will free up messages in the console, so that it doesn’t get too crowded when we are testing further debug statements, and since we know the collision detection is working and we added the “Game Over!” Debug statement to the Game Over function it’s unnecessary to keep it.

Save the script and test out the script changes in the Unity Editor by hitting Play in the Unity Editor; make sure the Debug statement in the GameOver function is firing in the console.

Image may be NSFW.
Clik here to view.

Adjust the scale of the Square obstacle Game Object by increasing the X and Y values to 3. Save the scene and project.

Image may be NSFW.
Clik here to view.

Player Death Effect Creation and Implementation

Create an Empty GameObject rename it to “PlayerDeathEffect.” Reset the transform component in the inspector. Click on the PlayerDeathEffect object in the Hierarchy and add a particle system to it.

Image may be NSFW.
Clik here to view.

The Particle System should now be a child of the PlayerDeathEffect game object. Now we need to adjust some aspects of the newly created particle system on the PlayerDeathEffect game object. Change the Material on the Renderer component to Sprites Default.

Image may be NSFW.
Clik here to view.

Now on the Shape component of the Particle System we will change it to Circle. Change Radius to 0.0001 and the Radius Thickness to 0.

Image may be NSFW.
Clik here to view.

Change the Start Size to 0.1. Change the Start Lifetime to 1. Change the Start Speed to Random Between Two Constants, and make these values 0 and 50.

Now check the Size Over Lifetime box on the Particle System. Click on the Open Editor button on the Particle System component in the Inspector window. You will see another window popup:

Image may be NSFW.
Clik here to view.

Feel free to adjust this window size to whatever makes you comfortable to work within. Now make sure you select the Size portion of the Size Over Lifetime component on the Particle Effect itself.

Image may be NSFW.
Clik here to view.

We are going to select the 7th option at the bottom of the window from the left side.

Image may be NSFW.
Clik here to view.

Check the Limit Velocity over Lifetime and adjust the Dampen to 0.27.

Image may be NSFW.
Clik here to view.

Then adjust the Rate Over Time to 500 under the Emission parameter.

Image may be NSFW.
Clik here to view.

Change the Duration to 0.05 and make sure Looping is not checked on the Particle System component. Set the Start Size to Random Between Two Constants and make the first value 0.01 and the second value 0.1, and change the Start Color to Red.

Image may be NSFW.
Clik here to view.

We need to create a prefab of the PlayerDeathEffect by selecting the game object and dragging and dropping it into the Prefab folder we created at the beginning of this tutorial. Save the Scene and Project.

Image may be NSFW.
Clik here to view.

Instantiation of the PlayerDeathEffect

Open up the Player script, add a Public GameObject variable and name it “deathEffectObject.” We are going to Instantiate the PlayerDeathEffect so that when the Player dies the Particle System we have added plays upon collision on an obstacle during game play, but also visually appears at the point of collision, we can use the Quaternion.idenity parameter to do this. We also need to make sure we Destroy the effect after about 0.5 seconds so that effect is removed from the scene and hierarchy so that it doesn’t hog our resources and slow the game down any. We will be instantiating the PlayerDeathEffect inside the PlayerDeath function in  the Player script.

public GameObject deathEffectObject;

 void PlayerDeath()
    {
        
        Destroy(Instantiate(deathEffectObject, transform.position, Quaternion.identity), 0.5f);
        gameManagerObject.GameOver();
    }

Save the script and go back into the Unity Editor. Here we need to select the Player gameobject in the hierarchy and select the PlayerDeathEffect under the player script where we now have the spot open since we made the variable Public in the script.

Once you have added the PlayerDeathEffect Prefab to the PlayerDeathEffect component of the player script in the Inspector window you can then delete the PlayerDeathEffect game object from the scene since we are now instantiating the Particle System upon collision w/ our square obstacle. Save the scene and the project and hit the Play button, you should now see the particle effect play upon collision with the square obstacle.

Image may be NSFW.
Clik here to view.

Handling Player Death and Stopping the Player Movement

Open the Player script, add a new function called “StopPlayerMovement” this function is going to completely stop the player game object from moving once the function is called. Call this function inside the PlayerDeath function, but we need to make sure the StopPlayerMovement function is called after the Particle Effect is played upon collision, but we also need to execute the StopPlayerMovement function before the GameOver function is called. We can do this by calling the StopPlayerMovement function between the two other functions in the PlayerDeath function.

void PlayerDeath()
    {
        Destroy(Instantiate(deathEffectObject, transform.position, Quaternion.identity), 0.5f);
        StopPlayerMovement();
        gameManagerObject.GameOver();
    }
void StopPlayerMovement()
    {
        PlayerRigi.velocity = new Vector2(0, 0);
        PlayerRigi.isKinematic = true;
    }

What we are doing in the StopPlayerMovement function is setting the velocity of the Player game object to 0, and then we are setting the rigidbody that is attached to our player to kinematic. A kinematic rigidbody is not affected by gravity and forces, like the Dynamic rigidbody, which is what it was originally set to. Essentially these two lines of code in the StopPlayerMovemnt function are giving us complete control over stopping the player from completely moving once it collides with an obstacle.

We now need to create a private bool called “playerIsDead and set the initial value to false. We will be setting this bool to true inside the PlayerDeath function.

bool playerIsDead = false;

void PlayerDeath()
    {
        playerIsDead = true;
        Destroy(Instantiate(deathEffectObject, transform.position, Quaternion.identity), 0.5f);
        StopPlayerMovement();
        gameManagerObject.GameOver();
    }

We also need to create an if statement to check if the bool playerIsDead is equal to true in the FixedUpdate function, and then return.

private void FixedUpdate()
    {
        if (playerIsDead == true) return;
        PlayerInput();
        PlayerMovement();
        
    }

Go ahead and save the script and test the changes inside the Unity Editor. The player game object should come to a complete stop and remain right where it stopped when it collides with the square obstacle.

Image may be NSFW.
Clik here to view.

Font Asset Creator and Displaying the Score to the Player

It’s now time to setup the font we are going to be using with TextMeshPro in the Font Asset creator that now comes with Unity. Inside the Unity Editor click on Window>TextMeshPro>Font Asset Creator.

Image may be NSFW.
Clik here to view.

You should now see this window popup:

Image may be NSFW.
Clik here to view.

In the Font Source parameter click on the radial dial and choose Oswald-Bold. Now click on Generate Font Atlas. This will take a few seconds and you should now see this in the window:

Image may be NSFW.
Clik here to view.

Click Save and make sure this is saved in Assets>TextMeshPro>Examples&Extras>Fonts. You can now close the Font Asset Creator window.

Setting up a UI Canvas and the Game Over Panel

Add a UI Panel to the scene. You will notice once you add this to the scene you will see that we now have a canvas element and then the Panel is a child of that game object and there is now an EventSystem object in the hierarchy.

Rename the Panel object to “GameOverPanel” On the Inspector window look for the Image(Script) component on the GameOverPanel object, and change the Source Image to None. Adjust the color to black and change the Alpha value to 255.

Image may be NSFW.
Clik here to view.

Add a button to the GameOverPanel as a child to that object. Go ahead and delete the text portion on the button object, we won’t need this. Adjust the position of the Button object Y value to -320, and adjust the Height to 105.

Image may be NSFW.
Clik here to view.

Add TextMeshPro Text to the button game object as a child in the hierarchy.

Image may be NSFW.
Clik here to view.

Add the word “Restart” to the text input box field in the inspector window. Change the font size to 40. Make sure the alignment is set to Center and Middle. Change the color to black.

Image may be NSFW.
Clik here to view.

You can rename the button to “RestartButton” now in the hierarchy.

This is now a good place to save the scene and project, and this will conclude the second part of the Hyper Casual Game Creation tutorial.

Web Class: An Overview of Unity and C# Programming Basics

Transcript Part 1

– The transfer component allows you to specify a game objects position, rotation, and scale. We’ve looked at how to position objects. Something that was missing that needed to be mentioned was that the unit of our positioning is called Unity unit, and it’s equivalent to one meter, ^when it comes to physic calculations or virtual reality. So assume for all matters, that one unity unit is one meter. What we’ll do in this lecture is look at rotation, the second, of these transform properties here. So, what I’m gonna do is select my cube and click on the rotation button here. That will activate the rotation gizmo.

Remember that a gizmo is simply a tool widget that appears in your unity later on that you can use to modify different things in your games. So in this case, I see the rotation gizmo here and what I can do is drag any of these lines to produce a rotation about a particular axis. For example, if I want to rotate this cube about the z axis, the blue axis, I, what I’ve done is selected the blue line which turns then yellow when selected and I can rotate my cube in this manner. You can see in the transform component, how the values for that rotation changes. You can do the same thing with your other axis, with x and with y. And what I want to mention is that this rotation here, these values are in Euler angles. Now, what are Euler angles?

Let’s take a look at this concept of angles. An angle can be found by joining two segments by a vertex, like this. The separation of these two segments can be described in degrees, so it is a measurement unit. Where if you have one segment like this and this is vertex that joins it to the other vertex, you can describe all the way to 360 degrees, in this manner. For example, if the other segment is here, that is called 90 degree angle and that is called a right angle. If, for instance, you have, something like this, that is a 180 degrees, that is called straight angle. So these are all useful math concepts, that you need to know when working with unity and transforms. Now how does this actually relate to rotation, because so far what we’re describing, is just simply the separation between two different segments. Well, Leonhard Euler came up with the concept of Euler angles to describe the rotation of object in 3D by giving the rotation in angles of all three axis.

So that you can have a rotation in y, for example, so you could rotate your cube like that. That would be a rotation on y or about y, is the correct way to say it as well. You could have a rotation about x, like this, and a rotation about z like this. And unity provides us exactly with those tools. Now how do you know when the rotation is positive or negative? Because in this case we are sort of going that way but what if we want to go the other way? Well, because of Unity’s left-handed coordinates system. That can be easily determined by using your left hand. So with your left hand, point your thumb towards the direction of the axis, towards the positive direction of the axis, And then simply close your fingers like shown in the figure. That will give you a positive rotation. So if you have, let’s say, some sort of game object, like some sort of car or something and you want to rotate it about this y axis. The positive way of rotating, if you specify rotation in a positive number it will go this way. And if you specify a rotation in a negative number it will go this way. So now, if we go back to Unity, we can easily see this in action. So, I’m gonna reset the rotation here, set it back to zero, and I’m gonna click outside and click on it again.

And you can see for example that the y axis has it’s green rotation handle here, and if I rotate it, in this positive way that I was describing before. Imagine that your thumb points up here in your left hand. See how the numbers is positive, if you on the other hand, rotate it the other way, that is negative. So that is how you can rotate the elements. Something else that I wanted to show you in this lesson, is how we can move our object considering their rotation that was applied to it. Let me explain it in a more clear way. You can see here, we have our cube that doesn’t have any rotation applied to it. It has zero in rotation in x, y, and z. The blue axis, the z axis, as you can see, matches this face of the cube, So, I can move it along that face. But once I rotate my cube, so if I apply a rotation and if I unselect it and want to move it again.

You can see that the blue axis no longer matches that face. Because it still matches the global coordinates. However, if you click here, where it says global it will toggle into local, so it will go from global to local, and what that does. What local does, it allows you to move them with the movement tool. Your game object in the local coordinate system which was modified by the rotations. So we can now then move it along this axis here, or move it this way. Even though that doesn’t match the x and z values of our scene. Now, the best way to really get a good grasp of rotation in the editor, either by moving things around, and also by adjusting numbers here manually, which you can do as well. Is to actually go for a little challenge.

So, I’ve actually prepared a challenge for you, which consists on starting with something like that and putting together, that simple bridge. So that will combine a few of the things we’ve covered, because you’ll be rotating things but you will also be moving things around. I will show you, then, the solution of the challenge. So have a try, and if you are unable to solve it, that’s fine, because we are going to cover it step-by-step. Now, a couple of things. Don’t try to make it exact and precise. As in, the bridge doesn’t need to be in the exact half of this area and also this distance here doesn’t have to be the same as the distance there. When it comes to the platforms, I’ve given them a 45 degree inclination, so that you know, but you can try with a different numbers as well. So have a try and then come back for the solution, but before you do that, actually, a quick tip. If you have multiple game objects in your scene, you can easily select many of them at the same time by pressing ctrl or cmd on a mac and then clicking on them. So you can select many of them and then once you’ve done that you can move them all at once. So, keep that in mind.

Now, have a try at the challenge and come back for the solution. Alright, so you’ve had a try and hopefully you were able to put this together. But if you didn’t that’s fine, at least you had some fun, you had a try and you’re getting better and better at using the unity editor. So let’s go for the solution, so I’m going to find that folder, I’m going to select the file and everything is loaded for us to start solving this challenge. So, I want to mention that there is not a single way of solving this challenge. It’s really up to you and don’t worry too much about particular details. Just try and see what works best. So I’m going to start by rotating this about the y axis in 90 degrees, so that the bridge is in the correct orientation. So I’m gonna drag it here and I’m going to look from above, just to make sure that the elements are kind of in the right positioning. Whoops. And what I’m going to do now is rotate the stairs to the bridge. This one for example, I really want to do is rotate it about the z axis, and I want to rotate it in a positive way. So that it looks that up.

So I’m, literally, using my left hand to try and show you how to do it. So, that’s 45 degrees positive and with this one, if you also use your left hand, you realize you need to do a negative rotation. It needs to be in z. So minus 45 as well. Now let’s join these things. Let’s put them together by using vertex select, type v and then pick this vertex there and, yup, it needs to snap in the right location. Whenever you have that stuff that you just saw, just press f and that will bring the elements into focus. Okay, so that seems good to me. So I’m going to do the same thing with the other part. I’m going to grab that, type v, grab the top vertex and make sure that it is in the right one, I think it is, and yeah, it seems that it’s fine. Now grab all of them, select them. Press ctrl or cmd, so that we are selecting all of them. You can also select them from here, so you can go like that, and now we just need to bring it down to the floor. And It doesn’t need to be a precise, it can be something like that.

Transcript Part 2

The transform component of a game object includes the position, rotation, and scale. What we’ll do in this lesson is talk about scaling. When you select a game object, you’ll notice that the default scale is one. If I go here and click on the Scale button, the scale gizmo will appear in my game object, and that allows me to change the size of my game object very easily by simply dragging the handles that appear in the gizmo. You can see that I can scale my game object in all different directions, and I can scale it either up or down as well. So I can make it bigger or smaller.

How does this exactly work? What is a scale? If we have a cube that has a size of one in all sides, and let’s say that this is x, so that’s the x direction. If I want to change the scale of x and set that to two, or to any number, what I’m doing is multiplying that number by the size of the object in that direction. So if we set this at two, we’re now effectively doubling the size on x, so the final object will look something like that, and this will have a size of two. When you have a scale that is greater than one, you’re increasing its size. And when you set a scale that is less than one, you are effectively reducing the size of the game object. If we set a scale of say, 0.5, what we are doing is reducing the size in half. So if we had our cube like this, and we went and reduced the scale on x and set it to 0.5, this is the x direction, then the cube will be reduced to something like this.

So the size will be cut in half, basically. You can easily see that here, for example, if I’m increasing zed here to a number that’s greater than one, it’s bigger. And if I reduce it, eventually, you set it to something smaller and you are reducing the size. We have now covered the transform, so you know about position, rotation, scale, and in order to access these buttons here quickly, if you don’t wanna be clicking the buttons, you can use the keyboard as well. By using the keys Q, W, E, and R, that allows you to easily go through all of these tools. ^Remember that the first one allows you just to move the scene. It’s the same thing that you can do ^with the middle button of your mouse. And regarding this last button here, it is used to resize two-dimensional objects, so we’re not using that for now. We’re working with three-dimensional objects here. Another topic I wanted to cover in this lesson is that of parent-child relationship between game objects in Unity. So far, all the game objects that we’ve worked with don’t have a parent. They are top objects here in the hierarchy.

But, you can have that kind of relationship between two objects. So, what I’m gonna do is create another object. I’m right-clicking and going to 3D Object, and I can select from the different primitives, so I’m gonna pick a cylinder. So I have a cylinder now. Let me change its position. I’m pressing the letter Q just to start using these shortcuts. And if I want this cylinder to be children of the cube, all I have to do is to drag it in here in the hierarchy view. You can drag the cylinder onto the cube, and now that relationship has been established. What does that exactly mean? What it means is that the transform of the children is relative to the parent. For example, if I move the parent, you can see that the child object moves along. The position of the cylinder is no longer in relation to the origin in the world space, but it’s in relation to the origin of the parent. The origin of the parent is this point that we see here. That is the parent’s pivot point. The position of the cylinder is thus established in relation to that point.

For example, if I set that cylinder to a position of zero, that will actually put it in its origin, in the origin of the parent. If I move the parent around, the parent, as you can see, it’s not on the origin, so it’s in a different position. And yet, if I go to the children, the children is in the origin because that is in relation to the parent. I’m gonna move that away. I can also change, for example, the scale, and the scale of the children will adapt accordingly. This parent-child relationship will be used all over the place, and you’ll be using it all the time when working with Unity. Some situations, for example, imagine that the parent object is a player. So, I’m gonna rename this. You can right-click and click on Rename. You can also press F2.

I’m gonna call this Player, and let’s imagine that this is some sort of tool or weapon, and imagine that your player needs to be carrying this around. So this parent-child relationship allows you to easily do that. The parent, imagine, needs to be carrying a gun, or some tool, or some item. So that is one case. Another example is, if you recall the challenge of the Position lecture, there was some sort of humanoid figure that was made of different cubes, so that is another example where you might wanna put all of that inside of one parent object, and then you just move that parent object. But, the parent object contains the different parts of the game character, or whatever item, or thing that you wanna have in your level. Another example, imagine that your scene has, I don’t know, 500 trees, and you don’t wanna have all those 500 elements here because it’s gonna be very hard to navigate this hierarchy view. What you can do in those cases when you want to group elements, you can create an empty object and put them inside of that empty object.

So, I’m gonna create an empty object. You can go to create here, Create Empty, or you can do a right-click and then Create Empty. You can call this, for example, Environment, and then you could have a lot of different elements. For example, different trees. You can add elements like that directly inside of another object. We’ve covered a lot of ground, and what I want you guys to do now is have some hands-on practice, so we’re gonna go to challenge mode. So let’s open the challenge. This challenge consists on opening this scene that’s gonna have a nice looking tree, and a very distorted tree. What you have to do in this challenge is go into this element, which is gonna be a parent with some children, and I want you to change the scale. Only the scale, don’t change the position or anything else. And you have to change the scale of the parent and also of the children so that it has the same scale values that this other tree. So, start by going to this other tree and see what values are present for scaling, and then go to this tree and try to change those values so that it matches the other tree. So have a try and post your video, and then I’ll show you a solution.

All right, so assuming you’ve had a try, I’m gonna show you how you can easily solve this challenge. I’m gonna go and open the challenge file. And, no, I don’t wanna save this scene. This is located in another project, yes, I want to open another project. All right, so my scene is ready and I’m ready to solve that challenge. Let’s go and see how we have this environment object, which contains the ground, nice looking tree, and ugly looking tree. Nice looking tree has a scale of one in here, and this one has a scale of five. Let’s start by changing that to one so that they match.

Now, if we go inside both of them, there’s a trunk that has a scale of 0.2, 1, 0.2, so I wanna have that same thing here. And now, on top, I have one, two, one, so I’m gonna go here and make sure that I also have two in here, that’s looking a little bit better, and one in here. So there we go. We’ve got now all trees looking the same. Get ready for the next lesson where we will cover the basics of materials so you can see how all of these things look good because they have colors, they have materials. So, that is what we’re doing next.

Transcript Part 3

There are three important concepts that we have to cover. The first one is that of shaders. Shaders in Unity are scripts that describe the mathematical calculations required to determine what colors should be shown on the screen, what color should each pixel be. So when you see your game, it is the shader what determines what exactly you see according to the light and to other settings. A material on the other hand, is what defines how a surface will be rendered or drawn on the screen. And a material has a shader associated with it. So a material has a shader, and depending on the shader, there will be certain options, certain parameters, that you have to enter. Some of these parameters might be values of different colors. It could be other numbers, or it could be different textures.

A texture is simply an image, a bitmap image. And depending on the shader, the shader might require a few images. So, basically, to summarize, a shader is a script that is written in a language called HLSL and that shader would require certain parameters, certain textures, and it is the material where we specify all of those things. When we create a material, we assign a shader to it and then we enter all these things and then we can give this material to a 3D model. For example, you can create a cube, create a material and then you can assign the material to the cube. Let’s go to Unity and create our first material.

So, in Unity I’m going to start by creating a cube, to which we will assign a material. In my project view, I’m going to create another folder here, which I’m going to call Materials. I like to organize my projects in this way. So I’m going to enter that folder. And I’m going to right-click and go to Create, and select here Material. So I’m going to create a new material. And we can call it something like Basic Material. So if I select this material here, you will see all the properties of this material, in the Inspector.

The first thing to select is the shader that’s going to be used. Unity comes with a shader called the Standard Shader, which is a very flexible and robust, and efficient multi-purpose shader. So that is the one that we are going to be using. There are other shaders for other purposes but we will be using and covering this Standard Shader here. And there are a few parameters here that we have to enter. The albedo is a very important concept. So let me explain what that is. You might have heard the word albedo if you’ve studied Astronomy. So the albedo is the proportion of the light that reflects back. So different materials have different albedo values. But in Unity, albedo actually means something different. It doesn’t mean the percentage of the light that is reflected. It actually sets a base color for the surface.

So, in simple terms, it is the base color of the material. So let’s go and select a color. I click on the color there and I get this color picker so I can pick any color I want. And once I’ve selected a color you can see that your material now has that albedo color. And I can drag my material to the cube to assign that material. If I click on the cube, you will see that the cube and all elements that you create that are obviously visible, like a cube or all the primitive cylinder spheres, they all have a mesh render which is a component that determines how that particular game object is show, is drawn on the screen, is rendered on the screen. So you can see here that in materials we actually see our material. If we create a new cube, and I’m going to move it away, you can see that by default the cube has something called a Default Material. So, our first cube has the material that we’ve created for it.

There are two other parameters here that are very important. The metallic and the smoothness value. The metallic parameter, specifies how much the material will reflect its environment as opposed to just showing its albedo color. The smoothness simulates “micro-surface” on the material and that affects how it reflects light. So the more smooth it is, the more even the reflection is going to be. And we’re going to talk about emission in a little bit. The best way to get a feel of what these parameters do is actually to try and experiment. But if you need some help, there is a very useful material chart in the Unity documentation that explains how you can easily achieve different effects, what sort of color you’ll need on your albedo, and then what parameters you can set on your metallic and smoothness.

Now let’s go to Unity and have a play with these things. Before modifying those things, what I would like to do, is actually add a couple more things here. So I’m going to add a plane that we can position underneath these elements. And I also want to add a second light. As you know, we have a directional light, which is light that comes from this direction as shown here. And I would like to add a point light, which is light that comes from a single point. So I’m going to right-click and go to Light, Point Light. It created a light here. As you can see the light has a transform component that we’re already familiar with and a light component, which is what makes that light a point light. I’m going to draw that here and I’m going to change the color of that light to something else, something like green so that it gets something a bit more interesting. And there should obviously be some reflection on the ground. I’ve created another material here called Ground Material so I’m going to select a color for that material, let’s make it brown, and I’ll just position that in there.

Okay, so let’s go back to our basic material and play with these metallic and smoothness parameters. Out of both parameters I find smoothness the one that’s the easiest to understand. Because you can easily visualize surfaces that have a micro-surface on them, for example, the ground or blanket and those surfaces will usually reflect light in a way that is not so concentrated. For example, if we said this, we can compare that when it is very smooth it looks like a billiard ball pretty much, and also the light tends to be more concentrated. Whereas, when it’s set to a low number, it can resemble more the kind of surfaces that have this characteristic. The metallic value, the more metallic it is, the more that it reflects the environment. When you can really appreciate the metallic value is when you have, for example, a sky box.

So, if we look up we can see that this sky, it’s pretty boring right? It’s very plain. But if we had a sky box with clouds and more elements, by using the metallic value, you could reflect some of the stuff. It would become a bit more intuitive. But, as you play with these parameters and also keep that chart in mind you can achieve a lot of very good looking materials. The other property here that I want to cover is emissions. A material that has emissions is a material that emits its own light, basically. So let me create a new material. So I’m going to go and add a new material. I’m going to call this Emissive Material. And by the way, I think the ground should have a low value of smoothness and then it looks a bit better when you set a bit of a higher metallic value here.

So that’s my opinion when it comes to grounds like this. Anyway, back to emission. We have to activate the emission here. And then we can set the value of the light that will be emitted, the color. So, we’ve set that to green and we can also give it an albedo color. And as you can see, that looks kind of radioactive. So, we can assign it to this one here. This is actually emitting some light. If you played with more advanced lighting options that will come later in the course you can actually get this to show this light and to really illuminate its environment. So that happens when you do something called baking light. Another property here that’s interesting to discuss is transparency. So I’m going to go and create a sphere, move that somewhere here, and create a material that will have transparency. So I’m going to go Create, create a material, and I’m going to call this Glass Material.

So, for our glass material, we can give it an albedo color, for example, five. And then you can play with this alpha color, but it’s not going to work unless you go here, in rendering mode, and check on transparent. We check on transparent and then you can set the alpha channel, and that will give it the transparency. So if we drag this onto here, we can easily see how our sphere is transparent or semi-transparent. So in that way you can achieve that effect. And the fifth type of material that I want to build here is a material that uses a texture, an external image file. So let’s call this Sand Material.

And what I need to do is import an external image file. I’m going to create a new folder here called Textures. And, if I go to my file explorer, I already have a few textures that we can use. These are all open source things. I think I got this one just from the GIMP program. But if you search there are a lot of open source and free textures that you can use. And also, premium textures. So, the way to import this is simple as simply dragging the file onto Unity. If you click on it you will see that this is a texture and there are some options here. We will leave all these in its default. So let’s go to our material and I want to give that material to a floor, so that we make it sand, a sandy floor. By clicking on that circle next to albedo, we can bring up this menu with available textures.

So I’m going to select the sand. And, at first you can see that it doesn’t look too good, because it’s expanding the image to cover all the whole area and this sand texture is meant to be repeated, multiple times in such an area. So the way to work with that, the way to fix that, is to go to Tiling, underneath Emission. Tiling has nothing to do with Emission by the way, it’s just located very very near. And this is the number of times that the tile or the texture will be repeated. So if I change, for example, to an X we are repeating on the X-axis we’re repeating it twice, but just once on the Y. So as you can see it will stretch. It looks horrible. So, what if we do that on the Y as well? that looks a little bit better. We have now four times, the texture. And if we do three times, that looks much much better. And let’s do four, and just to show you, if you have too many it kind of looks weird, because it’s just repeated too much.

I found that four looked okay in this case, so I’m going to leave it at four. And, we could also play obviously with these parameters if we don’t like the way that the light is being reflected or anything like that you can just find the sweet spot, find whatever works for you. And, you can also set an albedo color, if we wanted this to have a bit of a martian aspect, we could change it to like red and that would give us our martian soil. So we have all different types of material here. We have this sandy material, that you can be like “Yeah, in real life, sand is not smooth,” but sometimes in Unity you just have go with whatever kind of looks best. So, I guess it could be more like that, that’s a bit more realistic, yeah. And then we’ve got this other ground material that basically had like a very low smoothness. Then we have the transparent material and we also have an emissive material like a radioactive cube.

And this original material is the one that was made kind of like a billiard ball, very metallic, very smooth. So, what we’re going to do now is go to the challenge. And, the challenge will bit a bit different in this case. So, the challenge will basically replicate everything we’ve done in this lesson but without you obviously looking at the lesson. So trying to do it on your own. You can always just look at the lesson again to find out how any of these things are done and of course do check the documentation that I pointed out. So, create a new project in Unity. Create five cubes or five primitive shapes, it can be spheres or cylinders, a plane. Create five materials and start with the basics. So, start by simply setting a simple color, just change the albedo.

Then start playing with the metallic, with smoothness, to create something that’s looking like metallic, kind of like that billiard ball that we created. Then create your own emissive material, your own radioactive material. And, create a semi-transparent material, something that looks like a glass. And, end up by creating a material with a texture. So use any image that you want, and you can of course download the solution that is basically the files, the project that I just put together so you can use that sand it’s open source as well. (groovy music)

Transcript Part 4

The Unity Editor can help you with many, many things. But there will come a time when you will want to implement your own custom logic or the logic for your game. And for that you need to learn scripting. What we’ll do in this lesson is get started with scripting, which is the same as programming or coding, or however you want to call it, using the C# programming language. I’ve created a new project here, and the very first thing that I’m gonna do is create a folder for my scripts. So I’m gonna right-click and go to Create, Folder, and I’m gonna call this folder Scripts. Inside of that folder I’m gonna create my very first script. So I’m gonna go to Create and select C# Script, that is C and the hash sign Script. I have to enter the name of my script now, and the convention is to start with a capital letter.

So I’m gonna call this Hello, and then World, also W will be in a capital letter. That’s just how people write their names of their scripts. So I’m gonna press Enter, and that has created a new script for us. If you select that script here, you can already see the source code of the script in the Inspector window. To open your script, double click on it. In my case that will open the script in Visual Studio, which is the officially recommended editor for Windows. If you are on a Mac, the script will be open in a program called MonoDevelop that works in a very similar way. Maybe, by the time you watch this, Visual Studio for Mac will be out, and you will be able to use Visual Studio as well. So we’ve opened our script, and if you have never done any programming before, this can seem like a very strange thing. What does this all mean? And even if you have done programming, but you haven’t done any C#, this might also look pretty strange.

So, I’m gonna start by deleting this whole part here, this whole part that says void Update and those brackets, I’m gonna remove all of that and just keep this stuff here. And what I’m gonna do next, I’m gonna explain what this is in very simple terms with no technical term usage, and then we can move up from there and start adding some code. And now we can explain what this is. So the best way to understand programming, and this is programming in general, is to think of a cooking recipe. So, in a cooking recipe you have different steps. For example, if you want to make pasta, the first step is to boil the water, and then you need to add the pasta, and then let’s say that you need to stir. So you have different instructions, and they can all be understood in human language in basic terms, and they all need to be performed at a certain order. So it goes from top to bottom.

The same thing happens with programming. You’re basically issuing statements that the computer needs to execute, and they are also executed from top to bottom. Let’s say that we have the full recipe of pasta here, and we might want to use that recipe in different meals or in different events. So, for example, you could have some sort of dinner, a dinner party or something, where you need to make the pasta. And let’s say that you also need to make a dessert. So that is another recipe. So this recipe can be put in what would be called a method, and that method could be called something like MakePasta. So every time that you want to make pasta, you just use the method MakePasta, and that method has all these instructions.

So when you’re preparing your dinner, you don’t have to type each one of them. Write this down, you just say, just make the pasta, and you already have the instructions to make the pasta. So if we now go to this code here, we are gonna start from the inside to the outside, making sense of everything. All of these instructions, they are very clear steps, would go, let’s say, here. This Start text, it is a method. So it would be something like, for example, MakePasta could be Start. And this green text here that says, Use this for initialization is a comment. That is a comment for humans to read. So whatever is preceded by these two signs is a comment for the programmer to read. The computer is gonna ignore this. So what we have here, we will have instructions here, and those instructions are put inside of a method, in this case the Start method.

Now, what do these brackets mean? The brackets, these curly brackets are used to put everything together like the same thing that you have a burger, and you have a bum on the top and a bum on the bottom, and then you have your burger here and the lettuce and all the other things. So, think of the brackets as the bum that goes on the top and at the bottom. Things need to be within a certain space scope. So that is what these brackets mean. What if we go one step even further. So at this point we kind of have an idea what this is. Basically, start some method, but what about this Class? This is a class and it’s called Helloworld. We gave it that name. Think of a class as like a Lego block, think of the class as a Lego block. So, you have a block that is almost like a Lego piece that you can use in different parts. So you could have, for example, one character in your game that is gonna use this Helloworld, and it’s gonna do something. And then you could have some other character in the same game that uses that same component. So that is what a class is. Think of it as some sort of block that can be reused. And again, the brackets here are doing the same function as the burger bums on the top and at the bottom.

Then, what about this top part here? Since we said that this was like a piece of Lego, these would be other pieces of Lego that other people created that we are using in our script. In particular, this one that says UnityEngine. It gives us access to the whole Unity API. And these other two are part of the C# programming language. It’s created by Microsoft, and this is part of the, it’s called the .NET Framework. So those are just tools that come with the programming language that we can use, and when we create, so let’s go back to Visual Studio, when we create a new script in Unity in this way, this is created for us automatically. The instructions that we put inside here, for example, boil the water or things like that. Like it says here, they will be used at the beginning for initialization. When our game starts, and the very first frame is shown on the screen, that is when the Start method is executed. And the last part that hasn’t been mentioned is this MonoBehaviour thing here.

So, we will go over this in later lessons, but for now, just think that all this does, it just gives us the fact that we can use Start like that, it comes from here. So this gives us access to Unity’s way of working with things and connect with the Unity game itself. So, that would be a very, very general, basic way of looking at programming and a script. Now, what can we do in our Start method? When people learn how to code, usually, they like to do what’s called a Helloworld, which is when you just say hello to the world. So, what we will do is just show the text Hello World. For that, if we type print, we can show something on the screen, and what is it that we want to print, we need to write the message. So what I want to write is a message that says Hello World.

But this kind of feels weird because see how it’s kind of underlining the words, and that is because when you are going to write a text what’s called a string, you need to use these quotes. So we are going to print Hello World on the screen. And see how it’s still showing us this red line, it means that there’s something it doesn’t like, and it is because we are missing a semicolon. Whenever you type this type of statements, you have to put the semicolon at the end. So, we have now a little script, which all it does, it will say Hello World at the beginning of the game. So let’s go back to Unity and see how we can make this actually happen. When a game begins, that is when you press play. So I’m gonna press play, and I’m not seeing any Hello World anywhere. So why is that? It’s because in order for a script to actually do something, you need to put it in your game. You need to assign it to a game object. So you need to create a game object or use an existing game object, and give it the script, so that then the script has life and actually runs when the game runs. So, what I’m gonna do now is create an empty game object because we don’t really wanna show anything. I just need a game object here.

An empty game object only has the transform component. So it’s not shown, it doesn’t have a render component, it doesn’t have a material. And I’m gonna rename this and call it just Hello space World. That’s just gonna be its name. And there are different ways of assigning a script to a game object. One of them is by simply dragging the script all the way to the game object, and that will make it appear here as a component. I can remove that component by going here, Remove Component. So, another way would be to click Add Component and then find Scripts and find that Hello World. So that’s another way of adding it. So now that the script has been assigned in our game, we can actually play our game, and you will see the Hello World. So let’s play the game. And you can see down here Hello World. If you go here next to Project to Console, the console is an area that we use to communicate with the script. In the sense that we can send ourselves messages such as this this, and also, if there’s any error in your code, it will be displayed here.

See that Hello World entry, if I click on it, and then I go down here, it will tell me the exact location of that message. In this case the file is called HelloWorld.cs, and the line is number nine. So if you go to that file, which is by the way called HelloWorld.cs, that is the extension for C# scripts, and if you go all the way to line number nine, we can see our message. So, that is how you can create a script and assign it to an object. And what we’ll do in the next lesson is make this a bit more interesting and introduce the concept of variables, so that we can actually pass on things to our scripts. So before you go to the next lesson, I have a very simple challenge for you. The challenge consists on creating a new script and assigning that script to a game object.

The script, all it needs to do is say hello to yourself on the console. So you can write anything you want on the script. Once you complete the challenge, you can join us on the next lesson. (upbeat music)

Transcript Part 5

Variables are a very important concept in computer programming. They allow you to store and retrieve information from your computer’s memory. You can, for example, store the name of the player and a variable, and then you can show that later to the user. You can do all sorts of things with variables. You can do mathematical operations. And what we are gonna do now is create our fist variable. There is one important step when you create a variable, which is the variable declaration. And then there’s also another step, which is the variable assignment.

Just so you know, both things can be done at the same time. So we can also have variable declaration plus the assignment at the same time. So let’s declare a variable. As I said, something that will describe the name of our player. In C#, when you create a variable you need to specify the data type of the variable. That means, is our variable a number? Is our variable a string, which means text? Is our variable a true or false value, or is there a decimal point number?

Well, in this case, it’s a text, so it’s a string. So we’re gonna type string. That is the data type. Now, we need to give our variable a name. I’m gonna call it playerName. That’s gonna be the name of my variable. Now, because we finished our statement, we declared our variable, I’m gonna type semicolon. As you can see, the editor is gonna highlight that because we’ve declared the variable, but we’re not using it. So that is obviously not optimal. That is why the editor is telling us, please use that variable. Let’s do an assignment where we give this variable a value. We assign by using the equal sign. And because it’s text what we want to give, it needs to be inside of double quotes. So this is gonna be, for example, Mr Pink. We finish our statement, so semicolon.

So we have declared a variable, and we have assigned a variable. And it’s still complaining because we haven’t really used that variable. So let’s show that to the user. And by the way, notice how I’m using comments just to keep track of what we’re doing. So it’s always a good practice to comment your code so that when you come back to it later it’s easy to know what is going on and what each thing actually does. As we saw before, we can use the print method. So I’m gonna open brackets so that we can pass in what it is that we want to print. And what it is that we want to print is the player name. Now, see how asset type, the name of the variable that we’ve previously declared, I can see that in here. It is being suggested to me that that variable has been declared, and then I can just use that. So if I click on that suggestion, or press Enter, we will actually save ourselves the time of typing. So that is called order completion. And it’s common in code editors.

We can now save. And if we go to Unity. And I need to start by clearing the console because I was doing other things here. Now, I’m gonna play my game. And you can see here, Mr Pink. So we are getting that shown. We are basically declaring a variable assigning, and also showing it on the screen. Now, what if we want to do both things at the same time? String, let’s call this enemyName, and we’re gonna call this Miss Orange. Close that statement, and that’s it. So we are declaring and we are assigning. By the way, before you assign, so in between these two lines, the actual value of this variable is null, which is a special key word in C# to determine that something is basically nothing, or it hasn’t been declared yet. So that’s null. And we can also show this to the user. So we can show that, print. And I’m gonna make use, again, of this order completion. And there we go. Now, what other types of variables can we create in Unity in C#? We’ve seen string.

Well, there’s quite a few of built in types. These are all called data types. There are a few built in data types, or types that we can use. And as we create our own classes, we can also use those to declare variables. But for now, let me show you some of the basic ones, some of the ones that we’ll be using the most. So we have integers. For that we use the int keyword that gives this big range of numbers, probably not gonna use all the way to the extreme, who knows. An example would be just to type 100. Then we have float, which are numbers that have decimal points, and you specify the decimal point just with a point, and you have to type the letter f at the end of the float. Now, strings that we saw, we use the string keyword, and it’s just for text. So like, Hello World, for example. Booleans can have a value of true or false, for example, false or true. And see how we’re not using quotes here. We just type true or type false.

For a full list of the built in data types just go to .URL, which will take you basically here. And then you can see some of the other types that are available. This documentation is the part of the language API of the things that come with the C# language. So let’s go back to our code, and let’s declare another variable, so the float, for example. Let’s say the energy of our player. We can declare float energy, and, in this case, it can be something like 1.5. That would be the value of the energy. Or you can have an integer in the number of lives, for example. Number of lives int n, and you can have 10 lives. So that would be another example. Also, you can check whether the player is alive or not. So is alive. And you can have a Boolean, and then something like that, isAlive can be true, or it can be false. So in that manner, you can declare variables in these other data types. Now, regarding floats, there’s something interesting here, which is that, let me show you in a note.

Now, something interesting here is that when we declare a float, for example, 1. If the number is 1 we can type 1f, right? But we can also just type 1. And 1 will always convert to 1.000. This is an integer. This would be a float, 0000, all the way to infinity, really. So that works. If you don’t wanna type the f when you are writing integer numbers, you can do it like that. C# under the hood is really doing this transformation for you. Now, if you try to type, for example, 1.5f, that’s fine, but if you type 1.5 and you are missing the f, you will get an error. And the reason for that is, if we go to that original list of built in data types, besides having float, you also have double. And double has a much higher range of numbers than float. So it goes all the way to 10 to the minus 325. So that’s really, really, obviously, a really big or small number, and that is obviously more than this, or a bigger range than this. So if you type 1.5, that is actually a double, and a double cannot convert it to float, because you are losing part of the number, part of the information of the number. And C# is not gonna know how to transform that.

The same thing happens if you try to go from float to int. That 1.5, for example, how does that translate to int? Is it 1 or is it 2? We don’t know, because ints don’t have this part. So avoid that, and also, avoid that. So to summarize regarding this, when you are using float and it has a decimal number, decimal point, just always use the f, and if it doesn’t, you can avoid using the f if you don’t to type the f each time, which I have to confess, is something that happens to me. So let’s go back to our editor and look at that. So you can see how energy is 1.5f, but if we don’t type f we get that error thing. It says here that something from type double cannot be converted to float. Same if I type 1, we won’t get that error because an integer can be converted to float very easily.

So that was a bit of clarification that I wanted to make, which might be a bit too early, but it’s just something to keep in mind. Now, the other thing I wanted to cover in this lesson are Arithmetic operations, which can be performed with integers and floats as well. So the Arithmetic operations that we have here are addition, subtraction, multiplication, and division. For example, let’s say that you want to calculate the total score of a user. And let’s say that you have the total score is they completed 10 levels, and each level gives you 10 points. So you’ll have 100. You could have this saying the levels completed. She completed 10 levels, so she completed 10 levels. And then your total score is the levels, oops, the levels completed times 100. So you can get that. And in that case, we’re using the multiplication. Or you can easily total, for example, total could be 10 plus 1.5f. As I mentioned, you can convert from integer to float, but be careful that if you try the other way around, for total2, if you try that, you’re actually gonna get an error, because, as I said, you cannot go the other way around in this implicit manner.

You can explicitly convert them, and you can define how it’s gonna be converted, but in this case, try to avoid it. Now, the last thing is, well, we still have subtraction. It’s quite easy. So the number of lives could be a number minus another number, like that. That will be 4. And division, of course, the parts that you get out of something, could be, for example, 100 divided by 50. In that manner, you can divide. You can also combine operations. So you can have a combination. You can have, for example, 100 plus 1.5f times 10 divided by 100. And just like in algebra, multiplication and division go first, and then addition and subtraction follow. So that is the same that with algebra. And you can also use brackets, and by using brackets everything that’s inside the brackets will be executed first. I can easily show this on the screen like that. Print combination, and that will show the total to the user. Something else that I can do is concatenate two different strings and including a number.

So let’s show something like the result for my name. By using the plus sign we can join two strings. We can concatenate two strings. So result for player names. So I’m gonna copy that, and I’m gonna go here. That will say the result for Mr Pink. And then I wanna have some more text, so another concatenation is. And let’s now, actually put this total here. So that will show the result for Mr Pink is, and then the result of this operation. So let’s go to Unity and see what we get with that. So let’s press play. And the result for Mr Pink is 10.15. What is really happening here under the hood is that combination is actually being transformed to string by C#. And then the two strings are joined together.

So we’ve covered a lot of ground, and basically, I’m gonna do a very quick recap. So we are using variables to store information, and to manipulate, and resend that information. We declare variables like that, specifying a data type. We have all these different data types to use, and obviously, a lot more here. And then there’s the part of the assignment where you actually give the variable that value, or that can be changed later as well.

We can easily work with numbers in this way, but keep in mind that you cannot go in an implicit way from a number that has more detail to a number that has less details. So you cannot go from float to int, but you can go from int to float. You can use the same operations as in normal algebra. This is what you use for division, multiplication. And you can concatenate different strings, join different strings in this way by using the plus sign. And when you join a string with a number that is not a string, what is really happening is that that number is being converted to a string. And, well, in this case, combination is being converted to a string, and that is how we are able to put this together. So before you move on, let’s do a challenge so that you can get some hands on experience. Create a script that converts Celsius to Fahrenheit degrees. This is the formula. If you have a number of Celsius, you multiply that by 9 divided by 5 and then up 32. And that will give you the Fahrenheit as a result.

So create a script where you declare a variable, and you declare a variable, which is the temperature in Celsius. And then you perform the calculation. And then you show that to the user. So have a try, and then I will show you a solution. So pause the video now and have a try. All right, so let’s solve this problem. We’re gonna create a variable that’s gonna be Celsius. And so, we have, for example, 20 Celsius. And for the result, we’re gonna create this Fahrenheit value, variable. The calculation is gonna go like that. We’re gonna do C times, what was the formula, 9 divided by 5 plus 32. And now, we can show that to the user.

So print the result is + f. And if we run that on Unity, we execute that, we get our result, 68 degrees Fahrenheit. So let’s move on now to the next lecture. (upbeat music)

Transcript Part 6

Imagine you want to create a character in your game. And to describe that character you want to have a variable for its name, for its energy, the amount of coins and to keep track whether the character is alive or not. So if we’re just using variables we create a variable for each one of these things and we could define it’s name, energy, coins, if it’s alive or not. But what happens when you want to create a second character?

You’re going to run into an issue that you’ll have to create another four variables and call them something different like second name or second energy. And what if then you want to create ten characters? All of these variable names are going to start to get very confusing and you’re going to have all of these variables floating around. It’s going to be hard to work like that. So there is a better way. And that better approach, that better ways is to use a class.

Think of a class as a blueprint that we can create to define an object, in this case a character. This class of us can have member variables which are variables that belong to the class and they can be accessed anywhere inside this class. In this manner we can create a variable to keep track of the character name, its energy, its coins and whether it’s alive or not. We can create then instances of that character and what that means is after we define the blueprint we can use that blueprint to actually create multiple characters for our game. So, by using the name of the class as a data type we can create variables that consist of new characters that we are creating. A class is basically a blueprint. A class definition doesn’t create any object. What actually makes things happen is when you create instances of that class. The same analogy with cooking recipe. You have a recipe that doesn’t mean you have a cake. You actually have to make a cake, so that is how you should see classes. That is the easiest way to understand the concept.

Now how can we get access to these member variables? We saw how we could create new characters but we haven’t seen how we can access them. And the truth is that the way they are defined here, we can not access them outside the class. We need to add something to that. What we need to add is the public key word which will make these classes and these member variables public. That means they can be accessed from outside the class. And when you have created public variables like that, after you initiate a new class, you can easily access those variables and change their values, just like you would do with normal variables.

And that brings us to the concept of encapsulation. In C sharp, if you want to have a public variable, you need to write the word public. You can also be explicit and say that a variable is going to be private and that means that that variable can not be accessed from the outside. You cannot access that variable from outside your class. If you don’t write anything which is was I had done before, that by default makes variables private in C sharp. So having these public and private approach which is called encapsulation in object oriented programming, means that sometimes you’ll be able to access variables right away without any intermediary if they’re public. But if they are private, the only way to access them will be through a method.

In Unity, when you create a public variable, so see how this is the script that we created, HelloWorld, when we create a public variable like that, it actually shows in the Inspector. And then we can assign a variable, a value to that variable. So that’s how it works in Unity. If you create a private variable, it’s not going to show like that in the Inspector. And we are now due to really talk about methods, which I’ve mentioned before. The best way to think about methods is the best analogy, we start up a factory. Methods can have input and they can also have output. The difference with a factory though is that some methods don’t need to have an input. They can not have any input at all. And also some methods are not going to have any output. So that is the main difference with a factory. For everything else it is a very good analogy. This is how we can declare a method in a class.

So see how we have a class here that has our properties. Public member variables of our character, name, energy, coins, and we’re also declaring a public method. That means a method that we can access from outside the class. See how we’re calling our method PrintName. And inside that method all that happens is we’re printing the name to the user. I will talk about void in just a little bit. So if we wanted to execute that method to call that method, we need to create an instance for a character, we can assign values to those public variable. In this case, there shouldn’t be a is alive, because I didn’t add that here. So, that actually shouldn’t be there. And we can print the hero’s name in this way. So that is how we can call this method here. Returning a value, the output of the factory. I’m creating here another method which is called GetScore. That method, what it does, it creates a variable, it’s a local variable inside that method of tight interjer. And the value of that variable will be coins multiplied by 100. Let’s say that we want to give this character 100 points for every coin that they collected. And we want to now return that, send that as an output outside of our method. So that, a few things here to notice is that, we have typed here int instead of void like before. So, that means that we are returning our variable of tight int. And that is exactly what we’re doing.

We return that value with the return key word. Also it’s important to mention one more time that methods can access all member variables. If you had public or private member variables, you would be able to access them in your methods like that. And now when we actually call the method, see how we are declaring a variable here called playerScore and that is equal to hero.GetScore. And when we do hero.GetScore, what is happening is that we’re calling the GetScore method and that will return an intejer and that intejer is placed in our player score. And then we can show that to the user, and do anything we want with it. Void means that there is no value returned. So we’ve seen void a few times. It basically means this is a factory that doesn’t produce anything, that doesn’t give any output. If you could do things like showing something to the user, many other things, but it doesn’t have a return value.

And now the other part of the factory, how do you get things in the factory? How do you pass in parameters? We’ve been doing that all along so, if you look at the print method that we’ve used a few times, it actually already has parameters. So, you simply pass these parameters inside the brackets when you execute the method. So let’s look at an example. Let’s create another method called GetScore but this time our GetScore method will have two parameters. The character, the score of the character will be a base score, so it will have dock value as a minimum. And then we’re going to define how many points we want to give the player or the character, per coin that they’ve collected. So, as you can see the operation here, the calculation of the score is simply the base score plus how many coins you got multiplied by the points per coin that we are giving and that is returned, that is passed back. And the way to pass these parameters would be the same thing we’ve down with print. In this case we have two parameters so we are passing two values. And see how these two values are intejers. So, they need to match the type that is specified in the method signature, the method definition.

We can also have default values for our member variables. If we don’t specify the value of energy in this case once we create characters, they will have an energy of 100 by default. If we don’t specify a default and we don’t enter any number, the value will be nul. And now it is challenge time so we’re going to have a challenge that is a two stage challenge. And after you have a try, I will show you the solutions. So let me explain what this challenge consists in. You’re going to go to your HelloWorld script which make sure it’s empty. It only has that start method. And the first thing you’re going to do is create a new method called PrintGame. And this method, all it’s going to do is going to print in the console the type of game that you want to make the most. So for example if your dream game idea is a VR RPG, just print VR RPG or any game idea that you have in mind. Then the second step is to actually, we’re going to execute that in start. So, you create your method and then you execute it in start. And by the way you create it here, so you create your method here. And then you’re going to execute it. And then you’re going to run the game so that we can actually see that in the console.

So you’re going to run the game. And after you’ve done that you completed part one. And now part two consists on creating a public variable of type string called myGameIdea and you’re going to place that here. So you’re going to place your public variable here. And after that, you are going to go to inspector and enter a value for that game idea. As I mentioned, when you create a public variable that will appear here and you can enter a value so it will appear under the game object that has the script and it will appear on the script component. And then you’re going to modify your PrintGame method.

Instead of just printing the game that you want to make the most, it’s just going to print whatever you’ve entered in this myGameidea variable. So that is the challenge and if you get stuck at any point, we are going to go through all the steps right now basically. So, pause the video, try your best and then join us to see the solution. Alright, welcome back. I had coffee and it was amazing. No kidding, I’ve been here all along. So let’s actually solve this challenge. I’m going to create a new method here, void PrintGame. This is not going to have any parameters, so I’m just going to type the bracket. And as you saw, I just type one bracket and the other one is created for me. So it does make life easy by doing those things. I’m opening now my curly brackets with are the barrier buns that contain everything that goes in this method. And now we’re going to print a message to the user. And I’m going to go with that VR RPG idea.

So I want to make that kind of game. And now in my start method, I’m going to execute this PrintGame method. So, I’m just going to type PrintGame and close the brackets so that we’re executing that. Now let’s go to Unity and play the game and see if that works. So I press play and yep, we can see that the RV RPG in here. So, we got part one of the challenge solved. Now second part of the challenge was to create a public variable of type string called myGameidea. So I’m going to go here and I’m going to type public string myGameIdea and I’m going to save. You have to save in order for this to work. So I’ve saved and now I go back to Unity and I have to click on Unity somewhere. And what is really happening under the hood is that the script is being compiled. That means it’s being transformed to zeros and ones and that’s something that Unity, if the script is compiled it means that there’s no errors and therefore we can see this here. If there was any error, we would see in the console.

So now I see myGameIdea, and I’m going to type a different game idea. So, let’s type VR adventure game like Zelda. So I’ve type dot, but I’ve actually, I’m not really doing anything with this yet so that was the other part of the challenge was to modify your PrintGame method to show the value of myGameIdea. So I’m going to copy that. And I’m going to go here and I’m going to delete that hard coded string and I’m going to paste the name of my variable which is this one here.

So let’s go back now to Unity, run our game, and we can see our message. So we completed the challenge. So thanks for watching this lesson and I will see you on the next one.

Transcript Part 7

The demo we’ll be building in the next videos is a very simple balloon popper game or experience, however you wanna call it. I have this balloon here, and if I click on that balloon, I’m increasing its size. Up to a certain point, because if I go too far, it will disappear. We’ve popped the balloon. There are many concepts that we’ll cover by building this little demo.

Some of those concepts are inheritance, we’re gonna talk about accessing the balloon scale, about detecting clicks on a game object, about destroying a game object, and also we are gonna use what’s called a conditional operator, to check whether the size of the balloon, the scale of the balloon, is greater than a certain number. So, let’s dive right in and build this little demo. I’ve created a new project, which I’ve named Balloon Popper. Inside of that project, I created the Scenes folder. Saved my scene inside of that. And what we’re gonna do now is create our balloon. So I’m gonna go here and create a new 3D object. It’s gonna be a sphere. And I’m gonna rename that, and call it Balloon.

I want my sphere to look a bit nicer than that, so I’m gonna go and create a new folder called Materials. Inside of that folder, I’m gonna go and add a new material. So let’s call this Balloon Material. And I’m gonna give it a color of red, and just strike that in there. And, maybe change this a little bit. Lower the smoothness value. Okay. So we have our balloon. And now I wanna create the script for our balloon. So I’m gonna go create a new folder, called Scripts. And inside of that folder, I’m gonna go and create a new script. Create C-Sharp script. I’m gonna call this BalloonController.

And I’m gonna open that in my code editor. We are not gonna be using the Update method here, so I’m gonna remove it. And, there is something that I want to mention. So, what I would like to do is be able to detect when the user clicks on the balloon, and when that happens I’m gonna increase the size of the balloon. So I’m gonna increase the scale of the balloon. Each time the user clicks, I’m gonna be increasing it in a certain number, which I’m gonna call scale factor. And once it reaches a maximum scale, it’s gonna pop. As I mentioned before, we need then, we have these two properties that we are interested in. We need the scale factor, so how much the scale is gonna increment each time you click, and also what the maximum scale is gonna be.

So, for that I’m gonna create two public variables. One of them is gonna be the, how much it grows each time. So I’m gonna put it public float, and let’s call this scaleFactor. And I’m also gonna create another one, which is gonna be maximum scale. So public float, actually this, yeah this will be a float as well, so it will be maximumScale. I can give this default values, so I can say that when the scale reaches three, it’s gonna pop, and each time we’re gonna multiply the scale by 1.2. So it increases 20 percent each time. And now we need to figure out how we can detect that click input in the balloon. And that brings us to this MonoBehaviour thing here on the colon. This is forcing us to have that awkward inheritance conversation, so we’re gonna have that conversation, and then we are gonna detect the user clicks.

So, let me show you two very similar classes. You have a Player and an Enemy. So as you can see, there’s a lot of repetition here, and in programming, repetition is always bad. We are repeating these two public variables, and we’re also, we have this exact same method called damage, which basically takes energy from the player or the enemy. And by the way, if you want to reduce a variable, energy in this case, I’m writing energy equals energy minus the amount of energy that we want to take to damage our character. But when you write this, that is the same as writing energy minus equal amount, that is the same as that. So, anyway, we have this thing, and a repetition is bad, so, a better approach for this, is that of inheritance.

And, inheritance, what it is, is you create an object, and then other objects inherit all of the variables of the member variables, and all the methods from that parent object. We create a parent that is called character, and that character has everything that is common to all characters. That is the energy, name, and that damage method that we have created. And see how we’re creating two classes that are much smaller than the ones we had before, because they inherit from Character, and that is expressed with this colon symbol. So the Player character has everything that the- sorry, the Player class has everything the Character class has, that is all of this here, except that it also has its own lives. And the Enemy has the same things that Character has, but it also has this hasClaws member variable. And that brings us to MonoBehaviour, which is what we’ve seen already in our Unity scripts. MonoBehaviour is the base class of all Unity scripts.

So whenever you create a script in Unity, it inherits from MonoBehaviour. And, MonoBehaviour brings in a lot of functionality that we can use out of the box. Even the very start method that we’ve been using, is part of MonoBehaviour, and the print method that we’ve been using to show things in the console, is part of MonoBehaviour too. And, MonoBehaviour has very good documentation, in the Documentation API. And in here we can find all of these methods that are available for us to use. For example, the Start method is presented here. And there is the Update method as well that we will use later. And even the Print method is up in here as well.

So, let’s have a bit of a challenge at this point. And I want you to go through the documentation of MonoBehaviour that I just showed, and try to find a method that maybe can help us detect that the mouse has been pressed on our game object. So, you have to go to the documentation, find the method that you think could help us, and then implement that method in our code. And print in the console when the game object has been clicked. So, in our Unity code, we are gonna implement this other method. So, a method that will help us that will detect a mouse press will be added here, and inside of that method you will print in the console. Keep in mind that for that to work, don’t forget to add this balloon to our game object. So we haven’t done that. So I’ll do that now. So we’re gonna add it here. And now, we can see it in … Let’s see if there was some sort of error. Wait, it’s not showing, so let’s go balloon. Oh yeah, there it is. So it was showing it twice actually, so I’m gonna remove it once. And we have it there. So, make sure that the script is added here, and then play your game, and that is when you should be able to click the balloon.

So, have a try. It’s okay if you can’t do it. These are all things we hadn’t really covered, so I want you to try to get your hands dirty and explore the documentation a little bit, because that is the main thing here. You need to become familiar with the documentation, and the only way to do it is just to practice. So, have a try, pause the video, and then I will show you a solution. Alright, so you had a try, and if we go to this documentation here, you might have come across this OnMouseDown method. So it says, OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider. It’s okay if you’re not sure what these things are. Collider is a component actually that detects that a collision has occurred with that game object. So if you see here, we have that Sphere Collider component. And we will cover that later in detail.

So that is okay, if it all sounds very new to you. So, this method then, it looks like it could be useful. And, in here we see an example on how it’s used. So, I’m gonna go to VisualStudio, and I’m gonna type void OnMouseDown, and you can see that it’s already anticipating that that method is here, because we are inheriting from MonoBehaviour. I’m gonna press enter. VisualStudio creates this nicely for me. When it comes to method, you can leave that private if it’s created automatically. I personally like not to have it, so that is just my preference here. So I’m gonna delete it, so that it looks the same as the other ones. And a lot of like the documentation of Unity as well.

So, when the user presses the mouse button, what was the other part of the challenge? We wanted to print something in the console. So let’s go and do that. Print, and let’s call this mouse pressed. Now, let’s go to Unity. Our script is assigned, and we can play our game. We’re playing our game. We’re now on the game view. And if we click on our balloon, you will see in the console that we can now detect that.

So we are finally adding some interactivity here, and this is very exciting, because on the next lecture, we’re actually gonna make this balloon grow, and eventually disappear once it’s reached its maximum size.

Transcript Part 8

Let’s now finish up our balloon experience or interactive demo and to do our quick recap we have our balloon script and we defined two public variables. We have the scale factor and we want to multiply the scale by that number each time that the user clicks and we have the maximum scale. Once the scale reaches top value, the balloon will be destroyed.

So, if we go to our code, we’re actually not going to use the start method here so I’m gonna delete that. And what we need to do here is be able to access the scale and if we can access the scale, we need to be able to increase this value and also we need to be able to check if we’ve passed the maximum value, the maximum scale value. So, I’m writing all this in what’s called psuedocode, basically it’s describing an algorithm in plain human language, in english in this case. So, we want to access the scale and we want to increase the value of the scale and we want to check if we’ve passed that number and if so, we want to destroy the balloon. And I’ve used the word destroy for a reason that you will see later.

So, if that’s not the case, we’re not going to do anything. So, first step, how can we access the scale? If we go to Unity, you will see that the scale of an object is part of its transform component. So, we need to find a way to access our transform component and, lucky for us, in Unity there’s a quick way to access the transform component simply using MonoBehavior we have direct access to the transform component by using just simply that in transform and that gives us the transform component.

And what exactly is the transform component? If I hover the mouse, you’ll see that it is of class transform and if we go to documentation, for transform you will see that there is obviously a lot of information and understanding the transform well is one of the most important things when you’re developing with Unity. We want to be able to access the scale so if I go here through the different variables that are available, I will run into this localScale variable and this is what we need to use access and to modify the scale of our balloon. Now, the scale itself is a value of, it is of type Vector3. In the next lecture, we are covering vectors in a lot of detail, so, for now, let’s just assume that Vector3 is simply a type of object that gives us access to values X, Y, and zed.

So, that is all we need to know for now about vectors and also that if we multiply a Vector3 by a number, we’ll be multiplying X, Y, and zed. As I mentioned in the next lecture we’re gonna talk about vectors in a lot of detail. So, we have here an example of how to access this and we are actually going to combine these two operations, we are gonna increase the scale. Increase the scale. So, for that we’re gonna type transform dot localScale using autocompletion and we want to multiply this localScale, the new localScale will be the old localScale multiplied by scaleFactor. And that will work but when you have something like this, when you’re incrementing or multiplying something by assigning the result as itself times something or the value by something, you can just type a short version, which is, I’m gonna copy and paste, I’m gonna keep that there. Simply, the operation sign equal. That is the same as the above and this is just a better way to write it. So, that should already allow us to increase the size of our balloon. Let’s go and play our game and see what happens.

I’m gonna press play and if I click, you can see that the scale is being increased, and it’s being increased all the way to any number I want because we haven’t really set that maximum yet. And this also allows me to show you the game view and if we go to the scene view, we’ll select our balloon and press F to focus on that, we can actually see how it’s showing the values of game mode. If we stop the game, it will reset back to the original values and we can change its position, and change its scale, and do anything that we want but once we stop the game, it is set back to the original values.

And let’s press F to come closer, okay, so, let’s now make use of that limitation and make our balloon disappear, or destroy our balloon, if we’ve reached that amount. I’m gonna use now what’s called an if statement. So, I’m gonna type if and check for a condition. What condition do we want to check? We want to check that transform dot localScale and some number here, we need to check whether it’s greater or equal and that maximum scale. But see how it is complaining because this is our vector and we are comparing a vector with a float number. What we need to do here is access either X, Y, or zed. So, if you go to the documentation Vector3, you will see that Vecto3 has variables, it has public variables, it has X, Y, and zed. So, we access the component and since we’re increasing all of them, we’ll just pick any, X will do. So, if this is true, if that statement is true then I’m going to execute some code in here. So, I’m gonna put this in here and what I’m gonna do is just type destroy and I’m gonna type gameObject.

So, there’s a lot happening here. We’re typing destroy, which is a method that allows us to destroy an object and gameObject is, just like we have that reference to the transform, we also have the reference to the actual game object itself, so this object here. When we type gameObject in a script, that gives us access to the game object of the game. So, if I save that and I go back to the game and run the game, you will see now that as I increase the size, once I reach a certain point, it will disappear because we’ve basically killed it. If we stop the game, everything goes back to normal. So, to summarize what we’ve done here, we’ve accessed the transform component. There is a way, that we’ll cover later, to access any component within a game object, because the transform is so commonly used, it’s so important, there is this shortcut, which is just typing transform. From transform, we’re accessing its local scale and as we saw in the documentation, localScale is of type Vector3. The type Vector3 represents a value of X, Y, and zed and we do want to modify the scale in X, Y, and zed. So, what we’ve done is multiply that by a scale factor and that multiplies X, Y, and zed, all of them.

So, we can take any of them and compare it to the maximum scale that we defined. Notice how this is greater than and then we add the equal to make it greater than or equal to a certain number. If that is so, then we call this function, this method which allows us to basically destroy the object and Unity takes care of that destroying process for you. We are gonna have a challenge now. So, go to your script and add the start method back and instead of that method, create an if statement to check whether the value of scaleFactor is smaller than or equal to one. If that is the case, show a message in the console saying that the value is too small, it should be bigger, otherwise we’re not increasing the size of our balloon, we’re actually making it smaller and smaller. So have a try and then I will show you a solution.

Alright, you have your try and now let’s implement this in our code. So, I’m going to add this start method back. So, void start, that’s gonna create for me, I like leaving this private here. Alright, that is just my coding preference, my style preference, you don’t have to do anything like having that private keyword in there. So, what we said was that we were going to create an if statement, so, type if and what is it that we’re going to check? We’re going to check whether this value, scaleFactor, is less or equal than one. If that is the case, we’re going to print a message that says scale factor is too small. Let’s save that, go to Unity and let’s try this out.

So, I’m going to go here and change this to one, whoops, one, I press play and it says that the scale factor is too small. Actually, if I click nothing happens because the scale is just being multiplied by one, so, it’s not being modified. What if I set a smaller number, 0.5 and I press play?

You’ll now see that we are actually making that smaller and smaller. And just to make sure that everything works fine, let’s set it to two and now we can increase it and it disappears just like before. So, that was the solution of the challenge.

Transcript Part 9

Vectors are very important concept in game development and that is why we need to cover them. Let’s start with 2D representation of a vector. So I’m gonna draw my coordinate system here. I’m gonna have Y and X. And vectors are commonly represented by an arrow, like so. In math, a vector is a geometrical object that has both a magnitude and a direction.

So in this case here the direction is given by the orientation of the arrow and the magnitude corresponds to this length. So this is the magnitude. If you call your vector V, the magnitude is also written commonly like so with that line on top. So in order for it to have that magnitude the vector ends up at one point and that point has certain coordinates. In this case, let’s say that this point is located in one, two, so X equal two and let’s say that for Y, this is also located in two. Although to make it easier, maybe we can say that it’s located in three. So let’s say that this is one, two, three. So our vector V can be represented by the numbers two comma three.

Normally in math a distinction is made between vectors and points, because it is also how we write a point in space, a location in space. It can be in two dimensions or three dimensions. But when it comes to working with Unity, points are also treated as vectors. So when we talk about vectors we are gonna be using that for points as well. So a location, for example of an object, will be represented as a vector. So we have now this idea of what vector is and there are some operations that we can do between vectors. The first operation to talk about is addition. So let’s say that we have two vectors here so we have a vector called V and a vector called U.

How can we find the location or the result of U plus V? There is a geometrical way to determine that. I’ll explain the geometrical way, then I’ll explain the mathematical way, the actual calculation of that sum and then I’ll show you a couple of examples where that makes sense from an intuitive point of view and a game development point of view. So the geometrical way to find that result is simply grab this, let’s say we want to add this one to this one, it doesn’t matter in which order you do it. All you have to do is just draw one vector starting from the tip of the other vector. So if this vector is like that, then I’m going to draw that exact same vector and the final point here is going to be that location that will be U plus V. So this V, this is U and this is V. When it comes to the calculation that is actually very simple. In just one dimension if I tell you add one plus two you will know that is three obviously. But if you think about, if you had a coordinate system, you have one, you have two, and you have three. If I tell you this, I’m basically telling you go to one first, and now go two more. So one, two, and that leaves me in three. So it is the exact same thing that we did here. And what actually happens is that, if let’s say one of your vectors is X0 comma Y0 and you’re adding it to another vector that is X1 comma Y1 the result will simply be just adding each one of the coordinates like so.

If you are not much of an algebra person, I can easily show you with numbers. So if we need to add for example, one comma two and we need to add that to five comma 10, the final result will simply be six and will be 12 here. Because we are doing this set operation, we’re basically telling the person or the calculation we’re telling on X go to one and then go five further from that point, so that’s six. And in in Y the same thing. Now a couple examples. I’m gonna start a new page to show you those examples. So let’s start with the first one. You are located somewhere on a map. So let’s say that this is you, this is meant to be you and that corresponds to a certain position, so a certain X and a certain Y. We’re gonna call this X0 and Y0. So this is your original position and I tell you now move out one to the right and move two up. That basically means where you are you move one in this direction and then you move two in this direction. So I can make that a vector. In this case it’s a vector minus one, whoops, minus one because we’re moving on the negative direction on X and two. So I’m basically adding two vectors here and that is one example when you add two vectors and obviously very intuitive that the final result will be here.

So whenever you have an object in a certain position and you need to move it to a certain amount of meters or unit to units or feet from that position, you are basically adding vectors. So that is one example. Another example is when things are moving at certain velocity. So vectors are used obviously for velocity as well. And it’s actually better to make it with just the drawing. So if you are moving in a car in this way, a certain velocity, let’s call that velocity V, and if you throw a ball out of the window towards this direction and you throw the ball at a velocity U, the final velocity, the actual velocity of the ball, for someone who’s on the outside looking at that, it’s not gonna be just on that direction, because the car’s moving. Let’s say it’s moving really fast. The ball will most likely, will obviously not move in that direction. It will actually be a sum of both vectors. So we can draw this U vector here starting from the tip, and the final velocity of the ball, which we can call B will be this vector here. So that is another example of where you can do it.

The other operation that I want to cover is scalar multiplication. So scalar multiplication. And that is when you multiply just normal number to a vector. So you have, let’s say a vector V that is equal to one comma two and let’s say that you want to multiply this vector by a number, by a value, let’s say 10. The way to do that is actually quite simple. So if you have something like this, the final result is you simply multiply this scalar value by each one of the components of the vector. So the final result here will be 10 and 20. This process is called scaling a vector. Something we need to talk about is how we calculate the magnitude of a vector. This is the length of the segment.

So for example for a vector V, the magnitude is usually written like that. You won’t have to do this directly when using Unity, but I think you still need to be familiar with how it is calculated. And that brings us back to, back in Greece this guy called Pythagoras. I’m not sure how we pronounce it, I don’t speak Greek. But basically he came up with this theorem where you have a triangle that has a right angle, and if the two sides are A and B and this side is C, you have a relationship that always holds true. That means that if we want the value of C we actually have to do the square root in here and that gives us the value of C. When it comes to vectors, it works in the exact same manor. So if you have a vector here and let’s say that this vector is X0 comma Y0, the magnitude of that vector, so this is V. The magnitude of that vector will be the square root of both of these. When a vector has a magnitude of one, that is called a unitary vector.

So unitary vectors have a magnitude of one. You can make any vector into a unitary vector and this is also something that you won’t have to do manually in Unity, but the way to do it is that you simply divide each one of the components by the magnitude. So if you do that, the result of this, this is how unitary vector is expressed in this way. The result of this, the magnitude of that will be one. So you can do the math and you will end up with this having a magnitude of one. And why is that even important? Well there will be times when you are making games, when you are working in Unity where when you’re only interested in the direction, and then you want to multiply that direction by a certain scalar. So you could have for example, you know that the current of the ocean goes this way and so you can express that as unitary vector. And then if you know the speed you can multiply that speed by the scalar and that will give you the velocity vector. So that is one way where this can come in handy.

Now let’s have a look at how Unity implements vectors. So I’m gonna open the documentation and bring you to the Vector3 page. The Vector3 is the object that Unity uses to represent vectors. And like I said, the representation of vectors is quite broad. We are using vectors for positions and also for other values that involve an x, y, zed, component, for example the scaled or the rotation when it is expressed in Euler angles, so in an angle for x, for y, and for zed. So if you look at the documentation you’ll see that there are some directions that already come by default and these are all unitary vectors. For example, you can easily refer to the up direction, which is zero on X, one on Y, and zero on zed. So that is the up direction. These directions are gonna be used very often when working with Unity. And there are other variables that you can get like the magnitude or the normalized version of the vector, which I explained and there are some other operations that could come in handy with working with vectors.

Now what we’re gonna do is work on an example, and then we’re gonna end up with a challenge. So let’s open Unity and start a new project. I’m calling mine Vectors and Updates, because we’re also gonna cover the update method here. And I save my scene in the Scenes folder. I create an empty Scripts folder. And what I’m gonna do now is actually add an object here. It’s gonna be a cube. I’m gonna add that cube and what we’re gonna do is create a script that changes the position of this cube and when it reaches certain boundary, it goes to the other direction. So that will pre-practice the concepts that we’ve seen. So in Scripts I’m gonna go and create a new script, and I’m gonna call this Cube controller. So I’m gonna open that. We’ve spoken about Start. You know what Start is used for. This is run when the first frame is running the game, so the beginning of the game. We’re gonna delete that, ’cause we’re not gonna use it in this example.

The update method is something that we haven’t covered, but it’s clearly explained here what it does. Update is called once per frame. So in each frame of your game, the update method is executed. In the documentation the update method is under MonoBehavior, because it is the MonoBehavior class that brings this method to us, that we can use. And it is explained here as well, when it is used which is on every single frame. So it is common to add things here, that you want to check at all times. And in this case we want to be moving our cube at all times and we’re gonna do that from here. So we can access the transform of our cube, ’cause we’re gonna be adding this script to our cube. We can access it by typing transform. That gives me the transform of my cube. If I type position, that will give me a vector, a vector position. And if I want to move my position, let’s say up, so we said that we had this up direction.

We’re going to move our position up and for that we need to type in, we want to be adding something on each frame. And what is it that we’re going to be adding? We are going to be adding Vector3.up, so we’re gonna be adding that vector, which has a magnitude of one. So let’s start with that. And by the way remember that plus equal, this is the same as doing transform.position equals transform.position plus Vector3.up. So let’s start with that and you’ll see what happens. So I’m gonna drag my script onto my game object and I can see that it’s been added and I’m gonna run my game. So you can see how it went up really, really fast because we’re moving it too fast. So let’s have a speed that is not as large. And we can add that speed as a public variable and give it a default value of 0.1f, public float speed.

So what I’m gonna do now is multiply this here. And as we saw, this means that each number in the vector will be multiplied. So let’s try again. Let’s go to cube and see how we can now enter a different value here if we want and if we press play, our cube is moving up. So that works fine. Let’s add something else to this. We can, for example, check if the location is too high, we can make it go back. So we can make it bounce up and down. To implement this up and down behavior, we need to check the position of the cube. So if the position of the cube has reached a certain number, let’s say we want our cube to, if it reaches 10 in the y-axis, in the vertical axis, if it reaches 10, then we want it to move down and when it’s moving down if it reaches minus 10, we want it to move up. So for that we’ll be using an if statement, which allows us to check a condition. Before I write any code, I’m gonna actually write pseudo-code, which is instructions of what we want and the steps that we’re gonna take to get there.

So we want our cube to move up and down between values of minus 10 and the value of 10. So if we reached the position of 10 we now need to down. To be even more precise, if we reach the value of 10 and we were moving up, then we need to now move down. Also if we reached minus 10 and we were moving down, so we were on our way down, and we reached that point, then we need to move up. So now that it’s clear what we want to do, let’s actually write the code. So we’re going to write an if statement here and we’re gonna a check the position of our object. So I’m gonna type in transform.position.y.

Remember that the position is a Vector3 and I can access x, y, and zed in this way. So I’m gonna check if this is greater and equal than 10 and also if we were moving up. If we were moving up, that means that the speed is positive, because up direction is a positive direction. So I’m gonna write it in English first. I’m gonna write and speed is greater than zero. The way to represent and in code is with two signs like this. So this means and. Both these conditions need to be true in order for this code to execute. And what exactly is this code gonna do. Well if our speed was say one going up, now we need our speed to be minus one. So we need to multiply speed, whatever value of speed we have by minus one. So the new speed needs to be the old speed times minus one. And as we’ve been doing, same that we did here, we’re actually gonna write this in a better way. So this is the same as this, we’re multiplying the speed by minus one. And now our cube is going down.

What about the second condition? We can type it here. So if transform.position.y is less or equal to minus 10 and we were moving down, so and speed was less than zero. So if that is the case we again need to change direction and we’re using the same code, ’cause if the value’s negative this will make it positive. Now it doesn’t make sense to check both conditions each time because if this condition is true, we don’t really need to check the second condition. For that we can use an what’s called an else if statement, where this condition is only checked if that condition was false. Now that we’ve written this code, let’s see it in action. I’m gonna press play, which is gonna activate game mode. It’s going all the way up and all the way down. And if you monitor the values in the transform, it will show you that it reaches 10 and then it goes back down. Before we go onto challenge mode, there’s only one thing that I wanted to point out. It’s not relevant at this point but it’s something I wanna mention that will be taken care of later in the course. Basically update is called once per frame, but the frame rate of your game might not always be a constant. Sometimes if you have a very slow computer, the frame rate might actually go down, so the frequency at which this is called is not constant. And that means that this speed value actually should, we should adjust this by the time that has passed in between these iterations. But don’t worry about that now, but I just wanted to put that out there, that this is not always called at the same interval of time. So now that we’ve done this, let’s go into challenge mode and have a try at the challenge and then I will show you the solution.

All right, so the challenge starts by creating a private variable that is of type Vector3. Let me show you how you can do that. So we have this public variable here. Just create another variable, but instead of float it needs to be type Vector3 and you can call it however you want. You can call it say v. Then this next step is to add the Start method back and instantiate that variable to any vector you want. What exactly does that mean? It means that you’re adding again the Start method. Just so we have create, you have to add Start method again, and then inside of that method, let’s say that you called your vector variable v, a way to instantiate a variable is to type the equal sign, it’s assign a value basically and type in new Vector3. And Vector3 needs to a have a value for x, for y, and for zed. So you are creating a new vector in this way and you’re doing that inside of your Start method. So hope that that makes it more clear. Then in Update, you’re going to use that vector that you created instead of Vector3. So we’re no longer gonna have Vector3 here, instead you’re gonna have that vector you created. And the last step is not related to the other three steps. And it is to make the, it should just say Y here, so ignore the X part, it should just say Y. The Y hard-coded values should be public variables. So what does that mean? So we have these hard-coded values, is when you have numbers in your code, which is always undesirable. So you shouldn’t have this 10 and minus 10. It’s better to create variables for them. So you’ll have a minimum value and a maximum value and you can assign those from the inspector.

So have a try of this challenge and I’ll be right here for when you finish and I’ll show you the solution. All right, so you had a try and it’s okay if you didn’t complete because this was a very difficult challenge and I tried to incorporate a lot of the concepts that we’ve seen before. And the main, what pays off really here is just the trying aspect, because all of these things, you’ll get accustomed to them as you repeat over and over and over. Eventually all of these things will make a lot of sense and hopefully be very intuitive and easy as well. So let’s start by creating that private variable first which is of type Vector3. So I’m going back to my code and to create a private variable, I can either type private or I can not type anything. I’m gonna choose not to type anything, just type Vector3. I’m gonna call my variable vector and that’s it. That’s part one. Now part two, add the Start method back and instantiate that variable to any vector you want.

So I’m gonna add my Start method back and Unity auto-completes that for me, but I like to delete that private part and I’m going to instantiate my vector to a new vector object. So there’s new Vector3 and I’m gonna enter the value of one, one, and one. So that is my new vector that I’ve created. Part three of the challenge is that in Update use the vector you created instead of Vector3.up. So I’m gonna copy that and I’m gonna paste it here, replacing the Vector3.up. And we can see now actually in Unity, we can see what will happen. We will get that happening. Last part of the challenge. Make both the range in X and Y public variables, so ignore the X part, just the Y part here. Sorry about that. So the Y part is this one. And I need then two public variables. One is the minimum Y and the other one is the maximum Y. And I’m gonna give this default values that we already had before. You don’t have to give them default values, that’s just an option. So instead of having that minus 10, now I have that variable. And instead of having 10, now I have my variable here.

The process of cleaning your code in this manner, of organizing your code, is called refactoring and it’s a very important process. So now our code is more clean, because it doesn’t have hard-coded numbers. And if we go to Unity you’ll see that your cube, once this refreshes, it has the values that we enter and we can obviously enter this, so I can have a much more tight range, and I can play my game and I can see what happens now. So we have that going now and that’s all for the challenge and that is all for the lesson. And feel free to come back to this lesson if you need a refreshment on vectors or any of these topics.

Transcript Part 10

In the following videos we’ll be creating our 3D platform for our game. But before we jump into coding and building and using Unity, there is a concept that I wanna cover and it is something that we should be doing before writing a single line of code in our game. Which is, a game design document.

Game design documents are used all over the game industry from big studios to indie developers. And what they are is a very short document that describes the main concept of your game. There’s not a single template for these sort of documents. So it really depends on the scale of the project and whether it’s something just for yourself, or you’re working with contractors, with a team, or in a large organization. But, some things in general you should include have to do with the concept of your game, what your game is about, what the main game player or game mechanic is. And also, describe some of the assets you will be needing. There is a very good article in that link which is an article on Gamasutra that describes the anatomy of a game design document. But in my opinion that is more for the corporate world. It’s still interesting to read and can give you some things depending if that is your case. It might be very useful but in a smaller scale you want to do something a little bit simpler. And again there’s not a single way of doing it.

So what I’ll do now is just the sort of document that work well in my case. So I’ve already created a template for our document. The main concept of our game is going to be a 3D platform game. Kinda like Mario where you run around collecting coins, avoiding enemies and you have to reach the goal in each level. So, our game will be built for desktop. Which includes Windows, Mac, and you can build for Linux as well. So Unity allows you to build for all the different desktop platforms very easily. And now I’m gonna describe a little bit more of the concept but not using words but using sketches. Which is what really works well for me. The level of detail of the sketches will depend, obviously, whether you are sharing this with someone else, with contractors or team, or it’s just for you. So, my concept, what I have in mind is having very small levels that are kinda like platforms.

The art is floating in this space. In those platforms there is a player which is gonna be like cube with a face. So that will be our player. And forgive me for my horrible cubes and bad lines. So the player move around, it will be jumping, and it will be collecting coins. Which will be your scores. You’re gonna see your score up here. And it’s gonna show you how many coins you’ve collected. It’s not just gonna be flat like that, but there will be platforms that you can jump into. And in each level is going to have a goal, eventually. Which will be like a portal, like a sphere. Levels are also gonna have enemies. These are gonna be bad ass enemies that move up and down. They just move up and down, that’s all they do. So they have a certain range and they move up and down. So you have to avoid them so that they don’t crush you. You will lose if you run into an enemy or if you fall off then you lose, game over. There will be levels that are sort of like these and other levels can have multiple platforms like that. And the camera, the camera will follow the player as the player moves within the level. So the player can move in this direction and the camera will follow.

You can also extend the game to make it so the camera follows you in any direction. And there will be all sorts of platforms with enemies and lots of coins. So, this, I think is enough to give us an idea of what this game will be about. And what I’m going to do next is just copy this thing into my document. So you can use whatever clipboard, or paint, or anything. Just grab the image and then put it in here. ‘Cause these things need to have sketches and images. And obviously if this a more, if you need to communicate this with someone else you might want to do something better. I usually work with very simple images with my team. So this can do, then I can describe my game more if I want. Some of the game mechanics that we mentioned include; player will be controlled with the arrow keys, and there will be jumping. So those are the only things the player can do. Game over if you run into enemies or fall off.

Which also brings me to, I can describe a little bit of the UI. There will be a Home screen. There will be a Game Over screen. We’re going to be showing, we’re gonna collect coins and show the score. And I also want to have a high score in my Game Over screen. It is obviously multilevel. So you find a goal and move onto the next level. And we are going to play a sound when collecting coins. I think this describes the main thing. Enemies will move up and down. And there will be platforms on different heights that you can jump into. So, as you can see this is a very, very simple description of the concept of the game, but it already gives me a starting point. And these documents are usually updated as well. As the game makes progress. Now what assets are we going to need? We are going to need some models. So we are going to need our model for the player. So I’m gonna write, subtitle, models. We’re gonna need a model for the player, for the enemies, probably something for the terrain. And I’m gonna write the coins and the goal.

But in reality we will be using Unity’s primitive shapes for this. That is something you can decide as you go. Initially it was a requirement to have a model for those things. Also, what about textures or images? I will want to have some sort of rocks background. That I can put in my ground and also in the bottom of the game. Then I also want, what about audio, I want the coin sound. Coin collection sound. I think that’s all I want. Then for the UI, I wanna have a cool pixel art font. And I also want a background for the Game Over screen and Home screens. So I think that is all that we need. And in this manner I can always add more things if there’s something that I didn’t think of. I can add it later. Okay, so now we have a clear idea of what we need to build. And this can obviously be communicated with other people. The very next step, because some of these things might take time.

You might be giving these model jobs to a contractor online, or a friend of yours, or someone else, or you have to do it yourself. But you also wanna work on say, the game mechanics. What you can do next is a prototype. And that’s what we’ll be doing in the next videos. Which is when you are creating the game mechanics before you have the assets. So I wanted to do it that way in this course. So you could see that process and see how it is when we add the models later. Which we will. Alright, so that is the basic of game design documents. And now, I have an open ended challenge for you. Which means a challenge that you have to complete and that we’re not going to be showing you because obviously it’s your game idea.

So, what I would like you to do is to make a game design document of your game idea. And if you don’t have a game idea, come up with one. It can be similar to existing games. If you can’t come up with one, just pick your favorite game and make a game design document for that game. So that you can mentally deconstruct how the game was built. And besides thinking of the finished game, I’ll also want you to think of what would be the simplest possible implementation of your game idea. So if you wanna make a game that has all this class of characters and enemies. Could it work with just one type of character? One type of enemy? Could you implement that? Would that make it easier for you? Because the way to reach higher goals when it comes to projects is to make them into smaller chunks. And then smaller chunks are much easier to work on. And it’ll take you, maybe, just a few days to do a simple prototype.

Where as a full game could take months because of all the assets. So, I really want you to start getting into the mindset where you can work on your ideas with just the minimal elements. We’re using default assets. Using whatever comes in Unity or free things from the web. Just to get things going. And then you can make things more complex. As you go, as you get some feedback from players or from friends or testers of your product. So, that is all and I will see you in the next video.

 

Creating a 3D Smash Game in Unity – Part 1

Introduction

If you’ve ever had a look at the mobile games that are currently ranked at the top of the app store, you might find one called Smash Hit. The basic idea of the game is that the camera is constantly moving forward in 3D space and it is the job of the player smash these panes of glass that are in the way of the camera. The player does this by spawning steel balls at the place where they touch the screen. When the steel ball collides with the pane of glass, the glass shatters. This is a pretty fun game but instead of going and downloading it, let’s create our own version (’cause that’s what true game developers do).

Configuring the project *SUPER CRITICAL!*

Open up Unity and click “create”. This next step is very important, if you fail to do this you may end up halfway through this tutorial and find out that you have to start over (like I did when I was creating this project). Name your project and then change the Template to “Lightweight RP”.

Image may be NSFW.
Clik here to view.

This means that you can use Unity’s Scriptable Render Pipeline to make custom shaders for your objects (which we will be doing in this tutorial). If you have never heard of SRP (Scriptable Render Pipeline), you can check out this tutorial on the Game Dev Academy that goes into much more detail, https://gamedevacademy.org/supercharging-materials-with-the-scriptable-render-pipeline-in-unity/. Now that you have performed the very crucial step, let’s go onto creating the basic mechanics.

Required Assets

Here is the link to the assets that are going to be used, Assets . You can make these your self in whatever program you chose (I used Blender for obvious reasons).

Creating the first mechanic: Ball Spawning

Before we start destroying things, we must first create the thing that is going to destroy the other thing. If that sentence didn’t make sense, I have utilized my skills as a graphic artist to illustrate what we are going to be doing:

Image may be NSFW.
Clik here to view.

Which means that in this section, we are going to be making this guy:

Image may be NSFW.
Clik here to view.

Let’s get started by first explaining what you see in the project panel.

Image may be NSFW.
Clik here to view.

This may seem cluttered but we need it to be here when we start adding shaders and such. Go ahead and create a new folder called “Prefabs”.

Image may be NSFW.
Clik here to view.

In the Scripts folder, create a new C# script called “CameraCharacter”.

Image may be NSFW.
Clik here to view.

In order to avoid creating more scripts that necessary, we will create one script for our camera (the camera is where we will be spawning balls anyway) and from that script, we will incorporate all the things that we wanted (like ball spawning, continuous motion forward, etc). Go to the Scenes folder and create a new scene called “Scene1”.

Image may be NSFW.
Clik here to view.

Drag the “CameraCharacter” script onto your camera and let’s get started coding.

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Spawning a ball at the place where the player touches is probably the trickiest part of this project. There is a little bit of fine tuning involved in order to get it to work just right. The first thing we need is a game object to spawn and a float variable that determines the force to which the object is spawned:

public class CameraCharacter : MonoBehaviour {

      public GameObject ball;
      public float ballForce;

void Start () {

Then, in the update function, we first find when the mouse/screen (this game will work on mobile) is touched and then spawn the ball, as a local game object, at the camera’s position. And finally, this part adds some force to the Rigidbody attached to the ball:

if (Input.GetMouseButtonDown(0))
        {
            GameObject ballRigid;
            ballRigid = Instantiate(ball, transform.position, transform.rotation) as GameObject;
            ballRigid.GetComponent<Rigidbody>().AddForce(Vector3.forward * ballForce);
        }

Let’s set this up by creating a sphere with a Rigidbody. Scale this sphere so that it is half of its original size. And then create a prefab of this by dragging it into our prefabs folder.

 

Image may be NSFW.
Clik here to view.

Assign the prefab to the new “Ball” field on the CameraCharacter script and the hit play.

Image may be NSFW.
Clik here to view.

You’ll see that you can click and spawn a new ball.

Image may be NSFW.
Clik here to view.

The only problem is that you can’t spawn it at the mouse position. To do this, it involves (what I think) is the only slightly confusing part of the script. We create a new Vector3 that utilizes a couple of local floats which log the mouse position. Then we use a method in the Camera class that converts the screen coordinates to world coordinates. And then we finally set the Z-axis value for the method to be an attribute of the Camera class, called “nearClipPlane”, plus a float value that offsets it forward slightly. This is what the entire code looks like:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraCharacter : MonoBehaviour {

    public float spawnHelper = 4.5f;
    public GameObject ball;
    public float ballForce = 700;

    private Camera _cam;


    // Use this for initialization
    void Start()
    {
        _cam = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {

        //Local floats
        float mousePosx = Input.mousePosition.x;
        float mousePosy = Input.mousePosition.y;

        //Confusing part :-)
        Vector3 BallInstantiatePoint = _cam.ScreenToWorldPoint(new Vector3(mousePosx, mousePosy, _cam.nearClipPlane + spawnHelper));


        if (Input.GetMouseButtonDown(0))
        {
            GameObject ballRigid;
            ballRigid = Instantiate(ball, BallInstantiatePoint, transform.rotation) as GameObject;
            ballRigid.GetComponent<Rigidbody>().AddForce(Vector3.forward * ballForce);
        }
    }
}

I hope some of what is going on makes sense. If it doesn’t, just think about it, you’ll understand it, I promise.

With that said though, you’ll now see that it will spawn a ball at the mouse’s position.

Image may be NSFW.
Clik here to view.

You can tweak the “ballForce” and “spawnHelper” to help you understand what is going on here.

Image may be NSFW.
Clik here to view.

Creating the second mechanic: Breaking Glass

It is now time for the fun part, DESTROYING STUFF!! Seriously, you’re not a real game developer until you take some pleasure in seeing things break apart and scatter all over the place. With that said, there are a couple ways we can go about breaking things: taking a game object and having a script create fractures, or create the fractures yourself in a third-party program (i.e. Blender since you are an indie developer). I chose the latter and have done all the hard work for you on this part. If you look in the asset pack, you will see there are three cubes.

Image may be NSFW.
Clik here to view.

Each of these cubes has been fractured and brought back together so that it looks like a complete object when in reality it is a bunch of little pieces. The way this is going to work is that as soon as the ball hits a piece of glass, we spawn one of these. Pretty simple. Create a new folder called “Models” and import the fractured glass.

Image may be NSFW.
Clik here to view.

If you open one of the objects, you will find a complete cube.

Image may be NSFW.
Clik here to view.

This is important because this cube has the exact dimensions of the fractured glass. Drag the model into your project and delete everything except this cube.

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

Add a Box Collider, make it a trigger, and make it a prefab called “Glass”.

 

Image may be NSFW.
Clik here to view.

Next, we create a new script (in our Scripts folder of course) called “GlassShatter” and assign it to the glass prefab.

Image may be NSFW.
Clik here to view.

Now we need to drag in each fractured glass model (this part is tedious), delete the complete cube, assign a Mesh Collider (if it doesn’t already have one, and a Rigidbody to each fractured glass piece, and then make a prefab with this labelling convention: “Glass1(broken)”.

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

You should now have three prefabs labelled “Glass1(broken)”, “Glass2(broken)”, etc.

Image may be NSFW.
Clik here to view.

With the editor stuff out of the way (at least most of it), we move on to Visual Studio to start crafting our script. Open up “GlassShatter” and create a new array of Game objects called “shatteredObject”. Then, we use OnTriggerEnter to determine whether or not the ball has overlapped, if it has, we instantiate a random game object from the “shatteredObject” array and simultaneously delete ourselves.

public class GlassShatter : MonoBehaviour {
    public GameObject[] shatteredObject;
    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("destructive"))
        {
            //picks a random gameobject in the array
            int objectIndex = Random.RandomRange(0, shatteredObject.Length);
            Instantiate(shatteredObject[objectIndex], transform.position, shatteredObject[objectIndex].transform.rotation);
            Destroy(gameObject);
        }
    }
}

This script requires that the ball posses a tag with the label “destructive”. Let’s go ahead and select our ball,

Image may be NSFW.
Clik here to view.

create a tag called “destructive” (make sure it is exactly how it appears in the script),

Image may be NSFW.
Clik here to view.

and then assign it to the ball.

Image may be NSFW.
Clik here to view.

We also need to populate the “shatteredObject” array in the editor. Set the range to 3 and drag in each “Glass(broken)” prefab.

Image may be NSFW.
Clik here to view.

If you don’t already have one, drag into the hierarchy a “Glass” prefab and fire a ball at it.

Image may be NSFW.
Clik here to view.

If everything was done correctly, it should shatter into a million pieces. Congratulations! Now take a moment and just appreciate the destruction you have caused.

Creating the third mechanic: Moving Camera

The third, and probably most straightforward, part of this tutorial is the moving camera. The way we do this is by using something called a Character Controller. The reason is that we can easily move the object in code (literally just one line) and it has physics interactions. So go to your camera and create a Character Controller component.

Image may be NSFW.
Clik here to view.

Then go back to your CameraCharacter script and let’s make this thing move!

Image may be NSFW.
Clik here to view.

I’m just going to give you the final script (which means we won’t have to come back to it in this tutorial series) so that we can get past the coding and onto designing.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class CameraCharacter : MonoBehaviour
{
    public float speed = 1;
    public float incrementFactor = 0.02f;
    public float spawnHelper = 4.5f;
    public GameObject ball;
    public float ballForce = 700;
    public GameObject button;

    //We use this when we implement UI
    public static bool camMoving = false;

    private CharacterController cameraChar;
    //A boolean whose value will be determined by OnTriggerEnter
    private bool collision = false;
    private Camera _cam;


    // Use this for initialization
    void Start()
    {
        cameraChar = gameObject.GetComponent<CharacterController>();
        _cam = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("Speed is " + speed);

        float mousePosx = Input.mousePosition.x;
        float mousePosy = Input.mousePosition.y;

        Vector3 BallInstantiatePoint = _cam.ScreenToWorldPoint(new Vector3(mousePosx, mousePosy, _cam.nearClipPlane + spawnHelper));

        //This checks if we have collided
        if (!collision && camMoving)
        {
            cameraChar.Move(Vector3.forward * Time.deltaTime * speed);
            //This is so that the camera's movement will speed up
            speed = speed + incrementFactor;
        }
        else if (collision || !camMoving)
        {
            cameraChar.Move(Vector3.zero);
        }

        if (Input.GetMouseButtonDown(0) && camMoving)
        {
            GameObject ballRigid;
            ballRigid = Instantiate(ball, BallInstantiatePoint, transform.rotation) as GameObject;
            ballRigid.GetComponent<Rigidbody>().AddForce(Vector3.forward * ballForce);
        }
        
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("glass"))
        {
            collision = true;
            Debug.Log("Collided with glass!! Man down!!");
            camMoving = false;
            button.SetActive(true);
        }
    }
    public void StartCam()
    {
        camMoving = !camMoving;
    }
    public void Reset()
    {
        SceneManager.LoadScene("Scene1");
    }

}

 

There is a lot here that we won’t be using in this tutorial. But, notice the “OnTriggerEnter” method will check if the overlapped game object posses the tag “glass”. You probably know what to do, go to your glass prefab,

Image may be NSFW.
Clik here to view.

create a new tag called “glass”,

Image may be NSFW.
Clik here to view.

and then assign it to your glass prefab.

Image may be NSFW.
Clik here to view.

The idea of the collider on the camera is that if the player fails to break the glass in front of it, the game should restart or something. Now, here is where you, the game designer, gets to make a decision: do you assign this tag to your “Glass(broken)” prefabs (knowing that if the camera touches the shattered pieces it stops moving) or do you exercise mercy on your players and let them hit the broken pieces all they want? It’s up to you. Also, your camera needs to have a Capsule Collider that is a trigger and sized appropriately (also your decision on the correct size). I recommend making the Character Controller’s “height” and “radius” values near zero, otherwise, you might get it “riding-over” the top of the broken pieces.

Image may be NSFW.
Clik here to view.

With all those things done, and everything tweaked the way you like it, let’s drag in some Glass prefabs and enjoy our moving camera while smashing through some glass!

Image may be NSFW.
Clik here to view.

Conclusion

Whew! Congratulations on getting through the tutorial! I know it doesn’t seem like much of a game, but in the next tutorials, we will be adding shaders to supercharge our game objects, a UI system, and other things to basically make it feel more like a game. We have done most of the hard work, so we shouldn’t have to do much more coding here on in. I hope that what we have done with creating mechanics first, and seeing what those mechanics can do, will make you want to continue in this tutorial series. In the end, you will have a complete game equipped with a menu and a level, all of which I encourage you to modify and change to match whatever look you are going after. With this in mind, I’ll see you in the next tutorial.

Keep making great games!


Web Class: Using Python for game development with Pygame

Transcript Part 1

Hello and welcome to the course. My name is Pablo Farias Navarro. I’m the founder of Zenva. In this course, you’ll learn how to code in Python by creating this simple game using a library called Pygame.

The game that you’re making is similar to the Atari classic Frogger where you have to move a character across the screen avoiding the enemies that are moving and trying to get you. The main goal of this course is for you to learn the basics of Python programming. We are assuming that you have no prior programing experience in this course so we’ll cover everything from scratch and what makes this course very unique is the fact that a lot of these concepts are gonna be taught in a very visual way because you are putting all of these things in practice as you ware building the game that we just saw. The author of the course is Max Schallwig, Python programmer and online trainer and the library that we’ll use as I said is Pygame.

Pygame is an open source library for the Python programming language which allows you to create two-dimensional games. We’ll cover the installation of this library and of Python in the course.

Now, online courses are an amazing way to gain new skills. I watch online courses all the time myself and what I really like about them is that you can go back and rewatch the lessons. In case you are not sure about something, you can download the course code, that includes the assets of the projects as well and what works best when it comes to learning for a lot of people is to code along, basically have the code editor open and type what you’re seeing on the screen and trying to get things working as you go. Other people prefer to watch all the videos as if it was a Netflix show, we have people that do that, so it’s really up to your learning style and that is the great thing here is that it’s completely up to you how you want to engage with this course.

What we’ve seen from a lot of students is that those who plan for success will make a weekly plan on when they’re gonna watch the lessons are the ones that tend to finish them, so keep that in mind and just a few words about our company. We’ve taught programming online to over 200,000 students since 2012. Many of these students have used what they’ve learnt to improve their careers, start companies, publish games, so it’s an open invitation for you to really engage with the content of this course and to get the most out of it. Now, without further ado, let’s get started.

Transcript Part 2

Hey everyone. So, in this tutorial, we’re gonna learn all about the basics of python, and then we’re gonna go on and we’re gonna learn how we can create a simple game using Pygame.

So, to get started, first of all let’s see how we can download python. Now Python is a scripting language and it’s much nicer and easier to use and to read then some other languages are like C or C++ because it’s much more user friendly and it also works on a higher kind of level. So to get Python, we’re gonna go to “python.org” and on this website here, we’re just gonna look at the downloads tab. We’re just gonna click here.

Now usually if you go to downloads the website actually automatically detects what kind of operating system you’re using, so in this case for example, mac. If it gets it wrong, you can just go here to the download section and just choose whichever platform you’re using, or you can also choose it down here.

Now we’re gonna be doing all of our coding in Python 2.7. So to get that, we’re gonna click on this link here that’s gonna download Python 2.7 for us. And then we’re just gonna save that file, and we’ll be letting it download in the background in a second. So once your download is completed, we can go over here and head into the download section and just open up the downloaded file. Then we need to continue through here and also go through the read me and make sure you understand this, and afterwards we’ll continue again going through the license now, and we have to agree to the license.

Then we have to choose our destination, so I’ll just install it here on my local hard drive. It’s not a very big file so nothing to worry about here. Then we’ll click install and I’ll just put in my password here and there we go, we’ll let the installation run. Shouldn’t take all to long and… Well yeah, let’s wait for it to finish. And once that’s done, then we’re pretty much ready to go and start programming in Python.

So that’s pretty much it for the installation part. So here we go we’ve just finished the installation. Now we can close this. We can also immediately move this to the trash. We don’t really need the install anymore. We can directly clear that and yeah, that covers it. So now we’ve got this great Python environment downloaded that we can use to write code in and execute all of our code. So to open up our idle environment, we can just go into our finder, and for me, my environment is in this Python 2.7 folder that’s down in the applications.

So that’s where my Python package is an then you see here we have this idle link and where this shortcut and we can just double click this to open. If you’re not really sure where it is, so you should probably just go into the applications and look for your Python 2.7. Otherwise you can also use the Mac Spotlight and just search for idle here. And then I’ve actually got the 3.5 version installed too, but make sure that when you scroll down, you look for the version and it says version 2.7 here and then you can open that and we can get started with that. So this is how the coding shell is gonna look like for us.

To actually make a program, we can go here into file and create a new file, and now we have a new Python file here that we can later code in that we have to save as a Python executable. And we can also use that later on to just run the module here on the run module and everything will be ran in our Python environment. So that’s how we’re gonna go ahead about executing code but we’ll see a lot of that in the later tutorials too.

Hi everyone, what I’m gonna do now is show you how to download the version for windows. So I’m gonna go to downloads and I’m not gonna click on download the windows version that it says here. Instead I’m gonna go into Windows, and I’ll be presented with a list of versions. I’m gonna scroll down until I find a 2.7 version. The highest 2.7 version. And from all of these, the one I’m gonna choose is the one that says “x86” which means 32 system, 32 bit system.

Even though my computer is a 64 bit computer, we’re still gonna pick that one and I have to tell Google Chrome yes I want to download that. It’s downloading. The reason why we’re picking the 32 bit is because Pygame, the game library that we’re using in this course doesn’t support the 64 version of Python. So that’s why you have to pick the 32 version of Python here. So it’s downloaded. I’m gonna go and click “open” and run this installation. So I can choose where I want this to be installed. I’m just gonna click “next”. This will install the software.

Okay, so the installation has completed. I’m gonna click on finish, and now if I go to my start menu, I can type “Python” and that will bring me the idle which is the same that we use so on the mac installation video. So now let’s continue and start learning how to code in Python.

Transcript Part 3

Hey, everyone. It’s Max and welcome back to our Python tutorial. So, in this tutorial, we are going to learn how we can set up our Pygame instance. How we can create this Pygame to appear on the screen so that we can start doing cool stuff with it.

Alright, so, the last tutorial we downloaded and installed Pygame, and now let’s go ahead and actually use it. So, we are going to go back over to our coding environment, into this IDLE here. And actually just deleted the code that we used before, so that we have this blank space to work with. But we are still using this new file. If you want, you can just open a new file up like this, and then just start coding in here, as long as you remember to save it as a, or using a .py extension. Yeah, I just cleared my old file, and then we will just continue on like that.

Alright, so to actually use Pygame, what we are going to do is you are going to need to “import pygame.” So, what does that mean? Well, we’ve downloaded Pygame and we’ve, it’s now like an extra extension that we have to Python. But it’s not always included. And the reason for that is because if you download a bunch of modules and you have to import them all the time, your files are just going to be huge and everything is going to take up a lot of memory, just because everything needs to be imported all the time.

And there are hundreds and hundreds of modules if not enough that all since that you can have and download and so you really don’t want all of that space taking up everything. So if you want to use an extra module, you are going to have to, here you are going to have to import it. And if you are importing something, you also want to make sure that you’ve downloaded it and installed it beforehand. Like we did with Pygame.

So, what we are doing here, is we are using the import cue word, and then we are typing in, or we are putting in here the name of the module or the package for the library or framework, whatever you like to call it, and that we want to import.

And so what’s happening is Python goes and it looks up the modules or what the libraries whatever that are available and it searches for the Pygame library, and if it finds it, it imports it and it makes all the features contained in Pygame available to us. So that’s what we are doing with this “import pygame.” Alright, so now that we have that out of the way, now that we can actually start doing stuff with Pygame, let’s look at how we can do that. So, to access things from Pygame, we actually always have to go and type “pygame” first and then we put dot, and now we can start accessing stuff from Pygame.

So, the reason that is like that is because first we imported Pygame, and now, every time we want to use something from it we have to access that library, so we have to go into the library and then we put a dot, so that indicates we want to go into the library that this is not just a variable name or something, and now once we do this dot, we can now access all of the stuff inside this library.

Now if you want to know everything that’s available inside this Pygame library you can look at the documentation, but otherwise you can just follow along with this tutorial and I’ll show you some of the cool stuff that’s available inside this library that we can use to start off with.

Alright, so the first thing that we are going to need to do to actually set up our Pygame system is we are going to need to go into the Pygame library, like this, and we are going to need to call the init method. So, what we are doing here is we are going into this Pygame library and we are calling a function called “init.” So, we see that it’s a function because it has the open and close parentheses, it doesn’t take any arguments in here, that’s just law there are no defined arguments, there are only optional arguments, so doesn’t take anything in here, we don’t need to pass anything. And what this does is going to initiate everything for us. It’s going to make it ready for us to use. So we need to do that at the very beginning each time we want to use Pygame. It’s also called a method, just because it’s part of this library and there are lots of classes and objects and stuff contained inside, so pretty much big bundles that all have their own attributes. But we are going inside here, and we are accessing this, and we are pretty much just calling this function.

So we’ve seen a function before, the function that we created was the add one, where we put in a number and it gives us back a number that adds one. This function here, or this method, is a little bit more complicated, but what it really does is it just sucks everything up for us and make it ready for us to use. Alright. So the next thing that we are going to need is we are actually going to need a screen to do stuff on. So we are going to need to define our window. So we are going to create a “screen” variable, and we are going to make this equal to the following, and so now, now we’re going to learn how we can create this screen.

First of all we’ll need to go into Pygame, so that’s where we get our screen from. And now we’re going to access something called “display.” What display is, is display is an object inside of Pygame. And now, what is an object? An object is pretty much this big structure that has a lot of functions associated with it, and it has also its own attributes, and so its own kind of aesthetics it has its own variables inside, and so it brings a lot of features with it. In this case, it’s a display and so the object display pretty much contains everything that you’d want in the display or that you want to do with the display. So what we’re doing is we’re going into Pygame and in Pygame, there’s this object called display, and display itself has a bunch of methods or functions so functions are methods, and they’re called methods just because they’re part of this object, display has a bunch of methods that we can use and it also has some attributes that we can access as well. But what we want to do is we want to access one of the methods and specifically we want to access the method of display, which we do by adding another dot here, so the dot means we’re going to go inside here and access one of its methods or attributes.

So the method we want to use is called “set_mode” like this. And so, we open and close parentheses because it’s a method, and it can take input, and the input that we’re going to provide it, is just going to be the size of the window that we want. So for example, we can use the size, maybe, 900 by 700 or something. So that’s going to be the size of this window that we want to create. So what we’ve done is we’ve gone into Pygame, then we went into this display object here, so this display object self, you can kind of imagine of having many features that you can use that all work around this same display principle, and we use this set mode method that’s contained inside, and we gave it the input of 900 by 700. And all this is going to do for us is going to create a screen, so that’s also why we saved it in a variable called the screen, because it’s the best fit name for that. It’s going to create a screen the size 900 by 700 for us.

Alright, good. Now we’re going to look at how we can keep this screen going so, one thing we can do for example right now, is we can start running our module and we’ll have to save it first. So we run it, and we see this thing pop up on our screen. And so this is the screen we’ve created. What we see, first of all is, I get this spinning ball, this spinning beach ball, I’ll explain in a second why. But we also see that we have this screen created here, this screen created here. Now the reason that my screen is only a quarter of the size of my window is because my Mac is using this retina display and so the resolution is a little bit off. So that’s why by me it’s only taking up a quarter of the window, usually you get the full kind of window taking up by this black screen here, but just because of the resolution of my computer and everything, everything is a little bit confused. We only have this smaller black screen going on right here.

So if that’s the case for you, if you also have a built-in retina display or something, then you may expect this but otherwise you know, everything should go fine, and this is not really a big of a deal, the only thing that maybe a bit tedious is that this window here is a bit smaller. There are ways to fix it but we would have to use another module for that, so we’re not really going to go into that, that much in detail. Now, the reason I’m getting this beach ball here is because our Pygame pretty much updates continuously, and there are a bunch of events coming in, and now these events, there are so many events now that I’m not doing stuff with and it’s pretty much piled up and there’s too much for my computer to handle right now for this Pygame program to handle right now so it’s lagging.

So we’ll look at in the next tutorial how we can get around that and how we can make sure that we don’t start lagging like we do right now.

Transcript Part 4

Hi everyone, it’s Max. Welcome back to our Python tutorial. Let’s continue on where we left off last time which was we created our display but it was start lagging a lot so now we’re gonna look at how we can fix that.

And now what we’re gonna do is first of all we’re gonna create a variable and we’ll call it just finished or something, and this variable is just gonna keep track of if our game is finished or not. So first we’ll just assign it the value false. Quick introduction to Boolean variables, we’ve seen that a little bit before, we had conditions, for example we checked, when we checked zero is less than ten, this gives us a value of true, and then when we checked ten is less than ten, this gave us a value of false. So we saw that when we did while loops but let’s just talk about it for one more minute or so. So what we get here with this Boolean variable is that we have here an option of true or false. And depending on what the state of our game is, we can either change this value to be true, or we can change it to be false.

Now technically you can also think of it as numbers too, so like zero and one or something like that. But to make it a little bit more obvious, it actually has its own values of just being true or of being false, so it can be in two states, our values can either be true or they can be false. And so that’s what’s going on with these Boolean variables. And so we can check, as long as something is false, then you know we ought to do it, or we do it and as soon as it turns true, as soon as our state changes, then we’ll do something else or something like that. Alright, so let’s start off and let’s start dealing with these events that piled up. And the way that we’re gonna do that is first we’re gonna start off with a while loop. And we’re gonna say, while finished is equal to false.

So what does that mean? Right now, we’re just saying, while our game is not finished, like this. Make this a little bit bigger so that we can see that. So what we’re saying is, while and then while our value contain is finished is false, we’re gonna do the following. What we mean with this is while our game is not finished, because once our game is finished, and finished is gonna take on the value true. Alright, so, we’re going to the next line. Make sure that we indented it to be inside of this while loop, and now we’re going to use a for loop. And we’re gonna say, for event, so event is going to be our variable name that we’re creating here, our looping variable name, in the following, we’re going to go, and I’ll just write this out first, and then I’ll explain what exactly is going on. So we’re going to pygame and now we’re going to go into the event object, so an object that pretty much takes care of all the events that are going on. And I’ll also explain what events are in a second.

And what we’re gonna do is we’re gonna call the get method. And then we’re just gonna have a colon here, and we’re gonna do the following. So what this is doing, every loop is, it goes into pygame, into the event object and it calls this get method. And this get method pretty much gives us all of the events that have happened since the last time we checked. And we go through all of these events one by one, so event takes in a value of each of these events one by one, and we go through them individually. Then we can do things with certain events. We can also later check for certain events, or we can do other things, just using these events that we’re getting from, getting the events from this event object here. So every time something happens in the game, or in our pygame, or every time something even doesn’t happen every time there’s an update, new events are created.

And so to make sure that they don’t pile up, we’re gonna get them continuously, and we’re gonna loop through them, and we’re just gonna deal with them and even if we don’t do anything, that still deals with them because we at least checked it. Alright, so that’s what we’re doing right now. We’re just gonna go for event in pygame.event.get, and all that we’re gonna do right now is we’re going to pass. Now what pass is, pass is just a special kind of keyword, so we can see that it’s color coded, and pass means don’t do anything. And so the reason that I put in here a pass, rather than nothing, is because as soon as I have a loop created and a colon and stuff, Python expects something to be here, I can’t just start on a next line and type more code, Python expects at least one line of code in here. And if I don’t wanna do anything, I’m just gonna put pass for now, so that I don’t really have to take care of any of this stuff and I can just go through it and go over and over.

So that’s what we’re gonna do right now, just to make sure that we’re not really lagging and just that we’re taking care of all of these events. And then we’ll add to that a little bit more in a second. So let’s just run this first. Here we go. And we see that, even if we wait a little bit now, I’m not getting this spinning ball of death anymore, the speech ball or whatever it is that you’d like to call it.

Alright, good, so, now that we’ve got this going, let me just close this here, and in the next tutorial, we’ll continue on about how we can extend this just a little bit more.

Transcript Part 5

Hey, guys; it’s Max, and welcome back to our Python tutorial.

So, you may have also noticed that at the state we were in the last tutorial, if you close the X window on the pygame window that popped up, nothing would actually close. So we’re gonna take care of that right now. And instead of just passing here and not doing anything, we’re actually gonna look at this event and see if, you know, a certain condition is fulfilled. And we’re gonna do this through learning a new thing, which is called an if statement; and while I can put up here the general structure, so if and then we have this kind of statement/condition. If the statement/condition, then; or usually if the statement/condition is true, and then we do the following here. So just, just some code; so that’s the general structure, but let’s just see that in action.

So what we can do, for example, is we can check if, and then what we’re gonna do is we’re gonna go into our event; so for each of these events that are being created here, we’re gonna look at each individual event that we get. So remember when we did the four, the number in the range, we got the numbers zero, one, two, three, four, five, six, seven, eight, nine? Here we’re getting similar things for events; but instead of getting numbers, we’re getting individual events. So we can access each event, and each event that we get from calling get, the get method on this pygame.event object, each of these events actually has its own attribute called a type.

And so you can just imagine this attribute as being a variable that’s contained inside of this event. So this event itself has many, many properties; and one of the properties that this event has is a type, and so that’s what we’re accessing right now, the type of the event. And, again, we use this dot here to indicate that we’re going inside of the event to access its property called type. So now that we have the type of the event, and the syntax may look a little bit confusing and stuff; and you’re like, well, how do you know that? Well, you can never really know; so the only way that you really know what the event contains in everything is just to look at the documentation. But if you don’t wanna read through all the documentation just getting started, you can also just look at tutorials or like we’re doing here. I will tell you some of the properties that are contained inside of these things.

So you can never really just guess and know. You just kind of have to look it up in some way or another; and in this case, I’m telling you that type is one of the properties that is contained inside of event. That’s just the way that the creators of pygame created this event object. It contains a property called type, and so that’s what we’re gonna be using. So what are we gonna do here? We’re gonna check if the event type is the same as, and now we’re gonna look at a special event in pygame called quit; and then we use the colon here. So let me just explain what we’re doing here. We’re going into the event, and we’re looking at the type of the event.

So what kind of event is it, pretty much; is it, so you know, is it a move, is it a (mumbles) jump, you know, change color, like, all of these things. That’s kind of what you can imagine this as. What kind of event is going on; what happened? And we’re looking at if the event is, well, like an exit event or like a quit or we wanna close the window or something like that; and to check that, pygame has actually created a quit method. So, yeah, so it would just go in here, or this quit event rather; and it’s this default event that’s included in pygame, and we’re just checking if the event type that we’re getting is one that’s equivalent to a quit event that, in pygame, corresponds to us quitting the game. So, for example, us closing the window. So that’s what we’re checking right now.

So pygame itself, or the pygame module, the pygame library, contains this quit object that, you know, represents a quit event. So it pretty much indicates that the event type here is quit, and that means that we wanna quit the game. And so if that is the case, if they’re equal, what we’re gonna do is we’re gonna take our finished variable and, now that we know that the event type is a quit type, so that means the user wants to quit the game, we’re gonna say the game is done. So even though we didn’t finish the game, we’re gonna say the game is done because the user wants to quit the game; so we’re gonna say finished is true. And what that’s gonna do is it’s gonna change our while loop here; and our while loop is no longer gonna be fulfilled, so finished is no longer gonna be equal to false. Finished is now equal to true and so true, checking if true is equal to false gives us the overall statement of false because true is not equal to false. And so we’re no longer gonna execute this while loop here. All right, so, that’s what we’re gonna do now.

And so if we run our module, then we see that everything is, you know, still good and stuff here; and then, well, my console’s a little bit slow sometimes, so let me just, well, it looks like we got this error message going on here. Oh, my bad, so we were not supposed to have open and close parentheses here. Let me just force quit Python right here or this, there we go, all right, so, my bad. The quit is not supposed to have open and close parentheses; it’s just supposed to be quit without anything. So let’s take that away and let’s rerun that. That gave us an error, and here we go. So now everything works grand.

Everything is working. We’re not getting the spinning ball of death. We also don’t see any errors popping up here; and if we click Close, then your Python should close. For me, it’s always a little bit (mumbles); and, you know, if things are going on so, no matter what happens, for me, I just always have to force quit it. But if your computer is just a little bit different, then everything just should close normally without you having to deal with these nuances.

So that’s what’s going on here, so that’s what we did here with this setting this finish property to true.

Transcript Part 6

Hey, everyone, it’s Max and welcome back to our Python tutorial. So, in the last tutorial, we looked at how we can create this pygame screen, how we can go through it, process all of the events and also process what happens when someone quits the game, so when they click the close button.

So that’s great, but we only got a black screen. So, let’s deal with that a little bit, and let’s make something a little bit more interesting. So, what we’re gonna do now is we’re going to learn how we can create a rectangle on the screen. Okay, so, how are we gonna go about that? Well, what we’re gonna do is, first of all, we’re just gonna create a rectangle, and we’re gonna save it in this rect, we can call the variable rect. We can call it rectOne or something like that. Just give it a name to indicate what your rectangle should be. So this is just the variable name that we’re gonna store our rectangle object in. So, how do we create it? Well, we create it by, first of all, going into pygame, and in pygame, we’re going to access the Rect object, and now we opened and closed parentheses, and although this opens and closed parentheses, this does not mean that it’s a method technically. So, we can have opened and closed parentheses for objects as well as methods or functions, you know. Method’s just functions for objects. But what this opened and closed parentheses allows us to do is it allows us define some starting parameters for our rectangle. And specifically, what we can define is going to be a x, a y, as well as a width and a height of our rectangle. So we can define the starting positions, the x and y conditions, as well as the width of a rectangle and the height.

So these are the properties that we can put in here. So, for example, we can put it at the x, y coordinates of zero, zero, so that’s where one of its corners is going to be. Then we can give it a width of maybe 30 pixels, and we also make it 30 pixels high, so just that everything is square, so that everything is consistent, and we’ll just create a squared rectangle at the position zero, zero, yeah, with these parameters here. So, that’s gonna be its size. So that’s the rectangle that we’ve created, and we’ve actually saved this rectangle in this variable called rectOne. So, we can access our rectangle later on by just accessing this rectOne variable here. Alright, so now we wanna add it to the game. So, to do that, we’re going to go into pygame, and what we’re gonna do is to add this rectangle to the game. So now we’ve created the rectangle, but now it’s not really anywhere.

So now we wanna add it into our window. So what we’re gonna do is we’re gonna draw it into our window, and in this draw object, we’re actually gonna look at another property, which is going to be rect. So, what we’re doing is we’re going into pygame. We’re accessing this draw object, and inside of this draw, we’re saying what exactly do we wanna draw? So, there are different shapes that we can draw. One of those shapes is a rectangle, and that’s exactly what we wanna draw. So, we wanna draw a rectangle, and here, again, we can pass certain parameters. So, that’s why this draw object is kind of the bigger class, the bigger object that in itself contains different attributes, different features, different functions or methods that do different things. And, generally, the object is responsible for drawing, but depending on what we wanna draw, we have to access different methods.

In this case we access the rect method, and that way it’s gonna allow us to draw rectangles. Now, we have to put in here some parameters. So first of all, we have to define the screen that we wanna draw to. So, our screen is the screen that we created up here. Now, in case you gave your screen a different name, like screenOne, your screen will be screenOne here. So you wanna make sure that the variable that you saved the display in or the screen is the one that you’re gonna be passing in here because that’s the one that you’re going to be wanting to draw to. But we’re just leave our name as screen. Now, something else that we can do is we can put in here a color. This is gonna be in the form of red, green and blue. So, we’ll look at that in a second. And the final thing that we’re gonna put in here is going to be the rectangle object that we wanna put in there. So, we’re gonna draw onto our screen. We’re gonna draw onto our screen, or we’re gonna draw a rectangle onto our screen that has this color, and this is the rectangle that we want to draw on.

So, those are the parameters that we need to pass with it. Now, let’s quickly define our color. So, to define our color, we’re gonna create a variable called color. And we’re gonna have it be equal to the following. Now, before, when we created a variable, we usually just put in one thing. Like, we put in, you know, the word Hello or the string Hello or the number one or the integer one or the floating point number 1.0 or something like that. So, we’ve always put in one number. But for the color here, we actually need a RGB value, red, green, blue. So, the way that we’re gonna do that is we’re gonna look at something called a tuple. So, to create a tuple, we’re gonna make it equal to, and then we open and close parentheses. And what this does is it nicely packages up several values for us. And so, now, we can pass values in the form of a tuple or in the form of these packaged numbers.

So, for example, to create a fully blue color, I’m gonna first put in the number zero. So, again, we’re creating R, G, B, so zero of the red value, and then comma is gonna indicate that we’re gonna have a new element. Zero of the green color, and 255, so maximum, of the blue color. So, that’s just the scale that this RGB works on. So, what we’ve created here, rather than assigning a single number or a single word or string or whatever, we’ve created something called a tuple, which we can imagine as a package of, in this case, numbers. But it can also be a package of other things, like a package of strings for example. But in this case our color contains a tuple that contains itself three numbers. So, color is a little package that contains three numbers, that contains the number zero in its first position, it contains the number zero in its second position, and it contains the number 255 in its third position.

Now, this by itself may mean different things for different inputs, but if we’re putting it in here, then for the draw object and the rectangle method, these three values together correspond to RGB values. So, they correspond to red, green, blue values, and so, if we put this tuple, this package of three numbers in here, that’s gonna correspond to the color blue because blue is maximum. So, the scale goes from zero to 255. And so that’s what we’re doing in here. We’re using this tuple is what it’s called. It’s just a package to help us pass several numbers in one element here. And we also see here, each element is separated by a comma. Alright, so there is one more thing that we need to do. So, now that we’ve created our rectangle, and we’ve drawn our rectangle, we need to update our display, we need to update our screen. So, we’re gonna go into pygame, and we’re going to access the display object, and in it we’re going to call the flip method. And, pretty much, what this allows us to do is it allows us to update.

So, what we’ve done now is we’ve created first a pretty much blank screen because we haven’t added anything to it. We’re going through the events. Once we finished going through the first events, we’re creating a rectangle, position zero, zero with width and height of 30, and we’re drawing this rectangle to the screen with the color blue. And now that we’ve done all that, we still need to update our display. So, if we’re pretty much entering the next frame or whatever it is not we know, and now we need to update it, so that we have this rectangle in there. And so that’s where we need this final call here of the display object in pygame, and we need to use this flip method.

So, that allows us to update our display, it allows us to update the screen that we’ve created. So, if we run this, then we see up here, we created this little rectangle. So, for me this rectangle is a little bit hidden in the top left corner. That’s just because it’s covered by this bar here. But if we go back into our rectangle that we’ve created and change the Y position to maybe 50 to move it down a little bit and then rerun this, then we see our rectangle is now this nice square that’s created right here.

Transcript Part 7

– Hey everyone, it’s Max and welcome back to our Python tutorial. So again, let’s continue off just where we left last time.

If we remember where we left last time, then we can see here, if we run our module again, we’ve created this rectangle here on the screen, this blue little rectangle. And we’ve actually created it at a position of (0x,50y). And the width and height are 30. And we also saw that if we created it at (0,0) it was little bit hidden, so that’s why I moved it down just a little bit by changing the y coordinate. One thing that you’ll also read from here is that the (0,0) location is in the top left corner. And then if we increase x and y, we’re pretty much going across the screen like that. So that’s how we change the x and y coordinates too, so that’s what we did in the end there. Just increasing y so that it’s not hidden under this bar, that’s still part of the screen and we just moved it down just a little bit.

Alright, so now we’re gonna look at how we can get our rectangle to start moving. So the first thing that we’re gonna do is we’re actually gonna redefine our x and our y coordinates. So, right now we’ll just put these here. We’ll have x be equal to 50, and y equal to 0. And actually we’re going to move these out and have them be before our loop because these are our starting coordinates, so that’s what we wanna start at. And all we’re gonna do is we’re just gonna replace our– Oh, we actually want x to be 0, sorry, and y to be 50. So we’re gonna replace our x coordinate here with the x variable that we’ve created up here. So that’s gonna be our x position, and 50 is gonna be replaced be our y condition. So if we run this, and save of course, then we see there’s actually no difference right now, just because 0 and 50 have been replaced by x and y which still contain the values 0 and 50. So there’s no real difference. The only difference is that we now have these initial values stored, and if we want to move it then we can continuously update these.

So that’s why we’ve created them in a form of variable, rather than just hard coding them in here. So yeah, that way we can just continuously update them. And that’s also one of the uses of variables is that we can continuously refer to their previous state. Alright, good, cool. So now that we’ve done this little adjustment, created this variable here so we can see this rectangle here now in the same format but using x and y instead. Let’s learn how we can see, or how we can start to move our rectangle. So what we’re gonna do in Pygame is– Or in our coding environment here is we’re gonna go in to Pygame. And we are going to want to check if a certain key is pressed. So to do that, we’re going to go into key.

And what we’re gonna do here– so again we’re going into Pygame, where now I’m going into the key object and we’re gonna call this method that’s actually already being suggested to us here called “get_pressed”, like this. And what this does for us is it just returns to us all of the pressed keys, in a kind of form of– Well actually it’s in the form of an array or a list but we’ll see more of that in a second so that we can really understand this. But yeah, what we’re doing right now we’re just getting all of the pressed keys in the form of a long list. Alright. And we need to save that in somewhere.

So we can call that, maybe, “pressed keys is equal to the following”. So the pressed keys, are the keys that are returned to us from this get pressed method. So what exactly is being returned to us? So, what’s being returned to us is a variable– Oh actually sorry, it’s a list, also called an array. So I’ll show you an example of an array on just a quick side note here. You can create an array like this, using open and closed square brackets. And arrays, just like true/false, which we’ve created for the color right here. It could also hold several elements, And each element is separated by a comma. So for example, our first number could be 0, the number 0, and then we can have 1.2, that’s our second element which we separate here by comma. Then we can say maybe 4.5 or something like that. We can also put in here the word or the string “Hello”.

And so that’s what an array is for us. And so we can see it’s pretty much a collection. Well it’s actually a way of storing data so it’s actually a form of a collection, or grouping relevant data, so similar data that we can access, and it’s held in this list. Alright so what we’re gonna do is we’ll print out our array here, just as a kind of short little side example we’re gonna do this just to understand what we really get when we have this get key pressed so that we really understand what we’re doing and why it is that we’re doing that. We have to understand these arrays or these lists, so we’ll quickly cover that now. Alright so, if we run our module and we click okay, then we have the Pygame being loaded here and stuff what we’re really interested in is the output in console that we have right here.

And so we see again this list, which we see is a list because it has open and closed square brackets at the front and the end. And each element is separated by a comma. So that’s the whole array or list that we’re printing out. We can access individual elements by going, by having, this array variable here that stores our lists or our array and by putting open and closed square brackets behind and by putting, now, the index of the variable or of the element that we want to access. So let me explain to you what the index is too, how they work. So the index works as follows. For a list that has several elements the first index or the first element has the index 0. The second element has the index one, the third element has the index two and the fourth element has the index three and so on. If we were to have a fifth element it would have the index four and so on. So the only difference is in programming we start counting at 0. So rather than the first element having the index one, the first element actually has the index 0. So that’s how indexes work like. Alright, let me just shift this back here, just a little bit.

So that’s in general how indexes look like or how they work. So to get out a certain element we have to access it in the list through calling its index. So for example, if we wanna access the first element which is the element with index 0, we put in the square brackets behind our variable name this index. And notice here we’re assigning a list to it, and here we also have the square brackets but since we don’t have this assignment here since it’s right behind our variable name that contains the list that means we wanna access that element. So if we run that, now we see if we go over here we get the output 0 which is our first element.

If we put in the index one then we get– Save and run– Then we get here the output 1.2 which is our second element if we look at the index two, then we get the output 4.5, which is our third element. And if we look at the index three, and save and run this, then we get the fourth element which has index three, since in programming we start counting at zero, which is “Hello”. So we can go up, we can also go backwards and to access, for example, the last element, we can put in here instead of three, we can put in here the value negative one. So we’re counting backwards. So this is 0, this is negative one. So here you will also get “Hello”. If we go the second last element, negative two, we get 4.5. Like this.

So that’s the basics of lists in Python. And we’ll be using this to access the elements that we get returned from here. So that’s kind of important for here. So we’ll comment this out just so that we can reference to it later, and that’s also what we’re getting back from here. And lists, or arrays are really really great because they allow us in one variable to store a bunch of information or to group a bunch of information to store it in the same variable that’s related.

And for a list that has, you know, maybe a length of 100 we don’t have to create a hundred different variables we can just create one variable that contains a list with 100 elements.

Transcript Part 8

Hey everyone, it’s Max, and welcome back to our Python tutorial.

So in the last tutorial, we saw a little bit of an introduction on arrays or Python lists, and how they work, and how they store data. And we looked at that because we looked at this pygame.key.get_pressed method which returns to us an array that has an index for each of the keys. And it allows us to check if a key is pressed or not. So that’s what we get back here is we get this huge, huge list, or this huge, huge array, of all the keys. And for each individual key, we can check if it has been pressed or not.

So, one more thing quickly before we get into looking at the keys. We first have to understand how we can access the keys. And so, we’ll again look at that by printing something. And you will have noticed that to print I can do the open and closed parenthesis or I can just put a space here. Whatever it is that you prefer. Whatever you’re used to. Or if you’re not used to anything, you can do whatever you like, as long as you’re consistent. Probably that’s best. All right, so how do we know what key is pressed? So, if we go into pygame, pygame actually has for each key certain values. So for each key there is a certain value that’s saved. And we can check that key is pressed.

So for example, if we’re gonna use the space bar, we’re gonna go into pygame, and we want to access the space bar key. So we’re gonna go into pygame. And then we’re gonna type in K, underscore, space like this. And what that does is this is the space bar key that’s saved in pygame. So this pretty much gives us the reference to that space bar key. And so if we run this, and we’ll see in a second why we’re running this, what we get back if we run this is we get back a number. And now the reason that this is important is because this number that we get from the space bar key that’s saved in pygame is actually the index of the space bar, or of the space bar key, that we get when we call this get_pressed method on keys.

So really what we get here is we get a list of all the keys. And to find the space bar, we have to look at the space bar key in this array. So for example, what we get back would be something like… And now this isn’t exactly how it’s structured. But it would be something like the up key, and then we’d have the down key, and then we have the left, and maybe then we have the space or something, and there is stuff before. Now there’s stuff after. And there’s stuff before. And again, this is probably not the exact order. But this is just to show you the example. And so we get this huge list that contains all the keys. And to access the space bar key, the one that we’re really interested in, we have to know what index it has in this whole list that contains all the keys. And so that’s why it’s important to know that this K_SPACE is a number, and that number corresponds to the index in this list of all the keys that is returned to us. All right so, if you understand that great. If not, then we’ll just continue working with it and you’ll probably see in a second what I mean with that.

All right so, what we’re gonna do is we’re gonna do another if statement. And we’re gonna see if, and now we’re gonna look at the pressedKeys. If our pressedKeys, and now the element… So again, we get this whole list of all the keys returned to us. And the key that we want to look at is the pygame.K_SPACE. Oops sorry. K underscore space. So key underscore, and then what key it is. It’s the space key. And the reason that we do the pygame is just because everything that we’re doing is contained inside pygame. And it’s all made consistent inside of pygame. So that’s what we’re doing here. Actually, maybe something that would be interesting to see is before we even check this if statement is just to print out what that value would be. So before we go any further, let’s just print out whatever the element in this list is, just so to really understand what we’re doing. So we’ll run this and save that one more time. And now, what we see here is we get an output, just a bunch of zeros. So we’re not pressing the space bar key. And now, let me move this over a little bit. If I press the space bar, we see all of a sudden get a bunch of ones returned here. So that’s what’s going on when I press the space bar key.

So let me just run that again just to keep that running in the background, but to stop all of this spamming of numbers. And well great. Now everything froze because of it. So let’s just force quit this. Okay and… Yeah, there we go. And while that’s quitting, okay good. Maybe we’ll also just close that. And again, force quit this so that we’ve reset everything. But yeah. So that’s pretty much what’s going on when we press the space bar key is it is continuously being checked. And we also see that it’s continuously being checked at certain frame rate and everything. And so, that’s the values that are stored in this pressedKeys. All right. So now what we’re gonna do is we’re gonna check if pressedKeys. And now if the pressedKeys of, or if the pressedKeys is equal to the following value. So we notice that what we get returned from here is either zeros or ones. So if the value contained in pressedKeys for the space key is equal to one, then what we’re going to do is we’re going to increment our y coordinate a little bit. So we’re gonna make our block, our rectangle, move up and down.

So what we’re gonna do is we’re gonna say y is equal to. And now maybe we say y plus five or something like that. But remember there’s a shorthand for that. We can also say just plus equals five. So that’s the same thing as saying equals y plus five. So we’re just gonna increment y by five if the space key is pressed. That’s what we’re gonna do right now. And so if we run this, and remember the y coordinates is the up and down coordinates. So if we run this, what should happen for us is once we press the space key, we see that we’re moving down. Now, this isn’t exactly what we wanted. But every time we press the space key, we see that we’re moving down, which is already a great start. Now, we have a little bit of a problem of this blue line appearing as kind of a trail. And the reason that’s happening is because we continuously draw a new rectangle. So what we’re doing, and that’s also why we save these x and y coordinates from before.

We’re continuously incrementing our y coordinate by five every time we have the space bar held down, for every tick of the computer, and we’re creating a new rectangle, and we’re drawing that rectangle to our screen again. But all of the old rectangles are still there. They’re not being removed. So that’s why we have this kind of tail that’s going on. And to avoid that, the one thing that we’re gonna do is we’re gonna go into our screen and we’re just going to access the fill method. And again, here we’re gonna put in a color, an RGB color. And we can actually define the color black to be zero, zero, zero. So that’s the same as the tuple we defined above. So this here is the color blue, which has a value of zero red, zero green, and 255 blue. The color black has zero for every color. So again, RGB colors here. And what we’re gonna do is before we draw the rectangles to each tick, we’re just going to change the color of, and whoops sorry, one extra too many parenthesis there.

We’re just gonna change the color of our screen again back to black. So if we run our module now, we see that when I press the space bar, our rectangle is nicely moving up and down and we no longer have this tail because every tick or every frame of our game, our screen is taking on, is being completely black again, and then we draw the rectangle again. And if I move it, all of those rectangles are no longer seen because they’re completely overwritten because we’re making everything black again. We’re completely filling it up with black. And so that eliminates the tail. And since we only draw a rectangle once every tick, or every frame, we see only one rectangle on the screen here too.

And just through pressing the space bar, we can move it down in the y direction because we said here if the space bar is pressed, then we increment y by five.

 

 

How to Create A Hyper Casual Game for Android in Unity – Part 3

Part 3: Keeping track of the score, item pickups, and endless obstacle spawning

This is the final part of a three part tutorial series on how to create a Hyper Casual game. Please make sure you have followed and completed the first and second parts of the tutorial and completed them before starting Part 3. Here are the links to Part 1 and Part 2.

This part of the tutorial was made in Unity version 2018.2.13f1, which was the same version used in the previous tutorials.

Source Code Files

You can download the tutorial source code files here. All the project files are located in the main folder. The asset folder contains additional intermediate files that were used during the process of creating the game sprites.

Changing the Background Color

Change the background color on the Main Camera to Black (feel free to change this to any color you like, the color of the background will not affect how the game is played). 

Adding the needed libraries

The following libraries need to be added: SceneManagement and TMPro to the GameManager script.

using UnityEngine.SceneManagement;
using TMPro;

Disabling and Activating the GameOverPanel

Make sure you have disabled the GameOverPanel in the inspector window. We will be activating it only when the GameOver function is called in the GameManager script. Add a public GameObject to the GameManager script, and name it GameOverPanel, set this in the inspector and as well on the script component attached to the GameManager object in the scene. This is so the script knows what GameOverPanel to be activating when the GameOver function is called. In the GameOver function we need to set the GameOverPanel to be active. Save the script.

public GameObject GameOverPanel;

public void GameOver()
    {
        Debug.Log("Game Over!");
        GameOverPanel.SetActive(true);
    }

Restart button functionality

Add a RestartGame function to the GameManager script. Inside this function we are simply going to load the scene again.

public void RestartGame()
    {
        SceneManager.LoadScene(0);
    }

We then need to setup the on click event on the restart button in the inspector window.

Image may be NSFW.
Clik here to view.

Item pickups

Of course, no Hyper Casual Game would be complete without a collectible of some kind, we will be creating some diamond pick ups next. Create an empty game object and rename it to “Item.” On the transform component set the X position to 3 and the Y position to 6. Create a new diamond sprite and set the color to yellow. Make the Diamond a child of the Item game object. Rename the diamond to Diamond1. Add a circle collider 2D component and set the Is Trigger to true. Reset the transform component. Adjust the scale to 0.5 on both the X and Y values. Add a new tag to and name it “Item.” Make sure to tag the Diamond1 with this tag. Make the Item game object into a prefab by dragging it from the hierarchy into the Prefabs folder.

Open the Player script and we need to add an if statement to the OnTriggerEnter2D function that will detect if the player gameobject collides with a game object tagged as “Obstacle” and then call the PlayerDeath function there and else if the player collides with a game object tagged as “Item.” The else if statement will remain empty until we add in function to increase the score.

private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.tag == "Obstacle")
        {
            PlayerDeath();
        }
        else if(other.gameObject.tag == "Item")
        {
            
        }
               
        
    }

 

Setting the Score with TextMeshPro and Increasing It

Select the Canvas game object in the hierarchy and create an empty game object and name it “Score.” Make sure this is a child to the Canvas object. Create a UI>TextMeshPro-Text object as a child to the Score object. With the CurrScore object selected adjust the alignment to center and middle in the inspector. Change the font asset to Oswald-Bold. In the Text Input Box put 1. Adjust the Font Size value to 290. Change the Hexidecimal color value to B7B3B3. Adjust the Alpha to 80.

Image may be NSFW.
Clik here to view.

On the Rect Transform component adjust the Width to 270 and the Height to 280. Check the Autosize checkbox and change the Max value to 535.

Image may be NSFW.
Clik here to view.

Open the GameManager script and add a public TextMeshUProGUI variable called “currScoreText.” Add a private int currScore variable. In the Start function set the currScore value to 0.

public TextMeshProUGUI currScoreText;

    int currScore;

	// Use this for initialization
	void Start () {

        currScore = 0;
        ScoreSetting();
	}

Open up the Player script and call the ScoreIncrement function in the else if statement where the player is colliding with the Item pickup. In order to do this correctly you must reference the gameManagerObject then call the ScoreIncrement function, it should look like this:

void Awake()
    {
        
        gameManagerObject = GameObject.Find("Game Manager").GetComponent<GameManager>();
    }

 private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.gameObject.tag == "Obstacle")
        {
            PlayerDeath();
        }
        else if(other.gameObject.tag == "Item")
        {
            gameManagerObject.ScoreIncrement();
            
        }
               
        
    }

Save the script, and open the Unity Editor, the CurrScore game object in the scene needs to be attached to the Game manager component in the inspector window on the open spot Curr Score Text, just drag the CurrScore object from the hierarchy to the open spot on the Game Manager component, and then hit Play and test out the changes. Every time the player now collides with the diamond item the score will increase. We can’t forget to call the Destroy function on the item pickup so that once the player collides with it, and then the score increments, we need to destroy the game object in the scene so it no longer remains in the game. Do this under the gameManagerObject.ScoreIncrement function on the Player script, make sure to save the script and test that the item is indeed being destroyed after the player collides with the object in the game. Save the scene and Project.

Destroy(other.gameObject);

Delete the Item prefab form the Hierarchy, we will be instantiating this object along with the obstacles randomly through code next.

Random infinite obstacle and item pickup generation

An important aspect of Hyper Casual games is to increase replay-ability. We want to keep the player coming back to play our little game, so one way to do this is by adding randomly placed obstacles and item pickups. This way the player experiences a somewhat different game every time they restart the game. We made our item pickup into a prefab and now we are going to turn the SquareObstacle into a prefab, but first we need to add some more squares to the SquareObstacle gameobject.

Select the Square obstacle gameobject in the hierarchy and duplicate the Square four times, this will now give you a total of 5 Squares that are children to the SquareObstacle. You can easily duplicate an item by hitting Ctrl-D on your keyboard.

Some values on the squares transform component needs to be adjusted. See the screenshots below for the adjusted values:

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Make the item prefab game object a child of the Square Obstacle. Duplicate the Diamond1 four times. See the screenshots below for the transform component adjusted values:

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Make the SquareObstacle into a prefab.

Create an Empty Game Object and reset its transform component. Rename this to “RectangleObstacle” Drag a square sprite from the sprites folder under the RectangleObstacle and make it a child of it. Rename the square to Rectangle, adjust the X value on the scale of the transform component to 3. Adjust the Y value of the Position on the transform component to 5. Duplicate that rectangle 4 times. Make sure to add the tag “Obstacle” to each one of the Rectangles, so that when the player does collide with one it will work properly. See the screenshots for the transform component adjustment values:

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Make the RectangleObstacle game object into a prefab. A quick note, here you should be comfortable enough at this point to adjust any of the scale or even position transform values on the obstacles to some vlaues you may favor more than how they are laid out in this tutorial.

Delete both the RectangleObstacle and the SquareObstacle form the Heirarchy. Save the scene and Project.

Create an empty game object and reset the transform component. Rename this object to “ObstacleGenerator.” Create and attach a new script to this game object and name the script “ObstacleGenerator.” This script is going to control the infinite instantiation of all our obstacle prefabs. This is going to be done by measuring the distance between the player game object and the obstacle prefabs. Every time the player gets within a distance of 25 between the obstacle prefabs a new obstacle will be instantiated. We are going to use an array to hold the obstacle prefabs and then use the Random.Range function to choose a random obstacle to instantiate every time the player is within the distance of 25. Add the following code to the ObstacleGenerator script:

public class ObstacleGenerator : MonoBehaviour {

    public GameObject Player;

    public GameObject[] obstacles;

    private int obstCount;

    int playerDistance = -1;
    int obstcIndex = 0;
    int distanceBetweenObstc = 25;

    // Use this for initialization
    void Start () {

        obstCount = obstacles.Length;
        CreateObstacle();
	}
	
	// Update is called once per frame
	void Update () {

        int PlayerDistance = (int)(Player.transform.position.y / (distanceBetweenObstc / 2));

        if(playerDistance != PlayerDistance)
        {
            CreateObstacle();
            playerDistance = PlayerDistance;
        }
	}

    public void CreateObstacle()
    {
        int RandomObstCounter = Random.Range(0, obstCount);
        GameObject newObstacle = Instantiate(obstacles[RandomObstCounter], new Vector3(0, obstcIndex * distanceBetweenObstc), Quaternion.identity);
        newObstacle.transform.SetParent(transform);
        obstcIndex++;
    }
  
}

Save the script and open the Unity Editor and hit play to test the changes. You should now be able to see the obstacle prefabs being instantiated as the player moves upwards. Next, we need to make sure we are destroying the obstacles and item pickups that are being instantiated so that they do not remain in the game scene and “hog” the resources and cause crashing of the game. We can do this by creating an empty game object and making it a child of the Player. We are going to rename this object “Obstacle Collector.” This is essentially going to follow behind the player and as the player moves upwards it follows behind it since its now a child of the Player game object. As this Obstacle Collector collides with the game objects tagged “Obstacle” and also “item” they will be destroyed.

Add a Box Collider 2D to the Obstacle Collector set the IS Trigger to True and set the Y offset value on the box collider to -12.41 adjust the size X value to 54.63. Add a rigid body 2D component, and set the Body Type to Kinematic. We have to use a rigid body on this so that collision works properly, and we are setting it to kinematic, remember kinematic body types are not affected by forces or gravity. Kinematic body types also use less resources. Create and add a new script to the Obstacle Collector and name the script ObstacleDestroyer.

Image may be NSFW.
Clik here to view.

Add a private void OnTriggerEnter2D function with the parameter other. Inside this function create an if statement that will check if the ObstacleCollector collides with any obstacle tagged “Obstacle” and also “Item” then Destroy the game object.

private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Obstacle" && other.gameObject.tag == "Item") ;
        {
            Destroy(other.gameObject);
        }
        


    }

Save the script and open the Unity Editor and hit play to test the changes. You should now see the obstacles and items being removed from the game scene as the Obstacle Collector collides with them as the player moves upwards.

Adding Rotation to the Obstacles

Some pizzazz is needed to our obstacles; we can accomplish this by adding a simple rotation script to the obstacles so that they randomly rotate in a direction. This will add a nice “Juicy” effect to the game.

Create a new script and name it Rotation, open it up for editing. Add a public variable called “RotSpeed” with no initial value.

Create a private void function and name it “ObstacleRot”. Inside this function we can rotate the obstacles by using Transform.Rotate Vector3.forward and multiplying this by Time.deltaTime and the RotSpeed. We will need to call this function in the update function, but we also need to do an if check to see if the RotSpeed is not equal to 0, then call the ObstacleRot function.

public int RotSpeed;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
        if(RotSpeed != 0)
        {
            ObstacleRot();
        }
	}

    private void ObstacleRot()
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * RotSpeed);
    }

Tutorial Conclusion

So that’s it! You have successfully created a Hyper Casual game. Some ways to add some more polish to this little game are to add a camera shake element triggered by the player’s death, or even change the background color randomly every time the game is restarted. Some pickup effects could be added where the particle effects come into play, when the player collides with an item. 

Web Class: How to Pool Objects in Unity

Transcript Part 1

Even though we worried about making the bullets not last forever, so they’re not going to use very important space in memory, there is something else we have to worry about. Every time we add a bullet to this game, every time we do this instantiation process, it takes some time for Unity to get that element, to put it inside the game, and make it work, okay.

So actually creating and deleting elements, they are expensive operations. So you have to avoid that as much as possible. And at that moment, you might ask yourself, okay I’m a bit confused now, the bullet is something that has to be instantiated, but I have to avoid instantiating things. And it sounds funny if you say it, but what you have to worry about is pooling objects. And that pooling of objects is as follows.

You are going to have a little manager, something that is going to hold a certain object, a bullet, for example, then it’s going to preload a certain amount of objects. So maybe you want to preload 20 bullets, for example. And you’re going to make these objects inactive. They’re going to be kind of dormant. They’re going to be unavailable for use. Basically they are sleeping, and they are hidden in the game. And every time you want to spawn a bullet, instead of instantiating, you’re going to get a bullet from the pool of objects, because we already have one available. So that bullet is going to be activated, and you can do whatever you want with it. So, it might seem a bit confusing, a bit complex for you to understand that, maybe if that’s your first game, or one of your first courses you’re taking on game development, but this is one of the most important subjects in game development, which is object pooling. It’s going to save you lots of processing power. And memory as well, okay.

So, we want to make a pooling manager. So I’m going to come here in the Hierarchy. We need to right click, and need to choose create empty object. We’re going to take this game object from, outside the game controller, it’s going to be right here, and I’m going to rename that, let’s see, PoolingManager, or ObjectPoolingManager, or ObjectPooler, whatever name you think is going to work well. I’m going to call it ObjectPoolingManager, okay. We hit enter, it’s in the position 0,0,0. It’s not going to make any difference later, but still, let’s leave it like this. And now we need to make a script for it. So I’m going to the scripts folder, I’m going to right click, select create, C# Script, and then ObjectPoolingManager and then hit enter. And before we move forward, we’re going to make a folder. We’re going to organize these scripts. So I’m going to right click, select create, folder. I’m going to name this as game. And I’m going to select both the bullet and the player and drop it here. And I’m going to make another folder, and I’m going to name that Utils. Okay, I’m going to put the ObjectPoolingManager inside there. I worry a lot about folders because it’s important to keep things organized. And now that we did this, we’re going to put a reference to that ObjectPoolingManager. We need to drag and drop the script here. So, what I’m going to do is. At the player, okay so if you open the player script. Which is this one.

Instead of instantiating the bullet like this, calling instantiate, we’re going to try to get a bullet from the ObjectPoolingManager. So we want to access the ObjectPoolingManager, but how do we do this? There are two ways. One way is to make the player to reference the ObjectPoolingManager and well, make a direct call for it. But that might be a bit ugly, and that’s not going to be easy to reuse later, because if you make other elements, if you want to pool a particle effect for example, or other bullets and several different things. If you want to access the pooling manager from other places, from the player, from the enemy, from the turret, from the door, whatever elements you have, you need to think of a better way to do this. So we need to make a little mix of the simple return pattern.

So, the ObjectPoolingManager is going to have a reference to the only instance of that pooling manager that is going to be available in the scene. Which is this little guy here. So what I’m going to do here, is type private static ObjectPoolingManager instance, so there’s going to be a reference to the instance of the ObjectPoolingManager. And now, I’m going to type public, then static ObjectPoolingManager Instance, with an uppercase I. I’m going to open and close curly braces, and type get, and, once again, between curly braces, return instance, okay. So it’s a very simple pattern that we’re making for defining a property. If we go the player and we type player. If we type ObjectPoolingManager.instance, we should access the instance that we have here. However, right now it’s going to return null.

So what we can do here is, instead of using start, we can use Awake. And we can type instance equals to this. So, the Awake method happens before the Start method. So we’re going to insure that instance is going to be set once this Awake method is going to be called, okay. And all of the other elements can access it in their Start method, otherwise we have to worry about the script execution order, but let’s worry about that later. Okay, so this is going to be, to make us able to access the ObjectPoolingManager, so as a simple test, I’m going to make here another method, let’s get rid of the update. And it’s going to be public and then GameObject, and let’s name this as GetBullet, for example. We’re going to name it like this. And I’m going to print just a message here. I’m going to type Debug.Log and say hello. And I’m going to type return null. Okay, we’re not going to return any bullets right now. So let’s save this. In the player, just to test it out, I’m going to type ObjectPoolingManager here where we spawn a bullet dot Instance.GetBullet, which is this one here, okay. So let’s see what happens if we do this. I’m going to save, let’s go to Unity. Let’s select the console by the way to see the messages. And now, if we press play, here we are. If I click, I’m printing the hello message. Which means the player is accessing the ObjectPoolingManager without having a direct reference to it. Which is perfect, exactly what we want.

Now, we want the ObjectPoolingManager to be able to access the bullet prefab, to know what the bullet prefab is. So, I’m going to type here, let’s type below these pair of lines, public GameObject bulletPrefab. Okay, so let’s save this, by the way, and go to Unity, wait a little bit, and in the ObjectPoolingManager we’re going to drag and drop the bullet, just like we did with the player. So, prefabs, bullet, drag, drop. Perfect, there we go. And now, what we want to do here, is we want to preload a certain amount of bullets. So I’m going to type public int bulletAmount, and let’s use 20 as default. And here, in the Awake method, we’re going to instantiate 20 bullets, but we’re going to leave them disabled. So, how are we supposed to do this? We’re going to type it like this: for int I equals to zero, while I is lesser than 20, then do something, and finally i++. So, this is a basic loop that’s going to execute 20 times. But instead of using 20 here, we use bulletAmount.

Okay, so you can scale that to whatever you want. And when this happens, we’re going to type GameObject bulletObject, or we can just type here prefabInstance, because we want to make that easier to reuse later, equals to instantiate and then bulletPrefab. Okay, once we do this. Let me, instantiate, there we go bulletPrefab. Once we do this, we also want this bullet to be under the ObjectPoolingManager to keep things organized, otherwise the bullets are going to appear at the root of the Hierarchy. So, prefabInstance. transform.SetParent and we pass transform as a parameter, because it’s going to reference the ObjectPoolingManager. And after we do this, I’m going to type prefabInstance.SetActive and I’m going to pass false as a parameter, okay. So we’re going to instantiate 20 bullets, and all of them are going to be disabled. So this time, if I save this. I go to Unity, and I wait for the processing to be finished.

If we press play, and we look at the Hierarchy, you see that the ObjectPoolingManager has an arrow, because it contains several objects inside it. If you open, you’re going to see the 20 bullets in there sleeping, in their dormant state. Okay, which is good, now we have them. Now, for the getBullet method. What we have to do, is we have to store all of the references for the bullets that we have here somewhere. So we’re going to need a list of bullets. So here, I’m going to type private List of type GameObject and it’s going to be named bullets, simple as that. In the Awake method, before we instantiate the bullets. Let me, let’s add a comment here, so preload bullets. We need to type bullets equals to a new List of GameObject. Okay, that’s a generic list of GameObject. And you can also start by including its capacity. So we already pre-allocate a certain amount of spaces in our memory to load bullets, and the capacity is basically bulletAmount.

Okay, so we’re going to make a new list that can store up to 20 bullets, which is good, okay. And for the getBullet, we have to worry about something, we need to store the references for the bullets, before we try to use the getBullet. So here, when we instantiate the prefabs, I’m going to type bullets.Add, in between parentheses, I’m going to pass prefabInstance, just like that, okay. And if you go to Unity, well you’re not going to see the changes yet, we’re simply going to preload the bullets, they’re going to be stored internally in the list, in a generic list. But now we have to learn how to use them.

Transcript Part 2

We have now set the entire ground work for making the object pooling to fully work. So now we need to go to the object pooling manager, and we have to make the get bullet method to work. And how we’re going to do this, let’s take off these two lines. We want to iterate over all of the prefab instances that we have loaded here, and we need to check if any of them are inactive, because if it is then that’s the bullet that we’re going to use. So to do this, we’re going to type for each game object bullet in bullets. That’s an easy way to make a loop. We’re simply going to check that list for all of the bullets that we have.

Now we check if bullet.activeInHierarchy, this is a property that says basically if the game object is active in the scene. But instead of checking if it’s active, we want to check if it’s inactive. So we add an exclamation mark in the beginning of this statement. So we check if we have anything inactive. If this is the case, then this is the bullet that we want to use. So the first step is we’re going to make it active by typing bullet.SetActive and pass true, as a parameter. So the bullet is going to be back to how it should be. And after that we type return bullet. But there is a problem here. Maybe all of the bullets are being used, so we are going to iterate over all of them. None of them are going to be available because they are all already in the scene. And then we have to return something. If we reach this state, then it means we should instantiate another bullet. So we can just grab the code that we made here for making a new prefab. You can just copy that and paste here.

We’re making a new bullet. There’s only two to use this set active here. So we basically make a new prefab instance. We set its parent to be the object pulling manager, and finally we store it in the bullet’s array, in the bullet’s list. And after we do this, we type return prefab instance. So that’s going to return what we just added. And we’re going to basically add the bullet. And back in the player, instead of using this instantiate method call here, we’re going to use the get bullet from the object pool manager. So I’m going to paste it here. Alright, so now the bullet object is spawned by using the object pooling manager. I’m going to remove the reference for the bullet prefab. The player no longer needs to know what is the exact prefab. And in the bullet there is one important step here.

Instead of calling destroy game object, instead of removing the bullet from the game entirely, we’re going to type GameObject.SetActive false. Otherwise the bullet would disappear after it has been instantiated. And then it would happen over and over again. So we need all of these changes. So let’s test them out. I’m going to save that. Let’s go to Unity. Wait for the compilation to be complete. I’m going to change the bullet amount to two. And I’m going to press play.

So if we go to look at the object pooling manager, we have two bullets. If I shoot one, you see that it got active and then deactivated. But then if I click again, the bullet quickly blinks in the screen. So why is this happening? If you go to the bullet script, you’re going to see that the live timers is only set in the start method. And very important to know is the start method is only called when the object is instantiated. But since this is going to be pooled, we’re going to change the start to OnEnable. So let’s give this a try. We’re going to save this. Let’s go to Unity, wait a little bit more, and we’re going to press play. I’m going to click here, and yes, OnEnable with the case. Now every time I click, the duration is set back to its original state, so the entire lifetime. And take a look at the object pooling manager to see how things are working here.

If I click bullet one is instantiated. If I click twice, both of them are active, because we need two bullets in this case. We’re basically reusing bullets no longer re-instantiating. We’re just retrieving from the pooling manager. If I click several times, new bullets are adding to the pooling manager. So I can click four times very quickly and it’s going to use all of the bullets available.

So basically you can click like crazy, very, very frequently, and the bullets are going to be reused. No more memory allocation, no more very large amount of processing involved in adding these bullets. And now you can pretty much see the limit that you have here. So seven bullets, but let’s change that to eight, just to make sure. So the game is going to have a little time to load in the beginning, but that’s going to save you a lot of time in the future and it’s going to make sure that the game is going to be very efficient.

Using Objective Indicators to Enhance Your Unity Project – Part 2

Introduction

In this second tutorial, we’ll be creating a multi-indicator system based on the core methods we employed in Part 1. This upgraded project will include a custom dynamic link library, multiple indicator control, and user definable UI sprites.

Tutorial Requirements

To complete this tutorial, you’ll require a basic understanding of Unity and Visual Studio workflow.

Asset Package

To avoid unnecessary repetition, the new asset package contains a preconfigured scene and several additional components. You can download the assets here. Unzip the package, making a note of the location.

Asset Usage

The components are released under the ‘Creative Commons 0’ license.

The Unity Project

We’ll begin by creating a new Unity project named ‘Indicator_System_Part_2’

Image may be NSFW.
Clik here to view.

Next we’ll import the asset package you downloaded earlier…

  • Right click inside the ‘Project /Assets’ pane
  • Select ‘Import Package / Custom Package’
  • Navigate to and select the ‘IndicatorSystem_02_Assets’ package
  • Click ‘Open’ to display the ‘Import Unity Package’ window
  • Click ‘Import’

Image may be NSFW.
Clik here to view.

Now we’ll open the preconfigured scene…

  • Open the ‘Project / Assets / Scenes’ folder
  • Double click on the ‘IndicatorSystem’ scene

Image may be NSFW.
Clik here to view.

To finish the scene set up we’ll align the scene view to match the Main Camera view…

  • Select the ‘Main Camera’ in the ‘Hierarchy’ pane
  • Open the ‘GameObject’ menu and select ‘Align View to Selected’

And finally, we’ll remove the redundant default scene…

  • Open the ‘Assets /Scenes’ folder
  • Right click on the ‘SampleScene’ and select ‘Delete’
  • Click ‘Yes’ to confirm
  • Save the scene

You can close Unity as we’ll be switching to Visual Studio to create the dynamic link library.

The Dynamic Link Library

You can think of dynamic link libraries as portable containers for functions, instructions and resources. Aside from their inherent ease of deployment, they offer several additional advantages when compared to static link libraries.

  • Portable modular format
  • Memory efficient
  • Reduced disk space requirements
  • Reusable across projects
  • Simultaneous process access

Visual Studio Installation

We’ll be using Visual Studio to create our DLL. If it’s not present on your computer, you can install it via the Unity installer list.

Image may be NSFW.
Clik here to view.

Creating The Visual Studio Project

Before you open Visual Studio, create a parent folder for our library…

  • Create a folder named ‘Net Libraries’ in an accessible location such as your desktop

Now we can begin to create the VS project…

  • Launch Visual Studio
  • [BP] Open the ‘File’ menu and select ‘New / Project’

Image may be NSFW.
Clik here to view.

To ensure compatibility with earlier Unity releases, we’ll be using a NET Framework class.

  • Select the ‘Visual C# / Class Library (.NET Framework)’ option
  • Enter ‘IndicatorSystem’ in the name field
  • Click the location ‘Browse’ button
  • Navigate to the ‘Net Libraries’ folder you created earlier
  • Click ‘Select Folder’
  • Set the ‘Framework’ field to ‘.NET Framework 3.5’
  • Click ‘OK’ to create the project

Image may be NSFW.
Clik here to view.

Visual Studio will create the new project in your ‘Net Libaries’ folder and open the class script window…

Image may be NSFW.
Clik here to view.

  • Save the project

Adding Unity References

We’ll need to add a couple of Unity references to the project…

  • Open the ‘Project’ menu and select ‘Add Reference’

If you’ve accessed the Unity Engine and Unity UI libraries before, they’ll be listed in the Reference Manager list. If not, you’ll need add to each component manually…

Image may be NSFW.
Clik here to view.

  • Click the Reference Manager ‘Browse’ button
  • Navigate to each location in turn
  • Click ‘OK’ to add each reference

Once both libraries appear in the the Reference Manager list, you can add them to your project…

  • Select both libraries and click ‘OK’
  • Save the project

Image may be NSFW.
Clik here to view.

Class Export Settings

Before we begin scripting, we’ll set the class export settings…

  • Open the ‘Build’ menu and select ‘Configuration Manager’
  • Set the ‘Active solution configuration’ field to ‘Release’
  • Set the ‘Configuration’ type to ‘Release’
  • Click ‘Close’
  • Save the project

Image may be NSFW.
Clik here to view.

The Indicator Library Script

The ‘Indicator’ library script handles the on screen UI indicators by tracking the position of the player object in relation to each target position. Canvas point conversion is handled by the ‘UpdatePosition’ function which also updates each target’s enabled status and UI position.

  • Delete the existing class code
  • Enter the following script

using System;
using UnityEngine;
using UnityEngine.UI;

namespace IndicatorSystem {
    // Create Objective Class
    [Serializable]
    public class IndicatorClass {
        [HideInInspector]
        public Image indicator;
        [HideInInspector]
        public Text label;
        public Transform target;
        public Sprite sprite;
        public Color color;
        public bool enabled;
    }
    // --
    public static class Indicator {
        // Declare Alignment Vector
        private static Vector3 alignmentVector;

        // -- Update Function
        public static void UpdatePosition(Transform player, IndicatorClass[] oc) {
            // Recurse Objective Class Elements
            foreach (IndicatorClass element in oc) {
                element.indicator.gameObject.SetActive(RelativePosition(player, element.target, element.enabled));
                // Set Indicator Status
                if (element.indicator.gameObject.activeInHierarchy) {
                    element.label.text = LinearDistance(player.position, element.target.position) + "m";
                    // Convert Target Position To Viewport Point
                    alignmentVector = element.indicator.rectTransform.anchorMin;
                    alignmentVector.x = Camera.main.WorldToViewportPoint(element.target.position).x;
                    // Update Indicator Position
                    element.indicator.rectTransform.anchorMin = alignmentVector;
                    element.indicator.rectTransform.anchorMax = alignmentVector;
                }
            }
        }
        // --
        private static float LinearDistance(Vector3 playerPosition, Vector3 targetPosition) {
            // Zero YAxis Coordinates
            playerPosition.y = 0;
            targetPosition.y = 0;
            // Return Linear Distance
            return Mathf.Round(Vector3.Distance(playerPosition, targetPosition));
        }
        // --
        private static bool RelativePosition(Transform player, Transform target, bool status) {
            // Return On Null Player / Null Target / Disabled Element
            if (!player || !target || !status) {
                return false;
            }
            // Return Relative Position Boolean
            return Vector3.Dot(Vector3.forward, player.InverseTransformPoint(target.position).normalized) > 0;
        }
        // --
        public static bool PopulateClass(Canvas canvas, Image indicator, IndicatorClass[] oc) {
            // Return On Null Canvas / Null Indicator / Null Class
            if (!canvas || !indicator) {
                return false;
            }
            /// Instantiate Indicator Components/
            foreach (IndicatorClass element in oc) {
                Image indicatorClone = UnityEngine.Object.Instantiate(indicator, canvas.GetComponentInChildren<RectTransform>());
                indicatorClone.color = element.color;
                indicatorClone.sprite = element.sprite;
                // Populate Objective Class Elements
                element.label = indicatorClone.GetComponentInChildren<Text>();
                element.indicator = indicatorClone;
            }
            // Return Structure Validation
            return true;
        }
    }
}

  • Save the project

Building The Library

Once you’ve entered the code and saved the project it’s time to build the library…

  • Open the ‘Build’ menu and select ‘Build IndicatorSystem’
  • The ‘Output’ window will open to display the build progress

Once the project has been compiled you should receive the following confirmation…

Image may be NSFW.
Clik here to view.

If you receive an error message, compare your code with the original script, amend as necessary and repeat the build process. But all being well, you’ve successfully created the dynamic link library.

  • Save the project
  • Close Visual Studio

Importing The Library

The dynamic link library you’ve created will be the core of the Unity project so it should be imported before we create scripts which rely on the custom functions.

  • Launch Unity
  • Open your ‘Indicator_System_Part_2’ project

Now we’ll create a new asset folder…

  • Right click inside the ‘Assets’ pane
  • Select ‘Create / Folder’
  • Rename the folder to ‘Plugins’

The DLL can be imported using the standard method…

  • Right click on the ‘Plugins’ folder
  • Select ‘Import New Asset’
  • Navigate to your ‘Net Libraries’ folder
  • Drill down to the ‘obj / Release’ folder
  • Select the ‘IndicatorSystem.dll’ component
  • Click ‘Import’
  • The DLL import settings pane will be displayed

Image may be NSFW.
Clik here to view.

The Project Scripts

The project requires scripts for the camera, player and indicator manager. All scripts include descriptive comments.

The Camera Script

  • Open the ‘Assets / Scripts / Camera’ folder
  • Double click the ‘FollowCam’ script to open your script editor
  • Delete the existing code
  • Enter the following code…

using UnityEngine;

public class FollowCam : MonoBehaviour {
    // Public Declarations
    public Transform targetObject;
    public float cameraDistance = 12.0f;
    public float cameraHeight = 3.0f;
    public int heightDamping = 3;
    public int rotationDamping = 3;
    // Private Declarations
    private float currentHeight;
    private float currentAngle;
    private Quaternion currentRotation;

    // --
    void LateUpdate() {
        if (!targetObject) return;
        // Increment Camera Height & Angle
        currentHeight = Mathf.Lerp(transform.position.y, targetObject.position.y + cameraHeight, heightDamping * Time.deltaTime);
        currentAngle = Mathf.LerpAngle(transform.eulerAngles.y, targetObject.eulerAngles.y, rotationDamping * Time.deltaTime);
        // Populate Rotation Quaternion
        currentRotation = Quaternion.Euler(0, currentAngle, 0);
        // Set Camera Position
        transform.position = targetObject.position;
        transform.position -= currentRotation * Vector3.forward * cameraDistance;
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
        // Look At Target
        transform.LookAt(targetObject);
    }
}

  • Save the script
  • Drag the ‘FollowCam’ onto the ‘Main Camera’ game object

We’ll need to add a ‘Player’ object reference to the ‘FollowCam’ script…

  • Select the ‘Main Camera’ object
  • Click the ‘Inspector / FollowCam / Target Object’ select icon
  • Double click on the ‘Player’ game object

Image may be NSFW.
Clik here to view.

The Player Script

  • Open the ‘Assets / Scripts / Player’ folder
  • Double click the ‘PlayerMotion’ script to open your script editor
  • Delete the existing code
  • Enter the following code…

using UnityEngine;

public class PlayerMotion : MonoBehaviour {
    // Private Declarations
    private float verticalInput;
    private float horizontalInput;
    // Public Declarations
    public float motionSpeed = 10.0f;
    public float rotateSpeed = 90.0f;

    //--
    void Update() {
        // Assign User Input
        verticalInput = Input.GetAxis("Vertical") * Time.deltaTime * motionSpeed;
        horizontalInput = Input.GetAxis("Horizontal") * Time.deltaTime * rotateSpeed;
        // Apply Motion / Rotation
        if (!horizontalInput.Equals(0) || !verticalInput.Equals(0)) {
            transform.Translate(0, 0, verticalInput);
            transform.Rotate(0, horizontalInput, 0);
        }
    }
}

  • Save the script
  • Drag the ‘PlayerMotion’ script onto the ‘Player’ game object

Image may be NSFW.
Clik here to view.

The Target Manager Script

The target manager script references the ‘IndicatorSystem.dll’ and serializes the user configuration inspector pane.

  • Open the ‘Assets / Scripts / Manager’ folder
  • Double click the ‘TargetManager’ script to open your script editor
  • Delete the existing code
  • Enter the following code…

using UnityEngine;
using UnityEngine.UI;
using IndicatorSystem;

public class TargetManager : MonoBehaviour {
    // Public Declarations
    public Canvas canvasReference;
    public Image indicatorReference;
    public Transform playerReference;
    // Class Reference
    public IndicatorClass[] indicatorClass;
    // Private Declarations
    private bool classValidated;

	// --
void Start () {
        // Populate Indicator Class / Return Validation
        classValidated = Indicator.PopulateClass(canvasReference, indicatorReference, indicatorClass);
	}
	// --
    void LateUpdate () {
        // Invoke Update Function
        if (classValidated) {
            Indicator.UpdatePosition(playerReference, indicatorClass);
        }
    }
}

  • Save the script
  • Drag the ‘TargetManager’ script onto the ‘Targets’ game object
  • Select the ‘Targets’ game object
  • Set the ‘Inspector / Target Manager / Indicator Class’ size to ‘4’
  • Open each ‘Indicator Class’ element

Image may be NSFW.
Clik here to view.

Target Manager Configuration

We need to add references to the the target manager script. The indicator system will not operate if it encounters a null reference.

Canvas Reference

  • Click the ‘Canvas Reference’ selection icon
  • Double click to select the ‘Canvas’ game object

Indicator Reference

  • Drag the ‘Assets / Prefabs / Indicator’ prefab to the ‘Indicator Reference’ slot

Player Reference

  • Click the ‘Player Reference’ selection icon
  • Double click to select the ‘Player’ game object

Target References

  • Click each ‘Element / Target’ selection icon
  • Double click to select the corresponding ‘Target’ game object

Sprite References

  • Click each ‘Element / Sprite’ selection icon
  • Double click to select your choice of indicator sprite
  • Save the scene

The Custom Color Palette

The ‘Assets / Editor’ contains an ‘IndicatorPalette’ component which contains a selection of example colors for use with the UI sprites.

  • Click on the ‘Element 0 / Color’ field to open the ‘Color Selector’
  • Left click the ‘Palette Selector’
  • Select the ‘IndicatorPalette (Project)’ option
  • Choose a color for each element

Image may be NSFW.
Clik here to view.

Indicator Enabled Option

  • Activate all ‘Element / Enabled’ options
  • Save the scene

Image may be NSFW.
Clik here to view.

Testing The Scene

Having made it through this final tutorial, you’ll be pleased to know that we’re now ready to test the project!

  • Press the Unity ‘Play’ icon
  • Use the arrow keys to move the player object around the scene

If the 4 objective indicators are visible and the distance information is valid, then you’ve succeeded. If there are no visible indicators, check the ‘Target Manager’ script references to ensure that they are correctly assigned.

System Deployment

Once configured, the indicator system operates on an automatic basis, but you can set any indicator’s enabled status from script.

‘indicatorClass[index].enabled = true / false’

Please refer to the ‘Target Manager’ script comments for full deployment information.

Conclusion

So that’s it for now: we have now finished this project allowing you to create a fully portable multi-indicator system for use in your own creations. We upgraded it from the core methods employed last time, to include a custom dynamic link library, multiple indicator control, and user definable UI sprites. Hope you enjoyed this tutorial, found it helpful, and that it will prove useful for your games. Please feel free to share your thoughts in the comments down below – otherwise, until next time.

Web Class: Setting up and customizing an FPS Controller Character in Unity

Transcript Part 1 

Hello, everyone. This is Glauco Pires, for Mammoth Interactive, and welcome to the First Person Shooter tutorial in Unity.

So to begin, we have to open the Unity software and click on this button to make a new project. And in this screen here we have to set a project name which is simply going to be FPS Shooter, or just Shooter, whatever you think is better for you. And, we also have to set the project location. So, I like to use a project folder that is right under my home folder, just to keep things organized. It’s not a good idea to leave things and documents under the desktop folder, because it’s going to mix up with other things. Okay, and once we do this we have to make sure that we have 3D enabled, just make sure you’re not going to make a 2D project. So we’re going to mark this one, and we’re now going to click on create project.

So we have to wait just a little bit for Unity to set up all the files for us for the beginning scripts and well, all of the procedures to open, and we’re going to be in this screen here.

Okay, so we want to make a first person shooter game, and there is one important thing to do. Unity is very friendly regarding using asset packages. So, some people from around the world, they use the asset store for Unity, and they build things that you can’t simply purchase or download for free depending on what’s available out there. And you can already use these things in your projects. So, there is no need to reinvent the wheel. Some things are already done so we can worry about making the game and not, uh well, reinventing the wheel.

So, for the first person shooter game there is a lot of work already done for us and already packaged with Unity. So if you installed your Unity software and you didn’t change anything regarding the standard assets, they should already be here in your project. And to include everything related to first person shooters, we’re going to the assets option here, we’re going to go to import package, and you’re going to see that there are several options available here. There is custom package in the case you download it from the internet and you want to add anything to your project. But it also has other things here, like 2D, cameras, characters, effects, particle systems, vehicles, there are lots of things available here. But the one that we want is characters. So we’re going to select this option here, a new menu is going to open, and we’re going to see this window here that says import Unity package. This is where the magic is going to happen.

So, if you collapse a few of these folders here, you’re going to see several different things. So there are characters, cross platform input, editor. So all of these folders, they do all the necessary work to make first person shooter character’s work in a very simple way. So if you go to the character’s folder you’re going to see that we already have this first person character. And we even have two more options, rollerball and third person character.

But, lets get first person character, okay. And we have audio, we have prefabs, we have scripts, so everything’s already built for us. What we want to do now is, let’s make sure all of the check boxes are marked. You can just click on this one if you enabled or disabled anything, so make sure everything is going to be selected. And we now press import. So that package is going to basically decompress, and all of its files are going to be added to our project which is basically this assets folder.

Okay, we have to wait just a little bit, some images are going to be a process, they’re going to be compressed depending on the build settings that you adjusted for your project, but well, we just have to wait a little bit. And after this is done, you’re going to see that with a simple drag and drop, we’re going to be able to enable the first person shooter mode, okay. So, just a few more assets in, there we go.

So, in the assets folder we now have this standard assets folder and here we have characters. Let’s enter this folder. Okay, just click here. And in the characters folder we have first person character, we open that. And now we have audio, we have a text file that says some guidelines here that you can read here if you want, and we have prefabs and we have scripts. So if you take a look at the guideline, the first option, the first entry that they say in these instructions is, there should be a flat ground to walk around on. Because if you add the player in an empty scene, that player is basically going to fall.

So we’re going to come here into hierarchy, we right click, select 3D object, and we can add two things. Either a cube, or terrain, okay. Or, we could also use a plane as well. I’m going to start with a cube, okay even though the plane works just fine. We want to keep things simple and well, we’re just going to adjust this in a better way by using cubes. So I’m going to select this cube here, and we have a new entry in the hierarchy. I’m now going to re-name that so right click, choose Rename, and we can name this as Floor, something very simple.

And we have this cube here. In the inspector, we want to make sure its position is going to be in the center. Zero, zero, zero. And the scale on X, let’s make it bigger, like 20. Y is going to be smaller than that, so lets use 0.1. So it’s going to look like that, a really flat floor. And Z is going to be 20 as well. So we have that little sheet where we can basically walk on.

Okay, it’s going to be something very simple for us. And now that we have that floor here, we should just change its color a little bit to make it easier to see where we are going to walk on. So, we can go to the assets folder, right here. We can right click, choose create, and then folder, and here we’re going to name this folder as project.

So, why do I do this? I do this because in the root folder for your project, which means the Assets folder, you might include different asset packages and each of these packages are going to make a folder here. So we have standard assets, and maybe want to add a multiplier later, maybe you download an asset pack for a toonish level, and there’s going to be another folder. So there should be several different folders for every different asset that you make. So a good idea is to make a project folder because we’re going to ensure that everything is going to be in this folder is created by us. It’s not going to mix up with other folders. In your first projects it might not be necessary, but even though I just said that, it is important for you to organize things from the beginning.

Okay, it’s going to make a lot of difference once you evolve your project to something bigger. So here in this project folder, we now right click, choose create, we’re going to make another folder, and we’re going to name this materials. And now inside this folder we’re going to make a material, which is basically the element that is going to shade this floor in a different way. So right click, create, then material, and I’m going to rename this as floor. Simple as that. And with that here, we’re going to change its color. Okay, you can just select the floor and look at the inspector, so its information is loaded here. We’re going to click in this large rectangle and use the color picker to choose anything we want. I’m going to choose a dark orange, okay like that. Or maybe a dark gray, should be okay as well. So I’m going to click here, choose that, and to apply this material to this floor we can simply drag it and drop here. Okay, so we have a dark floor.

Alright, now, if you go back to the first person character and look at the second instructions, it’s going to say place the first person character prefab in the scene. So this is the magic that is going to happen. If you go to the prefabs folder, you’re going to see two prefabs. FPSController and RigidBodyFPS controller. So, if you get an FPS controller, and you drag and you drop in the hierarchy, you’re going to see this element here, okay. So lets use the transform tool to move it up a little bit. And click on this arrow and move it up to this position. And you’re going to notice a few things. Okay, so that character contains a little audio icon and contains that camera here. Okay, so that means the character, the FPS controller, contains its own camera. And that makes sense because we are going to be looking through the perspective of a character, of a humanoid, or through a monster for example. It’s simply going to be here, and we’re going to see things like they see. That means we don’t need two cameras.

Okay if you look at the instructions, the 3rd instruction is going to say, if present, delete the main camera that exists in the new scenes by default. Okay, so if you look here, we already have a main camera in this scene. We have main camera, we have directional light, floor, and FPS controller. So, we’re going to delete this camera. No longer necessary. And now we have this FPS controller here. Okay, so at this point of this project, if we press the play button, we have to wait a little bit because this is the first time this game is going to be played.

But, once you are here, I can hear the footsteps of the player. You can’t hear them right now because of my recording. But well, if you walk, the footsteps are playing. If you press pace, you jump, and there is even a jumping sound, which is very good. If you don’t want to hear the sounds you can just press mute audio here, in the game window, and its going to be better for us to walk around the scene.

So, just with little adjustments we can already have a player here. We can even run if you hold shift, you can walk really fast in this game. And we can pretty much start working on the first person shooter.

Transcript Part 2

Whenever you are making games, it is important to understand that things need to be highly customizable. Analyze that. You may write a lot of code for making a character to move, for it to jump, for it to shoot but at certain points, you have to be very quick about how you change things because making games is a thing that requires a lot of creativity and a lot of experimentation. So, while the game is running, you need to be able to adjust variables, to adjust the settings for the player and for the enemies for the entire game and then adjust that and for example, you might have a team where you have a game designer like you have a fellow artist, programmer, sound designers, and they might want to change some settings, so a good thing about Unity is that it can easily make things customizable and we’re going to learn how to do this in the next lessons.
The first thing that we want to check is to select the FPSController in the Hierarchy and look at the Inspector. So, we have several components here like transform character controller but the important one as we want to check is the first person controller script. You’re going to see there are lots of fields here, we have check boxes, we have text fields, we have some knobs that we can drag and change that here, jump speed, gravity, multiplier, so there are lots of things here that we can use and that we customize. So for example, if you press the play button right now, you are now running the game. What you can do is you can change these variables to experiment, to try new things, so maybe the walking speed for your game might be too quick and you can change that from five to three and run speed shouldn’t be 10, maybe six, you can just get here, change these numbers and if you walk now, you’re going to walk slower than before. If walk speed was set to 10 for example, then the player would walk really, really fast, you can see that it’s moving up and down very quickly because well, it’s moving very quickly. So, let me go back here to five and 10. You shouldn’t use this as walking setting right now. It’s basically when you hold shift, then that checkbox disappears. That’s something that is dynamic. You don’t need to change that and we also have other settings.
Let’s see some of the most important ones. We have walk speed, run speed, we have the run speed lengthen, that’s okay, and we also have the jump speed. That is, for example, if you choose 20 here and you jump, you’re going to jump much higher than before, so that could be thought as the impact of your jump, of your legs, how strong you’re going to perform a jump and we have the gravity multiplier. This one is pretty interesting. If we choose 10 here and we jump, we barely leave the floor because the gravity’s going to be very strong but if we change it to one, for example, and we press space, it’s going to feel like we are in the main. So, why do we have this gravity multiplier? It’s basically part of these variables were set here. The default variables for the gravity, so you might want to check this, if you go to Edit, Project Settings and then you go to Physics, we’re going to see that the gravity sets in minus 9.81, so that’s the real value for the gravity that actually happens in the real world but when you’re playing the game, sometimes you don’t want realism to be all over it because that is going to make your game not entirely fun. So, for example, if we were to jump like this, with the gravity multiplier one, it wouldn’t be very good except if we were in the moon or in another planet, so maybe if you’re making a space game that would be interesting but if we use gravity multiplier as one, then we would have to reduce the jump speed, so if you jump, it’s going to look like this. However, you see, we still have a lot of air time by doing this jump. We jump and then we return quickly to the floor but that’s not realistic at all, that’s very small, very slow movement, so that’s why we have to play with two things, the jump speed and gravity multiplier and the value that we have here for jumping is is pretty much default on every, every, every first person shooter game you play, either it’s in a mobile phone, it’s in a video game, it pretty much feels like that almost every time, so that’s why we have this gravity multiplier.
Now, if you go to mouse look, there going to be a few settings here, so the most basic of them is the sensitivity. If you played old first person shooters, you might remember that you can set these things in the console. Right now it’s set to two on X and Y and we’re moving like this. I’m moving my mouse around, looking to the left and to the right. If I change that to five on both of them, then it’s going to be much more sensitive. I’m moving the mouse in a very short length and we are turning our heads very quickly here. So, that’s something that you might even want to allow your players to change later in the settings screen but I’m gonna leave it at two.
Now, we also have here clamp vertical rotation. This one is very interesting. So, if you’re playing a first person shooter game it is very usual for you to be able to look down all the way and to look up all the way as well. If you are making a first person shooter game where you are a turret or if you are in a weapon you might want to change this setting, so you ensure that this is checked and you might define the minimum X and the maximum X. This is the rotation. It’s how low or how high we can look. So, if we change that to minus 20 and 20 for example, if I look up, there is a vertical limit, so right now I’m moving my mouse upwards but we can’t look up all the way. If I move the mouse down, same thing applies, I can’t look directly, well, 90 degrees down, I can look to the floor but there is that limit here. That’s interesting if you are holding a turret.
And also one other interesting thing is we have this move setting. If you mark this checkbox, and you look around, so if you move your mouse, then Unity is going to ensure that that movement, that look movement is going to be very smooth. It’s going to slowly change from one target, from the one place you’re looking before, to the place you’re looking, so again this is interesting for turrets. As turrets might be very strong weapons, you might use low values for the smooth time, so it takes time for you to aim at an enemy that’s coming at you. On the other hand, if you aim correctly and you shoot, you’re going to destroy that enemy very quickly.
So, let me just restart the scene to reset these settings and that’s important. If you are in the play mode and you change these settings and you stop the game from running right now, all of the settings are going to be reset to how they were before you pressed the play button in Unity, so what you want to do is you want to tune your things, tune these values here, tune all of these fields and right now the numbers that you think are going to work well. So, you stop the scene, then set them and move forward.
And another one that’s interesting to see is the head bob. By default in Unity that head bob is set as active, so if you look, you’re going to have that movement as you are walking or as you are running. It’s the natural movement of your head. It moves up and down vertically but for some players that might induce some nausea at some players, so we might want to disable that feature completely, so you can just click on this checkbox and if you walk there is no head bob at all, that’s common, however, if you want to use the head bob, you can change its settings here. There is the horizontal, the vertical range and well, some other settings here that we might want to change. And the same applies for the jump bob. If you jump and you land you notice that there is a little vibration. If you change this bob amount to one for example, you can see that more clearly, so if you land, there is that little kick back when you land, it’s like you’re landing on your feet and your knees they bend a little bit for you to land safely. It’s something very natural.
Well, I’m showing you that just to give you the idea that it can change and that you can customize things. And once you make your scripts which we’re going to do very shortly, we want to make sure it’s highly customizable like this one here, so we can change things very, very quickly and I’m going to leave the default values here because they work very well for me. I think they are all basically okay but feel free to pause this video right now to stop the course a little bit and change to the values that you think are going to be comfortable for you.

 

Intel Features our Founder and Learning Community

Zenva’s Founder Pablo Farias Navarro was recognized by Intel as an Innovator of Tomorrow. In this interview, hear as he shares his story, and how Zenva was inspired by his dream to make learning to code accessible to everyone.

Today, Zenva has inspired over 350,000 students to learn programming and upgrade their development knowledge – regardless of where they live, or whether or not they are connected to the main innovation hubs.

With the access to the most popular, cutting-edge techniques that Zenva provides, discover how our students have been able to reach their development dreams – whether through teaching these skills to others, by expanding their portfolio, or embarking on a freelance career.

Using Unity’s Scriptable Object System: Pizzaria Project – Part 1

Part 1: What are scriptable objects, why would you use them, a UI Setup, and the Dialogue Controller

During this three part tutorial series, we will be creating a small project consisting mainly of UI (User Interface) elements.  The user will be taking customer orders and making “digital pizzas” according to what the customer has ordered. We will use scriptable objects to hold the data of the pizza ingredients, and the dialogue data for the employee to customer speech. You will learn what scriptable objects are and why you should use them to increase your productivity when including this system in your projects.

To ensure that you will be able to effectively follow along with this tutorial, you should be comfortable with:

  • C# Programming
  • Unity Editor
  • Visual Studio 2017
  • Adding components to game objects
  • Serialization
  • Creating UI elements such as text objects, buttons, and panels.

Source Code Files

You can download the tutorial source code files here. All the project files are located in the main folder. The asset folder contains additional intermediate files that were used during the process of creating the game sprites.

What are Scriptable Objects?

Scriptable objects are essentially data holders. They are great for holding large amounts of data for games that require inventories, card games and, dialogue systems. Scriptable objects are not Monobehaviours and need to inherit from ScriptableObject in your scripts. They also are not attached to GameObjects and are saved as .asset files in your projects. Scriptable objects can be dragged and dropped onto inspector reference components in projects. They can be created by adding the [CreateAssetMenu] attribute inside a script.

For even more information regarding Unity’s Scriptable Objects check out the fantastic Unite 2017 talk given by Ryan Hipple! Here is the link: https://youtu.be/raQ3iHhE_Kk

Why use Scriptable Objects?

Scriptable objects require little memory. The data persists through run time. You can edit Scriptable Objects during play mode. This makes play testing easy, because values such as enemy health, damage values, etc. can be changed while playing and those values will remain the same after exiting play mode. With that being said this can also not be so good if someone making the changes during play mode doesn’t revert the changes if they are unwanted.

User Interface Setup

Before proceeding any further with this tutorial go ahead and make sure you are using Unity version 2018.2.18f1. You may use an older version of Unity, but you may notice differences between the version used in this tutorial and your version, and it may make it difficult to follow along effectively. Go ahead and create a new 3d project, you can name the project whatever you like. Generally Unity will default to windows build settings on a new project, but for some reason if it didn’t make sure you are set to a windows build.

Create a UI>Panel. Rename the Canvas game object to “UI Container.” Rename the Panel you just created to “MainPanel.” Select the UI Container in the Hierarchy and on the Canvas element in the Inspector change the Render Mode to World Space, and drag the Main Camera into the Event Camera spot in the Inspector window.

Image may be NSFW.
Clik here to view.

Essentially, we are going to create an effect as if the user is a Pizzaria employee and we are going to make it seem like this is a First Person view aspect where the user is turning and looking at the different computer screens in the actual Pizzaria workplace. This project could also be expanded on afterwards and turned into a Virtual reality real world application where maybe the workplace could train new employees using this application.

Select the MainPanel object and adjust the Pos Y value to 250, Width value to 400, and the Height value to 300 on the Rect Transform component in the inspector.

Image may be NSFW.
Clik here to view.

Duplicate the MainPanel object, and rename the second one to “CashRegisterPanel.” On the Rect Transform component adjust the Pos X value to 181, Pos Y to 250, and the Pos Z to -250.

Image may be NSFW.
Clik here to view.

Duplicate the “CashRegisterPanel” object and on the Rect Transform component adjust the Pos X value to -181, Pos Y to 250, and Pos Z to -250. Rename it to “CookPanel.”

Image may be NSFW.
Clik here to view.

Add a UI Button object to the MainPanel and rename it to “GoToCashRegisterBtn.” Now adjust the Anchor Preset by holding Shift and Selecting the Bottom Right, let go of Shift and select Bottom Right again. This is going to set the Anchor point so that are button doesn’t move around if the resolutions are changed.

Image may be NSFW.
Clik here to view.

Make sure the Image(Script) component in the Inspector is set to UI Sprite. Rename the Text component on this button to “CashRegisterBtnTxt.” In the text field type “Cash Register” Leave the font at Arial, change the Font Style to Bold and Italic. Change the Font Size to 12. Adjust the alignment to center and middle. Horizontal Overflow should be set to Wrap and Vertical Overflow set to Truncate.

Image may be NSFW.
Clik here to view.

Duplicate the “GoToCashRegisterBtn” rename this object to “GoToCookBtn.” Rename the Text on the button object to “CookBtnTxt.” Change the text in the Inspector to “Cook Pizza.” Adjust the Anchor to Bottom Left; follow the same procedure as we did for the “GoToCashRegisterBtn.”

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Select the “MainPanel” object in the Hierarchy and add a UI>Panel as a child object. Rename this Panel to “Title.” Adjust the Anchor setting to Top Center and follow the same procedure as we did with the previous anchoring of the two buttons we had already created.

Image may be NSFW.
Clik here to view.

Change the Color to Red on the Image(Script) component in the Inspector. Adjust the Width on the Rect Transform component to 175 and the Height to 45.

Image may be NSFW.
Clik here to view.

Add a UI> Text object to the MainPanel as a child of it. Rename it to “PizzariaTxt.” Adjust the anchor to Top Center.

Image may be NSFW.
Clik here to view.

On the Rect Transform component adjust the Width Value to 175 and the Height value to 45. In the Text field put “Pizzaria.” Adjust the Font Style to Bold Italic. Adjust the Font Size to 35. Adjust the Alignment to Middle and Center. Horizontal Overflow needs to be set to Wrap and the Vertical Overflow to Truncate. Change the Color to white.

Image may be NSFW.
Clik here to view.

Select the CashRegisterPanel and create a UI>Panel, the new panel needs to be a child of the CashRegisterPanel. Rename this object to “MenuItemsContainer.” The MenuItemsContainer will house the different menu items that customers can order from the Pizzaria, we will add these items, which will be done via scriptable objects in Part Two of the tutorial.

Set the Anchor Presets to Middle Stretch.

Image may be NSFW.
Clik here to view.

Add a Horizontal Layout Group component to the MenuItemsContainer object from the Inspector. Make sure the child Alignment is set to Middle Center. Uncheck all the boxes for Child Controls Size and Child Force Expand.

Image may be NSFW.
Clik here to view.

Add a Scroll Rect component to the MenuItemsContainer from the inspector. In the Content field make sure to drag and drop the MenuItemsContainer into that spot on the inspector. Make sure Horizontal is checked and Uncheck Vertical. Set the movement type to elastic. Elasticity should be set to 0.1, and feel free to play with this value to your preferences. I felt like leaving it at 0.1 was a good fit. Make sure Interia box is checked. Deceleration rate can be left at 0.135. Scroll Sensitivity can be left at 1. If you are not happy with this value, you may adjust this as well to your liking.

Image may be NSFW.
Clik here to view.

Select the MenuItemsContainer in the Hierarchy, and add a UI>Button; make sure the Button is indeed a child of the MenuItemsContainer object.  Set the Anchor Preset to Top Left. Adjust the Width value in the Rect Transform to 100 and Height to 200.

Image may be NSFW.
Clik here to view.

Add a Layout Element component to the Button from the inspector window. The Min Width box should be checked and the value set to 100. The Min Height box should be checked and this value set to 200.

Image may be NSFW.
Clik here to view.

Duplicate this button 3 times, you should now have a total of 4 buttons that are children of the MenuItemsContainer object. The buttons should now look like this in the scene window:

Image may be NSFW.
Clik here to view.

If you hit play and the Main Camera is rotated you can test out the scroll rect by holding the left mouse button down on the buttons and sliding them back and forth. Remember, these buttons will make up the menu items the user is going to be pressing after they take a customer order from the main panel. The main panel will house the dialogue between the user and the customer. We will start adding the dialogue portion of the project in at part two of the tutorial.

When hitting play mode the game window should now look like the screenshot below, my resolution was set to 1024X768, at the time of this screenshot:Image may be NSFW.
Clik here to view.

Dialogue Panel Setup-

Select the MainPanel in the Hierarchy, and create a UI>Image. Make sure the new Image object is indeed a child to the MainPanel. Rename the image to DialogueBGImage. Set the Anchor Preset to Middle Stretch.

Image may be NSFW.
Clik here to view.

Select the MainPanel object in the Hierarchy and add a UI>Text object as a child. Rename this object to “CustomerDialogueTxt.” Adjust the Anchor Preset to Middle Center.

Image may be NSFW.
Clik here to view.

On the Rect Transform component in the inspector we need to adjust the following values: Pos X to 0.5, Pos Y to -11, and Pos Z to 0. Width to 379 and Height to 188. In the Text field type “Customer Dialogue Holder” and then copy paste it till it fills the whole black background area like so:

Image may be NSFW.
Clik here to view.

Change the Font Style to 15, and adjust the Alignment to Middle Center. Set the Horizontal Overflow to Wrap and Vertical Overflow to Truncate. Leave the Color at white.

The place holder dialogue text is simply there so we can see how the real dialogue will fit later on. We will be “feeding” the real dialogue text in with scriptable objects later on in the tutorial series.

Now is a perfect time to go ahead and rename the SampleScene that is already in the Unity Project folder in the Scenes folder to “Main.” Save our scene and project. Create a new folder in the Assets directory and name it “ScriptableObjects.” We will be saving and storing all the scriptable objects we create for this tutorial in this folder. It’s important to keep projects organized so you can easily locate files, scripts, materials, sound effects, art, etc. without wasting valuable time. Create another folder and name it “Scripts.” You should now have the following folders created:

Image may be NSFW.
Clik here to view.

Setting up the Dialogue Controller

Create an Empty Game object and rename this object to “DialogueController.” Reset the transform component. With the DialogueController selected in the Hierarchy add a new script component to this object and name it to “PizzariaOperation.” Open the script up in Visual Studio.

Add the using UnityEngine.UI namespace to the top of this script.

using UnityEngine.UI;

Declare a Text variable and call it txtComponent. This variable is private, but we need to make it so it can be viewed in the Inspector, we can do this by adding the [SerializeField] attribute to this variable. We will be dragging and dropping other components onto this script in the Inspector later on in the tutorial.

[SerializeField]
 Text txtComponent;

Save this script and go back to the Unity Editor, once the script compiles and with the DialogueController object selected in the scene check out the Inspector window, and where the PizzaOperation script is located in the Inspector window you should now see we have a field called Txt Component available.

Image may be NSFW.
Clik here to view.

Click on the small circle selector button next to the None(Text) field in the Inspector. Select the CustomerDialogueTxt object from the list.

Image may be NSFW.
Clik here to view.

Open the PizzariaOperation script in Visual Studio and we need to add a line of code to the Start function. Save the script.

txtComponent.text = ("Placeholder");

For right now the string “Placeholder” will display in the Dialogue panel when the Play button is hit in the Unity Editor.

Image may be NSFW.
Clik here to view.

Save the Scene and Project. This is a good place to conclude the first part of the tutorial. Part 2 of this tutorial series will finish up the DialogueController, and we will begin creating our scriptable objects that will hold the data for the employee to customer dialogue. See you next time!


Web Class: Unity FPS Shooting – Design and Implementation

Transcript Part 1

Whenever you change your scene by adding new game objects by dragging and dropping prefabs here, you have to save it. If you look right now at the Hierarchy, it basically says Untitled because we haven’t saved this scene at all. And to save it, you can just go to File and Save Scene or hit Command + S or Control + S depending on the operating system you’re learning this. So I’m going to press Save Scene and I’m going to save this as Level1. It’s going to be the first level that we’re making. Now we press Save.

And if you look, that file that I just added is going to be in the root of the project, in the Assets folder. So we want to make a new folder inside this Project folder and drag the scene inside it. So I’m going to enter there, right-click, create Folder, and this is going to be named Scenes. And now, I’m going back to the Assets folder and I’m going to drag this scene and drop it here. And now we make sure we have everything organized. And now that we have this, now that we have a Floor, a Direction Light, and a Player, we should be able to start working on shooting some bullets in this game. This is very important because, well, the first-person shooter is a shooter game, so we need a weapon and we need to shoot some pellets or bullets.

So the first thing that we start by doing is to make a weapon here that the player’s going to basically drag around. So at this point of this course, it is important for us to understand about Hierarchy, how Hierarchy works in Unity. So if you look at the Hierarchy window, we have Level1 and we have several elements here, but the Directional Light, the Floor, and the FPSController, they all belong to an entity, that is the entire game. So it is important for us to come here and right-click, choose Create Empty and rename this GameObject as GameController. This is going to be used later but still, it’s important to have a notion of what’s happening here.

Let me put this GameController in the position zero zero zero, so it’s in the root of the world here. And now, we’re going to select all of the elements that we have here. We can select the first one, hold Shift, and the last one, and drag and drop to GameController. So, everything belongs to the game. Now, the weapon is something that belongs to the player, and our player is this FPSController. So we want to start by renaming this FPSController here into Player, just so it’s clearer for us that this is our player, the guy that is going to move around.

So, now that we have this Player and we want to add a weapon here, we want to add that weapon, it doesn’t matter its shape, it could be a cube, it could be a sphere, whatever you want. It needs to be inside this FirstPersonCharacter. Why is that? Let’s make a little test here. I’m going to select the Player, then I’m going to right-click, choose 3D Object, and then I’m going to choose Cube. If you look at the game window, you can see a preview of what the player is looking.

Right now, we can’t see a thing but if you go to the Scene window, you select that cube here and you move it forward like this, if you select the blue arrow, which stands for the depth axis and you move forward, and you look at the game, you start to see the cube. So let’s make a simple test here. At this point, if I press Play, if I look up and down, the cube is going to be there but if I look to the sides, then the cube is going to follow us. It’s not exactly what we want right now but this is starting to, you might realize that we are getting there.

So if you look up and down, the cube is not going to follow. And why this happens, if you play the game and go to the Hierarchy and you select the Player, you’re going to see that the player rotates in the y-axis but not on X and Z, just the Y one. This happens because of how the looking of this player is calculated, how the act of looking around is calculated.

So if you press Esc now to regain the focus of the mouse and you select the FirstPersonCharacter, you’re going to see that it rotates on X. And by having X and Y, we can pretty much look anywhere. First-person shooter games, they, in general, don’t use the z-axis unless you were in a zero gravity scene, if you are controlling a ship, but well, we just need X and Y. And to make sure that we can use both of these axes, we need to go to the Hierarchy and drag the Cube to the FirstPersonCharacter. Now, if we look around, the cube is going to follow us to whatever we are looking. And by having this, we can now have a weapon. But you needed to understand that.

We have the Player, we have the FirstPersonCharacter and the Cube needs to be under the FirstPersonCharacter. So, I’m going to stop this scene and here, I’m going to right-click in FirstPersonCharacter and I’m going to choose Create Empty. And I’m going to rename this GameObject to Gun. Now, the position is zero zero zero, and that position is relative to the FirstPersonCharacter, which its position is relative to the Player. So, this entire hierarchy here is a collection of relative positions.

So now, I’m going to grab this Cube and put it inside the Gun and I’m going to choose the Cube and put it to position zero zero zero. If I grab the Gun now, the Gun game object, if I move it forward, you see that its position changed to zero zero and around two and a half, and the Cube is still in the position zero zero zero because this is relative to the parent. Since the Gun is in this position here, the Cube is also going to be, and that’s pretty much why the rotation works. If you put the Gun here and you rotate around, the Player’s rotation is minus 18, FirstPersonCharacter is 0.7 on X, so the Gun and the Cube are also going to have that rotation because they’re all set to zero.

And now, what we want to do is we’re going to select this Cube and we want to remove this Box Collider. We’re not going to make any collisions with that element. So we click on this cog and choose Remove Component. And now, we want to reposition this gun to another place but before that, let’s make a very, very simple design. I’m going to choose this Cube element here. I’m going to change its Scale on X to 0.3, Y to 0.3 as well, and Z to 0.3. So let’s make Y just a little bit bigger, maybe 0.5. If you look at the game, it’s going to look like this. And if you select the Gun game object and you change its position here, you can already see how it’s going to look like. So if we change to 1.4 and minus 0.3, no, 0.6 on Y, it’s going to look like this. It’s going to be in the right position of the player, You can change that to the left side of course if you want. You just have to select the Gun and change the value for the position here. If it’s positive, then you add a negative sign, so it’s going to be in the other side.

And to finish that, we go back to the Scene window, we’re going to select this Cube and we’re going to duplicate it, so it’s going to be in the same position as the first cube. We’re now going to move it to another position in Z, so maybe one in Z. Y is going to be 0.3 and Z is going to be something like one, something like this. And now, let’s move it closer to the base of the gun, the handle of the gun, so 0.65. And we’re also going to adjust Y, so it’s going to be somewhere here. I think that’s 0.1. So this is the shape of the gun that we have right now. We have the Gun element, which holds all of the other elements inside, and we have the two cubes.

If we go to the game windows, you see that a gun is here and if we press Play, you can see that the gun is going to follow you. You can see that it renders some shadows and if you want to disable that because since we right now don’t have a player model, you can just select the cubes, both of them, and where we have Cast Shadows, you can just disable that, and the shadows are going to disappear and we just have our weapon here. So we can just walk around and the gun is going to follow us completely. And so this is not entirely dull.

We now go to the Project folder, Materials, we want to make a material for that gun. So right-click, Create, then Material, and we need to name that as Gun, and we’re going to click here and change its color to light blue, like this one. After that, we can just drag and drop the material and we need to ensure that we are in the Scene window. Going to drag and drop here and drag and drop there. So we now have our Gun inside the Player. The Gun contains no collisions at all, not going to be used, and we can walk around.

So, what we want to do now is to make that gun to shoot bullets.

Transcript Part 2

Now that we have this gun here, we need to work on the logic for shooting some bullets. So, so far we’ve been using things already provided by Unity. We made game objects, we had a directional light, we viewed the first person character, we’ve used some cubes to design this gun, but we don’t have something specifically set to make the logic for shooting, okay, that doesn’t exist yet So we have to make our own logic. To do that, we have to make some scripts.

We’re going to need a script for the player and a script for shooting bullets. But you might ask yourself, hey, we already have a script here. We have the first person controller. So we can just open this script and then change it. Don’t do that, okay, it’s very important for you to understand that. This script is only for the movement and for the physics of the first person controller. There’s nothing related to shooting here. Yes, you could change that, it would work the same way, but it’s better to have our own script that is going to do other things, okay, besides movement. Something to work with movement.

So to make a script, we’re going to the project folder, we already have materials and scenes, but now we right click, choose create, then folder, and this one is going to be named scripts. Simple as that. And inside this folder, we’re going to make two files. So, right click, create, C sharp script. This is going to be player, or hero, whatever name you want to use. I tend to use player because that’s pretty much the form of the entire millions of games that you can make, okay, we always have a player. And now we right click, create, C sharp script, and I’m going to name this one bullets, and then hit enter. So every time you hit create, there is this little spinning wheel here to say that the code’s compiling, and after that’s done, we can already work on using this script.

So before you went to the script, it is important to remember to add it to the scene to add it as a component to the player. So make sure you have the player selected in the hierarchy, and you can select the player script and drag and drop it either like this in the player or dragging it and dropping it here. I prefer this one because it’s just faster, but make sure you have the player selected, okay? So we have the player script and that is going to basically, it’s guaranteed that that script is going to load. Now I’m going to double click the player script and you have to wait a little bit for MonoDevelop to open, but it already comes bundled with Unity if you haven’t changed anything in the installation process, and we have that empty class here.

So the first thing we want to do is to understand when should we shoot bullets, and we have two methods here, we have start and we have update, and for clicking in Unity, we should use the update method. Since this is called on every frame, on every time your game is processed by the device it’s being ran, okay, so if it’s on a smartphone, on a smart tv, whatever target platform you have, the update method is going to be called once per frame, and this is the perfect moment that we can use to check if we are clicking, okay?

So you want to listen for the click in the left mouse button, okay, a basic left click, and to do that, we need to use an if block. So we’re going to type if, open and close parenthesis and the curly braces, and to ask if we are clicking the mouse button we are going to type input to access the input class in the system, dot get mouse button, and you notice that there are two, three options actually. Get mouse button is going to return true at every moment, every time, every frame, the given mouse button is held down. So this is used for machine guns, for example, because if you hold down the trigger, then it’s going to shoot bullets, several bullets okay, dozens of them at every second, however for pistols, that’s not how it should work.

We should use get mouse button down, because that’s not an automatic weapon. You shoot one bullet for every time you press the trigger. So if you press the trigger, you have to release it and press it again, okay, that’s how basically pistols that are not automatic work. So if you look at the summary here in MonoDevelop, it says return true during the frame the user pressed the given mouse button. This is very important. Since we are using this in the update method, it’s basically going to work. So, get mouse button down. Now we’re going to the pass the button that we want to use, and we need to pass zero for the left mouse button, but it can use one or two for the right and middle mouse buttons, and just to see if this is working, we’re going to print a message here. So I’m going to type debug dot log, okay, so we can print a message in the user’s console, and I’m going to pass between quotes the message “fire”.

Now we’re going to save the script, go back to Unity, and wait for that script to be process, and after this is done, I’m going to press play, so the player’s going to be back in the scene, you can move around, and if I click, you’re going to see that a message printed here. Fire, okay. If you click, it’s going to be highlighted in the console window, which is right here, okay? So we can, if we click several times, we’re going to see the fire message, so great. We already know how to listen for the left mouse button press. Now, we have to actually shoot the bullets, and how do we do this? Bullets, they work a bit differently than some elements that we have here.

We designed the gun, but how the game is working right now is we have one gun, okay. There is no need to transform that gun into something that can be reused later, but that doesn’t apply for bullets, because bullets, they appear all the time, okay. We need to make a system here where a bullet can be substantiated dynamically in the game, and then we take it off, okay, so how do we do this, how do we make that work? We have to go here, so our hierarchy, and we have to make one bullet. So in the game controller, I’m going to right click, choose create empty, and I’m going to rename this game object as bullet. It’s going to be in the position zero zero zero, but let’s bring it in front of the weapon so we can see it once we design it. Alright, and inside that bullet, which is in this position, I’m going to right click, choose create empty, and I’m going to rename this game object to model, and then you might think hey, we have something different now.

At the player, we made a gun, and that gun already had the cube elements, but why do we have the model here? This is a tip that I’m giving to you because sometimes you need an intermediate game object before you add the visual elements, just like we have the first person controller. We have the main object and we have the first person character. It’s important to have this because if you want to make a ninja game for example, where you have shurikens, you want to rotate the model, okay. We just want to rotate the visual part of the bullet, and if you don’t do this, if you try to rotate the bullets, depending on the technique you’re using to make that bullet move forward, or whatever direction you’re shooting it, then it’s not going to work.

So it’s important to separate the logic, okay, the logic part, the code part, from the visual. That’s why we add this little model element here. You can also name this container if you want, okay, both work just fine. Let’s use container. Now, I’m going to right click, choose 3D object and then sphere, so we have this huge sphere in front of the weapon. I’m going to start by removing the sphere collider, it’s not going to be present here, you’re going to understand why. The scale is going to be zero dot three, I think. Yes, zero to three looks perfect. It’s going to be zero dot three, and we want to change its color as well.

So, we go to our materials folder, right click, create material, bullet, and I’m going to change the color to yellow so it’s very easy to spot in the game, and I’m going to drag and drop here. And if you want to change the color and test it right in the game, you can just click here and basically change it to whatever color you want. You see the results immediately here, okay. So why did I remove this collider from the bullet, okay. You might know that colliders are used for basically processing collisions to see if one object is overlapping another or if there’s a physical collision between them. I took it off from here because this is not where the collisions are going to be processed. It should be processed in the bullet game object, okay? Remember, this is the logical part, and this is the visual part, so in the bullet, we need to add the bullet’s crypt to it, so we already made that, I’m simply going to drag and drop to the bullet here or here, and we already have a descript here, nothing special but it’s going to work, and now I’m going to click on add component, and we can have either a box collider or a sphere collider, so if you click on that component you have that search field, just search sphere and we already have sphere collider.

If you look at the scene window it’s a bit bigger than the bullet, so let’s change that radius to zero dot two. It’s okay to make it bigger than the actual sphere because let’s forgive the player a little bit if they miss a shot. It’s important to have that little tolerance so the player doesn’t get frustrated for missing a shot, but it’s really up to you. If you want to change that to something like one dot five so it’s going to be precisely the size of the bullet it’s going to work, but I like to add a little tolerance.

Now, this bullet is not going to behave completely in a completely real physical way, okay. We’re not going to shoot it and if it hits the floor it’s going to bounce and roll around. We want to keep things simple, okay. Sometimes you need to simplify things, so you’re going to make sure that you’re game’s going to behave very well. And because of that, I’m going to mark this is trigger check box okay, so we’re just going to use the bullet for checking for overlaps. So basically, the bullet’s going to go through elements. It’s going to go through the floor if you shoot looking at the floor, it’s going to go through the enemy, however, if it goes through the enemy, it’s going to hurt it or kill it, okay. So let’s use this is trigger checkbox here.

So we have the bullet, we have the sphere collider, and now that we have this, we want to transform this bullet into something that can be reused later. In Unity, that’s called making a prefab, okay? It’s just like the name set, something that has been previously fabricated, something that has been previously made for us to reuse later. Since we are going to make use of several different bullets, it’s interesting that it is a prefab. So what we’re going to do is, we’re going to the project folder, we’re going to right click and create a new folder that is named prefabs, like this, and now we’re going to select this bullet and we’re going to drag and drop to the prefabs folder, and we’re going to have the bullet here. If you look at the hierarchy it’s written in blue, okay, it’s something very simple. Just written in blue because it means it’s a prefab instance it’s a copy of the original prefab, which is this one, and if you want you can even delete it from the scene because it’s already saved. You can just drag and drop again, and it’s going to be back.

Now we’re going to save our scene, and we have to work on making this bullet appear.

Transcript Part 3

Now, how do we instantiate these bullets? We have to view with the player script. So I’m going to open it right now. We just have this little message here that says fire when click. What we need to have a reference for the bullets prefab. To make that reference in Unity, we can only make a very simple public variable here. So at the top, I’m going to type public GameObject bulletPrefab, like this.

And if you save that and go to Unity, and you wait a little bit for that processing of the code to be read and you select the player, you see that we now we have that bullet prefab set here. So, to get that bullet prefab to work, we’re going to open the prefabs folder, and I’m going to drag this bullet from here to here. So, you just drag and drop. And it’s going to be in this position. Now, that we have the reference for the bullet, you’re going to notice that “Bullet Prefab” is set in bold. This is happening because that’s something new that wasn’t present, or wasn’t set in the prefab. And, remember, this prefab, if you choose select, you’re going to reference the EFPSController. So, this is the moment that we have to fork things a little bit. We want our player to be our own player prefab.

Our own first person controller, where we’re going to add new things. This is important because if you make auto-levels, you need to ensure that the player is going to behave the same on every level. And if you change the player, maybe you change the player’s weapon, then there might be some differences from each level because, well, we can forget things, we’re only human. So, now, we’re going to open the Prefabs folder, and just like we did with the bullet, we’re going to drag and drop the player here. And now we have the player, which is basically it’s gun, it’s the only visual element that we have here.

And now, how do we instantiate these bullets? There’s a very simple method for that. I’m going to remove this fire message from the update message, the update method, and I’m going to type GameObject bulletPrefab equals to Instantiate, bulletPrefab. This method is enough for adding a prefab instance. If it was only set as this, and you ran your project, it was going to work. But we want to keep a reference to it and you’re going to understand later. Instead of calling this bullet prefab, we’re going to name this bullet “object”. It’s the instance of the bullet prefab. So, let’s use this pattern here, bulletObject. So I’m going to save that, go to Unity, wait just a little bit.

And if you press play now, here we are, if we click, the bullet is going to be instantiated. So, if you look at the hierarchy, every time a click a new bullet is added here. But there is a problem. All the bullets are in this position. Which is odd, why they’re coming here. This is happening because the prefab, the way you save it, so even the position is going to be preserved. So, when we instantiate a bullet, we want to add it to a certain position. So, what we can do here is we can type bulletObject dot transform dot position equals to transform dot position. What is this? We are accessing the bullet object that we just instantiated. We access the transform component and we change it’s position to be the same position of the player. So writing this, is the same as typing this, which is the player script that you’re dealing with, dot transform, dot position. You can just leave it like this.

Now, this time, if we save and go back, and we give this a try, we can press play button, OK, so here we are, and if we click, it’s going to be where the player was. OK, so basically, if I click, it’s going to be where I’m standing. Which is good, however, if we click, we need to step back for us to be able to see the bullets. And that’s something that we have to adjust as well. And one thing that we might want to do, is to make it spawn right in front of the player. So, we’re going to type here a plus sign and type transform dot forward. So what happened here?

We’re setting the bullet’s position to be where the player is standing, plus transform dot forward. And there is an interesting difference between these two values here. This is a Vector3 element, it’s a structure in Unity, a class in Unity, that contains three values, x, y and z. So, it can position things. And this is basically a point in space. It’s a place, basically. This one is also a Vector3. But, however, this is basically, you have to think of this as a direction. It’s a vector, and it’s size is going to be one. Can you imagine there’s an arrow that is going to point somewhere. So upwards, downwards, to the left, to the right, and it’s size is always one, because this is going to make our calculations easier. But the thing is this is not a place in space, it’s an arrow that is pointing somewhere.

So if we look to the left, transform dot forward is going to point left. If we look up, transform dot forward is going to point up. So, this is basically what we need. This means that the bullet is going to be at the exact place where the player is plus one unit in the direction the player is looking at. So now, if we try that again, wait for the compilation to be finished. And we press play. This time if I click, the player is going to be one unit in front of the player. Which is great. However, you see that it’s still not in a good position. It’s not exactly where we are looking. So, if you go to the scene and you select the player, the player is going to be here, you’re going to see that the player is in this position.

However, the first person character is in this position. So, it’s, there’s a little offset a little vertical offset. So, it’s going to be important for us to have a reference to the player’s camera, which is here in the first person character. So, what I’m going to do is go into the player I’m going to type here public, Camera playerCamera. And now instead of using transform dot position and transform dot forward we’re going to use playerCamera dot transform dot position. And playerCamera dot transform dot forward. It’s important to see those differences just how the structure of the first person character was made. We have the player game object here but we have the camera which is the first person character here. Now, we select the player, and we’re going to drag the first person character from here to here.

So, we’re going to be able to reference its camera. And since we changed the prefab, we can hit the apply button for it to be saved. Let’s give that another try. I’m going to press play. Here we are. If I click, the bullet’s are going to be in front of me. If I look up or I look down, it doesn’t matter, it’s going to be in front. And the other thing that we might want to adjust is if you look at the scene window, the bullet is very far, the weapon is very far away from where the player is. This is happening because the gun is basically too big. So we want to make it very much smaller than it is right now because we’re going to have some issues where we look at the bullet and the weapon is going to be in front of it. So that’s a bit odd. Now, we’re going to select the gun here.

And to make that simple, we can just scale it. So maybe I’m going to change that to zero dot three on x, y and z. And you’re going to notice that it’s scaling the elements right below it in the hierarchy. Which is exactly what should happen because we have a hierarchy here. Now, the gun is very far away from the player, and to help you, you can just go to the game window, select the gun and you can click on these letters x, y and z and basically drag them around until you find a good position for the gun. So, I’m going to make it closer to the player, like this. I think this is going to work well. And if you look at the scene now, the camera’s much, the gun is much closer to the first person character. You might need to adjust a little bit but, well, we just have to experiment and see things are working well. OK, so maybe a little bit closer to the player. I’m going to change that scale to zero dot twenty-five on the x, y and z. Bring it closer, like this, x comes to the left as well, and y moves up, so it’s going to be better.

OK, but well, I think this is good enough. We don’t have to worry too much about this because the bullet’s are going to move. So, now, we’re able to spawn bullets, they’re not going to be very far away from the gun it’s going to be okay. But now we have to make these bullets to move forward because we are shooting them. So, how do we do this? We already learned how to use transform dot forward. So we want to use this to make the bullets to move in the correct way.

So, what we’re going to do here is type bulletObject dot transform dot forward equals to transform, or better yet, playerCamera dot transform dot forward. This is very important here because it’s going to make your life much, much easier if because, otherwise we would have to calculate the angles. That’s not necessary at all. We just set the forward vector just like we did with the position, to be the same forward vector as the player camera.

So, it’s going to point to whatever the player is looking at. And with that in mind we can now go to the script of the bullet, so, scripts folder, double click on the bullet to make it open, and we can make a logic for it to move. And that’s going to be very simple. We can simply come here and type public float speed and I’m going to define that as 8f by default. OK, this is a floating point number so we add an f here. And in the update method we are going to make the bullet move. So, I’m going to simply add a comment here that’s going to say make the bullet move And we’re going to type transform dot position plus equals transform dot forward multiplied by speed multiplied by time dot deltaTime.

So, what happened here? When we transform dot position plus equals, it means we’re going to increase the position by passing another vector as a parameter. Another structure, another vector structure as a parameter. And what is going to be that. It’s going to be transform dot forward. So, it’s going to be an arrow that is going to point somewhere. That means that our position is going to have an offset of one, because every direction has a size of one. But, we’re going to multiply it by speed, so we’re going to increase that forward vector it’s going to be bigger or smaller. And we also multiply by time dot deltaTime. So, we make sure that the game is going to behave more or less the same on different devices. We do that because we are in the update method and faster devices call the update method more times, more frequently, than slower devices. So, we use the time dot deltaTime here to scale that correctly. Now we’re going to save, go back to Unity, wait a little bit, and after that is done we’re going to press play.

And here we are holding our weapon. If we click, then the bullet is going to move forward. Which is good. You notice that it comes from the middle, so it might be a little bit odd. Because we might want it to come from the weapon. But that’s something very, very small. It’s barely noticeable if you select the bullet. And you increase the speed. So, for instance, we can stop the scene, change the speed to 20, for example. And if we press play now, no need to recompile the code, we can still shoot the bullet forward. It’s going to work just fine for us.

However, you notice the bullet is lasting a lot of time here. The bullet’s basically exist forever. And this is going to spend very, very important memory, very important resources from your game. So, if you have a hundred bullets in your game all of them are moving forward, so all of them are going to use space in the memory. So, we have to adjust that. And what we can do for the bullet is add a life time to it. So, we can come here to bullet and type public float lifetime or we can name this as lifeDuration, for example, and set that to be something like 2f, so it’s going to last for two seconds.

And now we need a private variable, private float, and we’re going to name this as lifeTimer. This is going to basically store for how long it’s going to be the internal clock for the bullet that is going to count down, and once it reaches zero, we get rid of the bullet. And now we have this start method here, so we’re going to use it, and we’re going to type lifeTimer equals to lifeDuration. And in the update method, we’re going to check if the bullet should be destroyed. And to do that, we’re going to type here lifeTimer minus equals Time dot deltaTime. So, if lifeTimer holds three and we decrease Time dot deltaTime in the update method, it’s going to work exactly as the seconds passes, exactly as time passes. And we have to check if lifeTimer is less or equal 0f, it means it’s time to destroy it. So, we can simply type here destroy and pass gameObject as parameter, which is the same as typing this dot gameObject, which is the same as referencing the bullet that is running this script.

Now we can save this, go to Unity, wait for the processing to be finished. And now we press play. So here we are, holding our weapon. If we click, a bullet is added but apparently the lifetime’s still not working. And yes, they disappeared. So, let’s see what’s in the full value that we have here. Life Duration is set to two. We set lifeTimer to be life duration, so, yes, this should last for two seconds. So, press play. Zero, one, two. And the bullet disappears in the hierarchy.

So, since the bullet travels really fast, we might want to change that duration. Instead of two, we might want to use zero dot seven, for example. Whatever you think is going to be better. But, anyway, the lesser, the smaller the life time, the shorter it’s going to be, it’s the duration where the bullet’s going to be alive. And, well, you’re going to use your memory in a better way.

Creating a 3D Smash Game in Unity – Part 2

Introduction

Benjamin Franklin once said, “the best video games that I have ever made were the ones where I persisted and didn’t give up.”* Whether or not Benjamin Franklin actually said this, he is right. Welcome to Part 2, and congratulations on continuing this tutorial series on creating a 3D Smash Game in Unity! In this tutorial, we will be tying everything together into a complete game. We will be using the Scriptable Render Pipeline to add a shader to our glass and our ball. And we will set up a UI system for the start and end of the game. With that runthrough, let’s get started!

Check out Part 1 if you haven’t already

This tutorial is part of a series. You can check out the first part here. This is where you’ll also get the link to the Source Code files, as you won’t need to download additional ones from this part onwards.

Creating the shaders: Glass

Before we get started using the incredibly awesome SRP (Scriptable Render Pipeline), we need to first import the package. Go to Window -> Packages,

Image may be NSFW.
Clik here to view.

and download (or update) the Lightweight Render Pipeline.

Image may be NSFW.
Clik here to view.

Once it is finished importing, go to your Materials folder and right-click. Go to Create -> Shader -> PBR Graph.

Image may be NSFW.
Clik here to view.

Call it “GlassShader” and then double-click on it to edit it.

Image may be NSFW.
Clik here to view.

You can dock this window where ever you like, I either keep it in the editor window or detached completely.

Let’s talk glass, how do we go about making a glass shader? This is probably oversimplified, but for our intents and purposes, glass has a transparent component and a reflective component. There are other things like scratches and smudges which give a different set of looks but for all we need to know, glass is reflective and transparent. With this in mind, we could go for a hyper-realistic type of glass, or we could make it sort of stylized. Since we don’t have access to vast amounts of textures to make it look hyper-realistic, we will be going the “stylized” glass look. But how do we create a reflective and transparent glass? It is really simple, go to your “GlassShader” window and change the shader type to be transparent:

Image may be NSFW.
Clik here to view.

This just means that we can apply values to the Alpha field. Right-click and select “Create Node”.

Image may be NSFW.
Clik here to view.

Search “Fresnel” (pronounced Frah-Nell),

Image may be NSFW.
Clik here to view.

create a “Fresnel Effect” node and drag the output into the “Alpha” socket on the material node.

Image may be NSFW.
Clik here to view.

What does a Fresnel node do? In our case, it makes the edges opaque and the centre transparent, which is perfect since we are making a glass material.  The trick here is to find the right value for the power socket on the Fresnel node. What I did was to actually create a Vector1 property called “Fresnel Power” so that I can change this value in the editor without having to access the shader.

Image may be NSFW.
Clik here to view.

If you’d like, set a color for your glass

Image may be NSFW.
Clik here to view.

(I did a light blue) and then hit “Save Asset”.

Image may be NSFW.
Clik here to view.

Create a new material called “GlassMat” and set the Shader to be our “GlassShader”.

Image may be NSFW.
Clik here to view.

Now it’s just a matter of tweaking the “Fresnel Power”  in order to get the look your after. You could make it harder for your players by making the glass more transparent, or you could be merciful and make it slightly more opaque, it all up to you (I would try and be merciful).

Image may be NSFW.
Clik here to view.

When you think you’ve found the right value, we need to assign it to our glass objects. This, I found, was slightly tricky. We want the glass shards to have the same material as the glass pane. The best way to do this is to drag each broken glass prefab into the hierarchy:

Image may be NSFW.
Clik here to view.

Group select a few shards and then drag the material onto the selected objects.

Image may be NSFW.
Clik here to view.

Keep doing this until all of the glass (whether broken or whole) has the Glass Material. It can be tedious so just get through it as fast as possible. Once you are done, apply your changes to the prefab.

Image may be NSFW.
Clik here to view.

Creating the shaders: Steel Ball

If you thought the glass shader was simple, wait ’till you see the shader for the Steel Ball! Go to the Materials folder and create a new PBR Graph called “BallShader”.

Image may be NSFW.
Clik here to view.

Double-click on it and let us start making this shader! Change the workflow type on the base node to “Metallic”. That’s it! Now it’s just a matter of changing the “Metallic” value to make it look like a shiny steel ball. If you’d like, you could also make this a float property called “Metalness” (or something else that doesn’t sound as ridiculous) and then you could change its value in the editor. You might fiddle around with the Smoothness and Occlusion values if your ball still isn’t the way you’d want it to look.

Image may be NSFW.
Clik here to view.

Once, you’ve finished tweaking those values, that’s it for our Steel Ball shader! Create a new material called “BallMat” and assign our “BallShader” to this new material. Then we drag this material onto our ball prefab to see how it looks!

Image may be NSFW.
Clik here to view.

If it looks good, apply this change to the prefab.

Creating a level: Ground

Now that we have our shaders setup, let’s create a level to place these things in. First, I am going to create a plane so that our shards fall and bounce around, making it look much more realistic. When creating a level, I actually got creative and made several different planes, each with different sizes. I encourage you not just create one flat plane for your entire level, create several. Spread them apart and angle them if you think it looks cool. Just get creative! Second, I assigned a material to the plane to make it look less like a 3D primitive and more like an actual part of the game. The material I used was in ExampleAssets -> Materials. Just pick one that you think would go well with your scene. Here is my final result:

Image may be NSFW.
Clik here to view.

Feel free to make your level longer or shorter.

Creating a level: Glass Panes

Now that we have a ground, let’s add something on top of it. We are now going to be adding the glass blocks to our scene. When you do this, I have one command that you MUST follow, BE CREATIVE! Seriously, just go crazy! I have found it is best to place the glass blocks slightly above the ground so that the glass shards have room to fall, but, if you place the glass so that it is slightly overlapping the grounds, the glass will explode if you hit it. With this in mind, start creating! Here is my finished level:

Image may be NSFW.
Clik here to view.

Adding a UI Canvas: Restart Button

If you notice on your CameraCharater script, there is a field called “Button”.

Image may be NSFW.
Clik here to view.

If you look at the code:

private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("glass"))
        {
            collision = true;
            Debug.Log("Collided with glass!! Man down!!");
            camMoving = false;
            button.SetActive(true);
        }
    }

You’ll see that this button is activated when the camera collides with the glass. If you were scratching your head when you put this in your code I am now going to explain why it is there. In the original game (do not go and download it! You are making your own now so you don’t need the original), there is really only one scene. This means that the UI controls whether or not the game is running or stopped. Because of this, we use a button to restart the scene so that the player isn’t jarred back to the beginning immediately. Go to the hierarchy and create a new button called “Restart”.

Image may be NSFW.
Clik here to view.

In the CameraCharacter script you’ll notice a public method called “Reset”:

public void Reset()
    {
        SceneManager.LoadScene("Scene1");
    }

This is the method that will be called when we press our Restart button. Change the text on the button to say “Restart”,

Image may be NSFW.
Clik here to view.

Create a new “OnClick” action, drag the Camera into the field, and set the called method to “Reset”.

Image may be NSFW.
Clik here to view.

Disable the button, assign it to the proper field on the Camera:
Image may be NSFW.
Clik here to view.

…and hit play. Now we have a button that resets the game when we collide with a piece of glass!

Image may be NSFW.
Clik here to view.

There is just one thing I think we need to do before we are finished with the UI Canvas…..

Adding a UI Canvas: Start Button

…and that is to add a start button! It may seem like a trivial thing but it gives more control to the player which, in the case of our game, is a good thing. Create a new button called “Start” and place it directly over our Restart button.

Image may be NSFW.
Clik here to view.

If you have another look at the CameraCharacter script:

public void StartCam() {
        camMoving = !camMoving;
    }

You’ll see that there is a public method which sets a static boolean to a value different to what it was originally (by using the !boolean syntax). This boolean is false by default:

public static bool camMoving = false;

You’ll also see that the Update method has a series of logic statements which use this variable as well:

//This checks if we have collided
        if (!collision && camMoving)
        {
            cameraChar.Move(Vector3.forward * Time.deltaTime * speed);
            //This is so that the camera's movement will speed up
            speed = speed + incrementFactor;
        }
        else if (collision || !camMoving)
        {
            cameraChar.Move(Vector3.zero);
        }

        if (Input.GetMouseButtonDown(0) && camMoving)
        {
            GameObject ballRigid;
            ballRigid = Instantiate(ball, BallInstantiatePoint, transform.rotation) as GameObject;
            ballRigid.GetComponent<Rigidbody>().AddForce(Vector3.forward * ballForce);
        }

From a quick glance at where this variable appears, do you understand how it we are using it? We have a boolean that is static (in case we have other scripts that want to stop or start the camera) which dictates whether or not the camera is moving or not. So when we start creating this Start button, all we need to do is call the method which sets a different value to this boolean. And you know which method that is!

public void StartCam() {
        camMoving = !camMoving;
    }

Go to the Start button and create a new OnClick event. Assign the camera to the field and set the called method to be “StartCam”. Don’t forget to also change the text to read “Start”.

Image may be NSFW.
Clik here to view.

Now hit play and let’s see what it looks like!

Image may be NSFW.
Clik here to view.

It works, but the buttons are cluttering up our game view. They stay active even after we have pressed them. Let’s just have the Start and Reset buttons disable themselves whenever they are pressed. Create a new OnClick event in each button, drag the instance of each button into their respective OnClick event, then set the action field to “Gameobject -> SetActive”.

Image may be NSFW.
Clik here to view.

Leave the box unchecked on each one and we now should have a clean game view.

Image may be NSFW.
Clik here to view.

Well, I think that is all we need to do for the UI! Obviously, as it is, the buttons are very ugly so please make them more interesting. Here is another opportunity to get creative!

Fixing the Sky

Our game is almost complete! There is just one thing that I find not as aesthetically pleasing and that is the sky.

Image may be NSFW.
Clik here to view.

Now it may not bother you at all, in which case, just leave it as it is. But, I feel it would add another level of ambience if the game had a different color or style of background. In this case, I found it was only necessary to change the default skybox which can be found in the Materials folder.

Image may be NSFW.
Clik here to view.

This is a good thing to remember since you can get lots of varied looks without having to create your own skybox. I decided to have a go at tweaking these values.

Image may be NSFW.
Clik here to view.

I wanted a darker background because this would create a nice contrast between the dark sky and our light colored glass panes. In the end, I decided that these values were the result I was looking for.

Image may be NSFW.
Clik here to view.

In order for this to work though, we need to bring add a Skybox component to the camera and place the finished skybox in the “Custom Skybox” field.

Image may be NSFW.
Clik here to view.

Let’s hit play again and just appreciate our game for all its fine aesthetics and mechanics.

Image may be NSFW.
Clik here to view.

Conclusion

Congratulations on finishing this tutorial series! That is no small achievement, so you should be very pleased with yourself. I hope you found it helpful and instructive. At this point, you have learned two things, how to make a game similar to a popular mobile game, and what to do if you have no idea what kind of video games to make. If you ever find your self at your desk, staring at your computer because you have absolutely no video game ideas (every game developer has experienced this), then you know where to look for inspiration! Go to the app store, pick a game that you like to play, and then replicate it. This way you can improve or change things about it and you’ll be learning and improving your game development skills. So go to the app-store, pick a popular app, and

Keep making great games!

*Editor’s Note: Sadly as of this moment the historians haven’t discovered any evidence yet that game design was part of his famed routine.

Web Class: Creating Inventory and Crafting Systems in Unity

Transcript Part 1

Hey, guys. My name is Austin Gregory. And in this course I’m going to teach you how to create an inventory and a crafting system.

The inventory’s going to be your typical grid-based, slot, drag and drop style inventory system. And the crafting system is going to be heavily influenced by Minecraft’s crafting system. With the nine slots in a grid, that you can drag and drop items into. And then it’ll do the recipe look-up to see if you have the items to craft up a new item. And we’re gonna take two approaches to this. We’re gonna have a system in place where you have to have the items in a specific slot in the crafting grid for it to work. Similar to the way that Minecraft works, where you have to have items in a certain order to craft certain items. And we’re also gonna have it where you can actually just place items in the grid and it’s going to use the items just as a whole. Not care about the sequence of the items.

What I have in front of me is just a to-do list that we have to check off as we go here. And by the time we check off the last item, we will have a pretty sweet inventory and crafting system to work with. So the first thing we have to do is create our item and recipe data structures. And these are gonna be classes that allow us to define what an item and a recipe is. And we’re gonna talk about that here in just a second.

So, I have the window open for Unity to create a new project. I’m going to go to New. And I’m going to create a Unity project. It’s going to be Zenva – Inventory and Crafting. I’m going to select 2D. And I do not need analytics enabled for this. Does not matter how you do this for yours. And now I have my layout. That looks like this. This is how I work.

But I’m going to go to Layout. And I’m going to go to the Default layout, so we can all be working on the same layout. And we’ll go to Default and this is what you should see if you have the Default layout. Now we want to create a little bit of a folder structure here. I’m going to go to, I’m going to right-click on Assets. Going to go to Create. And I’m going to select Folder. And I want to have a couple of folders to keep my project semi-organized. I’m not so great at that myself. But we can do it a little bit better for this video, surely. So I’m going to have a folder for scripts. Then I’m going to right-click in here and go to Create again. And I’m going to have a folder for resources.

Now this is going to be where our item icons are. And our things that we have to load in dynamically are going to be stored in here. This is a special folder in Unity that allows us to access the data within it directly through a class called Resources. And we’ll get into that a bit later on. And also, speaking of the item icons, those are going to be available for you in the project download that you get. So in Resources I’m going to create a folder that’s going to be called Items. And that’s all we need for now.

So we said I want to create the Item data structure. So I’m going to do that in Scripts. It’s going to be a C# Script. So I wanna go to Create, C# Script. And I want to call it Item. And I’m going to open this up in Visual Studio by double clicking on that. And when you open it up, this is what you should see. We have some using statements up top here. Public class Item that inherits from MonoBehavior. Great. And we have some default methods. So what I want to do is I’m going to set this up and then we’ll talk about. I want to get rid of the inheritance from MonoBehavior. Because this does not need to inherit from that. I’m going to get rid of that. And we’ll talk about what a class is, here in just a second for those of you that would like a refresher. And I’m going to go ahead and get rid of these methods. We’re not going to be using those for this.

We’re going to create all of our stuff ourself here. And this is what we have. A public class called Item, with two curly braces. Cool. So quickly, what is a class? If you’re not familiar, a class is something that we can design that will act as a blueprint whenever we construct objects in the future. So think of a blueprint for building a building. You’re going to draw up all the specs for this. And then you’re going to hand it off to someone that’s going to follow the specs on that sheet. And build the building according to your specs. And it’s going to be the same thing for this class of Item. What we’re going to do is we’re going to write the specs for Item. And it’s not going to actually be an item. It’s just going to be the blueprint for an item. And then later on, we can construct our items based on this blueprint. And that’ll all make sense as we go.

So with that said, what does Item have to be? What is an Item? How can we define an Item? What an Item has to be in this system, at least, is it has to have a title, a name. Has to have a description. Some flavor text about it. Has to have an icon, we know that. Need an icon for this Item. Has to have a stat list, perhaps. So we can have some stats on our Items. Just a dictionary. Simple dictionary will cover that. As well as an integer that will be the identifier for it. So I’ll go ahead and type these out. I want to have a public int id, the identifier for it. And these are going to be publicly accessible. So public int id. I’m then going to have a public string. And this is going to be the title. Now I’m calling it title instead of name, because by default objects already have a name field. And we do not want to have any conflicts with already existing fields, right? It’s very simple to just call it something else. In this case, title. If you want to call it anything else other than that, you, more than welcome to.

Then I can have a public string for the description. Now these are just strings of text. So title’s going to be a name. Description’s going to be a paragraph, or something like that. And then like I said, we’re going to have the icon. The icon is going to be, a Sprite. So I’m going to do a public Sprite. And I’m going to call it icon. Great. So we can assign a Sprite object to this Item. And that will represent the Item in the UI. Pretty cool. I also want to have, like I said, the stat list. Now we’re going to use a Dictionary for this. Because what we want to do is what you want to have a name of the stat, say power, or defense. Then we want to have the number that the stat is. The level the stat is, or the value the stat is.

So the Dictionary allows us to do that very easily by having a string key and then having an int for the value. So I can say power is 10. And defense is seven. And all that is within a single collection. Pretty cool. So to do that, we first have to make sure we have System.Collections.Generic because Dictionary is a Generic type. I’m then going to type again, public. And I want to type Dictionary. And I get this. And what this allows me to do with these two brackets here, the two angle brackets. It allows me to define the type that this Dictionary is going to be.

Hence, Generic, it doesn’t know the type until I define it. So I’m going to have string and then int. So string, is going to be the key. Int is going to be the value. So power 10, defense 20, so on. Pretty cool. Pretty simple. And the way we look it up is we just pass it the value of the name, so power. And it will return the value of the stat, so 10. Very easy. I’m going to call this stats. Then I’m going to initialize it, with new Dictionary.

Now the reason I’m doing this and the way this works is because this, if I were to define it, isn’t actually initializing it as the object of Dictionary. It’s just defining the field. Then later on I could initialize it and then add data to it. But I’m going to go ahead and initialize it here. And then later on I’m just going to send data to the constructor for this Item. And then it’s going to add that to the Dictionary. So now I’m using the new keyword here. That means I’m going to create a new object from Dictionary, using the Dictionary constructor. And that means it’s going to create simply a new Dictionary. And store it in the field of stats. Pretty cool. So now I have a stats Dictionary.

So I mentioned the constructor. We need a constructor for Item as well, because I want to be able to pass data to Item. And then assign that data to the id, title, description, icon, and the stats Dictionary. And the way that works is I have a blueprint with this, these fields in here, right? Id, title, description. And I can create a constructor that allows me to pass parameters to this object that I’m creating. And it will initialize the object with those values as the default. If I were to do it without a constructor, and I just say new Item, kind of like I’m doing new Dictionary here. It will do the value. It’ll do the type default. So I’ll have, id would be zero. String would be empty. Description would be empty. And icon would be null. Because those are the defaults for those types. But instead, I want to initialize my Item with some values when I create it, right?

There’s no reason to create the Item in this case, unless it is an actual Item. So I want to have public Item. So I’m just saying public and then the name of the class. And that creates a constructor. And then inside the parenthesis we’re going to pass the parameters. We’re going to add the parameters that we can get into this Item. So I want to go to get the id, and we go int id. And I’m going to follow down the list here with the type and the name of the field. String title, string description, Sprite icon. And then, Dictionary. We’re going to do the same thing here. Dictionary and then it’s called stats.

Now, of course, these names do not have to match. It just makes it easier for me if they are the same. And then what I want to do is I want to assign those values to the values of the Item whenever we construct the Item. So if I were to go from another class and say new Item, like this. I could then pass in the values that I want this new Item to have. So, id of zero, name of Sword, and so on. And just pass the values. And then when this Item is created, when this object is initialized, it’ll have those values. Pretty cool. So I have to initialize it with that. So I’m going to say this.id. This referring to the Item I’m creating. The instance of the Item I just created. And that’ll make sense whenever you actually construct the Item here in a moment. This.id = id; So this refers to the instance field. And this refers to the parameter I just passed in. So now this.title = title. And this.description = description, this.icon = icon. Now then we’re going to do this thing a bit different here with the icon. But I cannot do it yet, until I get them actually loaded into the game. So I’m going to just have it like that for now.

But later on when I’m going to come in and load the icon from the Resources folder, based on the icon, or based on the Item name. So in fact, we won’t need the Sprite.icon to be passed in to Item. All we need to do is have the name and then load the icon based on the Item’s name. And we’ll get to that here in a bit. And then this.stats = stats. I also want to create a constructor that’s going to act as a cloning constructor. And that would not be something we don’t, that’ll be something we need a bit later on. But I want to go ahead and create it while we’re in here. And what a cloning constructor’s going to do, it’s going to take an Item of itself. So we have the class called Item. And I want to create a constructor that takes a parameter of Item and then just creates a copy of that Item. And the reason we do this, and you’ll understand this, again, later on.

But, I need to create a copy of an Item before I erase the reference to the Item. So I then have a hard copy of that Item. It’s a deeper copy of that Item, then I had before I made the changes to it. So all I have to do is I have to create a public Item. And it’s going to take a parameter of itself, of the self type. So it’s going to be Item called item. And this will probably be confusing for now. But you’ll understand later on exactly why we need this. And since I’m already in here, I want to go ahead and write it up. And I’m going to take and again, do this.id =. But this time, I’m going to do item.id, item being the parameter we passed in. Item has the field of id on it. It has the field of title on it. So we can grab those fields with that Item.

So whatever Item that I pass in to this Item constructor, I am then going to be cloning the information to a new Item. And this comes back to value versus reference type. Which I can’t really get into in this course. But you should probably check that out, if you’re confused as to why this works. This.title = item.title, this.description = item.description, this.icon = again I’m going to do item.icon for now. But I may have to load that in through the Resources. Well, I won’t because Item already have that. So that’ll be fine. And then, this.stats = item.stats.

So I’m just cloning the information over from Item to a new Item that I’m creating. And that’s going to be it for this lesson. In the next lesson, we’re going to create the recipe data structure. I’ll see ya there.

Transcript Part 2

Hey guys, welcome back. In this lesson we’re gonna create the crafting recipe class that’s going to define the blueprint for all of the recipes in our inventory system.

So the way this is going to work is our recipes are going to be based on the item IDs. And then we’re going to have an array of these IDs that defines what the recipe is. So if it requires two pieces of wood and a stone, and those are IDs one and two, respectively, then you would have an array that would have say, empty slots in it, they’ll just be ID of zero. You’ll have two that are one, and then one that is ID of two. And that makes up the recipe that would craft whatever item that would make for you. And then whenever we put items into the crafting table it’ll look up the recipe and see if one matches what is in the crafting table. So we’re going to have nine slots in the crafting table so it’s gonna be an array of nine items in the crafting table, each of those with an integer ID so we can compare those IDs in the crafting table to the recipes in our recipe database to see if we have any that matches what is in the crafting table. So, a crafting recipe is an array of nine integers. And those integers represent the item IDs.

So to do that I’m going to create a C# script, I wanna call it “Recipe–” let’s say, “Craft recipe.” And this is gonna be a class very similar to our item class. I’m going to get rid of the monobehaviour inheritance again, don’t need any of that stuff. And as well as the methods. So, what is a craft recipe? Again, it’s going to have an integer array of nine item IDs, got that, makes sense. But also I have to know what this recipe will create whenever the recipe is satisfied. So whenever I have all of the items that this recipe requires what item do you get in return?

And since we’re basing the system on the item IDs, all I have to do is define the item ID of the item you get in return. And that’s all we need for the crafting recipe. So I’m gonna add a public integer that is an array and I will call it, “required item– required items” there we go. With a lower case r. And an integer here, just quickly, it’s an integer ID, you have the two square brackets following the type that denotes that it’s an array. And all this is, is a collection of this type. So I could have one value in here that’s zero or I can have ten values in here that’s zero, seven, eight, four, twenty, and so on. It’s just a collection of those values. And you can access those values by passing in the key or the index that the values at you’re looking for.

So if you want the third element in that array you would look for the, well you look, in this case, for the second key, because it starts at zero and goes zero, one, two, three, four, all the way up to nine, if you have ten elements. So the required items are gonna be an integer array that contains just a bunch or just a few item IDs. I then want to have a public Int that’s gonna be the item to craft. And this is simply gonna be an ID of the item you should get in return for passing in the required items. And again, all the craft recipe is doing is defining what a craft recipe is. It doesn’t handle any of the logic for determining if you have the required items in the table, it doesn’t care about any of that. It only cares about defining what a craft recipe is.

Now again, I wanna have a constructor for this. So a public craft recipe, just like the item. And the parameter we’re gonna be passing in is an integer item to craft. And then an integer that is an array. That is the required items. And then I’m going to set required items to be– sorry this.requireditems to be equal to requiredItems, and then this.ItemToCraft to be equal to itemToCraft.

Very simple, now we have a way to create a crafting recipe so whenever we create our crafting recipe database, all we have to do is create new instances of the class we just created and then define the values. So we’re going to use the blueprint to define the crafting recipe and we’re gonna follow the structure that we have here. We’re gonna pass in an array of the required item IDs. Then we’re gonna pass in the value of the integer, sorry of the ID of the item that you get back for passing in those.

And then some of the system is going to handle actually making that stuff happen. This just defines the blueprint for the craft recipe. And quickly for an example of the array, if you’re not familiar with how they work exactly, I have the required items array here that I just passed in, or the actual, I can refer to the instance required items. And I have values in this would say if it’s initialized with values, it’s not currently, but if we pass in values it will be. And I can access them with a key so two is zero, one, two, so it’s the third value in that array that would give me the third item ID that this recipe requires, or eight would give me the ninth ID that it requires.

So to check if we have the items for the recipe we would have to compare the item IDs that the crafting table has in it to all of the item IDs in this array. So we have nine in the crafting table, potentially, we have nine in the craft recipe, potentially. But more often than not, the recipes are gonna have a bunch of zero IDs in it, which are just no items, and then they’ll have other IDs, say you may need to make a diamond sword. So you have a wooden stick at the bottom, and then two diamonds on top. And that would make a wooden– or a diamond sword.

Or you would have just two diamonds in there somewhere with a wooden stick somewhere and that would still make it depending on what system you’re gonna be using because we’re going to be making both of those as I explained in the introduction. That is it for the craft recipe.

In the next lesson we’re going to create the item database where we define the actual items in our game, using the item blueprint we just created. I’ll see you there.

Transcript Part 3

In this lesson, we are gonna create the item database for our inventory system. We are going to define all the items in our system. I’m not going to have many, but I’m sure you’ll have a ton for yours, because you have an actual game going. I just have a little demo going.

So, I want to create some just dummy items to play around with, and show you how to construct a simple database of these items, and then the next lesson we’re going to create the recipe database in a very similar fashion. So I want to create, again, a C# script. I’m going to call it ‘item database’. I’m gonna open this up in Visual Studio. Oh, and I want to check off item structure and recipe Structure. There we go! So now this is where it starts to get fun. We start to have some fun with data here, and I know that doesn’t sound too exciting, but trust me, it is.

So to do that, we are going to create another generic collection similar to the dictionary, except it only has one value, it doesn’t have the key value pair, like the dictionary where we have the stat name and then the stat value, it just has a value of a certain type. So to do that I am gonna say ‘public’, and I’m going to create a list. This is a generic list so we have to have the angle brackets once more, and like we defined the two types for the dictionary, we have to define a single type for the list, and it will hold a list of this type. So if I had integer, we’d have a list of ones and tens and hundreds or whatever it may be, but in this case, we’re gonna have a list of a type that we created called ‘item’. Right?

So we have the item type here. It’s a class, and then it has these things in here that we can use, right? Pretty cool, so I want to have a list of those, and that’s gonna represent my item database. I’m gonna call it ‘items’, and again, I’m going to initialize it, like I did the dictionary. New list item–pretty cool. So now what I want to do, is I’m gonna get rid of these methods (computer chiming) once more, Don’t know what that was all about, and I’m going to write a method that allows us to build the item database.

It’s just gonna be where I define the values from our items at. Then I want to call it in the ‘awake’ or ‘start’ method, and it’s going to handle the rest. So, I want to write a void, which means it returns no value, so if you have an int method, it will return an integer. If you have an item method, it would return an item. But in this case, it returns nothing. It’s going to be ‘build item database’, is what we’ll call it. Needs no parameters, it’s just going to do something.

Now, I’m going to create a new item list, and I’m going to populate it with items, and we’re going to do this all in one statement, it’s going to be very cool, and I actually have a new list created here, but I’m going to create a new list down here, so it’s not necessary to have it here, but I’m going to keep it there for now. So, I’m going to type items is equal to, so items is the list, keep that in mind, this is the field that we created called public list item items, and I want to say it is equal to, again, new item, or sorry, new list, of type item.

But this time we are going to initialize it with some values, and the values we’re going to initialize it with is just a few items, right, so we’re going to create some items. To do that we’re going to use the curly braces, and we’re going to add a semicolon to the end. So your curly braces, everything inside of the curly braces whenever we define a new object like this, will define the values that it’s initialized with so we want to initialize the item database items list with some items in it, just makes sense. So to do that we’re gonna say ‘new item’. We’re going to use that item constructor by saying, ‘new’, which means it’s gonna create a new object, in this case a new item and then we can pass in to the constructor values to build that item using that blueprint. Watch how this comes together.

So new item, now if I go inside here and I want to do my parenthesis, I can see I can pass in an item type which is the clone constructor that we created or I can pass in an ID, title, description, icon and stats. Now, like I said before, we’re not gonna be passing in a sprite icon, we’re gonna be grabbing that from the Resources folder so I’ll have to change that for this to work. I’m gonna pass in the ID of “1” for this, we’re gonna start at one instead of zero, because zero is going to represent an empty item, a null item, no item. So we can define our recipes using zero, meaning no item in that slot and one meaning that item or 20 being that item and so on, but zero means that slot is empty. Doesn’t require an item in that slot to craft, so we’re gonna start at one. Then also, the name of the item. We’ll make a diamond sword. Wants a description, well, a sword made of diamond. Very descriptive. Wants an icon, that is a sprite.

I’m gonna skip that for now even though I can’t do that legally, I’m gonna skip it for now and then remove it from the constructor here in a second. But it then wants a dictionary of stats. So in fact, what I’m then gonna do real quickly is I’m gonna go in here and I’m gonna remove this from the constructor. Because I’m not gonna be using in that way and then I am going to define my dictionary that is of stats. So I’m gonna do this on a new line down here. It doesn’t matter what line we’re on as long as we are within the same statement and a statement is defined by the semicolon and the starting point. So semicolon here is where the statement ends, all this is within the same statement. So I’m gonna say ‘new dictionary’ because we’re passing in a parameter of a type dictionary, we have to create that dictionary first. And that’s gonna allow me to set it up here very easily by just saying, yeah, it’s a ‘string, int’ dictionary.

And then what I can do is I can define, much like I’m defining the ‘items new’ list item here with default values, with default initialized values. I can do that as well because I’m just creating it here and then I can pass in some values that the dictionary will hold when it’s initialized. So to do that, again I’ll use the curly braces like we are for the items list constructor. And now within this it gets pretty cool here. What I can do is I can define a string value and then say the power being the string value and then 20 being the power level. So I’ll do that again in curly braces, and I’m going to have “quote” defining that this is a string, it’s gonna say, power and then comma, the value of power 15. So the diamond sword has a power stat of 15, very simple. And this is how we define the new item in our string and dictionary, the power is equal to 15. And I could define more, that’s the whole point of this, right, I can define as many as I want, so power is 15, we’ll say defense is seven, whatever it may be, up to you.

And you could do that for however many stats you have in your game and however you want to do that. And whenever you want to look up the value of the diamond sword, say the power stat, you would just go through, quickly I can show you here, say ‘items zero dot stats’, you could get the power level just like that and that will give you the power level in a string format, very simple. But I wanna have multiple items in my item database obviously so I’m gonna do that again kinda like I did with the power and defense here.

I have multiple items defined in the initializer for the dictionary. I could do the same thing for my items, so I wanna copy this and I’m gonna paste it. Notice the comma there, so I can add as many as I want now. And we’re gonna have this be ID “2”, you have to increment every time, and this is going to be a diamond ore. I’m just gonna say ‘a shiny diamond’. And maybe diamond ore doesn’t have a power or a defense stat, maybe it has a value stat. Maybe it’s worth a lot of money. Maybe it’s worth 2500 somethings, perhaps. And then again, I can add another item here that is of ID “3”, we’ll call it a steel sword. A sword made of steel.

Again, very descriptive descriptions and I can have again a power level of, this will be less than diamond sword ideally so it’ll be a power level of eight and it could have other stats as well. Again, however many you want, however you want to do this for your game, a defense stat. Maybe it has better defense than the diamond sword for some reason, I don’t know. Don’t know the lore behind diamond swords. And there you go, so now we have an item database at least with items defined. We don’t have anything that calls this method yet so it doesn’t actually happen but we have the meat of the database defined.

So now what I want to do is I want to make sure that whenever this object is initialized, whenever item database pops into the game, whenever the game starts, in my case because item database is always going to be there, I want to make sure ‘build item database’ gets called. The way I can do that is I can define a method, you notice when we started we had ‘start’ and ‘update’. Well we could do start and that happens when the object is initialized but a bit before that happens the ‘awake’ method is called. And I want to make sure that this happens before anything tries to access it, this is data that needs to be initialized at the earliest possible state. So I want to say ‘awake’. So I want to create a method that is a void. It is private by default, I want to get rid of that anyway and it’s called ‘awake’ so now what I can do is say ‘build item database’ is called on ‘awake’.

So whenever this item first awakens, the first thing it’s gonna do is call it’s ‘awake’ method. The first thing it can do that we’re gonna be accessing is call it’s ‘awake method’ and then that’s gonna happen and it’s gonna call ‘build item database’ so now we have these items defined on our item database in our game. Pretty cool– that’s no good on it’s own, we don’t have a way to go through and find a certain item that we’re looking for by the ID. Say we’re looking for ID of 15, well it would take us a bit of querying to get to that point to find that. So I want a simple method that I can call that I can pass it an ID and then it will return the item based on that ID. You can even do that by the item name or the item description, but I’m going to restrict it for now to the ID, to keep it simple. So, you know how I mentioned that ‘void’ means it returns nothing, then if you have a type there it returns that type of object, we’re gonna do that for this.

I’m gonna have a public method, we’re gonna be accessing it from elsewhere in our code. It’s gonna be a public method that returns a type of item and it’s gonna be called ‘get item’. Or ‘find item’ or ‘get item by this’ or whatever you want it to be. In my case, simply ‘get item’, it’s gonna take a parameter that is an integer ID so I can grab the ID of these items, find one that matches what I passed in here for the ID and then return that item. So how do we do that? There’s a ton of ways we can go about doing this. The best way for this course is to keep it very simple but also where we learn some.

So what I’m gonna do is I’m gonna loop through every item in the items database and in this case the items list and I’m gonna pass in a condition, if the item ID matches the ID I passed in, that’s the one I want, return that item. Luckily for us there is a built in way to do this on the items collection, so to do that I’m gonna say ‘items dot find’ and this is going to loop through, look at every single item in the items list and it’s going to compare it to a little query that we pass it. We’re gonna say, hey, I’m looking for this that equals this, if you find it, return that item to me and that I will pass it back to whatever called ‘get item’. So ‘items dot find’. This is where we have to define a predicate, which is why I just said we have to define a query.

So to do that I’m going to first use something that you have not have used up to this point, we’re going to use a lambda operator. So on the left side of the lambda operator you’re gonna have the input variable, which in our case is going to be a variable that will have the value of the item that we’re currently looped on top of. So if we’re looping over all the item in this and we get to the diamond sword here, whatever that we define on the left side of the lambda operator will be the member that contains that reference to that item.

So I’ll say, we can just say item, and then the lambda operator is on the left side, we have the input variable. Now on the right side we have the ‘expression’ and that’s gonna be what we are looking for, in a sense, the query that we are passing in. So I wanna check and see if the ‘item dot ID’ is equal to the ID that I just passed in. So item being the field, or sorry, the variable will be defined right here that will contain the item that we are looped on top of currently and once this happens it’s gonna then compare it to the ID we passed in for every single item but when it finds one it’s gonna be like, ‘okay, I found one’, then it’s going to give us that item back as a return value for ‘find’.

So then all I have to do is return that whole expression back out. And it’s gonna return the item, that define method found, to whatever called ‘get item’. — Very simple. Loop through every item, compare it’s ID to the ID we passed in, if it finds one, return that back to whatever happened, if it doesn’t find one, okay, no problem, so there we go. And you can see how easy this would be to actually do it for another value as well, so let’s say, ‘get item by string title’. Then we just do ‘item dot title’ and compare it to the title we just passed in. If it finds one, it will return it back just like this one does. And you can do it by any member on the item object. Member being a field on the item, in this case title, description, icon, ID and the stats list and that’s gonna be it for the item database.

In the next lesson, we’re going to create the recipe database, which is gonna be very similar to this except we have to write the ability to compare recipes to the items in our crafting table, we don’t have a crafting table panel yet, the window, the grid we don’t have that yet but we can easily work with just an empty array that will eventually be the items in the crafting table. And that’s going to be in the next lesson. I will see you there.

Using Unity’s Scriptable Object System – Pizzaria Project – Part 2

Part 2: Finishing up the Dialogue Controller, using Scriptable Objects to hold the dialogue data, and setting up camera functionality.

This is the second part of the tutorial series where we use Unity’s Scriptable Object system to build a Pizzaria project. Please make sure you have completed the first part of this tutorial series to ensure that you are able to follow along effectively and continue building the project with part two. The link to the first part of the tutorial is here

Source Code Files

You can download the tutorial source code files here. All the project files are located in the main folder. The asset folder contains additional intermediate files that were used during the process of creating the game sprites.

Customer Dialogue States

Open the Pizzaria project and navigate to the Scriptable Object folder in the project. Create a new script and name it “CustomerDialogueSO.” Open the script up in Visual Studio.

Remember that Scriptable Objects are not attached to any game objects in the scene. Scriptable Objects do not inherit from Monobehaviour, they inherit from ScriptableObject. The first thing that needs to be done with this script is to change “Monobehavior” to ScriptableObject, right after the colon. Delete the Start and Update functions, these are not needed in this script.

Create a string variable and name it “CustomerGreeting.” This needs to be serialized, so that it is visible in the inspector.

Now, in order for us to be able to create a Scriptable Object and add it to the project we need to add one more line to this script. Above the class declaration “CustomerDialogueSO : ScriptableObject” you must add this line: “[CreateAssetMenu(menuName = “CustomerDialogueSO”)]”

This line ensures that we are able to add a ScriptableObject to the project via the Unity Editor. 

[CreateAssetMenu(menuName = "CustomerDialogueSO")]

[SerializeField]
string customerGreeting;

Save the script and go back to the Unity editor, you can now Right Click in the Scriptable Objects folder and Create>CustomerDialogueSO. This will add an .asset file to this folder.

Image may be NSFW.
Clik here to view.

Name this new Scriptable Object “EmployeeGreetsCustomer”

Image may be NSFW.
Clik here to view.

We need to add another attribute to the CustomerDialogueSO script. Open the script backup in Visual Studio and below the SerializeField attribute we need to add a TextArea attribute so that the field next to Customer Greeting is large enough for us to see effectively for ease of typing directly inside the Unity Editor. The text area attribute can be 8,8.

[TextArea(8,8)]

You will see that the text input field became much larger, and you shouldn’t have problems entering or seeing what is being typed inside that field now.

Image may be NSFW.
Clik here to view.

In the Customer Greeting field we are going to fill this value in via the inspector with what the Pizzaria Employee will say to the customer when they greet them. Enter the greeting inside the value in the inspector “Welcome to the Pizzaria, how may I help you?”

Getting our beginning customer greeting setup and functioning

Open the CustomerDialogueSO script and create a public function and name it “GetCustDialogue.” This function needs to return a string, that string it’s going to return the customerGreeting string we created earlier on.

public string GetCustDialgoue()
    {
        return customerGreeting;
    }

This function needed to be public so that we can access it outside the script.

In this same script create a CustomerDialogueSO variable that is serialized and name it startCustomerGreet. Save the script.

Now navigate back into the Unity Editor and with the DialogueController game object selected in the scene, look at the Inspector window and you will see under the Pizzaria Operation(Script)  component the field called “Start Customer Greet” this is where we need to drag the scriptable object we created earlier called “EmployeeGreetsCustomer” to this field.

Image may be NSFW.
Clik here to view.

At this point we are going to need to know what part of the customer/employee interaction we are in. Create a variable called custEmployeeInteraction. Get reference from the  CustomerDialogueSO script.

CustomerDialogueSO custEmployeeInteraction;

What were doing here is deriving from the class we created earlier called CustomerDialogueSO.

In the start function we need to set the custEmployeeInteraction to startCustomerGreet.

custEmployeeInteraction = startCustomerGreet;

Earlier we hooked up the startCustomerGreet because we dragged the scriptable object asset we created earlier into the field in the Unity Editor. That scriptable object had all beginning customer greeting info already in it.

We need to now call the public function we created earlier from the CustomerDialogueSO script. It was the public function named GetCustDialgoue().

We can do this where we originally had put the string “Placeholder” and replace that with custEmployeeInteraction.GetCustDialgoue();

The start function in the PizzaOperation script should now look like this:

// Use this for initialization
    void Start() {

        custEmployeeInteraction = startCustomerGreet;
        txtComponent.text = custEmployeeInteraction.GetCustDialgoue();
    }

Save the script, navigate back to the Unity Editor and hit Play. The game scene should now look like this:

Image may be NSFW.
Clik here to view.

Navigate to the Scriptable Objects folder in the Unity Editor, it’s important we keep the project organized. Create a new folder and name it “EmployeeDialogueSO” we will be keeping all the Employee dialogue in this folder. Then create another new folder and name it “CustDialogueSO.” Drag the EmployeeGreetsCustomerSO into the EmployeeDialogueSO folder. Save the scene and project.

In order to advance through the employee to customer dialogue we will be using an array that is serialized and a public function that will return one of the variables in the created array.

Open the CustomerDialogueSO script and create a serialized array of type “CustomerDialogueSO” and name it “nextDialogue.” Then we need the public function called “GetNextDialogue” that will return nextDialogue.

[SerializeField]
    CustomerDialogueSO[] nextDialogue;

public CustomerDialogueSO[] GetNextDialogue()
    {
        return nextDialogue;
    }

What we have here is created a CustomerDialogueSO array called “nextDialogue” that is being returned when we will call the GetNextDialogue function via code. Save the script and navigate back into the Unity Editor.

Click on the “EmployeeGreetsCustomer” scriptable object asset file. Look at the Inspector and you will see the Next Dialogue array value that is now visible in the Inspector. It has a drop down arrow next to it and you can click this. We will be adding the other scriptable object asset files to this array right here in the Inspector after we create them.

Image may be NSFW.
Clik here to view.

Because, we made the array serialized we can add the elements directly to it from the Inspector window just by dragging and dropping them onto the array that is visible in the Inspector. This is one of the beauties of using the SerializeField attribute within Unity.

The size value field will actually be the size of the array. The size of the array will adjust automatically as we add the scriptable object asset files to it. Just remember arrays start from “0” instead of “1.”

A quick tip that will come in handy with this tutorial as we work inside the Unity Editor; this will save you a lot of trouble as you will be clicking on multiple files and then dragging them into the Inspector onto the array field.

If you navigate into the Unity Editor and look up in the upper right hand corner of the Inspector you will see a little lock icon. If you click on this lock while you have a game object selected in the scene this lock will actually lock the Inspector window so that as you’re clicking on multiple files the Inspector window will stay focused on that game object you chose to “lock.”

Image may be NSFW.
Clik here to view.

Creating the first customer to employee scriptable object asset

Open up the CustDialogueSo folder. Create a CustomerDialogueSO  asset. Do this just like how we created the first scriptable object earlier. Right Click>Create>CustomerDialogueSO in the menu.

Image may be NSFW.
Clik here to view.

Now we need to fill in the Customer Greeting value field: “Hi, I would like to order a medium pepperoni and mushroom pizza. Help the customer by inputting their order into the cash register. Hit the “Y” key to help this customer.”

This is what the customer will respond to the pizzaria employee after they are greeted by the employee.

Now we need to hook this up properly in the Inspector so that the employee to customer dialogue goes in the correct order. Select the scriptable object asset called “EmployeeGreetsCustomer” use the tip you learned earlier about locking the Inspector by selecting the lock icon. Then navigate to the CustDialogueSo folder and drag the CustToEmployee scriptable object asset onto the array field in the Inspector.

Image may be NSFW.
Clik here to view.

Managing the dialogue parts

We now need a way to control the different states of the employee to customer dialogue and be able to control what the employee can do next after the customer has place an order with the Pizzaria.

Create a private function named “PizzaDialogueManagement” This function is going to cause the dialogue between the employee and customer to advance by detecting if the “Y” key has been pressed by the user. Then the text component on the Dialogue Controller needs to pull in the custEmployeeInteraction.GetCustDialgoue. Make sure to call the PizzaDialogueManagement function inside the Update function in the script. Save the script.

// Update is called once per frame
    void Update() {
        PizzaDialogueManagement();
    }

    private void PizzaDialogueManagement()
    {
        CustomerDialogueSO[] nextDialogue = custEmployeeInteraction.GetNextDialogue();
        if (Input.GetKeyDown(KeyCode.Y))
        {
            custEmployeeInteraction = nextDialogue[0];
        }
        
        txtComponent.text = custEmployeeInteraction.GetCustDialgoue();     
    }

Hooking up the other scriptable object dialogue assets

A quick change needs to be made to the Customer Greeting field on the EmployeeGreetsCustomer scriptable object asset.

Add the text “Hit the “Y” key to help the customer” to the input field.

Create a new scriptable object called CashRegister, you can leave this asset in the EmployeeDialogueSO folder. Input the text “Click on the Cash Register button to navigate to the cash register. There you can input the customer’s order by selecting the menu item of what the customer wanted.”

Then drag the EmployeeGreetsCustomer scriptable object asset onto the array field of the CashRegister scriptable object in the Inspector.

Image may be NSFW.
Clik here to view.

It’s important to have all the array elements filled in inside the Inspector for the Next Dialogue array. You can double check that they are all hooked up properly by clicking on each scriptable object asset in the project and making sure they are hooked up according to the screenshots below:

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Once you verified that all the scriptable objects are hooked up properly go ahead and save the scene and project. Hit the play button and test what we have so far. The screenshot below is how the game screen should appear once the Play button has been hit.

Image may be NSFW.
Clik here to view.

Follow along with the prompt, and the second part should look like this:

Image may be NSFW.
Clik here to view.

And finally the third part should display this:

Image may be NSFW.
Clik here to view.

Camera Functionality

Select the Main Camera in the scene. Reset the Transform component in the Inspector so that the Main Camera is now at the origin. Make sure the UI Container is positioned at the origin as well, if it is not just Reset it through the Inspector.

Select the MainPanel and navigate to the Rect Transform component in the Inspector. Change these values: Pos X = 0, Pos Y = 0, and Pos Z = 260.

We will be using a built in function that Unity has called “LookAt” we will be taking the Main Camera’s transform and then move the camera by using the “LookAt” function to get it to move to the other UI panels when the Cash Register or Cook Pizza buttons are clicked on by the user.

Create a new script and name it “MenuNavigation.” Open the script in Visual Studio, add a public function and name it “LookAtPanel” it’s going to accept two parameters: transform and panelTransform. Inside the function were going to get the Camera to lookAt the transfrom of the panelTransform.

public void LookAtPanel(Transform panelTransform)
    {
        Camera.main.transform.LookAt(panelTransform.position);
    }

Save the script. Navigate back into the Unity Editor and make sure the Main Camera in the scene is tagged as “MainCamera.”

Select the CashRegisterPanel and adjust the Rect Transform to match the screenshot below:

Image may be NSFW.
Clik here to view.

Now select the CookPanel and adjust its Rect Transform component to match the screenshot below:

Image may be NSFW.
Clik here to view.

Create an empty game object and rename it to “PanelMenus.” Attach the MenuNavigation script to this object in the scene.

Select the GoToCashRegisterBtn and add a n On Click () function to this button. Select the PanelMenus object, this game object has the script MenuNavigation attached to it that contains the public function LookAtPanel. Select the MenuNavigation>LookAtPanel (Transform) from the drop down menu.

Image may be NSFW.
Clik here to view.

The On Click function should look like this:

Image may be NSFW.
Clik here to view.

Save the scene and the project. Hit the play button, and then click on the white Cash Register button: the camera should now change its focus to the CashRegisterPanel. Stop Play mode and test out the Cook Pizza button, now the camera should focus on the CookPanel once that button is clicked.

That comfortably concludes this second part of the tutorial. We will be adding in some more buttons to each panel to navigate back to the MainPanel later on in Part 3 of the tutorial. See you then!

Web Class: Game Character Customization with Unity Multipurpose Avatar tool

Transcript Part 1

Hey guys. My name is Austin Gregory, and in this course, I’m going to teach you how to create a cool little custom character creator like you see here based on the UMA tool on the Asset Store, the Unity Multipurpose Avatar tool. It’s completely free on the Asset Store and it allows us to build and define specific character changes and settings to customize and build our very own player characters for our games.

Now I picked a few of the attributes to change in this course, but you can do so much with this. You can change nose shape, eye shape, the size of the head, the shape of the head, hand size, foot size, colors of everything, outfits, whatever armor they’re wearing, if they’re wearing gloves or boots or anything like that, and you can also extend it with all your very own models and gear and equipment, whatever you may have.

So if we look here, what I decided to go with is height, muscle, weight, hair, skin color, and then our sex. We can change from male to female. It can also be based on a race. Maybe you have orcs. Maybe you have goblins, that kind of thing. It all works just fine here. So let’s just make a little guy. I’ll make a guy. I’ll make him a little buff, thin him down a bit, give him some hair, and we’ll make him green like the Hulk. And if I were to save this character out, then I can use him whenever I’d like. We’re gonna learn how to use him in a different world. So we can load the data in. Or I can also make a female, and I can just do the same things here, define the same stuff, change her hair up, change her skin color, and I can save that character out.

Now if I were to jump over into my other scene where I’m loading in this data simply by looking at some text that we are saving, I’ll load that data in and you’ll see my character is ready to go in my game. And we can run around and just have a good time as this pink lady.

We’ll be learning a lot in this course, guys. My name is Austin Gregory and I will see you there.

Transcript Part 2

Hey guys, my name is Austin Gregory, and in this course I am going to teach you how to set up a character creation scene where we’re going to be able to customize characters that we can then use in our games.

To do this we’re gonna be using a free asset on the Asset Store called the Unity Multipurpose Avatar system or U-M-A or UMA for short. This is going to allow us to customize lots of things about these avatars from DNA which is going to allow us to control facial features like the pointiness of the nose, the angle of the ears, the sharpness of the jaw.

We’re going to be able to control the height and the muscle build, the fat, the weight, skin color, foot size, all kinds of things like that. And there’s a lot of details there that we’re not going to control ourselves, but once you understand how to manipulate the height of the character, you can manipulate any of those details. Once you understand how to manipulate the weight of the character, you can manipulate any of those details as they’re all done in the exact same way. UMA allows us to do this very easily.

It also allows us to define a wardrobe for our characters and the handles, equipping and matching that very easily for us. Now for all of these we’re going to be using the built-in Wardrobe Recipes that’s going to allow us to get up and go in pretty fast using the clothes they provide for us. But if you are an artist or if you just like to learn this kind of stuff, you can definitely build your own based on the UMA model to allow you to add any kind of equipment or outfits or clothing that you would like for your UMA, and it will work with the system that we’re developing here.

As long as you build it in accordance with the UMA system itself, you’ll be able to stretch out the muscles and change the height and so on, and your outfits will match and will conform to the models. This as I said is free and it’s very very powerful. And we’re not gonna touch on a fraction of what it can do, but we’re going to use the stuff that we need to be able to create a simple little customizer like you see right here that I built. It’s a very simple tool, and these sliders here, you could change any data you would like about the avatar, the character. I chose height and muscle and weight for my example. That’s what we’re gonna be doing for this.

The height just controls the height of the character there. The muscle is separated into two parts, you have upper muscle and lower muscle. I have just combined them into one setting. And the weight as well, upper weight and lower weight. We’re changing the sex of the character, male and female. And we have a few hair presets that I added, depending on the sex, you’ll get different hair options. And then we have some skin color that may be a little alien but that was easier than trying to match actual human skin. So we’re changing the hair by changing some of the slots on our UMA. And the slots are what you can see here with like these gloves, how they kinda conform to the hands of the character, or if you had some shoes on or these pants in fact are a part of the slot system, and the shirt and this robe here.

But it’s a very complex system that’s easy to use that allows you to, let’s say you created this robe, you could say once this robe is equipped, hide the torso and hide the legs, that kinda thing. It’s a very simple slot system that handles obscuring and showing certain details based on the settings that you give it. So the first steps we’ll have to do is download and import UMA, obviously we need the tool, just right off the Asset Store. We’re gonna create a base UMA character, maybe throw on some clothes so they’re not naked, and then we’re going to set up a simple system to allow us to click on that character and rotate them kinda like you would get in a character creator if you’re familiar with an MMO or just any RPG where that has a character created and you can rotate the character around in.

And then in the next lesson we’re gonna set up the UI to get started building our characters. So let’s jump over to Unity here, and what I’m gonna do is I’m gonna create from the Unity Hub 1.3 here, I’m gonna create a new Unity project, and I’m gonna call it Character Customizer. It’s gonna be a 3D template. I don’t need analytics enabled for this because I don’t care. And I’m gonna click Create project. So here we are in the default Unity layout. If you want to get to this point, go up to Layout and go to Default so we have the exact same setup here. And the first thing I wanna do is go to the Asset Store, and let me connect here, I’m simply gonna search for UMA or U-M-A, Unity Multipurpose Avatar. It’s gonna be UMA, and there’s a bunch of options that pop up here but these are not what we want for this. There’s a bunch of tools on the Asset Store that are built and developed to work specifically with UMA, this tool right here. There’s a bunch of characters, there’s a bunch of equipment and models that you can get that work directly with UMA.

And there’s even character controller integrations and all kinds of stuff because UMA is a very big tool. It is the best tool really on the market for what we’re trying to do, and it’s free and open source, which we can’t go wrong with that. So I’m just gonna go here and I am going to just, if you don’t have it downloaded, make sure you download it, and then import it just like that. Now it’s gonna ask us what we want to import from all of these files and folders. We want everything in the UMA directory to be imported into our project. And this may take a while as there’s a bunch of stuff that you are importing. Once we have UMA imported, we wanna keep it very simple first of all, so we can just get started by having a character that is controlled and owned by the UMA Character System.

So to do that, I’m just gonna go over to Scene here, and the first thing I wanna do is I wanna create a plane that our character is simply going to stand on. We need something to allow our player to stand in our game world. So we’ll just have a plane here, and I wanna call it Ground. And we’ll just make it a bit larger, maybe 10 on the x and z there. And in the Game view we just have a big white plane. So what I wanna do now is I wanna place defaults-based UMA character. So we’re gonna go into the UMA folder, and I am gonna go to the Getting Started folder. This is where you can go whenever you just wanna get a quick start, and that’s exactly what we want to do. I need to drag out this UMA DCS prefab here, it’s Dynamic Character System. It gives us all the libraries, all the things our UMA character is going to need to work. So we’ll just drag this into our scene. Anytime you have an UMA character that you’re working with, you’re gonna want this in your scene. And then I want to drag out this UMA Dynamic Character Avatar prefab that allows us to actually build our character. So I’m just gonna drag this into my scene.

Now what we get here, first of all I’m going to rotate this, zero on the y so we’re facing the correct direction there. We have a placeholder model in our Scene view, but in our Game view there’s nothing there, and that’s fine, that’s because our characters are gonna be built at runtime whenever we actually generate the character. And the reason for that is there’s a lot of data that has to be loaded in that can only be loaded in whenever we’re actually running the game, that’s because if you make any customization changes, say, in our character creator, we wanna make sure that that’s loaded in whenever the game is loaded, so that we don’t even bother building the character before that point because all that data will be brought in at runtime. So let’s see what this looks like now if I were to run this. If I look at my Dynamic Character Avatar Script which is on the Character Avatar that we created, we see that we have Active Race set to HumanMale. That’s fine for now, we’ll leave that. And we have a bunch of stuff here, right?

This is just a crazy amount of stuff to look at, but we’re not gonna worry about most of it especially for now. So if I just click Play, what happens. I see a naked guy standing way out there. I can see his bum from here. So let’s actually take and bring him back towards the camera. And in fact let’s bring the camera, and let’s look at him from the direction we wanna see him from here. Let me just bring the camera a little closer. There he is. And there’s our guy standing there. So he’s naked, we don’t want him to be standing out here and getting too nippy, it looks cold out. So what I would like to do is if I were to go to my Character Avatar here, I see I have something called Default Wardrobe Recipes. Now the way UMA works, we talked about this a bit, but we are building Wardrobe Recipes that act as the clothing or the equipment that will be scanned on to our character. So the way we can do this is we have some built-in Wardrobe Recipes that we can simply drag and drop up here to see how it works by default.

So to find these wardrobe recipes, we’re gonna go up to Content. We’re gonna go down to UMA_Examples. And then I’m gonna go on down here to HumanMale because we’re working with a guy. There’s also a female version for this. And I’m gonna go to Wardrobe Recipes. And we see all of these options in here. These are just recipes that come by default with UMA, and again you can create your own, and there’s a ton of videos on how to create your own. It is a bit more in-depth than this is going to be as we’re just wanting to get a simple customizer in our game that you can then extend, right? So we’re going to get the base in place here that allows you to build your characters, and then when you wanna go crazy and create your own clothing and your own equipment, there’s resources out there for you. But in this case what I wanna do is just give him some clothing, so I’m just gonna drag, we have a robe here, I can just drag this robe, drop it on the Wardrobe Recipes drop box there. That’s the hood. We can add the shoes. And then we can add the actual robe itself. There we go, we have some clothing.

Now what you’re seeing what’s happening here is I’m just adding it to a list that is under Default Wardrobe Recipes. If I don’t want the male robe, I could just hit the X and take it off, right? Pretty simple stuff. I can also say we’ll just give him some underwear maybe, just so he is covered up a bit there, or maybe just give him some shorts, take off that underwear. There we go, we have some shorts on him. And we also have a shirt here. These are just the built-in clothes. You can actually do this at runtime, you can do this in our Character Creator that we’re gonna create. But we’re just gonna give them some default clothes so that they have some decency. So what I wanna do now, notice when I stopped playing the game, that goes away, and that’s just because that’s how Unity works. We all know that that anything you do at runtime typically is not going to be saved. So what I wanna do is just give him some shorts and a shirt. They don’t match but that’s fine, at least he’s not naked. Now this is on the HumanMale. We also have HumanMaleDCS which is what we’re going to be using. It’s the Human Male Dynamic Character System. So if I select that, my wardrobe is still there because it’s still HumanMale. And you’ll see male shorts works for HumanMale and HumanMaleDCS, but if I were to change my Active Race, which is a weird name, for the sex of the character, but it’s because you can create races for everything, maybe you wanna have an Orc race and you’ll have a male and female Orc, you maybe wanna have a unicorn race, you can have a male and female unicorn. I’m not sure what that would be.

But HumanFemaleDCS, now it says HumanMale and HumanMaleDCS wardrobe is still on her, but if we were to click Play, we will see, we see her standing faraway again, because we did all that in runtime, and she’s not wearing any clothes. So before we get up and close with her, what I wanna do is for the Female DCS, while these are already attached as the Default Wardrobe Recipes, I wanna add some clothes that work with a female. So I’ll go to HumanFemale, and I’ll go to Recipes, Wardrobe Recipes, and I want HumanFemale. There’s a girl version too but we’re gonna go with this. Let’s give her some, we can put her in an underwear, or maybe we’ll just put her in a shirt and some pants. So now we have HumanFemaleDCS and HumanMaleDCS clothes on. So depending on which race that we have selected, you’ll choose which one can go on in that race. So we’ll click Play now as the female, and you’ll see that she’s wearing some clothes.

Now while we are here, let’s drag this back closer to the camera, and we’ll just rotate around again. Now we’ll change this whenever we actually do our simple little movement system a couple lessons from now, but for now we’ll just get up and closer to camera so we could see what’s going on. There she is, looking good. She has no hair though. We can give her some default hair. We have FemaleHair1, 2 and 3 that come with this. These work just the same as the clothing as they count as perhaps a hat. You would have a hat, you have a hat of hair. We’ll give her the second option there. And if I click Play, we will see that she has some hair on. But if we were to change this over to a HumanMaleDCS, Dynamic Character System here, we will see that he still is wearing whatever we gave him, he’s ready to go to the beach, but he’s bald. So I don’t mind him being bald, but what I would like to do is give him perhaps a beard of some sort and then we’ll give him some hair just like that.

So now he’s got a five o’clock shadow, and, well, he still has very little hair. Let’s give him, we’ll give him, he’ll be bald on top here. There we go. It looks pretty good. And if we get any closer, we can see what’s going on with this. Doing this at runtime so it won’t stick but it’s fine. There he is looking pretty good. So that is going to be our base UMA model. These are the clothing that he’s gonna wear by default, and then we’re gonna create an editor that allows us to change his muscle definition, his height, his weight, maybe you wanna change things about his face, all that information is available to us. And we’re gonna be doing that by adjusting DNA values. Look at all the stuff in here. These are the stuff you get by default with the Default UMAs. If you’re creating your own characters and your own rigs and you follow a similar bone structure, you’ll be able to do the same stuff, or create your own.

Perhaps you have the unicorn, you wanna control the length of the horn. I don’t know why you’d wanna do that. But if you look in here, we can see, we can make, let’s just do, increase his arm length, increase the arm width, make him really really really bulky. We can change his ears, raise them up a bit, rotate them out, and increase the size of them. Make his, let’s see, make his head really small. (chuckles) It’s fun to play around with this stuff. He has a little, he has a big thick neck. And he is not very muscular but he’s bulky and he has a little belly and he’s tall. These are the kind of stuff we can do in the editor and it’s all the same stuff. So if we were to edit this value right here, you would know how to edit any of the other values. So that’s what we’re gonna do in the next lesson guys.

We’re gonna set up the UI so we can start interacting directly with the DNA that we have for our character. My name is Austin and I will see you there.

Transcript Part 3

Hey guys, welcome back. In this lesson, we’re going to set up the UI that’s going to interact with the DNA eventually.

It’s going to be the next lesson in fact when we start interacting with the data. But in this lesson we’re gonna lay out the UI. So we’re gonna add some sliders that we saw in that the first presentation that’s going to allow us to control some of those DNA attributes that we were just messing with in the last lesson. We’re going to add some buttons that allow us to change our hairstyle, to change our skin color, and just show you how you can do different things with different types of inputs. And with a couple different slots, and with some different data. Then we’re going to create a button that will eventually represent the create character or the save character button that will allow us to actually generate the data that we can then load into another scene later on.

So we can have our character in our game based on the character that we created. It’s gonna be pretty cool. So in Oom now what I want to do is first of all, let’s just do a split view here so we can see the game, and the actual scene view here. And I see where my character’s gonna be standing. And I want him to be standing a bit off to the left so we can have the menu on the right. I’ll just drag the camera to the right a bit. Probably something simple, you know, just like that. If we make this into like a 16 by nine, we can see what it’s gonna look like on a wide screen, which most things would be. We’ll go off to the right a bit more, and we’ll come in a bit closer maybe. Maybe cut off a bit and do a little angle down. Just a wee bit. Even a little closer I think. And then just raise it up a bit. And you could put some work into this, to get it how you would like. But this looks pretty good to me. So with that, what I want to do now start creating some UI elements.

Now I’m going to first create a simple panel that’s going to allow me to position all my elements where I want them on the canvas. So I’ll create a new panel here. And I’m going to hit F or double click on the panel to center it in my frame. In fact, we’ll go into 2D mode so we can do that a bit easier. And what I want to do is just create a panel that’s going to be off to the right of our character here. Just kind of floating out here. You know the kind of character creation screen that we’re going to be creating. The one that you see in most RPGs. Something very similar. And I don’t want this to be transparent. In fact, I just want it to be a darker color maybe. Up to you entirely how you want to do this. That looks pretty good. And I’m just going to call this customizer. And Inside of this we’re going to kind of section it off. At the top we’re going to have a title that’s going to be for the sliders that we’re going to have here. Then we’re going to have like a hair section that’s going to have a few options for hair. And then we’re going to have a few options for skin color. Which in my case I’m just going to have buttons, but in your case you could have images that would show you the color that you’re going to have if you’re going to click on that button or maybe just you know, have colored buttons to show you the kind of skin color that you would have.

So I’m going to create a UI text element or we could use TextMesh Pro here. In fact let’s use TextMesh Pro because it is a lot better and more efficient than the built in Unity Text. And it comes by default with Unity now. So all you have to do is actually select that, and you’ll get this window that says you have to import the essentials for TextMesh Pro to work. So we’ll go ahead and do that. It’ll just allow us to have crisper, more scalable text in our customizer here. We’re going to set this to be… First of all I don’t need the game view up for this. We’re just losing space there. We’re going to set this to be… Let’s make the panel not scale, I’m just going to anchor it to the right here. Because we want it to be a certain size, and not cause any issues here. And I’m going to grab this text element and we’re just going to drag it to the top left corner, make it about 20 in size, something like that. Maybe 24. And we’re just going to drag this up just like that. And I’m going to call this Character Settings. That’s going to be the title for this panel. Look in the game view, that’s what you’ve got. Pretty cool.

Now if I were to click play, we can kind of see where we stand here. There we go. So we have a guy standing here, then we’re going to have the options for the guy over here. Very cool. So the first thing I want to do in fact, is I want to make sure that we can organize this nicely, so we don’t just have elements flying all over the place. So I’m going to add a vertical layout group. It’s going to allow us to just kind of cascade our elements down this panel. So we don’t have to worry about positioning each individual one. We’re gonna have padding of maybe 10 units all around the panel. And then we’re going to have spacing between individual elements at about 10 as well. I might change that as we go. So now I want to take and add… If I were to go to UI, I can add text. And if I were to move it it’ll snap into the position that it should be in. Now I don’t like that kind of thing, where it’s going to be split among the total height of our panel. But the more elements we add, the better it’ll be spaced out. So we’ll just go with that for now. In fact, we don’t want to use regular text, we want to use TextMesh Pro text. And this is going to be height, because we’re going to create a height slider for this. And we’re going to set this to be about 20 in size.

Now what I would like to do here, is I would like to create an empty object inside of this that’s going to act as the parent for our individual slider and labels, because this is going to be a label pretty much for a slider. So if I were to take this text, add it to that game object, take that text then and make sure that it’s positioned inside of that, in a position that I like. And then take the game object here, and just make it fit inside of our element. The reason we’re doing this is because we’re going to have a slider and a label together, and we don’t want it to look weird whenever we start having it fill out the panel using the vertical layout group. And just show you how this would work, if I were to create inside of this new empty object a slider, I could position it where I want it inside of this object, but then this object itself will be positioned in the panel according to the layout. Which is exactly what we would want. So I can just resize this to make sense, and then just drag the slider down. And I would in fact like to start this at .5, just to be in the middle. So we can see that it does work.

Now what I would do is I can just duplicate this, and there we go. That’s how you would do it, right. So the more I add, the more that’d fit in there.e Now if you don’t like that, what you can do… If you were to come in here and say that we wanted it not to control the size of the height of the elements, what I could do is each individual object that we now have, we could set a height of like 50 units on it and just snap it into place. And each one would have the same height. And we’ll just have a nice little list of objects. Pretty cool. Maybe that’s too large. Not too sure, it’s probably fine. So the second slider we’ll use it for muscle. It’ll define our muscle attributes. Then our next slider we will use for weight. In fact, I think we should get rid of some of the spacing here. Make it like five. The next thing I want is a list of options for our hair. Just gonna be a couple buttons, maybe three buttons that allows us to click on them and change the hair that we’re using. Just all basic UI stuff that we’re doing here. Nothing specific to UMA at all.

So I’m going to create a UI panel inside of this panel. And you’ll see, where did we go there. We will set the height to be 50 and the width to be, well whatever the width should be if we were to actually go to customizer, child control size for the width there. Which means we’re going to get the full width of the panel no matter the size of the panel, which is what we want. Now if I were to take this I could say, maybe make it a 75 like that. Now this is going to have it’s own layout inside of this panel. It’s going to allow us to add as many buttons as we want, and they will layout nicely in a row. So to do that we would use a horizontal layout group. Just like that. And inside of this we could create a button. Or go ahead and create a couple of buttons. And we’ll just snap them into place. But that’s not what we want. We want them to be kind of square. So if I were to say 50 or it’s actually 75 tall isn’t it. So we’ll do 75 on the height there. Or we could go to the panel, and we could say the child controls width and height, right.

So we just have it fit the panel, no matter how many buttons that we have. And that allows us to also add some more padding so we can see the edge of the panel. And the spacing as well there. So then we could say this is hair A. And then this one is hair B. And then this one is hair C. Just like that, looks pretty good. And then we could add another panel below this one. And notice the layout system that we have going on here makes is very easy to just add new elements, and they just fall in line. It’s pretty cool. This one is going to be skin color. We could add another button in fact. So we have four options for skin color, just to show you some difference. And I’ll say just one, two, three, and four. And I could add a label above this, so we know hey this is the skin color. And to do that, all I’d have to do is go to customized UI, TextMesh Pro text. And in fact all these buttons are using the built in Unity Text. I would recommend changing those to the TextMesh Pro. But since we’ve already done all this, I’m not going to worry about it. But you should go ahead and go through if you plan on using this in a game, making these TextMesh Pro elements inside of the buttons. So I’ll just take this and place it above the panel. And notice the order in the hierarchy affects the order of the layout. Pretty cool. So I’ll just take and resize this. Make it 24 so it matches the character settings. Actually we’ll make it match the 20 of our individual labels. That makes more sense. So we’ll make it be 20, and then we’ll just fit it just like that. And this will say skin color. There we go. So that’s going to be our customizer.

Now these are the attributes that I decided to use. Again, there’s like a hundred built in attributes that you can individually change, and all the wardrobe changes you can make, and you can make any kind of skin colors you would like. I’m just going to choose four random colors for mine. And you can have tabs of different settings, if you think of how Skyrim does it, or how World of Warcraft would do something similar. Or maybe a more advanced MMO than World of Warcraft. Alright it’s just a lot of possible attributes that you can change using the exact same system we have set up here. But of course we can’t go over everything, that would take us forever. So if we click play now, we can just see what it kind of looks like. Got our dude standing here, and we can control these sliders, and they can change his hair and the skin color. Except we can’t yet. We’ll do that in the next lesson. But the last thing I want to do in this lesson is I want to add a button UI button. And I’m simply going to place this in the center of the player, at least around the center of the player. I expect him to be like right here. And I’m just going to anchor this to the bottom center. And this button is going to be save character. Or create character, whatever you’d like. And I’ll take the button and I’ll change the color of the button to be like a confirm color. So a nice blue, and then take the text color and make it white. And in fact we’ll hold down control and shift, sorry alt and shift and drag our button out to a size that we’d like. And then increase the text size. Again, in yours, you should probably use the TextMesh Pro here, instead of your built in text. But it is what it is for now. Click on play. And in fact, I want to move the camera over a bit, so we kind of line up a bit better with that.

So go out of 2D mode, double click on the camera until we find it here. We’ll zoom out a bit, go down a little bit, and then we’re going to go over a little bit. That looks pretty good. Maybe just a little bit more so we line up a bit better. And there we go.

So this is going to be the UI that we’re going to work with in the next lesson, whenever we start hooking up our UI elements to our DNA attributes. My name is Austin and I will see you in the next lesson.

Viewing all 1620 articles
Browse latest View live