Explore Free Game Web Classes – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Mon, 17 Apr 2023 08:21:45 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Game Web Classes – GameDev Academy https://gamedevacademy.org 32 32 How to Create Game Over State in Unity in 10 Minutes https://gamedevacademy.org/unity-game-over-tutorial/ Fri, 21 Apr 2023 01:00:04 +0000 https://gamedevacademy.org/?p=22034 Read more]]>

You can access the full course here: CREATE YOUR FIRST 2D GAME IN UNITY

Game Over – Part 1

In this lesson, we’ll set up the Game Over state for our game. In our game, the Game Over state will happen either when the Player hits an Enemy, or when the Player falls from the level.

The Game Over Function

To implement the Game Over state, we’ll go to the PlayerController script and do the following changes:

  • Add the SceneManagement library at the top of the script
  • Add the GameOver function to the PlayerController script
  • In the GameOver function, use the LoadScene function to reload the current scene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // Add me!!

public class PlayerController : MonoBehaviour
{
    // Older code omitted for brevity
    // Called when we get hit by an enemy or if we fall below the level.
    public void GameOver ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

And here’s what the PlayerController script looks like at the moment:

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D rig;
    public float jumpForce;
    public SpriteRenderer sr;

    private bool isGrounded;

    void FixedUpdate ()
    {
        float moveInput = Input.GetAxisRaw("Horizontal");
        rig.velocity = new Vector2(moveInput * moveSpeed, rig.velocity.y);

        if(rig.velocity.x > 0)
        {
            sr.flipX = true;
        }
        else if(rig.velocity.x < 0)
        {
            sr.flipX = false;
        }
    }

    void Update ()
    {
    // If we press the jump button and we are grounded, then jump.
        if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
        {
            isGrounded = false;
            rig.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }
    }

    private void OnCollisionEnter2D (Collision2D collision)
    {
        if(collision.GetContact(0).normal == Vector2.up)
        {
            isGrounded = true;
        }
    }

    // Called when we get hit by an enemy or if we fall below the level.
    public void GameOver ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

The Fall Game Over Challenge

As a bit of a challenge, we want you to implement one of the game-over cases yourself. In this challenge, you should make the fall-from-the-level scenario work as a game-over.

One of the ways to do so is to check whether the Player’s vertical position is below some level. Checking could be done in the Update function.

In this lesson, we implemented the Game Over function. In the next lesson, we’ll implement the game-over scenarios.

Game Over – Part 2

In this lesson, we’ll implement the Game Over scenarios.

The Fall Game Over

To make the Game Over happen when the Player falls from the level, we should make the following changes to the Player Controller > Update function:

  • In the Update function, check whether the vertical position of the Player is less than -4
  • If so, call the GameOver function
// Using directives omitted for brevity

public class PlayerController : MonoBehaviour
{
    // Older code omitted for brevity


    void Update ()
    {
    // Older code omitted for brevity


    // If we fall below -4 on the Y, then game over.
    if(transform.position.y < -4)
    {
    GameOver();
    }
}

    // Older code omitted for brevity
}

If you start the game now and jump from the level, in a couple of seconds, the level will reload from the beginning.

game level

game level

Here’s what the PlayerController script looks like now:

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D rig;
    public float jumpForce;
    public SpriteRenderer sr;

    private bool isGrounded;

    void FixedUpdate ()
    {
        // Get the horizontal move input.
        float moveInput = Input.GetAxisRaw("Horizontal");

        // Set our velocity.
        rig.velocity = new Vector2(moveInput * moveSpeed, rig.velocity.y);

        // Flip the sprite to face our moving direction.
        if(rig.velocity.x > 0)
        {
            sr.flipX = true;
        }
        else if(rig.velocity.x < 0)
        {
            sr.flipX = false;
        }
    }

    void Update ()
    {
        // If we press the jump button and we are grounded, then jump.
        if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
        {
            isGrounded = false;
            rig.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }

        // If we fall below -4 on the Y, then game over.
        if(transform.position.y < -4)
        {
            GameOver();
        }
    }

    private void OnCollisionEnter2D (Collision2D collision)
    {
        if(collision.GetContact(0).normal == Vector2.up)
        {
            isGrounded = true;
        }
    }

    // Called when we get hit by an enemy or if we fall below the level.
    public void GameOver ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

The Enemy Hit Game Over

We should also go to the Game Over state once the Player hits an Enemy. We’ll do this from the Enemy script.

But first, we need to add a way for an Enemy to know that it hits the Player, and not something else. Here’s what we’ll do:

  • Select the Player game object
  • Go to the Inspector window
  • Set the Tag property at the top of the Inspector window to the Player value

Now our Player is tagged as a Player. Well done!

Player game object

And here’s what we’ll do in the Enemy script:

  • Add the OnTriggerEnter2D function. This function is called when something enters the trigger collider
  • In this function, check whether we have a collision with an object tagged as a Player
  • If so, get the PlayerController component from that object and call the GameOver function on it
// Using directives omitted for brevity
public class Enemy : MonoBehaviour
{
    // Older code omitted for brevity
    private void OnTriggerEnter2D (Collider2D collision)
    {
        // Did the player hit us?
        if(collision.CompareTag("Player"))
        {
            // Trigger the game over state on the player.
            collision.GetComponent<PlayerController>().GameOver();
        }
    }
}

Now, if you jump into an Enemy, the game will reload as well. Here’s what the full Enemy script looks like:

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

public class Enemy : MonoBehaviour
{
    public float moveSpeed;
    public Vector3 moveOffset;
    private Vector3 startPos;
    private Vector3 targetPos;
    // Start is called before the first frame update
    void Start()
    {
        startPos = transform.position;
        targetPos = startPos;
    }
    // Update is called once per frame
    void Update()
    {
        // Move towards the target position.
        transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
        // Are we at the target position?
        if(transform.position == targetPos)
        {
            // Is our target pos our start pos? If so, set it to be the other one.
            if(targetPos == startPos)
            {
                targetPos = startPos + moveOffset;
            }
            // Otherwise, do the opposite.
            else
            {
                targetPos = startPos;
            }
        }
    }
    private void OnDrawGizmos()
    {
        Vector3 from;
        Vector3 to;
        if (Application.isPlaying)
        {
            from = startPos;
        }
        else
        {
            from = transform.position;
        }
        
        to = from + moveOffset;
        
        Gizmos.color = Color.red;
        Gizmos.DrawLine(from, to);
        Gizmos.DrawWireSphere(to, 0.2f);
        Gizmos.DrawWireSphere(from, 0.2f);
    }
    private void OnTriggerEnter2D (Collider2D collision)
    {
        // Did the player hit us?
        if(collision.CompareTag("Player"))
        {
            // Trigger the game over state on the player.
            collision.GetComponent<PlayerController>().GameOver();
        }
    }
}

In this lesson, we implemented the Game Over scenarios. In the next lesson, we’ll work on the collectible Coins.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript – Game Over – Part 1

Welcome back everyone. In this lesson we are going to be working on setting up our game overstate for our 2D platform here.

So the way the game over state is gonna work is pretty much whenever our player gets hit by an enemy or if they fall off the edge and down below our level, they are going to basically reset, okay?

The level is gonna restart and the player will spawn back up here. Okay, so how do we do this? Well, let’s go over and open up our player controller script right here.

Now inside of the player controller script, we are gonna go down and create a brand new function. And this function is gonna be a public void called GameOver. Okay? Like so.

Now the reason we are making this function a public function is because we need to be able to call this from outside of the script. For example, our enemy script here is going to be able to call that function.

So in order to do that, we need to make it public. Now, inside of this function, what we are going to do is basically reload our current scene.

So in order to do that, we first of all need to tell the script that we want to be able to access Unity’s scene manager. And to do that we need to go to the top and you’ll see here we have these three lines of code, okay?

They’re basically using, and then we have a library here. Now, the way code and C Sharp especially works is that you don’t have everything at your disposal right at the start, okay?

So for certain things you may need to access a library. In our case, we are accessing the Unity engine library which allows us to access things such as mono behavior, rigid body, sprite renderer, the fixed update function, the update function, okay?

These are all things that are built into the Unity engine itself. Now, the Unity engine doesn’t always give us everything we need since there are a lot of different code libraries that we can access.

So if we wanna get specific, we do need to actually add them here. So for example, in order to access our scene manager, we need to be using the scene management library.

Now to do that, we can go to a new line here and just go using Unity engine dot scene management like so, and now we have access to our scene manager. So let’s go back down to our GameOver function.

And inside of here what we are going to do is go scene manager dot load scene, okay? And this function right here, basically we need to give it either a scene name, so we can just go level one like so, which is the name of our scene, or we can give it a build index.

And our build index for level one is zero. Basically, the levels go 0, 1, 2, 3, 4, 5, et cetera. But what if we’re on level five, for example? We don’t wanna have to hardcode every single level we have.

So, instead what we can do is we can just get whatever our current scene is and reload that. So to do this, I’m gonna go SceneManager dot GetActiveScene.

Now this is a function call, so make sure to add the two empty brackets like so, and then dot buildIndex. So this here is basically getting the index for the current scene and loading that.

So this line of code essentially reloads our current scene. So we have our game over function, but at the moment it’s not hooked up to anything just yet. So if we were to play our game, nothing would happen.

So in order to make something happen, we are first of all gonna make it so that if our player is jumping along the level here and they fall off the platform we don’t want them to keep on falling down forever.

Let’s say once they reach below, we’ll say below negative four, okay? Once they go below negative four on the Y axis that is when we will basically call the game over function.

So to do this, we are gonna go up to our update function right here. And as a bit of a challenge, I want you to have a go at implementing this.

Here’s a hint. Basically, we are gonna have an if statement that checks to see if our Y position is below negative three or negative four, I’m pretty sure we said, and if that’s the case call the game over function. So have a go at that and I’ll be right back to see how you’re done.

Transcript – Game Over – Part 2

Pretty much what we want to do is inside of our PlayerController’s update function we want to check every single frame if our player’s y position is below a certain number.

So what we’re gonna do is we’re gonna create an IF statement here. We’re gonna go, if transform.position.y is less than, let’s just say negative four then what we are going to do is we are going to call the GameOver function like so, okay?

So that is what we need to do here and make sure it is inside of the update function since we do want to check this every single frame. So we can save that, we can then go back inside of Unity now.

And if we press play, we should be able to test this out. So let us go over to the side right here and jump off the edge. And as you can see, once we go below negative four our scene basically gets to reset.

So we are back at the start and there we go. Now one more thing and that is our enemy. As you can see right now our enemy is just passing directly through us.

So we need a way of making it so that when the enemy hits us the GameOver function gets called. So how do we do that? Well, let us go over to our enemy script right here, and inside of the enemy script we need to create ourselves a brand new function.

Now this is going to be the OnTriggerEenter2D function. So we’re gonna go void OnTriggerEenter2D. Now OnTriggerEenter works very similar to OnCollisionEnter yet they both differ in a certain way.

Collision is basically a solid hit, so you can think of when our player lands on the ground their feet are being planted on the ground’s collider, whereas a trigger is passing through something, okay?

So maybe you might want to have some sort of trigger when a player walks through a door that would be a trigger, okay? The player isn’t blocked, they can pass through it, yet we can detect when that pass through happens.

And that is what a trigger is. So what we need to do is we basically need to make it so that when the player is hit by the enemy we call the GameOver function. But how do we do that?

Well, we’ve got the function here that detects when a trigger has happened, but how do we know if it was a player or not? How do we know that what the enemy hit is a player and not a wall, or a coin, or another enemy?

Well, the way we can do this is by checking to see what the player’s tag is. And before we continue writing code, let’s go back inside a Unity and we need to give our player a tag.

So I’m gonna select our player here and if we go over to the inspector, you’ll see underneath their name they have this little tag dropdown. Now tag is basically a label that we can attach to a game object.

So I’m gonna click on where it says untagged and you’ll see there are a few preset ones here. We can click add tag to add a new one. But we’ve got player, sorry, I’m just gonna select that.

And now our player game object is tagged as player. And you can of course, create tags for other things as well if that’s needed.

But we’re just gonna tag our player for now. So back inside of our script, what we’re gonna do is we are going to check to see if the collision.CompareTag is Player. So the parameter here is collision.

This is basically going to be our player’s collider when the enemy hits us and we are checking to see if that game object’s tag is player, and if so then the condition is true and we can call the GameOver function.

Now, in order to call the players GameOver function, we need to access their player controller component. So to access another game objects component or get any component in general, we need to do a certain function call.

So I’m gonna go collision.GetComponent, and then inside of these two angled brackets we need to define the type of component we are searching for which is gonna be PlayerController, and then two empty brackets like so.

And then we can go .GameOver. Whoops, not GameObject, GameOver, like so. So basically what we have done here is we have accessed the collision component that we have hit.

In this case it will be the player after we do this IF statement. Then we are getting another component on that GameObject we are searching for the PlayerController and then we are calling the GameOver function on the PlayerController.

So we can save that, go back inside of Unity and let’s test it out to see if it works. So I’m going to press play right here and if we jump up into our enemy, we should see that when it hits us the scene gets reset and we can even jump into the enemy here to make sure it works.

There we go. So we’re able to reset the scene by having our enemy run into us. So we need to avoid them on this jump here. And if we jump off our level and fall down below that will also reset the level as well.

So yeah, that is a look at our GameOver state inside of Unity. Now, in the next lesson, we are gonna be looking at setting up our coins, okay? These are basically going to be the collectibles that our player will collect and that will increase their score over time. So thanks for watching, and I’ll see you then in the next lesson.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
Free Course – Learn Unity Engine in 90 MINUTES https://gamedevacademy.org/unity-beginner-tutorial/ Fri, 14 Apr 2023 01:00:29 +0000 https://gamedevacademy.org/?p=21848 Read more]]>

Start your journey into becoming an expert game developer by learning one of the world’s most popular Unity game engine – all for free in the complete Unity engine tutorial above! You can also download the project files used for the course below.

Download the project files

About

In this Unity tutorial created by Daniel Buckley, you’ll dive into the basics of the Unity game engine which allows you to develop 2D, 3D, VR, and AR games, mobile content, training apps, and more. You’ll first discover the Unity Engine platform, how to create a Unity project, navigate Unity’s Editor, edit game objects, apply materials to objects, and adjust lights and physics in various ways. After, you’ll dive into the C# Scripting system and learn a few core scripting techniques to build your first interactive project!

Whether you want to build games, training apps, or something similar, these foundations will form the core knowledge you’ll need to build any sort of Unity Engine game or project in the future!

New to Unity Engine? Enroll in UNITY 101 – GAME DEVELOPMENT FOUNDATIONS on our website and find quick access to additional resources!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Create a Start Menu in Unity https://gamedevacademy.org/unity-start-menu-tutorial/ Fri, 07 Apr 2023 01:00:18 +0000 https://gamedevacademy.org/?p=21812 Read more]]>

You can access the full course here: CREATE YOUR FIRST 3D GAME IN UNITY

Menu – Part 1

In this lesson, we’ll set up the Menu for our game.

The Menu Scene

This Menu will be a separate scene. Let’s create a new scene called Menu in the Scenes folder now.

Scenes folder

Then, we’ll double-click on the Menu asset to open the Menu scene. You’ll see a default empty scene in your Editor.

Menu scene

First, we’ll change the background we have:

