Bring your game to life with this easy-to-implement interaction technique!
Unity Quick Tips: Making Objects Follow the Mouse Pointer
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:
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 object using the
Here are a few ways you can enhance and optimize the script for making objects follow the mouse pointer in Unity:
- Limit the Follow Area: You can limit the area in which the object can follow the mouse pointer by adding a check in the
Updatefunction to see if the mouse position is within a certain range. If it's not, you can keep the object at its current position.
- Add a Smooth Follow: You can make the object follow the mouse pointer smoothly by using the
Vector3.Lerpmethod to gradually move the object from its current position to the mouse position.
- Add a Follow Offset: You can add an offset to the follow position to keep the object a certain distance from the mouse pointer. You can do this by adding a few lines of code to generate an offset vector and adding it to the mouse position before updating the object’s position.