Make object follow mouse: 2D game

Hi there,

I’d like to make a top down game that the sprite follows the mouse in a very nicely animated manner, i’m just wondering if there is a way to do so. At the moment i’m thinking about systematically making the only directions being to move horizontally and vertically, it will be a topdown shooter that you move with your right click of the mouse, but im mostly worried about making the sprite follow the mouses position when you right click. Please help me, is there any way of doing this/ doing this easily?

-Much appreciated in advance, Jackson

1420156--74704--$wizardMovement_down.png1420156--74704--$wizardMovement_down.png

I only need to know about the sprite moving, really cause it doesn’t work i’ve made it move

Here’s some code I wrote for you. Just attach it to any object you want to follow the mouse when right-click is down. I hope it helps!

using UnityEngine;
using System.Collections;

public class MouseMove2D : MonoBehaviour {

	private Vector3 mousePosition;
	public float moveSpeed = 0.1f;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetMouseButton(1)) {
			mousePosition = Input.mousePosition;
			mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
			transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
		}

	}
}
28 Likes

Thanks this help me, i am now using this to control a crosshair for my top down orthographic tank game.

I had to change line 19. to Vector3.Lerp so i could make the crosshair stay above the floor plane by using.

transform.position = Vector3.Lerp( new Vector3 (transform.position.x , transform.position.y, -5), mousePosition, moveSpeed);

where the -5 is the z distance.

i put this up because it took me a while to find out this information.

3 Likes

I know this thread is really old, but anyways:

Couldn’t you do

mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);

So it’s only one line?

2 Likes

Yep, just tested it and it works.

1 Like

I came across this thread in 2017

1 Like

Is there a way of moving the object in a constant speed rather than moving faster the further away the mouse is?

you can try to change lerp speed depended on distance between mouse and gameobject

void Update () {
        if (Input.GetMouseButton(1)) {
            mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 tmpDir = mousePosition - transform.position;
            transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed * 1f / tmpDir.magnitude * Time.deltaTime);
        }

    }

or use moving to mouse with normalized moving vector

void Update () {
        if (Input.GetMouseButton(1)) {
            mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 tmpDir = mousePosition - transform.position;
            //this line should disable moving near the end or the object will "jitter"
            //disable if-line to see what I mean
            if (tmpDir.sqrMagnitude > 0.1f)
            transform.Translate (tmpDir.normalized * moveSpeed * Time.deltaTime);
        }

    }

Use MoveTowards:

private void Update()
{
    if(Input.GetMouseButton(1))
    {
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePosition.z = transform.position.z;
        transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    }
}
1 Like

how can we do with point and click? when i click an empty location then object go to there.

store somewhere the clicked position and move to it.

private void Update()
{
    if(Input.GetMouseButtonDown(0))
    {
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePosition.z = transform.position.z;
        //transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    }
transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
}
1 Like

this code does not work. when click to object, then it does work

maybe the moveSpeed was zero, check the value in inspector (and the script is for left-click, change Input.GetMouseButtonDown(0) to 1, if right-click is needed ).

public float moveSpeed = 10;
    Vector3 mousePosition;

    void Start()
    {
        //to prevent that object will move to zero at beginn.
        mousePosition = transform.position;
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePosition.z = transform.position.z;
        }
        transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    }

I wrote this one but I cant point and click. its working only mouse drag. Actually the both of them must work as mouse down and mouse drag

void OnMouseDrag()
    {
        moveToPosition = true;
        mousePosition = Input.mousePosition;
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    }

    void Update()
    {
        if (moveToPosition)
        {
            increase += Time.deltaTime;
            direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
            transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
            if (Vector3.Distance(transform.position, mousePosition) < 100f)
            {
                moveToPosition = false;
            }
            transform.up = direction;
        }
    }

i can see its been 4 years since the last comment but i need the help.

so im tying to use the first code by unitylover but i keep getting this error:

NullReferenceException: Object reference not set to an instance of an object
point.Update () (at Assets/scripts/point.cs:14)

what can i do?

Pyrotech850, could you post your solution?
On line 14 inside point.cs, you are trying to use an object which is null. This is usually caused by either trying to GetComponent which is not available, or using a member variable which is not set in the editor.

1 Like

Hey there I just started programming and am wondering how i might be able to do it without needing to press left mousebutton. so i simply hover the screen and my object follows it… any ideas?

just try to delete if-check

using UnityEngine;
using System.Collections;
public class MouseMove2D : MonoBehaviour {
    private Vector3 mousePosition;
    public float moveSpeed = 0.1f;
    // Use this for initialization
    void Start () {
  
    }
  
    // Update is called once per frame
    void Update () {
            mousePosition = Input.mousePosition;
            mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
            transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
    }
}

yes you just wouldn’t use the dot lerp function at the end of Vector2 or Vector 3