How Click and Move in Unity part 2

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

Tristan Engel
1 min readSep 11, 2021

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.

--

--

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.