  • Select the Main Camera object
  • Go to the Camera component in the Inspector window
  • Set the Clear Flags property to the Solid Color option. This way, the camera will render color as a background
  • Set the Background property to a nice green color. This will be the background color of the scene

scene background

Now you should have the green background in the Game view.

Game view

Then, we’ll create a new Canvas object in the Hierarchy, as we did earlier.

Canvas object

The Title Text

Now, let’s create a title text for our game:

  • Create a new TextMeshPro object as a child of the Canvas
  • Name it TitleText
  • Position it above the center of the Canvas

Title Text

Canvas

Then, we’ll configure the TitleText > TextMeshPro component in the Inspector window the following way:

  • Set the Text to “My 3D Game
  • Enable the Bold Font Style
  • Make the Font Size bigger. We’ll go with 60
  • Set the Alignment to Center-Middle

TextMeshPro component

Here’s how your title should look like in the Game view:

Game view

The Menu Buttons

Next, we’ll create a button that will start the game:

  • Right-click in the Hierarchy and select the UI > Button – TextMeshPro option from the context menu
  • Name that button PlayButton
  • Make the PlayButton about the same size as the TitleText
  • Position the PlayButton in the middle of the Canvas

PlayButton

PlayButton in Canvas

Then, let’s select the child Text object of the PlayButton, go to the Inspector, and set the TextMeshPro > Text to “Play“.

TextMeshPro Inspector

Game View

Next, we’ll create a button to quit our game:

  • Duplicate the PlayButton by selecting it and pressing the Ctrl+D hotkey
  • Rename the duplicate to QuitButton
  • Move QuitButton to be below the PlayButton
  • Change the text on the QuitButton to “Quit

Quit Button as seen in the Unity Hierarchy

Menu screen with Play and Quiz buttons present

You can start this scene and click on the buttons, but nothing will happen right now, as we have to set those buttons up.

The Menu Script

Let’s create a script to control those buttons:

  • Create a new C# script called Menu in the Scripts folder
  • Attach this Menu script to the Canvas object

Menu Script

Then, we’ll open the Menu script and do the following:

  • Remove the Start and Update functions, as we won’t need them
  • Add the SceneManagement library so we could load the scenes from this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // Add me!!


public class Menu : MonoBehaviour
{


}

Our UI buttons can call functions from the scripts. So, we’ll create the functions that those buttons will call. Let’s start with a function for the Play button:

  • Create a new public function called OnPlayButton
  • In that function, make the Scene Manager load a scene with an index of 1. This will be our Level 1 
public void OnPlayButton ()
{
    SceneManager.LoadScene(1);
}

Next, we’ll create a function for the Quit button:

  • Create a new public function called OnQuitButton
  • In that function, call the Application.Quit function to make the game close
public void OnQuitButton ()
{
    Application.Quit();
}

Here’s what the full Menu script looks like:

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


public class Menu : MonoBehaviour
{
    // Called when we click the "Play" button.
    public void OnPlayButton ()
    {
        SceneManager.LoadScene(1);
    }


    // Called when we click the "Quit" button.
    public void OnQuitButton ()
    {
        Application.Quit();
    }
}

Updating The Scene

Now, let’s get back to the Menu scene in Unity Editor. We have to connect our buttons to the Menu script now.

We’ll set up the PlayButton first:

  • Select the PlayButton and go to the Inspector
  • There is a menu for the On Click event at the bottom of the Button component
  • Click on a plus icon there to add a new entry
  • Drag the Canvas object to the object field of that entry
  • Select the Menu > OnPlayButton function in the function field

Now, when you click on the Play button, this button will call the Menu.OnPlayButton function.

Menu.OnPlayButton function

Before testing this Play button, we have to add the Menu scene to the Build Settings:

  • Press the Ctrl+Shift+B hotkey to open the Build Settings window
  • Press the Add Open Scenes button to add the Menu scene to the list
  • Drag the Menu scene to the top of this list

Build Settings

If you start the game and click the Play button now, it will take you to the Level 1.

Play button

Level 1

The Quit Button Challenge

As a bit of a challenge, we want you to connect the Quit button to the Menu script by yourself.

In this lesson, we created the Menu and made it start the first level. In the next lesson, we’ll finish our work on the Menu.

Menu – Part 2

In this lesson, we’ll connect the Quit button to the Menu script.

The Quit Button Challenge Implementation

Here’s what you need to do to connect the Quit button to the Menu class:

