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.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
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
We will move our player to the clicked position.