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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

LeetCode Patterns Adventure 14— Remove Duplicates from Sorted List

Validating and Formatting Payment Card Text Fields in Flutter

Changing from Trunk Based Branching to Git-Flow

Managing Air freight, Sea Freight and land freight through a SaaS-based ERP Software

Google Kubernetes Engine By Example: Part 2

From Sales Associate & Lyft Driver to Software Developer Student

About the Black Square Online

Spring Boot Event Sourcing Via Kafka

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.

More from Medium

DesktopInfo — Conky for Windows

Moving Platform

’Twas The Code Before Christmas

Finding .Net Assemblies