  • Select the QuitButton game object
  • Go to the Button component in the Inspector
  • Add a new entry to the On Click event listener
  • Drag the Canvas object to the object field of that entry
  • Select the Menu > OnQuitButton as a function of that entry

Inspector with the QuitButton function in On Click

If you start the game and try to press the Quit button, nothing will actually happen. That’s because the Application > Quit function works only in the built project, and doesn’t work in Editor.

Game screen with final menu

In this lesson, we finished our work on the Menu. In the next lesson, we’ll set up one more level and connect them all together.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript – Menu – Part 1

Welcome back everyone. In this lesson we are gonna be looking at setting up our main menu. So this is gonna be in a brand new scene.

So let’s go down to our scenes folder right here and I’m gonna right click and go create scene. And I’m just gonna call this one, menu. Okay?

We then wanna double click on this to open it up. Yes, we’ll save the scene we’re currently in. And here we are in a brand new scene.

Now the first thing we’re gonna do is make it so that the background, if we go over to our game view here, isn’t the sky box, okay? We’re gonna make it a nice flat color. So let’s select our main camera game object.

And in the inspector, let’s change the clear flags from Sky Box to solid color. This basically means that if there is no object in the way it’s just gonna render a background color.

And we can of course change that by changing the background color property right here. And I’m just gonna make this a nice green, something like this perhaps. Okay?

And then what we can do is we can go ahead and create our canvas, which is gonna hold our UI elements. So I’m gonna right click and go UI canvas. That’s gonna create a new canvas and an event system.

And then on our canvas we are gonna have three different UI elements. We’re gonna have some text for basically the name of the game and two buttons, one that is for playing the game and one for that.

And one we press when we want to quit. Okay, so I’m gonna right click on Canvas, I’m gonna go UI, text-text Mesh Pro. Let’s call this one, title text. We can hop over into our scene view.

And if you’re not in this view that I’m right now you just wanna click on the 2D button at the top right corner of the scene view and then select the text or select your canvas and press F to focus in on it.

So for our title, I’m gonna position it just above the center like so and I’m gonna make it bold, font size, we can keep it at about 36 and let’s just center the alignment as well.

And I’m gonna call this one, My 3D Game. There we go. Okay, now next up we need two buttons. One to play the game and one to quit the game.

Now for buttons, we can right click on canvas go down to UI, and you’ll see down here we have a long list of different elements.

We could have sliders, scroll bars but you’ll see there is a button-text mesh Pro. Let’s click on that and I’m gonna call this one our play button.

Okay, so now for this button, I’m gonna increase it in size a bit like so, and then I’m going to open it up ’cause as you can see there’s a child object which is the text element.

And I’m gonna rename or I’m gonna change the text to display play. Okay, just like that. So if we look at our game view that’s what it’s gonna look like.

And then for the second button, we can just copy and paste the play button or control D to duplicate it, move it down tiny bit. I’m gonna rename this to our quit button and then change its text to say quit.

Okay, and there we go. So when we press play, we’ll as you can see, if I press play, I’m actually able to click on these buttons. You can see there’s a little color change but they don’t do anything.

So how do we make it so that when we press play it will launch us into our first level and quit will basically quit the game.

Well, for that we are gonna be creating a script. So let’s go to our scripts folder and we’re gonna create a new C sharp script called Menu.

And this menu script, I’m gonna go ahead and attach this to our canvas since I reckon that’s probably gonna be the best place to have it for now attached to the canvas.

And then let’s open it up. Now, inside of the menu script we’re not gonna be needing start or updates. So we can delete those two like so.

And instead we are gonna be adding in using UnityEngine dot SceneManagement because we do wanna be able to switch between scenes.

Now the way that the buttons work is that when you press a button, you can set it up so that it can actually call a function on a given component.

So what we’re gonna do on this menu script which is a component of Canvas, is we’re gonna create a function for pressing the play button and a function for pressing the quit button.

So I’m gonna create a public void and I’m gonna call this one, On Play Button. Now, it is important to note that this function has to be public because we are going to be accessing it from outside of this class.

And when we press the play button, what we want to do is lower it into the first level. So I’m gonna go SceneManager dot LoadScene. And there’s two ways you can do this.

You can of course enter in the name of your level one, okay. But later on you might go ahead and change the name of the level. You know, you might make it level one dot one or whatever.

So instead, I’m just gonna use the build index of one. Now the build index of one is not the first scene, but the second one, okay, zero build index zero is gonna be our menu scene.

And then build index one is gonna be our level one. So we can just enter in the build index like so. And then we have the quit button. So I’m gonna create a public void On Quit Button function right here.

Now what this is gonna do is it is going to quit the application. Okay? So if we have our game window up and we press quit, it’s gonna close down the game.

Now Unity has this already set up for us so all we need to do is go Application dot Quit. Okay? Just like that. And that is gonna close down our game pretty easily.

So yeah, on play button and on quit button, these are the two functions we have created. Now let’s go over and connect those to the buttons.

So back inside of the editor right here, what I’m gonna do is I’m gonna select the play button right here and I’m gonna go down to the inspector.

Now in the inspector you see that we have an image component which basically renders the button background image and then we have a button component and this is basically in charge of detecting when we’re clicking on it and changing the tint for when we’re highlighting, when we’re pressing, et cetera.

And you’ll also see something down here which says on click and it says list is empty. Now this is what is known as an event listener.

We’re not gonna really go into what an event is but basically this is a list that we can attach functions to so that when we press the button those functions are executed.

So what I’m gonna do is click on the little plus down here at the bottom right to add a new item to the list. And I’m gonna drag in the canvas to the object field here.

And then where it says no function, I’m gonna click on that, I’m gonna hover over our menu and then I’m going to select the on play button function right here.

So now when we click the play button, this on click event is gonna basically look at its list of functions and it’s gonna call those. So before we press play and test this out, let’s first of all go to file build settings and add the menu here.

Now to quickly add the scene you currently in, we can just go add open scenes, that’s gonna add the menu to the list but we want menu to be the first scene in the list. So I’m just gonna click and drag it up here.

That is because menu is now building index zero, level one is one, level two is two. We can then close outta this, press play. And then when we have launched into our game let’s press the play button and see what happens.

And you’ll see it takes us over to level one and then we can of course play through this game here. So yeah, that is the play button working. Now as a bit of a challenge, I want you to go ahead and set up the quit button right here.

I want you to connect this up to our on quit button function which of course is our menu script. That is a component of Canvas.

So it works in pretty much the exact same way as we’ve done with the play button but you’re of course choosing a different function. So have a go at that and I’ll be right back to see how you’ve done.

Transcript – Menu – Part 2

All right, so I hope you had a go at the challenge. Pretty much what we want to do is we want to create the On Trigger Enter function right here, okay?

So On Trigger Enter which has the collider as the parameter. And then what we’re gonna do is we’re gonna check, if other.CompareTag is Player.

So if the object that has hit the coin is of type Player then we are going to go, other.GetComponent, oops dot Get Component, PlayerController.AddScore and would send over a value of one for this coin, okay?

And then to destroy the coin we want to go Destroy game Object, okay? With a lowercase G, which references this game object that the script is attached to.

So that is all the code we need for detecting our overlap triggers, and then adding to the player score and then destroying the coin. So let’s save that. Let’s go back into Unity now.

And what we’re gonna do is we are gonna select our coin object, just move it over to a position where we might want it to be. Let’s just say over here, go to our game view, press Play and let’s see if it works.

So as you can see, our coin is spinning around and if I collect it, you’ll see that it disappears. And if we click on our player game object, you’ll see down in our player controller, we have our score property visible and it has a value of one.

Okay, let’s actually go ahead now and select our coin. Let’s go to a prefabs folder. Let’s drag it in there to save it as a prefab. And we can now copy and paste this coin a couple times to see how the score ticks up.

So I’m gonna select our player. I’m gonna press Play and keep an eye on the score property down here at the bottom right, okay?

When I start collecting coins you can see 1, 2, 3, 4, 5, and six, okay? And then of course, if we get hit by the enemy we get tail pulled back to the start and everything has been reset.

So yeah, that is how we can set up coins which then ties into our player’s scoring system. Now in the next lesson, we are going to be looking at actually setting up our level, okay?

We’re gonna be placing our enemies around, we’re gonna be placing our coins, getting the platforms and all that set up, and so that we can start actually getting some levels built, okay? So thanks for watching and I’ll see you all then.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
How to Set up Environments with QUIXEL in Unreal Engine https://gamedevacademy.org/unreal-quixel-tutorial/ Fri, 31 Mar 2023 01:00:34 +0000 https://gamedevacademy.org/?p=21708 Read more]]>

You can access the full course here: MAKE A PLANE ARCADE GAME IN UNREAL ENGINE

Environment – Part 1

In this lesson, we will learn how to set up our environment to create a more visually appealing game. By using Quixel Bridge, we can easily download high-quality photo-scanned assets for free. Quixel is basically a library of many different photo-scanned, 3D models that can be used for free within Unreal Engine.

Using Quixel Bridge

To get started with Quixel Bridge, go to Window and then Quixel Bridge. You can also undock the window for ease of use.

Quixel Bridge

Next press the Planet symbol and choose Environment.

Planet symbol and Environment

From here, Scroll Down and choose the Natural environment option.

Natural environment

This will give you many different environments to choose from, feel free to pick any environment you like, however in this course we will be using the Artic Ice And Snow environment collection.

Artic Ice And Snow

Now you can select an asset you like and click and drag it into your level, this will download and spawn the object in your level. It may prompt you to sign in before downloading in the bottom right.

asset

You can then move, rotate and scale your 3D model as you see fit within the level to build your scene.

You can also click and drag materials onto objects in your scene, to try this, select a ground material from Quixel Bridge and drag it onto our ground cube in the level.

materials

Now you can bring in any 3D models, materials, and props you like from Quixel Bridge to make your environment. Also, duplicate the rings we created previously to set up a course for your plane to fly through!

Environment – Part 2

In our example level we created a small, inclosed environment using the Quixel Bridge assets and made a large path of rings through out it for the player to fly through.

inclosed environment

Testing

We’re now ready to press Play to test out the game.

Testing

You should now be able to control your plane, fly through all of the rings and complete the course while increasing your score. You are now all set for creating your own arcade plane game, you could expand upon this in multiple ways such as adding weapons to shoot at targets with, a race objective around an obstacle course or adding collisions to the walls.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript – Environment – Part 1

Welcome back, everyone. In this lesson we are gonna be working on setting up our environment.

Now, right now you can see we have a pretty bland environment right here with just the rings, the floor, and the default sky.

So what we’re gonna do is we are gonna go ahead and use Quixel Bridge in order to get some high quality photo scanned assets into our game here. So to do this, we’re gonna go up to Window, we’re gonna go over to the Quixel Bridge.

Now, Quixel is basically a library of hundreds and thousands of different photo scanned 3D models. So these are high quality models that we can just drag and drop into our project for free, okay?

So in the bridge here, what we’re gonna do is I’m just gonna undock this window because we do sort of want it in the same view as our level here. And what we’re gonna do is we are just going to search for what we want.

So on the left hand side here, you’ll see there is a little planet. And I’m gonna hover over that, I’m gonna click on it, I mean, click on environment, and then environment here, we’re gonna go down click on natural.

And as you can see, there are plenty of different environments we can choose from. I’m gonna go Arctic Ice and Snow, just ’cause I think that’ll be pretty cool for a plane game.

And yet we can then go through, click on an asset that we might like, and you may have a option down here to log in before you actually download these.

And make sure you do that. Just log in with your Google account, with your Epic Games account. There’s plenty of ways to log in.

So once you do that, what we can do is we’re not gonna click on download because that will download it to our computer and makes it a bit hard to find.

Instead, what we’re gonna do is we are gonna click and drag on the thing that we want, and we’re gonna click and drag it into our level here. And then you’ll see that it spawns in like so, okay?

We can then scale it up, move it around, rotate it, and this basically just acts as a 3D model. And depending on which quality you set here, it depends on of course the size of the textures and the size of the model.

But overall, these models do look pretty good. And something else we can do is then, on our ground, we can click and drag on this material to apply it like so. And there we go.

We have that snow texture now applied to our ground. What I want you to do now is just go through and drag in the 3D models that you wish to create and set up your environment.

Okay, there are plenty of different models and environment set pieces here. So set those up. And also go ahead and start duplicating these rings and positioning them in places where, you know, you might have a nice challenging flight game to play. So I’ll be right back to see how you’re doing.

Transcript – Environment – Part 2

Okay, so you to go at that challenge. Pretty much just start placing those models around. As you can see, I also put these rings around, so the players to fly through them.

And you also got some other ground assets here to just add to the environment. So we can press play and test it out. Okay, increase our flight speed. Make it over to the ring little course I made over here. And there we go.

So as you can see, you can pretty much create whatever sort of flight arcade game you want. You might even wanna start adding in some weapons to the planes if you want.

You might add some targets that you could shoot down. Really, there’s a lot of things you can do with this little plane blueprint right here. You can of course, create rings like we’ve done. You can create weapons, create targets.

You might even wanna create a race around an obstacle course with collisions on the walls, so that if you were to bounce into them, the plane would explode. And yeah, that is our plane game inside of Unreal Engine.

Thank you for watching.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
Free Course – Create Interactable Objects in Unreal Engine https://gamedevacademy.org/unreal-interactable-tutorial/ Fri, 10 Feb 2023 01:00:00 +0000 https://gamedevacademy.org/?p=19826 Read more]]>

Master stories and simple game interactions in Unreal Engine by making a single system applicable to multiple objects. You can also extend the material covered here by checking out the full course below!

CREATE A WALKING SIMULATOR IN UNREAL ENGINE

About

In this free tutorial, instructor Daniel Buckley will walk you through the beginning steps of creating interactable objects in the popular Unreal Engine. Using the Blueprints Visual Scripting system, you’ll learn how to create and set up a player that detects interactable objects made with the blueprints class and a custom event that initiates interaction. Regardless of your game project pursuits, these skills for building interactable objects will provide you with new ways to express yourself creatively and add interactions via the Blueprints Visual Scripting system!

New to Unreal?  Consider downloading our free Unreal Engine 101 course!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Learn Unit Movement for RTS Games with Unreal Engine https://gamedevacademy.org/unreal-rts-movement-tutorial/ Fri, 06 Jan 2023 01:00:38 +0000 https://gamedevacademy.org/?p=19599 Read more]]>

You can access the full course here: BUILD AN RTS GAME WITH UNREAL ENGINE

Unit Movement – Part 1

In this lesson, we will start creating our Units.

Creating The Unit Blueprint

First of all, let’s create the Unit blueprint:

  • Go to the Content folder in the Content Browser
  • Create a new Blueprint Class in the Content folder
  • Select the Character as the Parent Class for that blueprint
  • Name that blueprint Unit

This Unit blueprint will be used as the base for both the Player and Enemy Units.

Player and Enemy Units

Next, let’s add some visuals to our Unit:

  • Open the Unit blueprint by double-clicking on it
  • Drag the Bishop model from the Content > Models folder to the Unit component in the Components panel

Components panel

Now our Unit has the Bishop model.

Bishop model

Then, let’s drag the Bishop model down so it fits nicely into the Capsule Collider our Unit has.

Capsule Collider

Or you can just set the Bishop’s Location in the Details panel to (0, 0, -88).

Location Details panel

Next, we’ll give our bishop the Unit_1 material in the Details > Material dropdown.

Material dropdown

This will make our Bishop blue.

Bishop blue

Setting Up The Unit’s Target Position

Now, let’s go to the Unit’s Event Graph tab. This is where we will create all of the logic for moving, attacking, and taking damage.

Event Graph

First of all, we need to create a variable to store the target movement position:

