Skip to content

Unity Character Movement using mouse click

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Introduction

In this tutorial, you will learn how to move the character using a mouse click in Unity. This type of movement is commonly used in RTS (Real-time Strategy games), RPG (Role-playing Games), TPS Games.

Prerequisites

  • Basic Knowledge of C# & Unity Game Engine
  • NavMesh Concept
  • Raycasting

Create a Character Movement Demo Project

  • Open Unity hub.
  • Create a new Unity project. ( Here I am using Unity 2019.4.5f1 )
  • Set Project name & location.
New Unity Project

Setup 3d Environment

  • Download this free 3d Environment from the Unity Store.
3D Environment Asset

https://assetstore.unity.com/packages/3d/characters/toony-tiny-people-demo-113188

  • Download this free 3d Character from the Unity Store.
3D Character Pack Asset

https://assetstore.unity.com/packages/3d/environments/urban/toon-gas-station-155369

  • After Downloading, import both assets in this unity project.
  • Open the “Demo_Scene_1” scene of the Toon Gas station asset as below.
Select Environment scene
  • Add 3D characters in the scene.
  • Select a character from the folder and drag it to the current scene.
  • You will find the location of the character as seen in the image below.
Select Character prefab
Character Look
  • Rename this character object to “Player”.
  • Change the properties of the Player object as below.
set Character’s position & scale
  • Set camera position & rotation for Top-Down view as below image.
Set Camera”s position & rotation

Setup Navigation Agent

Here we are using the Navigation concept of unity that uses to navigate player and movement.

  • All road, Terrain ground plane, and the obstacle cubes are marked as static as below
set all objects as static
Confirm Box
  • Go to Window 🡒 AI 🡒 Navigation and open up the Navigation panel.
  • Go to the Bake menu and click the Bake button at the bottom.
Navigation Bake process
  •  After some time, you should see a blue color navigation mesh appear on the scene window.
  • Character “Player” will able to move only in the blue part.
Nav Mesh Display

Character Movement using Raycasting & Nav Mesh Agent

  • Add a Nav Mesh Agent to the player object by selecting the player and go to Component 🡒 Navigation 🡒 Nav Mesh Agent.
  • This component helps to find the shortest path and moves the character to its destination.
  • After that, right-click on the Project panel and select Create 🡒 C# Script.
  • Name the C# script as “CharacterMovementScript“.
  • Assign this script to the Player object by drag-and-drop the script onto the player.
  • Then, double click the script to open up Visual Studio. It should look something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterMovementScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
  • Add the header Library for Navigation functionality.
using UnityEngine.AI;
  • Add Navmesh Agent and camera variable into the script
    //NavMeshAgent variable control player movement
    public NavMeshAgent playerNavMeshAgent;

    //A Camera that follow player movement
    public Camera playerCamera;

After that add the following code to the Update function.

    private void Update()
    {
        //if the left button of is clicked
        if (Input.GetMouseButton(0))
        {
            //Unity cast a ray from the position of mouse cursor on-screen toward the 3D scene.
            Ray myRay = playerCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit myRaycastHit;

            if (Physics.Raycast(myRay, out myRaycastHit))
            {

                //Assign ray hit point as Destination of Navemesh Agent (Player)
                playerNavMeshAgent.SetDestination(myRaycastHit.point);
            }
        }
    }
  • In the code, If the left mouse button is clicked then cast a ray from the position of mouse cursor on-screen toward the 3D scene.
  • If the ray hits anything, Unity will return the location (hit point) which you can use to set the NavMesh Agent’s destination.
  • Assign the Player to the Agent property and the scene camera to the Camera property on its Player script.

Output:

Here, In the output without any animation, the player looks like a static object. So we add some animation.

Applying animation to the player character

  • In the Project Window, Create an animator controller file to manage animation of the Player Character as below.
  • Assign this new animator controller to the animator property of the Player object.
  • For opening the Animator window, Go to Window->Animation->Animator.
  • Assign Idle and run an animation clip from the animation folder to the animator controller as below image.
  • Create a transition between animation clips as below.
  • Change properties Transition arrow
    • Disable HasExitTime checkbox.
    • Add Conditions
  • Create a bool parameter in the animator controller window that uses to put conditions on animation clips. We will discuss more about in coding part.
  • Open “CharacterMovementScript” in visual studio.
  • Create an Animator controller variable in the script that is used to handle animation runtime.
    //Control the animation clips of player object 
    public Animator playerAnimator;
  • Create a bool variable that use to check character is moving or not.
    //check character is running(moving) or not
    public bool isRunning;
  • Add a condition in the code that will check if the character is moving or not
        //Compare the value of the remaining distance and the stopping distance(Destination point)
        
        if (playerNavMeshAgent.remainingDistance <= playerNavMeshAgent.stoppingDistance)
        {
            //The remaining distance are less or equal than the stopping distance it means character stop moving and reached destination
            isRunning = false;
        }
        els
        {
            //If remaining distance are greater than the stopping distance than character still moving toward Destination
            isRunning = true;
        }
  • Now, set the value of the bool parameter – IsRun is true or false.
    • If the IsRun is true then character then Run animation clip will play.
    • If the IsRun is false then character then Run animation clip will play.
playerAnimator.SetBool("IsRun", IsRunning);
  • Assign the Character to the animator property of the script.

Final script

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


public class CharacterMovementScript : MonoBehaviour
{
    //NavMeshAgent variable control player movement
    public NavMeshAgent playerNavMeshAgent;

    //A Camera that follow player movement
    public Camera playerCamera;

    //Control the animation clips of player object 
    public Animator playerAnimator;
    
    //check player is running(moving) or not
    public bool isRunning;

    private void Update()

    {
        //if the left button of is clicked
        if (Input.GetMouseButton(0))
        {
            //Unity cast a ray from the position of mouse cursor on-screen toward the 3D scene.
            Ray myRay = playerCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit myRaycastHit;

            if (Physics.Raycast(myRay, out myRaycastHit))
            {

                //Assign ray hit point as Destination of Navemesh Agent (Player)
                playerNavMeshAgent.SetDestination(myRaycastHit.point);
            }
        }

        //Compare the value of the remaining distance and the stopping distance(Destination point)
        
        if (playerNavMeshAgent.remainingDistance <= playerNavMeshAgent.stoppingDistance)
        {
            //The remaining distance are less or equal than the stopping distance it means character stop moving and reached destination
            isRunning = false;
        }
        else
        {
            //If remaining distance are greater than the stopping distance than character still moving toward Destination
            isRunning = true;
        }

        playerAnimator.SetBool("IsRun", isRunning);

    }
}

Summary

In this article, you learned how to use click to move in Unity. So now you can go ahead and make your games in which the player is moving towards the location, in the game, that you clicked on.

 

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide