Unity 5: Click to move with pathfinding

I want to start off by saying that the credits for the code goes to BergZerg Arcade, a Youtuber who deserves far more publicity than he gets. If you are interested in Unity game development video tutorials go check him out! He also have a website where you can find his work, burgzergarcade.net.

Now, lets get started. This article is created for those who are new to game development and want to check out the Unity game engine.

If your Unity does not look like mine you can change the editor layout up in the right corner, there are three dropdowns: Account, Layers and Layout. Click layout and select "2 by 3" and everything should look like the images.

Setting up the environment

Since this article is focused on a click to me with pathfinding script I will not put a lot of time into the environment. I set up mine with four walls with a dead end, just to make sure I can see how the pathfinding will work when I click around the walls.

map_setup.png

Above you can see my environment setup. First off I created a terrain (Terrain), this is the large plain/ground you see on the image. Then I created a wall (Wall1) set the dimensions as I wanted them and then duplicated this (Wall2 and Wall3), then added the dead end using another wall (Wall4). I put them all in an empty Game Object (Walls) just to make it easier for me to see what belongs together, you can also move this group around as one object if you need to.

For the player I just set up a sphere (Player) with a cube inside (Face), the face is just to make sure I can see in which direction the player is looking, the front of the player.

The code

Okey, lets get to the coding part. I create a new C# script somewhere in my project, I put mine in Assets/Scripts and named it ClickToMove. 

Below you can see my script file and read the comments for each block to understand what is happening.

using UnityEngine;
using System.Collections;

// This line will make sure one player doesn't have more than one ClickToMove script
[DisallowMultipleComponent]
// This line will make it so Unity automatically add a NavMeshAgent to the player
[RequireComponent(typeof(NavMeshAgent))]
public class ClickToMove : MonoBehaviour {

    // This variable will hold the 3d position of where we are going.
    private Vector3 targetPosition;

    // The NavMeshAgent will do all the magic when we get there.
    NavMeshAgent meshAgent;

    /// 
    /// Here we will set our variables.
    /// 
    void Awake()
    {
        meshAgent = GetComponent();
    }

    /// 
    /// This method will run when we initiate our class.
    /// 
    void Start()
    {
        // Set the default position of our target to the player.
        targetPosition = transform.position;
    }
    
    /// 
    /// This method runs every frame and will check for player input and
    /// if we should move the player.
    /// 
    void Update()
    {
        // Check if the player is trying to move.
        if (Input.GetMouseButton(0)) // 0 = Left mouse button.
        {
            // The player clicked or is holding down the left mouse button.
            SetTargetPosition();
        }

        // We run MovePlayer() on every frame.
        MovePlayer();
    }

    /// 
    /// This method will set the position we want the player to move to.
    /// 
    void SetTargetPosition()
    {
        // Set up the plane and where the player is right no
        Plane plane = new Plane(Vector3.up, transform.position);
        // We then create a ray and set it to wherever the player clicked
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        float point = 0f;

        // If the position where the player clicked is somewhere in the plane we
        // will set targetPosition.
        if (plane.Raycast(ray, out point))
        {
            // We put this point into our Vector3.
            targetPosition = ray.GetPoint(point);
        }
    }

    /// 
    /// This method will move the player in the target direction, the player will
    /// stop when ever they reach their destination.
    /// 
    void MovePlayer()
    {
        // Since our meshAgent will handle the movement we just have to set the
        // destination and the rest will be taken care of by the meshAgent.
        meshAgent.SetDestination(targetPosition);

        // This is optional, just to display a blue line to where the player is
        // going. It makes it easier to see the result.
        Debug.DrawLine(transform.position, targetPosition, Color.blue);
    }
}

When the script is done the next step will be adding the script to the player. There are two ways for us to do this. First off we select the player object from the Heirarchy, then we either drag the script from the project tab to the Inspector or we click the "Add Component" button in the Inspector. If we do the later we must search for the script name and then click on it.

The result should be the following:

attach_script_to_player.png

You may notice that we automatically attached a NavMeshAgent when we attached the ClickToMove script. In the NavMeshAgent you can change movement speed, rotation speed etc.

If you try to run the game now you will see that everything is running without any errors but your player is not moving when you click around. This is because you are missing the navigation mesh.

Setting up the navigation mesh

The mesh will keep track of where the player can and can't move. So get over to the Navigation tab.

navigation.png

If you don't have the navigation tab visible you can find it in the menus under "Window" almost all the way down at the bottom.

You might also notice that I have selected the "Bake" tab in the navigation, this is where you will render the navigation mesh which will keep track of where you can move the player. To render the mesh you hit the "Bake" button in the bottom right corner of the Navigation tab. This might take some time depending on your environment size.

map_baked.png

Once this process is done you will see this blue tint color all over your environment, above you can see what mine looks like. All the blue is where the player can walk, you might also notice that the walls have this margin around them. If you want you can change the bake settings in the navigation tab to increase or decrease this margin. Play around with the settings so that it matches your game, I will just run with the default.

The result

Okey, now everything should be working. When you click around in the Game view you can move the player around and at the same time see where he is going in the Scene view marked by the blue line we added earlier in the code.

result.png

Now you can add this piece of code to your game and get the same result, a very simple way to make click to move with pathfinding in Unity 5.


If you have any questions, feel free to contact me at info@papershards.com. Just add a link to this article and the e-mail will reach me.

Linux: Groups and users

Linux users are important to any linux distribution, without a user you wont be able to administer your linux server at all. In this article I will go through the basics of linux users and groups.

Linux: Useful commands for daily use

Today I will go through a few useful tools that every Linux CLI (command-line interface) user will need. Listing files and directories, searching for files and directories, copy files and directories

A typical day of a web developer

Hi, my name is Jonathan, today I will tell you about a typical day of a web developer from my perspective.

Working as a Support Technician

Hello! My name is Emy and I work as a full-time support technician at a web bureau/web hosting company in southern Sweden. This article will give you.