  • Go to the Variables dropdown in the My Blueprint panel
  • Create a new variable called TargetPosition

variable TargetPosition

Then, let’s change the type of the TargetPosition variable to the Vector:

  • Go to the Details panel
  • Set the Variable Type property to the Vector type
  • Compile the blueprint so those changes would be applied to the blueprint

Vector type

By default, the TargetPosition is (0, 0, 0), which means, our Units will go to the (0, 0, 0) position at the start of the game. As we don’t want this to happen, we will initialize the TargetPosition variable with the Unit’s position instead:

  • In the EventGraph, connect the BeginPlay event node to a new Set Target Position node
  • Connect the Set Target Position node’s Target Position pin to a new Get Nav Agent Location node

This way, we will get the Unit’s start position from the Nav Mesh and set it to the TargetPosition variable.

Unit start position

Moving To The Target Position

Next, we want to move our Unit towards the TargetPosition:

  • Connect the Tick event node control flow pin to a new AI MoveTo node. This node uses the Nav Mesh to move Actors
  • Connect the Pawn pin of the MoveTo node to a new Self node. This way, we’re telling the MoveTo node to move the Actor which calls it
  • Connect the Destination pin of the MoveTo node to a new Get Target Position node, so this node will know where to move our Unit
  • Compile the Unit blueprint so the changes would take place

Compile Unit blueprint

Let’s go back to the GameLevel level, add the Unit to the level, and start the game to see what happens.

GameLevel level

The only thing which should actually happen is the Unit Actor positioning itself to be on the Ground. As we set the TargetPosition to the Unit’s position at the start of the game and haven’t implemented any input, our Unit has no reason to move now.

Actor positioning

Just to test the Nav Mesh, let’s disconnect the BeginPlay node from the Set node in the Unit’s Event Graph. This way, the Target Position would have the default (0, 0, 0) value at the start of the game.

Unit Event Graph

If you start the game now, you should see the Unit go to the (0, 0, 0) location. The Unit will even go around the obstacles we set earlier.

start game

Unit location obstacles

You may think that our Unit moves too fast. Let’s change the Unit’s speed now:

  • Open the Unit blueprint
  • In the Components panel, select the Character Movement component
  • In the Details panel, in the Character Movement: Walking dropdown set the Max Walk Speed property to 300

Max Walk Speed property

If you start the game now, you should notice that our Unit moves slower. You can test out different speeds and pick the one you like.

Don’t forget to reconnect the BeginPlay event node to the Set node before going to the next lesson.

reconnect BeginPlay event node

In this lesson, we created the Unit blueprint and made it go to the Target Position using the Nav Mesh. In the next lesson, we’ll add input handling, so we would be able to actually tell our Unit where to go.

Unit Movement – Part 2

In this lesson, we will make our Units moveable by Player.

Creating The Player Unit

First of all, let’s remove the Unit Actor from the level. Only the Cube obstacles and Nav Mesh should remain.

remove Unit Actor

We’re not actually going to use the Unit blueprint instances in the level. Instead, we will use it as the base for the Player and Enemy Unit blueprints.

Let’s create the PlayerUnit blueprint now:

  • Create a new Blueprint Class in the Content folder
  • In the Pick Parent Class window, go to the All Classes dropdown
  • In that dropdown, find and select the Unit class, to use the Unit as the parent class
  • Click on the Select button to create that blueprint
  • Name that blueprint PlayerUnit

Blueprint Class

blueprint PlayerUnit

If you open PlayerUnit’s Event Graph, you will see that its event nodes are connected to the Parent event nodes. The Parent event nodes are the ones we’ve defined in the Unit’s Event Graph. This means, PlayerUnit’s Event Graph runs the code defined in its parent – the Unit blueprint.

Event Graph

Selecting The Player Unit

Now, let’s implement the Unit selection with our Player Controller:

  • Open the RTSPlayerController blueprint
  • Go to the Event Graph tab
  • In the My Blueprint panel, add a new variable called SelectedUnit.

Blueprint panel

Next, in the Details panel, we’ll set the SelectedUnit’s Variable Type property to the Player Unit.

Details panel Variable Type

As we want to select our Units with our mouse, let’s enable the Mouse Cursor first:

  • Connect the BeginPlay event to a new Set Show Mouse Cursor node
  • Enable the Show Mouse Cursor property in that Set node

Show Mouse Cursor node

Then, we’ll add the Left Mouse Button event node, to get notified on when the left mouse button is pressed.

Left Mouse Button event node

Next, we will send a raycast to check if there is any object under our cursor:

  • Add a new Get Hit Result Under Cursor by Channel node to the Event Graph
  • Connect the Hit Result pin of that node to a new Break Hit Result node

The Get Hit Result Under Cursor node sends the raycast from the cursor position and returns the result of that raycast. A raycast shoots through space like a laser beam and returns the objects which got in its way.

Get Hit Result Under Cursor by Channel

Then, we will check if we hit the Player Unit Actor:

  • Expand the Break Hit Result node to see all of its output pins
  • Connect the Hit Actor pin of the Break Hit Result node to a new Cast To PlayerUnit node
  • You can collapse the Break Hit Result node now, as the used pins will remain visible

Now we have the Cast To PlayerUnit node which can tell us if we hit the PlayerUnit Actor by passing the control flow to its first pin.

Cast To PlayerUnit node

Finally, we can set the Selected Unit variable:

  • Connect the Pressed pin of the Left Mouse Button node to the input control flow pin of the Cast To PlayerUnit node
  • Connect the first output control flow pin of the Cast To PlayerUnit node to a new Set Selected Unit node
  • Connect the As Player Unit pin of the Cast To PlayerUnit node to the Selected Unit pin of that new Set node

Now, once we press the left mouse button, we check the object under our cursor, and if it happens to be the Player Unit, we’re saving it in the Selected Unit variable.

Selected Unit variable

Setting Up The Player Unit Movement

Next, we’ll make the Units move with the right mouse button click. Let’s add the Right Mouse Button event node to the Event Graph first.

Right Mouse Button event node

Then, let’s copy the raycast nodes we created earlier:

  • Select the Get Hit Result Under Cursor by Channel and Break Hit Result nodes we created earlier
  • Press Ctrl+C to copy and Ctrl+V to paste those nodes
  • Move the copy of those nodes to be below the RightMouseButton event node
  • The connection between those nodes must remain

copy raycast nodes

We also need to check if we actually have a Unit selected:

  • Connect the Pressed pin of the Right Mouse Button node to a new Is Valid node
  • Connect the Input Object pin of the Is Valid node to a new Get Selected Unit node

This way, on the right mouse button click, we’ll check if we selected a Unit first.

Is Valid node

Creating The Unit’s MoveTo Function

Then, we need to return back to the Unit blueprint to set up a way to set the Target Position variable from outside. We will make changes to the base Unit blueprint, as both the Player and Enemy Units will need to get their Target Positions from outside.

Let’s do the following now:

  • Open the Unit’s Event Graph
  • In the My Blueprint panel add a new function called MoveTo

MoveTo function

Next, in the MoveTo function Details panel, add a new input of the Vector type called ToPosition.

Vector type ToPosition

Finally, let’s make the Move To function set the TargetPosition variable:

  • In the Move To function graph, connect the control flow pin of the Move To node to a new Set Target Position node
  • Connect the To Position pin of the Move To node to the Target Position pin of the Set node
  • Compile the Unit blueprint to apply those changes

Now we can set the Unit’s Target Position with the Move To function.

Unit Target Position

Back To The Player Controller

Let’s return to the Event Graph of the RTSPlayerController blueprint now. We can finally connect the script we started earlier to the Unit’s MoveTo function:

