Bring your game to life with this easy-to-implement interaction technique!

Unity Quick Tips: Making Objects Follow the Mouse Pointer

Part 2 of Our Bite-Sized Unity Tips and Tricks for Beginners

Valdarix Games
3 min readFeb 14, 2023

--

Welcome to Part 2 of our series of bite-sized Unity tips and tricks for beginners! In this article, we’re going to show you how to make objects follow the mouse pointer in Unity. Whether you’re creating a game or another application, this is a great way to add some interactivity to your scene.

Here’s the code sample:

using UnityEngine;

public class FollowMouse : MonoBehaviour
{
private void Update()
{
Vector3 mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.z = 0;
transform.position = mousePos;
}
}

In this script, we use the Update function to continuously update the position of the object to match the position of the mouse pointer. First, we use the Input.mousePosition method to get the position of the mouse pointer in screen space. Then, we use the Camera.main.ScreenToWorldPoint method to convert the screen position to a world position. Finally, we set the z value to 0 to keep the object in the 2D plane and update the position of the…

--

--

Valdarix Games
Valdarix Games

Written by Valdarix Games

Turning my passion for video games and software development experience into a focus on video game development.

No responses yet