How Click and Move in Unity part 2

Using Mouse input and raycast to get a position in world space

In this article we create our script to move to a point on the map that is clicked.

Player Script Pseudocode

if Left click
then cast ray from mouse position
then debug log floor position
create game object at floor position

Player Script Actual Code

Create script and add it to Player gameobject.
RaycastHit hit is a variable that stores what the raycast has hit. Using hit.point we can get the world position to spawn the capsule at.

Ray ray is a Ray variable in which we set the origin point as Camera.main. Then we also store the direction of the ray in it based on our mouse position.

if (Input.GetMouseButtonDown(0))
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log("Ray: "+ray);
if (Physics.Raycast(ray, out hit))
Debug.Log("Raycast hit something");
Debug.Log("hit world pos: "+ hit.point);
GameObject capsule = GameObject.CreatePrimitive(PrimitiveType.Capsule);
capsule.transform.position = hit.point;

Player Script Result

Next Up

We will move our player to the clicked position.



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
Tristan Engel

Tristan Engel


Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.