  • Connect the Get Selected Unit node to a new Move To node. You need to make that connection first, as only the node of the Unit type can be connected to the Unit’s Move To function Target pin
  • Connect the Is Valid pin of the Is Valid node to the input control flow pin of the Move To node
  • Connect the Impact Point pin of the Break Hit Result node to the To Position pin of the Move To node

Now, when we click the right mouse button and we have a PlayerUnit selected, we will call the MoveTo function on it with the click position as the target position.

Player Controller

Testing The Movement

Let’s get back to the GameLevel level and test how our new input works. First, let’s add two PlayerUnits to the level to make sure that our selection works as it should.

Testing Movement

If you start the game now, you should be able to select a PlayerUnit by clicking it with the left mouse button and move it by clicking the right mouse button somewhere on the Ground. Though the selection itself is not displayed at the moment, we will work on it in one of the following lessons.

start game

In this lesson, we implemented the ability to move the PlayerUnits. In the next lesson, we will start working on the Combat system.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript – Unit Movement – Part 1

Welcome back everyone in this lesson we are gonna begin creating our units.

So first of all, we want to go down to our content draw and we wanna go to our content folder where we have our level and our other blueprints that have already been created.

And what we want to do is right-click go blueprint class and we want to select the character blueprint. Okay. And I am gonna call this one Unit.

Now this is gonna be the base blueprint for all of our different units, both the player and the enemy. And then from here what we’re gonna do is we are gonna extend from that for the player units and extend for that for the enemy unit.

Okay. So if you do want certain logics such as AI for our enemies cause our enemies are going to be able to attack on their own when a player gets within range but we don’t want our players to do that.

So we are going to basically have a separate player and a separate enemy blueprint. Okay. But this unit blueprint is basically going to be the parent class for both of those.

So all of the similar logics, such as being able to move to a location, move to a target is gonna be shared between them inside of this blueprint here. And we’re getting better understanding of how that works later on.

Once we start setting up the others, but for now let’s just open up this unit blueprint by double-clicking on it and we can then dock it like so. just to make it a bit neater.

Now, the first thing we want to do is give ourselves a 3-D model because right now we have no visual. So what I’m gonna do is I’m gonna open up the content draw.

I’m gonna go to our models folder and I’m just gonna drag in the Bishop 3-D model under the unit here, we can select that model.

And what we want to do is we basically wanna drag it down so that it is sitting at the bottom of this capsule right here. And this capsule is basically defining the bounds of our unit. Now let’s actually disable the grid snapping here so we can move it up a tiny bit, just so it fits correctly. There we go.

And let’s also give it a material now to give it a material we can go over to our details panel, go down to the materials and let’s give this one unit I’ll give it ‘unit_1’, which is just a blue one like so. And then we go, so that is our 3-D model. Pretty much all set up.

Now what we need to do is go over to the event graph where we are going to be spending most of our time, setting up the various different pieces of logic for our unit.

Now inside of this unit blueprint, we are gonna be making a bunch of different things. First of all, we’re gonna have it so that this unit can move to a target. It can also move to a position in the world.

For example, when we right-click on the ground our player’s gonna move to that position. When we right-click on an enemy, we want it to move and attack that enemy.

We’re also gonna have logic that works for attacking a target when we get within range and also for taking damage. So let’s start simple and just get our unit moving.

So first things first, we need to create a variable here which is actually going to determine the position we want to move to. So I’m gonna create a new variable down here.

I’m gonna call this one target position over in the details panel. We can change the variable type from a boolean over to a vector, which has an X, Y and Z coordinate that we are going to move towards.

We can click compile to save all those changes. And then over inside of begin play. What we want to do is initially we want to set our target position to be our current location. And that is because we don’t want our target.

We don’t want our unit I mean to start moving over to 0, 0, 0 at the start of the game, we want them to stand still. So we’re gonna set their target position to basically be their existing one.

So from begin play I’m gonna drag out and go set target position. And the target position is basically just going to be Get Nav Agent Location. Okay. So that’s gonna get the location of our AI agent.

And an agent is basically an entity that utilizes a nav mesh. So it’s basically gonna get our current location on the nav mesh. Now the active begin overlap node which detects collisions. We don’t really need that.

So we can actually go ahead and delete it like so. but the event tick we definitely will need. Now with event tick what we want to do is we basically want to be moving towards our target position at all times for now though. Okay.

So I’m gonna do is I’m gonna drag out from event tick here with the control and I’m gonna drag this into a node called AI move to, okay this one right here, AI move to, and this node right here basically we give it some information and it is gonna automatically calculate a path and move us towards our target location.

So what information do we need to give it give? Well, first of all, we need to give it the pawn or the object that we want to move, which is gonna be ourself.

So we can just right-click and look for the self node right here, get a reference to self and drag that into the pawn. Now we also need a destination and of course that destination is gonna be our target position.

So we can drag in target position, go get target position and connect that up like so. Okay. And pretty much that is all we need to do.

So now if we compile this, if we go back to our game level we can actually go to our content draw, go back to content drag in a unit here, there we go. They’re on the ground.

And if we press play, you’ll see that nothing happens because we initially set their target position to be their existing one. But what happens if we don’t do that? What if we go to unit? What if we right-click on the begin play node and just go over to where it says break node links.

That will disconnect it. If we click compile, if we go back to game level and we move our player over here, for example and we press play.

What you’ll see is our character now moves over or it’s trying to move over to the (0,0) coordinate which is pretty much inside of this cube right here. okay. So we can move it over, down below here.

So there is an obstacle in the way, and as you can see it moves around this obstacle towards the target. Now you may think it is moving a bit fast and it kind of is.

So what we can do is go over to our unit here and select our character movement component. And what we want to do here is just change the move speed. So if we go down to where it says, max walk speed.

We can change that to let’s just say 300. So now if we compile that, go to our game level, press play you’ll see that we move at a much slower speed and we can see the AI navigation a bit easier. But yeah, that is basically how we can navigate around obstacles using the AI move to node.

Now I’m gonna reconnect the begin play to that set target position because we do want to actually have our target position set to wherever we are right now by default.

And in the next lesson we are going to be looking at making it so that we can actually tell our player where to move. Okay.

We’re gonna be able to select our player with left mouse and right-click on the ground to move to a position. okay. So we’re gonna get that RTS movement and interaction set up. So Thank you for watching! and I’ll see all then in the next lesson.

Transcript – Unit Movement – Part 2

Welcome back, everyone. In this lesson, we are gonna get our player controller set up and working so we can actually start selecting our units and moving them around.

And we are first of all going to actually create another unit blueprint. And that is going to be our player unit. Because this unit right here, this unit blueprint, we aren’t going to ever be using it.

So, let’s go ahead and delete our unit that exists in our world right now, because we’re never gonna drag this unit blueprint into our world.

Rather, we are gonna create two other blueprints, a player unit, and an enemy blueprint. And those are both going to inherit, or they’re both gonna be a child class of this unit blueprint.

So it’s basically, we want the enemy and the player to both have the same characteristics and the same logic as each other, but they’re gonna differ in certain ways that we do want to give themselves different behaviors, such as the enemy is gonna have automatic AI, and the player is going to have the ability to be selected.

So, I’m gonna right-click. I’m gonna create a new blueprint class. And we need to pick a parent class. Now, we wanna go All Classes, because we want to search for our unit right here.

And this unit is gonna be our parent class. And I’m gonna call this one PlayerUnit. Now what happens, if I open this up, you’ll see that we have the player bishop right here. We have everything set up just as it is over in Unit.

Yet, if we go to Event Graph, you’ll see that our BeginPlay connects to this thing called Parent BeginPlay. And Parent BeginPlay is basically what this code here, or this logic over in Unit, that we are setting up here.

Because everything inside of PlayerUnit is sort of overriding or inheriting from Unit. That stuff already exists. And any changes we make to the Unit blueprint, those changes get applied to our PlayerUnit as well.

And then what we can do is just attach on extra logic, extra gameplay behaviors, to our player unit here that are more player-centric. And if we create the enemy blueprint, that’s gonna be more enemy-centric with the AI.

And of course we’ll get into this a bit later on on the specifics, but for now just know that PlayerUnit is basically inheriting everything from this unit blueprint right here, with the ability to add on its own extra unique properties.

So, now what we want to do is open up our RTSPlayerController blueprint right here. And this is going to be where we are detecting all of our mouse clicks, and keeping track of which units we have currently selected.

So inside of the player controller, what we want to do is go over to our Event Graph here, and we want to create ourselves a new variable. And this variable is going to be called SelectedUnit.

And the variable type is not gonna be boolean or vector, rather it is gonna be of type player unit. Like so. We can compile that to save those settings.

And now what we need to do is we need a way of basically determining when we click on a player unit. So, first things first, in BeginPlay, we’re going to connect this over into a Show Mouse Cursor node and enable that, because we do want our mouse cursor enabled by default.

We then want to delete Event Tick, since we won’t be needing that. And instead we want to create a Left Mouse Button node. And this Left Mouse Button node is gonna basically execute once the left mouse button is pressed or released.

Now, what we want to do is we want to basically determine if we are clicking on a player unit when we select it with the left mouse buttons. How do we do that? Well, we need to use a raycast, or a hit result.

So, for this what I’m gonna do is I’m gonna create a node called Get Hit Results Under Cursor by Channel. And this node right here, basically, it is going to shoot a laser beam from my mouse cursor to whatever we are pointing.

And it is then gonna return to us that information whenever it hits something. Now from Hit Result, we wanna bring this over into a Break Hit Result node right here.

You can then pop that open to see all of the different outputs we can choose from. Now, the thing we ought to check to see is the Hit Actor. And we to know if whatever actor we hit with our mouse cursor is a player unit.

So, we can drag that out like so. And we are going to put this into a Cast to Player Unit node. Now, a Cast To node, it basically takes in an object as an input, and it basically determines if this object is of type player unit.

If it is, this Control Flow executes. Otherwise, Cast Failed executes. So, basically this is only going to be true if the object we are clicking on is a player unit. So, let’s connect this up with the pressed input like so.

And then from Cast, if it is indeed a player unit, then what we want to do is we want to basically go Set Selected Unit, and go As Player Unit. And like so. So, now when we left-click on a player unit, it is going to set it as our selected unit.

Now, how do we get that unit to actually begin moving around once we have it selected? Well, for that, we are gonna create another event node called Right Mouse Button.

And Right Mouse Button, this gets executed when, of course, we click on our right mouse button. And what we want to do with this is we basically to start off with, want to see, first of all, do we have a selected unit?

And if we do have a selected unit, then we want to move it to whatever location we have hit. So, what we can do here is actually just to save some typing,

I’m gonna select our Get Hit Result under cursor, hold down Control, and select the other node here. I’m gonna copy that and paste it down here, just ’cause we don’t have to worry about creating those nodes again.

And instead of the Hit Actor, we want to get the Location. But we don’t wanna get that just yet. Instead, what we want to do is we want to go out from Pressed, and we want to check to see if we have a selected unit.

Because we don’t wanna try and move somewhere if we don’t have a selected unit. So out from Pressed, what we want to do is we want to check to see the Is Valid. Is Valid right here, a little question mark icon.

Basically, we give it a object and it determines if it exists or not. So, right now our selected unit if we get it like so, plug it in. If it has not been set, it is equal to what’s known as null.

Null basically means empty. And if it’s empty, that means it is not valid. Otherwise, if we have set the selected unit, it will be valid. Now, if it is valid, then we want to basically set its target position.

And to do that, we are gonna go over to our PlayerUnit right here. And actually not our PlayerUnit. We’re gonna go over to our Unit, so our base unit, because this could also be given to an enemy.

And we are going to create a new function down here called MoveTo. And the MoveTo function is going to contain a input. So, we can add an input right here. And it is gonna be called ToPosition. We wanna make that of type vector.

And basically what we want to do is set our target position to be this ToPosition. So, we just wanna plug it in like so and there we go. So, basically when this Move To function is called, we send over a position and it is gonna set our unit’s target position.

Now we wanna click Compile, go back to our RTSPlayerController. And then what we want to do is we want to drag in our selected unit here, go Get Selected Unit, drag that out, and we want to call the Move To function like so.

And we wanna connect that to the Is Valid of the Is Valid node. And the ToPosition is going to be the Impact Point, the point at which our mouse cursor has impacted, probably the ground that we wanna move to.

So, that is what we need to do in order to basically set it up for our unit to be selected initially. And then when we right-click, we want to check to see if we have a unit selected.

And if we do, we want to move it to wherever our mouse cursor has clicked on the ground. So, now we can click Compile. We can go back to our game level. We can then drag in a player unit here.

Let’s actually drag in another one as well just to basically see if the selecting works. Click Play. Okay, and now what we can do is we can click on our unit.

So, if I click on the left one right here, nothing really happens so far, but we will have a selection visual appear. And if I right-click, you’ll see that our unit is now moving to whatever position I am giving it, which is pretty cool.

Now, if I select this other unit with left mouse, as you can see, I am now controlling it, and the other one is staying still.

So, we can switch between our units here and move them around wherever we wish by clicking on them and then right-clicking on the ground to basically navigate over to that location.

So, that’s all working nicely right there. All right, so we got that all set up and ready to go. Now in the next lesson, I reckon we look at setting up some sort of enemy.

Because we need a way to actually begin attacking other units, and then later on, them having the ability to attack us. So, thanks for watching. And I’ll see you all then in the next lesson.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
How to Create a NAV MESH with Unreal Engine https://gamedevacademy.org/unreal-nav-mesh-tutorial/ Fri, 23 Dec 2022 01:00:24 +0000 https://gamedevacademy.org/?p=19377 Read more]]>

You can access the full course here: BUILD AN RTS GAME WITH UNREAL ENGINE

Nav Mesh

In this lesson, we will set up the Navigation Mesh for our project.

Creating The Obstacles

The Nav Mesh system allows Actors to navigate in the level. In this game, we won’t control the units’ movement directly. We will point to a place where units should go and then they will use the Nav Mesh to navigate the level. The Nav Mesh will also help our units go around obstacles instead of going through them.

Speaking of obstacles, let’s add a couple of cubes to the level. To add a cube to the level, select the Add > Shapes > Cube option from the main toolbar.

Shapes cube

A new Cube Actor will appear in the level.

Cube Actor

Let’s duplicate this cube now:

