Point & Click to Move in Unity

This tutorial will cover implement a point and click system to move the player around a room. If you don’t have one already create a Player script, attach it to your player, and open it. The first step is to create a Move function and call it in the Update function.

void Update()
{
Move();
}
void Move()
{
}

Next, you need to add the code to detect where the mouse is being clicked. To do this first you need to check that the left mouse button was clicked, use Input.GetMouseButtonDown(0) to check this. Inside the if statement get the ray of the mouse position based off of the camera. Create a RaycastHit variable, this will get the output of the Raycast check. In an if statement call Physics.Raycast passing it the ray and the hit with a distance of 100. This will do the raycast for you to see if it hits anything. You can log the hit point to check how it is working.

if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
Debug.Log("Hit: " + hitInfo.point);
}
}

Next, you are going to need access to the Nav Mesh Agent, so create a variable and then assign it in the start Menu. Don’t forget to include “using UnityEngine.AI” at the top so NavMeshAgent is recognized.

using UnityEngine.AI;public class Player : MonoBehaviour
{
private NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}

Now change the Debug.Log in your Move function to a call to agent.SetDestination.

if (Physics.Raycast(ray, out hitInfo))
{
agent.SetDestination(hitInfo.point);
}

At this point if you player is clipping through your game objects you will need to make sure they are set to static and then rebake your navigation.

Now your player will move where you click!

-Chris

--

--

--

Recommended from Medium

Library of RD.xml files for NativeAOT

Angular on AmazonWebServices

Use a Local Disk Through LocalVolume Provisioner in a Kubernetes Cluster

ProDrawer — Animated Drawer for Flutter

Chaos Oysters

Jersey Java RESTful API on an Alibaba Cloud ECS Instance

Kick off Session and First Sprint

3 reasons why conventional API monitoring is not enough

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Christian Carter

Christian Carter

More from Medium

Light her up — Adding emissions to your game objects using photoshop and blender

Point and Click Controller in Unity

Day 94: Wall Jumping in Unity

Making Moving Platforms In A Unity Platformer