Fork me on GitHub

Haydi Bakalım

03 November 2020

So today we are going to be making and object follow the mouse cursor in unity.

Currently I am using Unity 2019.4.10, So this can be applicable for future versions and maybe some older ones too.

We shall start with the default Sample Scene





Lets start by creating a C# script and call it MouseCursorFollow.cs
so this is the default script you will get

    using UnityEngine;

    public class GameManager : MonoBehaviour{
        
        //Use..
        void Start(){
            
        }

        //....
        void Update(){

        }
    }



You can remove both the comments.
Now we are going to declare all our variables.

    public Camera myCam;
    Vector2 mousePosition;
    RigidBody2D rb;



Now reference the scene camera to the game object which has this script attached.
Next attach a RigidBody2D component to this game object and set the gravityScale to 0
Get the RigidBody2D component through the start function.

    void Start(){
        rb = GetComponent<RigidBody2D>();
    }


Now we will set our local mousePosition variable to the actual mousePosition
and convert it with Screen to World point function from our cam.

    void Update(){
        mousePosition = myCam.ScreenToWorldPoint(Input.mousePosition);
    }



And we move our current position to the mousePosition with MovePosition from RigidBody2D.

    void Update(){
        mousePosition = myCam.ScreenToWorldPoint(Input.mousePosition);
        rb.MovePosition(mousePosition);
    }

So this is the final script.

    using UnityEngine;

    public class GameManager : MonoBehaviour
    {
        public Camera myCam;
        Vector2 mousePosition;
        RigidBody2D rb;

        void Start(){
            rb = GetComponent<RigidBody2D>();
        }

        void Update(){
            mousePosition = myCam.ScreenToWorldPoint(Input.mousePosition);
            rb.MovePosition(mousePosition);
        }
    }



Now go into the unity editor and hit play.
Everything should work as expected.