  • Make sure the Cube Actor is selected in the Outliner panel. You can select an Actor by clicking on it either in the Outliner or in the Level Viewport
  • Press the Ctrl+D hotkey to create a copy of this Cube Actor. Create as many copies as you want
  • Drag those Cubes to different positions on the level

Now we have the Cube obstacles in our level.

Cube obstacles

Setting Up The Navigation Mesh

Next, let’s go and select the Add > Volumes > NavMeshBoundsVolume option from the main toolbar to create a new Nav Mesh Actor.

Nav Mesh Actor

The NavMeshBoundsVolume Actor looks like a cube without visuals – only edges are visible. The NavMeshBoundsVolume Actor defines a volume, for which the Navigation Mesh will be generated.

Navigation Mesh

Now we need to configure the NavMeshBoundsVolume. First, let’s go to the Details panel and set the Transform > Location property to (0, 0, 0), so our Nav Mesh would be positioned in the center of the level.

Transform Location property

Then, we will make this Nav Mesh big enough to fit our level. Let’s go to the Brush Settings dropdown in the Details panel and set the (X, Y, Z) properties to (8000, 8000, 600).

Brush settings

This way, the Nav Mesh should be big enough to fit the Ground Actor inside.

Ground Actor

But how do we check that the Nav Mesh works? You should just press the P key to enable the navigation preview in the Level View. The walkable part of the level would be highlighted in green. The ground around cubes won’t be highlighted in green, which means this ground is un-walkable.

Level View

In this lesson, we added some obstacles to our level and added the Nav Mesh Actor to help our units to navigate around those obstacles. In the next lesson, we will start working on the units which can walk in our level.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

Welcome back everyone. In this lesson, we are gonna be setting up our nav mesh and our AI navigation for our project.

Because, since we are using units that we aren’t directly controlling with an input, so we’re not really telling them to move left, right, or whatever. Instead, we are telling our units to move to a specific location.

And if there is an obstacle in the way, such as a box or a big rock, we want our units to move around it, rather than trying to go directly through the center. So how do we do that?

Well, first of all, let’s go ahead and just add in some obstacles. So I’m just gonna go up to here, where we can add in some objects.

And I’m gonna add in, let’s just say a cube, okay? You can bring that down like so, maybe increase it in scale a bit. And I am just going to move a cube here.

Duplicate with Ctrl D and just place a couple of them down here, just so we have an understanding of what this nav mesh does.

Okay, so we have our cubes placed down. Now, let’s just say we have a unit that is behind this one right here, and we want it to move on the other side.

Now, typically when you’d move a blueprint, or move a character, you just basically tell it to move in the direction that you want it to.

Yet, we can’t do that, because there is an obstacle in the way right here. And we have to create what’s known as a nav mesh, which is basically an asset that determines all of the walkable space in our level.

So how do we do that? Well, let’s go up to this little dropdown here, where we can create objects. And actually instead, we’re not gonna go here.

We are gonna open up the Place Actors menu, or the Place Actors panel. And if you don’t have that, you can just go window, Place Actors right here.

Now, in Place Actors, what we want to do is, we want to look for nav. And you should see here that we have ourself a Nav Mesh Bounds Volume. And we want to drag that into our project here. Okay?

Now you’ll see that this is sort of like a cube, but without the visual. And this is because, the Nav Mesh Bounds Volume basically defines an area of which it will generate a nav mesh for.

So what we need to do is, go to our details panel. I’m gonna set the location to be zero on the X, zero on the Y, zero on the Z. So you can see it’s pretty much in the center of our world right here.

And we need to basically increase the size of this selected box here. So to do that, we can scroll down in the details panel, and we want to go down to the brush settings, okay?

And you see here, we have the X, Y, and Z values. Basically, we just want to… When I increase these, we can basically change how big this is going to be, okay?

So just make sure that the bounds of this box here fit our level, because only the objects within this selected boundary are going to be calculated for a nav mesh.

Now, we’ve got that here, but how do we know it’s working? Well, what you can do is, press the P key on your keyboard. And you should see now that we have the walkable ground selected, okay?

So you can see here, around our cubes, we have this sort of like a gap, like it’s being cut out. And that basically means that our cubes are defined as non walkable.

If something wants to walk through a cube, it is gonna calculate a path going around it, okay?

So basically, whenever we want to move from one spot to another, it is only going to be moving on this sort of selected green plain here.

So great! That is how we can set up a nav mesh bounds volume. Now in the next lesson, we are gonna be looking at creating a unit which can actually utilize this, and move from one spot to another using AI.

So, thanks for watching. And I’ll see you all then in the next lesson.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
Drawing Sprites with SFML & C++ – Game Dev Tutorial https://gamedevacademy.org/sfml-cpp-sprites-tutorial/ Mon, 19 Dec 2022 01:00:27 +0000 https://gamedevacademy.org/?p=12495 Read more]]>

You can access the full course here: Discover SFML for C++ Game Development

Want more coding topics for a school environment? The Zenva Schools platform which offers online courses, classroom management tools, reporting, pre-made course plans, and more for teachers.

Drawing Sprites

We’ve seen how to draw a basic shape but realistically, most of our games will use more than shapes. We will want to place graphics, icons, and other images into our games and we do so via Sprites. Setting up a Sprite is generally done in two steps with SFML: first, we load in a texture, then we create a sprite and pass in the texture. Once we have the sprite set up, we can set attributes such as the size and position and then display it by drawing it into the window during the run loop.

In our project, we should create a folder called assets that contains any assets needed in our game. We only have 4 so there’s no need to further divide the assets folder. Copy the “enemy.png” and “background.png” images, the “damage.ogg” audio file, and the “Arial.ttf” font files from your provided files and paste them into the assets folder. We will only work with the Enemy.png image for now. To create a texture, we first create a texture variable and then call the loadFromFile() function, passing in the path to the file as a string. It returns true if successful and false otherwise so we should perform a boolean test to see if the load was successful. In our main function, write this code after the code to create the window and before the run loop:

sf::Texture texture;
if (!texture.loadFromFile("assets/enemy.png")) {
  std::cout << "Could not load enemy texture" << std::endl;
  return 0;
}

This will create a variable of type sf::Texture and load the image into it. If the load fails, we print an error message and return. Sometimes, the load for an asset fails for some unknown reason so we should handle any errors properly. You will need to #include <iostream> at the top of main.cpp as well. Once we have the texture, we can create a sprite object called enemySprite and pass in the texture like this:

sf::Sprite enemySprite;
enemySprite.setTexture(texture);

The sprite will only be as big as the image provided and will default to be at position (0,0) or in the upper left corner. We can change the position like this:

enemySprite.setPosition(sf::Vector2f(100,100));

Which brings the sprite 100 pixels out from the left and 100 pixels out from the right and increase the size of the sprite by scaling it like this:

enemySprite.scale(sf::Vector2f(1,1.5));

This will scale the width of the sprite by 1 (no change) and scale the height to 1.5x its original height. Notice how both functions take an sf::Vector2f as inputs and each needs an x and y value. In order to draw the sprite, we change the draw code to this:

window.clear();
window.draw(enemySprite);
window.display();

We always have to clear the window before drawing anything and display the window after we draw to it.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

What’s up everyone? Welcome to our tutorial on Drawing Sprites. Here we’ll get a quick intro into what sprites are from a game context and how to create and use them in SFML.

So this is actually a two step process, the first thing we need to do is create a texture object. Once we have that we can create a sprite from it and then we can set the position and the scale. So let’s head to the code and get started. Alright, so just a quick heads up again, I took all the code from the previous section, not that we really did very much and put it in old code and I’ll continue to do this with each new section.

Alright, so what is a sprite from a game context? Well essentially, a sprite is gonna be an object in the game that has an image associated with it. So this is really the main difference between let’s say shapes and sprites in games is that a sprite has an image and a shape just has well a shape. It just has its boundaries, it has some sort of code to dictate what shape those boundaries will take on, be of circles, square, rectangle, etc.

So in our case, the background of our game and the enemy itself, those are both going to be sprites, we’re not really gonna be working with shapes very much. So like I said this is a two step process. The first thing we need to do is load in a texture and a texture needs an image to load. So that’s why I had you load in your assets folder. So your project should look like this, sfml project, you have your codes, and then you have your assets folder with the items in it. We’ll use the ttf as a font later on. Same with the damage.ogg, that’s for sound. For now we’ll at least want the enemy.png because that’s what we’re gonna be working with here. Okay, so as long as we have it in our project assets /enemy.png, then we can load it in like this.

Okay, first thing that we’ll need to do is create a texture itself so we’ll do sf, Texture, texture. Okay, now a texture just like the Render Window is part of the SFML Graphics library. Anytime you need a new module, you’ll need to load it in here. Okay, so we have a texture object, we actually don’t need to call a constructor, set it equal to a texture or anything like that. Once we create the object, we have access to it immediately and we need to call the load from file function, like this texture.load From file, oops! Not load from stream we want load from file.

Okay, and then we’re going to pass in the path to the file. So in this case this is gonna be “assets/ “enemy “.png”. Now this is actually gonna return true or false based on the success or failure. So we’re gonna say something like if text actually, we’ll say if not texture.load from file, then maybe we’ll just print out some message and return. So let’s just close that off and this should actually be in here.

Okay, so in this case, what we can do is something like Standard c out, I actually don’t think we have the iOS stream library so I’m just gonna include that now. Include your stream. Okay, good stuff. Okay, so now what we’ll do is c out something like “Could not load, “enemy texture”. Okay, and then we’re just going to end it.

All right and because we really want the game to only run if the texture is loaded, we’re actually gonna return false. Cool, so as long as this is the case oh actually you know what? This is returning will turn zero. Okay, so as long as the texture is loaded, so as long as this doesn’t return zero, then we have a texture rather an image loaded into this texture, and now we can use it with a Sprite. So to do that, we’ll do basically the same process as with the texture, we need to create the sprite object first, Sprite and we’ll call this like enemySprites or something.

Okay, and then we’re going to call upon the enemySprite . setTexture function and then we’re I’m just going to pass in the texture that we loaded. Okay, so this will associate a texture with a Sprite. So now the sprite is created It has a texture and we can draw it. We don’t know exactly what size or position well we do know what position it will be in which will be 00 by default which will be upper left corner and the size will be exactly the size of the image itself. We can modify that later on, and which we’ll do in just a minute here.

Okay, so just using the default values, if we want to draw this to the window, we simply call upon the window.draw and then pass in the Sprite. So in this case, enemySprite. Okay, cool. So we’ll get this Save, and let’s run the code, let’s see what happens. So clear it, let’s compile it, and then let’s run it and now you can see that we have this little sprite in our game.

Obviously there are some issues here it’s getting cut off so the screen is not big enough to begin with. Also, this is kind of in the top left corner, we might not want it there and might not be quite big enough. Okay, so this is all stuff that we can just maybe let’s do a 500 by 500 window. That way we have enough size to draw most of the things that we need. Then if we go to rerun it, we should probably see that’s not gonna take up the whole screen anymore. It’s just take up a part of it. So maybe we don’t want it in the top left. Maybe we want it kind of a bit centered.

So what we can do is maybe move it about 100 pixels to the right and 100 pixels down, might put it roughly in the center, okay. So what we can do is take this enemy sprite, enemySprite, okay and we can set the position of it. So, this is gonna take in an a Vector two f object like this SF Vector two f which will take in a vector two dimensional float, and this will need a width and a height or an X and Y value. So in this case, we’ll just do a 100 and 100. Okay, if we go to lets close this off, we go to rerun it.

Okay, so recompile it, again, every time you make a change, you have to recompile it, you can see that this has now moved, we can also change the height, let’s kind of make this guy a little bit taller, but we won’t necessarily change the width of it. So what we can do is lets close that up do the enemySprite . And we can scale it. Okay, weirdly enough, you can’t assign a specific width and height, you actually have to scale things.

Okay, so in this case, we’re going to again pass in a vector2f, capital V, Vector two f, okay and then we’re going to pass in the amount by which we want to scale the x and the amount by which we want to scale the y. So the x is going to remain exactly the same. So we’ll just do one, the y however, we want to change the height, maybe we’ll do like a 1.5 and see how that works out.

Okay, so we’ll go back to here. Well, I guess we don’t need to clear it. We’ll just kind of recompile and we’ll rerun it and now you can see that this guy is horribly stretched, but at least the scaling worked. Now there are plenty of other things that we can do with Sprites but this will be pretty much the extent of what we’re gonna do in this course with our Sprites.

One last thing to note before moving on to the next section is that the sprites bounding box is actually this whole rectangle. Weirdly enough, the bounding box doesn’t follow the image like this. This is gonna be the bounding box. So when when it comes to detecting mouse clicks on the sky, even if you click up here, it’s technically within the bounding box. So that’s going to register a click. Okay, we’ll get more into that a little bit later on. Just wanted to make you guys aware now. Okay, we’ll close this up.

Otherwise, that’s it. So in this section, we covered two things, loading in textures, and the second creating sprites and assessing their attributes. Definitely Feel free to play around with this. Maybe try to load in your background. See how well you can do with that. When you’re ready to move on, we’ll do pretty much the same thing but with text. So stay tuned for that. Thanks for watching and see you guys in the next one

Interested in continuing? Check out the full Discover SFML for C++ Game Development course, which is part of our C++ Programming Bundle.

For teachers, you can also try Zenva Schools which offers online learning suitable for K12 school environments and offers a wide array of topics including Python, web development, Unity, and more.

]]>
How to Make a Unity Camera Follow a Player – Platformer https://gamedevacademy.org/unity-camera-follow-tutorial/ Mon, 19 Dec 2022 01:00:16 +0000 https://coding.degree/?p=491 Read more]]>

