Search Unity

Make object follow mouse: 2D game

Discussion in '2D' started by Jackson-Collins, Nov 15, 2013.

  1. Jackson-Collins

    Jackson-Collins

    Joined:
    Nov 14, 2013
    Posts:
    2
    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

    $wizardMovement_down.png $wizardMovement_down.png
     
  2. Jackson-Collins

    Jackson-Collins

    Joined:
    Nov 14, 2013
    Posts:
    2
    I only need to know about the sprite moving, really cause it doesn't work i've made it move
     
  3. unitylover

    unitylover

    Joined:
    Jul 6, 2013
    Posts:
    346
    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!

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class MouseMove2D : MonoBehaviour {
    6.  
    7.     private Vector3 mousePosition;
    8.     public float moveSpeed = 0.1f;
    9.  
    10.     // Use this for initialization
    11.     void Start () {
    12.    
    13.     }
    14.    
    15.     // Update is called once per frame
    16.     void Update () {
    17.         if (Input.GetMouseButton(1)) {
    18.             mousePosition = Input.mousePosition;
    19.             mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    20.             transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
    21.         }
    22.  
    23.     }
    24. }
    25.  
    26.  
     
  4. Runalotski

    Runalotski

    Joined:
    Mar 4, 2014
    Posts:
    10
    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.
     
    Last edited: Mar 28, 2014
    Alaadel, sbagchi and MinnMinx like this.
  5. mads232

    mads232

    Joined:
    Sep 6, 2013
    Posts:
    48
    I know this thread is really old, but anyways:

    Couldn't you do
    Code (csharp):
    1. mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
    So it's only one line?
     
    mystifluent and sbagchi like this.
  6. Pkbiggums

    Pkbiggums

    Joined:
    Mar 19, 2013
    Posts:
    12
    Yep, just tested it and it works.
     
    mapesto likes this.
  7. zero_null

    zero_null

    Joined:
    Mar 11, 2014
    Posts:
    159
    I came across this thread in 2017
     
    sbagchi likes this.
  8. LaconicGames

    LaconicGames

    Joined:
    Aug 12, 2017
    Posts:
    4
    Is there a way of moving the object in a constant speed rather than moving faster the further away the mouse is?
     
  9. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    you can try to change lerp speed depended on distance between mouse and gameobject

    Code (CSharp):
    1. void Update () {
    2.         if (Input.GetMouseButton(1)) {
    3.             mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4.             Vector2 tmpDir = mousePosition - transform.position;
    5.             transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed * 1f / tmpDir.magnitude * Time.deltaTime);
    6.         }
    7.  
    8.     }
    or use moving to mouse with normalized moving vector
    Code (CSharp):
    1. void Update () {
    2.         if (Input.GetMouseButton(1)) {
    3.             mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4.             Vector2 tmpDir = mousePosition - transform.position;
    5.             //this line should disable moving near the end or the object will "jitter"
    6.             //disable if-line to see what I mean
    7.             if (tmpDir.sqrMagnitude > 0.1f)
    8.             transform.Translate (tmpDir.normalized * moveSpeed * Time.deltaTime);
    9.         }
    10.  
    11.     }
     
    Last edited: Dec 17, 2017
  10. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Use MoveTowards:
    Code (CSharp):
    1. private void Update()
    2. {
    3.     if(Input.GetMouseButton(1))
    4.     {
    5.         mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    6.         mousePosition.z = transform.position.z;
    7.         transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    8.     }
    9. }
     
    Alaadel likes this.
  11. freedom667

    freedom667

    Joined:
    Sep 6, 2015
    Posts:
    425
    how can we do with point and click? when i click an empty location then object go to there.
     
  12. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    store somewhere the clicked position and move to it.

    Code (CSharp):
    1.  
    2. private void Update()
    3. {
    4.     if(Input.GetMouseButtonDown(0))
    5.     {
    6.         mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    7.         mousePosition.z = transform.position.z;
    8.         //transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    9.     }
    10. transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    11. }
     
    kristosaber likes this.
  13. freedom667

    freedom667

    Joined:
    Sep 6, 2015
    Posts:
    425
    this code does not work. when click to object, then it does work
     
  14. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    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 ).

    Code (CSharp):
    1. public float moveSpeed = 10;
    2.     Vector3 mousePosition;
    3.  
    4.     void Start()
    5.     {
    6.         //to prevent that object will move to zero at beginn.
    7.         mousePosition = transform.position;
    8.     }
    9.  
    10.     private void Update()
    11.     {
    12.         if (Input.GetMouseButtonDown(0))
    13.         {
    14.             mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    15.             mousePosition.z = transform.position.z;
    16.         }
    17.         transform.position = Vector3.MoveTowards(transform.position, mousePosition, moveSpeed * Time.deltaTime);
    18.     }
     
  15. freedom667

    freedom667

    Joined:
    Sep 6, 2015
    Posts:
    425
    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

    Code (CSharp):
    1. void OnMouseDrag()
    2.     {
    3.         moveToPosition = true;
    4.         mousePosition = Input.mousePosition;
    5.         mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    6.     }
    7.  
    8.     void Update()
    9.     {
    10.         if (moveToPosition)
    11.         {
    12.             increase += Time.deltaTime;
    13.             direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
    14.             transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
    15.             if (Vector3.Distance(transform.position, mousePosition) < 100f)
    16.             {
    17.                 moveToPosition = false;
    18.             }
    19.             transform.up = direction;
    20.         }
    21.     }
     
  16. pyrotech850

    pyrotech850

    Joined:
    Apr 30, 2019
    Posts:
    1
    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?
     
  17. Ted_Wikman

    Ted_Wikman

    Unity Technologies

    Joined:
    Oct 7, 2019
    Posts:
    916
    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.
     
    MisterSkitz likes this.
  18. unity_uyKeJODa7It3CA

    unity_uyKeJODa7It3CA

    Joined:
    Jan 14, 2020
    Posts:
    1
    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?
     
  19. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    just try to delete if-check
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class MouseMove2D : MonoBehaviour {
    4.     private Vector3 mousePosition;
    5.     public float moveSpeed = 0.1f;
    6.     // Use this for initialization
    7.     void Start () {
    8.  
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update () {
    13.             mousePosition = Input.mousePosition;
    14.             mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    15.             transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
    16.     }
    17. }
     
  20. CaveManGaming_YT

    CaveManGaming_YT

    Joined:
    May 25, 2020
    Posts:
    1
    yes you just wouldn't use the dot lerp function at the end of Vector2 or Vector 3
     
  21. SupKittyMeow

    SupKittyMeow

    Joined:
    Dec 25, 2020
    Posts:
    5
    When I try any of them, It'll give errors
     
  22. crewking9

    crewking9

    Joined:
    Dec 14, 2020
    Posts:
    1
    My character is super slow and i dont know how to fix it.
     
  23. Alaadel

    Alaadel

    Joined:
    Apr 6, 2013
    Posts:
    30
    if you are using the above script, try changing the moveSpeed variable (in inspector) to 100 or something high.
     
  24. phoenix045

    phoenix045

    Joined:
    Mar 16, 2020
    Posts:
    2
    2021 go brrr
     
  25. unity_igNq9K2gLtkLhQ

    unity_igNq9K2gLtkLhQ

    Joined:
    Mar 11, 2021
    Posts:
    1
    2021 go BRRRRRRR also is there a way to make it so the object moves at a constant speed so it will move past the mouse if right click is not held and not just stop when right click is not held
     
  26. JellyCORE

    JellyCORE

    Joined:
    Jul 1, 2020
    Posts:
    1
    I'm pretty new to this, so I'm not quite sure this might work, but maybe one could store the Vector at which the object last moved when following the mouse, then use that Vector to tell it to keep going that direction? ^^
    Maybe that'd work!
     
  27. killeroid356

    killeroid356

    Joined:
    Feb 1, 2020
    Posts:
    1
    my god, just spent forever trying to "fix" my ingame cursor without realizing this was a thing, lifesaver <3

     
  28. TobiasjBurford

    TobiasjBurford

    Joined:
    Feb 17, 2022
    Posts:
    11
    If you want an offset you can do this:
    Code (CSharp):
    1. private Vector3 mousePosition;
    2. public float moveSpeed = 0.1f;
    3. public Vector3 offset;
    4.  
    5. void LateUpdate()
    6.     {
    7.         Vector3 mousePosition = Input.mousePosition + offset;
    8.         Vector3 smoothedPosition =
    9.         Vector2.Lerp(transform.position, mousePosition,
    10.         moveSpeed);
    11.         transform.position = smoothedPosition;
    12.     }

    :)
     
  29. FICinc

    FICinc

    Joined:
    Mar 6, 2022
    Posts:
    25
    Little code I made for my angry birds game for flinging:

    Code (CSharp):
    1. void Update()
    2.     {
    3.         if (//not important)
    4.         {
    5.             mv = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    6.             transform.position = Vector2.Lerp(transform.position,mv,1);
    7.             transform.right = transform.position - transform.localPosition;
    8.             if(transform.localPosition.x > 1)
    9.             {
    10.                 transform.localPosition = new Vector2(1, transform.localPosition.y);
    11.             }
    12.             if (transform.localPosition.x < -1)
    13.             {
    14.                 transform.localPosition = new Vector2(-1, transform.localPosition.y);
    15.             }
    16.             if (transform.localPosition.y > 1)
    17.             {
    18.                 transform.localPosition = new Vector2(transform.localPosition.x, 1);
    19.             }
    20.             if (transform.localPosition.y < -1)
    21.             {
    22.                 transform.localPosition = new Vector2(transform.localPosition.x, -1);
    23.             }
    24.         }
    If you want it to move freely, you can remove the if statements. Keep in mind you don't need the:
    Code (CSharp):
    1. transform.right = transform.position - transform.localPosition;
    If you don't want it to turn towards it's parent.
     
  30. netza17

    netza17

    Joined:
    May 7, 2022
    Posts:
    1
    hi i'm new to this, and want to know if ther is any way to make it only move in the x mouse position
     
  31. FICinc

    FICinc

    Joined:
    Mar 6, 2022
    Posts:
    25
    Code (CSharp):
    1. mv = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    2. transform.position = new Vector2(mv.x,transform.position.y);
    that should do it for whatever brick-breaker game you want to create.