Point & Click to Move in Unity
Objective: Set up logic for point and click character controller
While prototyping the Players gameplay we will use a 3D capsule object called Player in place of the player. Set up a scripts folder in the project, create a script called Player and drag it onto the Player(Capsule) in the hierarchy.
We will use a baked navmesh to identify to areas in the scene that our Player can move. You can see this navmesh in the above image, represented bty the light blue color around the level. For the Player to Identify and Interact with the navmesh, a Navmesh Agent is added to the Player.
We will be using raycasts and keyboard/mouse buttons for this controller. For more info on Raycasting in Unity visit Unity Docs.
For the initial action in getting the point and click system working, we need to allow the mouse to click an are in the scene and get/return the co-ordinates of that position. For this we need to check for the left mouse button click, casting a ray from the mouse position in the scene then getting the position in the scene back if we hit something as co-ordinates, which we can demo by creating primitive shapes such as cubes in Unity.
Next we need to move the Player to the point that has been clicked in the scene. The Player needs to move along the navmesh. Unity Doc.
We need to use the Unity AI namespace so we can import that first. We can then create a Private NavMeshAgent(called _agent) and assign it in the Start method using GetComponent. Using the UnityEngine.AI and NavMeshAgent gives us access to the SetDestination method, which we use for our newly assigned _agent to set the destination of the hitInfo point.