You can access the full course here: Create Your First 3D Game in Unity

Camera Follow Script

The simplest way to make a camera follow an object is to set it as a child. You can click on the camera and drag it into the Player object:

Main Camera in Unity being dragged as child of Player

Now the camera is set as a child of the Player.

Main Camera as child of player in Unity

If we press play, we can see the camera follows our Player.

Demonstration of camera as child of player in Unity

However, the camera not only follows our Player’s position, but it also follows its rotation.

For example, if you are facing right and hit the left key, the camera is also turned 180 degrees, and this is not ideal.

Creating A CameraFollow Script

First, we’re going to unparent the camera from the Player. (Drop it into where the blue line appears above the Player):

MainCamera being moved to top of Unity Hierarchy

And we’re going to create a new script called “CameraFollow” inside Assets/Scripts.

CameraFollow C# script in Unity Assets

We’re going to attach this script to the camera by dragging it into the Inspector.

CameraFollow script added to Main Camera in Unity

We can then double-click the script and open it up in Visual Studio. Here, we’re going to create two new variables:

public Transform target;
public Vecor3 offset;

The target will be used to reference a Transform component to follow, and the offset will be used to maintain a certain distance away from the player.

Inside the Update function, we’re going to update our camera’s position so that it follows the target’s position, but with some offset so that our camera doesn’t sit inside the player.

//Update is called once per frame.
void Update()
{
   transform.position = target.position + offset;
}

Let’s hit save and return to our editor.

Setting Up Camera

Now we’re going to drag in the Player into the Target slot.

Player being added to Camera Follow script's Target

We’re going to set the offset as (0, 2, -3.5):

Camera with offset set in Camera Follow Script

Unity demo of new Camera Follow script

We’re also going to set the x-rotation of our camera to be 20, so we’re looking down slightly on the player.

Unity Inspector with 20 on X Rotation

Demo of Unity with adjusted X rotation

If we hit Play now, you should see that the camera is following our player, while always maintaining the offset (0, 2, -3.5) away from the player’s position.

Demo of final Camera Follow script in Unity

Transcript

Welcome back everyone in this lesson, we are going to be setting up Camera Follow. And this basically means that we have our camera following our player around, so no matter where we go, we can always have our player in the center of our screen.

So here in Unity, what we want to do first of all, is figure out how we’re actually going to do this. Now, first of all, you may think we can just parent the camera to the player. So that whenever it moves, the camera moves as well. Okay well, let’s try that out and see if it works. So I’m gonna get our camera and I’m gonna drag that into the player object as a child. Okay, so the camera is now a child, and if we press play, we should be able to move our player around, right?

Well, let’s try it now. And you’ll see that when we move, our camera rotates as well with our player. And that is not what we want. We don’t want to pretty much be statically attached to our player like this, where you rotate and move with it. We only want to move with our player.

So to unparent an objects, we can select it, click and drag. And if we move it above player, you’ll see there’s this blue line that appears. Okay, we can just let go. And it is now outside of the player.

So, what we need to do is create a new script. Down here on my scripts folder, inside with project browser. I’m gonna right click create a new C# script called Camera Follow. Okay, Camera Follow right there. I’m gonna select the main camera. And I’m gonna drag this script into the Inspector to attach it as a component.

We can then double click on Camera Follow, to open it up inside of the, Visual Studio here. I’m gonna delete the start function since we don’t need, the Start function for this. We only need update and we are gonna be creating two variables. First of all, we need to give this camera a target.

Okay, what object do we want to be following? So I’m gonna to create and a new public, and then we can enter in Transform here. So a Transform component. We can be referencing a Transform component to follow, and I’m just gonna call this variable target. And also we need a another variable, a public Vector three, and this is going to be for the offset.

Now, when we have the camera following the player, we don’t want to be setting the camera’s position to be directly the exact same as the player’s. Because what that will do is make it so that the camera is inside the player. And we of course do not want that. So we need an offset, which is going to be applied to that position, so that we have maintained a certain distance away from the player.

So, down here on update. What we want to do is set our position. So we go, transform dot position, equals our targets position, plus the offset. So here we can go target dot position plus offset. Okay, and that is it. Just one line of code inside the update function. We are setting out position right here to be equal to the targets position plus the offset vector apply to that. Okay. And off of semi-colon save that script or turn to the editor.

And now what we can do is select our main camera. You’ll see down the bottom here in the Inspector, we have a target and an offset property. Target, we can drag in a transform. And offset, we can enter in a new vector, very similar to how we have up here our position, rotation and scale . So for the target, I’m gonna click and drag our player game object into the target property. So now it is referencing our player’s Transform component and fully offset.

Let’s just say the offset is zero on the X. We’ll make it one on the Y and we’ll make it something such as a negative three point five on the Z. So if we go up to our camera here and set it to zero, one, negative three point five, this is more or less what we’re going to be getting. Okay. let’s maybe also add a bit of a rotation to the camera.

So we’re looking down slightly on the player. So I’m gonna to set the X rotation here to be about 15. No, we could probably make that about 20 and I’m gonna set the Y position up to be about a two. So there we go. We can then change that down here in the offset to two. So zero to negative three point five.

If we press play now, you should see that the camera is now following our player. When we move around luxor. Okay, we can jump. We can move. And the camera is always going to maintain this offset away from the player’s position.

So there we go. That is how we can do a quick and easy, Camera Follow script inside of Unity. So thanks for watching and I’ll see you all in the next lesson.

 

Interested in continuing? Check out the full Create Your First 3D Game in Unity course, which is part of our Unity Game Development Mini-Degree.

]]>
Create a Basic Quiz using JavaScript https://gamedevacademy.org/javascript-quiz-tutorial/ Mon, 19 Dec 2022 01:00:15 +0000 https://coding.degree/?p=809 Read more]]>

You can access the full course here: JavaScript Mini-Projects – Language Learning Game 

Also available for school usage via the Zenva Schools platform which offers online courses, classroom management tools, reporting, pre-made course plans, and more for teachers.

Showing a Question

In this lesson we will start by simply showing a single question on the web page. To do this we will represent the question in a JavaScript variable, then display the question in HTML.

JavaScript Spanish quiz with basic UI

Project Setup

Like any web development project we need two key tools: code editor and browser. You can use your favorite code editor or an online development environment together with Google Chrome, Firefox or any modern web browser. In this course we use the free and popular Visual Studio Code ( https://code.visualstudio.com/ ). In your code editor, create two files.

Code File Description
index.html Our website HTML code for structuring and displaying our app in a web page
script.js Our JavaScript code for app logic and functionality

Question – HTML Web Page

Let’s starting by setting up the structure of our web page to display our question and alternatives. Inside index.html add the following HTML DOM (Document Object Model) elements as well as a reference to our JavaScript code file, script.js

<div id="title"></div>
<ul>
    <li class="alternative"></li>
    <li class="alternative"></li>
    <li class="alternative"></li>
    <li class="alternative"></li>
</ul>

<script src="script.js"></script>
HTML Code Description
<div id=”title”></div> The <div> tag is a generic HTML element. We provide an id so we can uniquely reference this HTML element from within our JavaScript code and CSS styling
<ul></ul> An Unordered List ( <ul> tag ) is a HTML element used to wrap HTML List Item elements ( <li> tags )
<li class=”alternative”></li> Add four List Items ( <li> tags ) to hold the four alternatives we show the user to select from. We provide each List Item with a CSS class of alternative so we can reference them from within our JavaScript code and CSS styling
<script src=”script.js”></script> At the bottom of our index.html file we add a reference to our JavaScript code file, named script.js, which will be loaded by the browser when this HTML web page loads

Question – JavaScript Object

Let’s start coding inside script.js, setting up our question as a JavaScript Object.

// define the object for the question entity
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};
JavaScript Code Description
let question = { properties: values }; Using the JavaScript let keyword and the curly braces ( {…} ), we set the variable question to be equal to a JavaScript Object which can contain any number of property:value combinations. To complete the syntax, follow the curly braces with a colon
title: ‘gato’,
alternatives: [‘dog’, ‘cat’, ‘bird’, ‘fish’],
correctAnswer: 1
Using the JavaScript Object Property:Value syntax (property and value separated by a colon and each combination separated by a comma). Here we assign our question variable three properties: title (String), alternatives (Array) and the array index of the correctAnswer (Number)

Question – showQuestion() Function

To keep our code organized and flexible we will create a JavaScript Function to show the question ( showQuestion ). This will enable us to execute the function by calling it, passing in the question object.

// define the object for the question entity
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// function for showing the question
function showQuestion(q) {
  // code
}

// call the function
showQuestion(question);
JavaScript Code Description
function showQuestion(q) { // function code } Function Definition. We define a function named showQuestion and set it up to receive a parameter named q, which will represent the question inside the function block
showQuestion(question); Execute Function. We call the function named showQuestion passing it the question object previously defined as an argument

Working with the DOM

The DOM connects the web page to our JavaScript code. Inside script.js, we use DOM Methods on the Document (Object representing the currently loaded web page) to select DOM Elements. Working with the DOM from JavaScript is a two step process. First, we select the DOM Element then we modify the DOM element.

Question – Show on Web Page

In our case, the question word (Spanish word) is stored in the question Object under a String property called title. In the HTML we represented the question word as a <div> with an id of title. Inside the showQuestion function, add logic to select and modify this DOM element.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// modified code
function showQuestion(q) {
  // new code
  let titleDiv = document.getElementById('title');
  titleDiv.textContent = q.title;
}

// existing code
showQuestion(question);
JavaScript Code Description
let titleDiv = document.getElementById(‘title’); Using the DOM method getElementById(),  passing it the id as a String (in our index.html file we set this id to be title), we select the element storing a reference to it in a variable ( titleDiv )
titleDiv.textContent = q.title; With a reference to the DOM element stored in a variable (previous step), we can now modify it. To do this, we set the textContent property of the DOM element ( <div> with an id of title ) to be the title property stored in our question variable (received as parameter q inside our function)

The web page now shows our question followed by an empty Unordered List ( represented by default with bullet points ) which will hold our alternatives.

JavaScript quiz with unordered list for answers

Alternatives – Show on Web Page

In our case, the alternatives (English words) are stored in a question Object under an Array property called alternatives. In the HTML we represented the alternatives as an Unordered List ( <ul> ) containing List Items ( <li> with a class of alternative ). Inside the showQuestion function, add logic to select and modify these DOM elements.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// modified code
function showQuestion(q) {
  // existing code
  let titleDiv = document.getElementById('title');
  titleDiv.textContent = q.title;

  // new code
  let alts = document.querySelectorAll('.alternative');
  console.log(alts);
  alts.forEach(function(element, index){
    element.textContent = q.alternatives[index];
  });
}

// existing code
showQuestion(question);
JavaScript Code Description
 let alts = document.querySelectorAll(‘.alternative’); Since we are selecting DOM elements by class (multiple DOM elements returned) rather than by id (one unique element returned) as we did above, we use the DOM method querySelectorAll(),  passing it a CSS Selector (in this case, class name preceded by a period – ‘.alternative’). A list of matching elements is returned and we store a reference to these elements in a variable ( alts )
console.log(alts); Log the variable alts to the console (see image below). Notice that alts contains each List Item element ( <li> with class of alternative ) in an array-like ordered list called a NodeList
 alts.forEach(function(element, index) {
element.textContent = q.alternatives[index];
});
We can now modify each element to contain one element from our question variable alternatives array property. To do this, we set the textContent property using the JavaScript forEach method which loops over each element in the alts variable

Console shows a list of DOM elements which will contain our question alternatives (<li> with class of alternative ).

Console showing list of alternative quiz answers

The web page now shows our question followed by our list of alternatives.

Quiz questions with unordered list showing various answer options

Handling User Input

In this lesson we introduce the concept of handling user input. We will do this by adding an event listener to the alternatives List Items so we can check if the user picks the correct answer.

Event Listeners – Simple Button Click

Before we add the functionality for our user to choose the answer they believe is correct, let’s start with a simple example of using an event listener to know when a user has clicked a button. When the user clicks the button, we log the message Clicked! to the console. Starting with the code from the last lesson, add the following code below the showQuestion(question) function call.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// existing code
function showQuestion(q) {
}

// existing code
showQuestion(question);

// new code
let btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  console.log('Clicked!');
});
JavaScript Code Description
let btn = document.getElementById(‘btn’); Select Button Element. Using the DOM method getElementById(),  passing it the id as a String (in our index.html file we set this id to be btn), we select the Button element storing a reference to it in a variable ( btn )
btn.addEventListener(‘click’, function() { console.log(‘Clicked!’); }); Add Click Event Handler. With a reference to the Button element ( btn ) which is known as the Event Target, we can now attach an event handler by calling the method addEventListener(), passing it a function with two arguments: a case-sensitive String representing the event type we are listening for ( ‘click’ ) and a function to call when the event occurs. When the event occurs, we run the code inside the function which in this case logs the word Clicked! to the console

Quiz with Click Me button under it

Note: you can optionally remove the code we just wrote as an example before continuing with the next section.

Event Listeners – Alternatives List

Next, let’s add event listeners to each List Item element ( <li> with a class of alternative ). As we did in the above Button example, we could assign each element an id, then select and add the event listeners one by one. However, since we already have a reference to this list from our last lesson (stored in the variable alts ), we can add the event listeners to each List Item element ( <li> with a class of alternative ) inside the existing alts.forEach() method. Recall that the function passed to the alts.forEach() method has two parameters, element and index. We can use the element parameter ( each alternative ) as our Event Target to attach the event handler to on each iteration of forEach. We can then use the second parameter, index, to check against our question’s correctAnswer property. If this comparison is true then we log Correct Answer! to the console else we log Wrong Answer!

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// existing code
function showQuestion(q) {
  // existing code
  let titleDiv = document.getElementById("title");
  titleDiv.textContent = q.title;
  
  // existing code
  let alts = document.querySelectorAll('.alternative');
  
  // modified code
  alts.forEach(function(element, index){
    // existing code
    element.textContent = q.alternatives[index];
    // new code
    element.addEventListener('click', function(){
      if (q.correctAnswer == index) {
        console.log('Correct Answer!');
      } else {
        console.log('Wrong Answer!');
      }
    });
  });
}

showQuestion(question);

Click each alternative one at a time and notice the result in the console. The only one that returns true is in fact the correct answer! ( gato is Spanish for cat ).

JavaScript quiz showing clickability of answers in the Console

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

Showing a Question

In this lesson, we are gonna get started with creating our project. And we’ll concentrate on something simple, just showing one question on the screen. In particular, we’re gonna be looking at how to represent a question as a variable in JavaScript. And we’ll be showing a question which is composed of a question title, as well as the possible alternatives, possible answers on the HTML document.

Let’s head over to our code editor and get started. I’ve created a new project, which includes index of HTML as well as an empty script file. To represent the question in JavaScript, we’ll be using an object, as that allows us to store an entity with different properties in a variable.

Let’s create our variable, it’s going to be called question. We know that questions have a title, which is the word in Spanish. Let’s create a sample question here. The title will be Gato, which means cat. Then we’re gonna be showing to the user a list of possible solutions. And those we’re gonna call alternatives. The alternatives the user will see, let’s say that they will be dog, cat, bird, and fish.

We know that the correct solution here is cat, which is in position. If we start here, this is position zero, this is position one. And so we want to store the correct answer here, just so that we can check later on. And that’s going to be in position one. Optionally, you can store the actual word as the correct answer. And I do have to say that for everything that I do here, there are many other alternative solutions. So feel free to explore other architectures, if you want to get a bit deeper into the language.

Next, in order to show my question to the user, I’m gonna have to create some containers where the different information will be displayed. So let’s go to HTML, and add our code above the script inclusion. Normally, you always add your script inclusion at the bottom of your document right before the closing of the body tag. I’m gonna add a div for the question title, I’m gonna give it the ID of title. Let’s type in some sample code for now.

So I should be seeing in the browser, that word up here. Next, for the alternatives, we’re gonna be using a list, an unordered list, and each one of the list items will show a different possible response. We wanna duplicate this line many times. And to do so in Visual Studio, you can press Ctrl C, Ctrl V, or Command C, Command V on the Mac, like so. And that will show what this is looking like.

What we want to do now is of course, replace this data by our own data. So I’m actually going to delete this because I just want to show you what that was going to look like. We’re going to give our list items a class, which is going to be called alternatives, alternative like so. Great, so let’s now go to JavaScript and start by adding the title here of the word that we want to show, at the moment it’s all empty.

The first step here will be to select the DOM element that we want to modify. And we’re gonna store that in a variable. I’m going to call my variable title div. And we’re gonna select this by doing document dot get element by ID, and then enter the ID, which is title. Going to zoom out a little bit, there we go. So now that we’ve selected it, now we can modify it. Title div dot text content, will be equal to question dot title. And that should be enough to show that title there, great.

To keep my code organized, I’m gonna place all of these in a function so that then we can call that function multiple times. Start by typing function. The name here will be show question. And the parameter will be that question that we need to pass in. So let’s call this question Q. And let’s move all of this code inside of our function. And make sure to add some indentation just for readability. And instead of question the title, we’re going to do q dot title, as that will be gathered from here.

And then we if we want to call this function, we can just do show function, and we can pass in our question. So if I run this code, it should be the exact same result.

Great, well, now let’s address the last part, which is the alternatives part. If you’re wanting to select every one of these, one at a time, you could go and add a certain ID to each one of them. But since they all behave in the same way there is a different way of doing this, which is to select it all by the class, in this case alternative, and then work on an iteration and change all of them.

Let’s go and select them all. In this case, we’re gonna be selecting them by class. In CSS, when you select by class, you type dot alternative, or name of the class, and then you add certain CSS rules. That’s how CSS works. Well, the good thing about the DOM API is that there’s a way to select everything by using the same type of queries that you’ll use in CSS. So in this case, we’re going to be selecting by a query.

And for that, we are going to be using document dot query selector all. This will go and select all of the elements that satisfy a certain CSS query. In this case, it will be dot alternative. That is the same query that you would use in CSS. We definitely want to put this in a variable. So let’s call this alternatives like that, just an average of an average deviation.

So after we’ve selected this, it’s always a good idea to check in the console, to be sure that it’s working as expected. And you can see here that we have four Li nodes selected. So four list items. To go over each one of them, we’re gonna be using the for each method, which is part of the result that you get from when doing these queries. For each takes a function as a parameter. And we can pass in different parameters here, one of them is the element itself and the other one is the index the position of the element.

Let’s open the function body. And in the function body, if we call this element variable here, this will give us access to each one of these as the iteration progresses. So we can go and change their values. Let’s type element dot text content. And we could change the value to let’s say, a. You can see that they’re all being modified to a. But we don’t wanna modify them to a, we wanna modify them to the corresponding alternative. For that we can access our q variable, which contains the question we’re passing in and typing q dot alternatives.

And now what position is this going to be? Well, the good thing here is that we have that index parameter. So that will start from zero and increase in each iteration. So if we do that, we can actually get all of these one at a time. Let’s save and check to see if it works.

And there we go. Well, that is all for this lesson. As you can see, we’ve created the basic HTML template that we’re gonna be using in our app. And we created a method that receives a question as a parameter. And inside of that method, you can modify the title that you’re gonna show as well as showing each one of the alternatives. For the alternatives, we selected them all using query selector all and then we iterate through each one of them and change their corresponding values. Thank you for watching, I will see you in the next lesson.

Handling User Input

In this lesson, I’m going to start with the code of the previous lesson. We are going to be taking that approach going forward, so that we can build up our app. The way user interaction will work here, is that the user will be able to click on any of the alternatives, and will check whether that’s the correct answer. But to keep things simple, at first, let’s go and try a simple example of using click events.

I’m going to add a new element here in my index.html file. It will be a button. It’s going to have a certain ID. And it will just say Click Me. We want to be able to listen to these clicks and show something in the console. For that, we’re going to start by selecting our button, document.getElementById, and the ID here it needs to be entered, and this will grab our button, and let’s refresh here so that we can see the button.

To listen to click events, type the name of your variable, and then .addEventListener. This is a method that allows us to pass what’s called an event listener. That basically means we are going to specify what event we want to listen for in this case, we want to be listening to a click event. And whenever there is a click event, something needs to happen, and that will be represented as a function here. This function will be executed every time that there is a click on the button. I can go and I can type console.log, and this will say, clicked, save, reload your index.HTML file, and if you click now, you’re going to see that every time you click, you are running these functions. So that’s really how they work.

Next, we want to be listening to events for all of these list items. You could go and give them all a separate ID, and you could select them individually and check that, but since we’re already selecting them all using query selector all, and we are iterating through them, for now, we are going to be adding our event listening here, and check that the answer is correct.

I say for now because there will be some changes made to this architecture later in the course. So for now, we’re going to type in our element, which is this list item. And we’re going to add that same event listener, add event listener. We are listening to click events, and let’s create our function here. In the body of the function, I’m going to access my element again and change the text content, just so that we can be sure that this is working.

If I refresh and I click on this list items, you can see that their content is being changed. And that means that our click listening is working.

And now we can get rid of these, and instead check for the correct answer. Now we need to get the answer that the user entered, which would be the position index. So let’s check the correct answer. And for now we’re going to list inside of here, later on we’re going to move it to a separate place.

How do we know if the answer that was submitted is the correct one? Well, we need to use an if statement to check, first of all, what’s the correct answer? The correct answer would be q.correctAnswer. So q.correctAnswer needs to be equal to whatever the user clicked on. And that would be in our case, the position of the current alternative, starting from zero, so that is index that we have already used to show the text. We’re also going to use that to check for correctness. So if this is equal, then we’re going to show in the console, correct answer.

Let’s go and save and refresh, and let’s check that, see if it’s working. I’m going to click on dog and nothing is happening. If I click in cat, then I see correct answer. If I click on bird and fish, nothing happens. We can add an else statement here to also show when something is not the correct answer, in the console. So let’s go and save, and you can see that’s the wrong answer, that is the correct answer. That’s the wrong answer. And that is the wrong answer.

Great, so we have a basic click functionality. This button that we added, we can definitely get rid off. So I’m going to leave that up to you. I’m going to keep that in this file, but in the next lesson, that is not going to be around. Well, that is all for this lesson. You have learned something really useful which is how to detect for clicks, basics of user interaction. Now your applications on projects can have a whole new layer of interactivity to them. Thank you for watching this lesson. I look forward to seeing you in the next one.

Interested in continuing? Check out the full JavaScript Mini-Projects – Language Learning Game course, which is part of our Full-Stack Web Development Mini-Degree.

For teachers, you can also try Zenva Schools which offers online learning suitable for K12 school environments and offers a wide array of topics including JavaScript, Python, Unity, and more.

]]>