Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Spawn sprite on click and makes the sprite follow mouse pointer while still holding the click?

Discussion in 'Scripting' started by FalconJ, Jan 27, 2016.

  1. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    I have this code for now:

    Code (CSharp):
    1.        
    2. if(Input.GetMouseButton(0))
    3.         {
    4.             RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    5.  
    6.             if(hit.collider)
    7.             {
    8.                 if(movingObject == null)
    9.                 {
    10.                     movingObject = hit.collider.gameObject;
    11.                     movingObject.gameObject.GetComponent<SpriteRenderer>().enabled = true;
    12.                     movingObject.transform.position = Input.mousePosition;
    13.                 }
    14.             }
    15.         }
    I use Input.mousePosition inside an Update() which intends to make the sprite always follow the pointer, but it doesn't work?
     
  2. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    You're halfway there. First confirm using debug.log's or breakpoints that you're definitely hitting a collider and assigning movingObject. Assuming that's correct, I'd say the issue is that you're setting

    Code (CSharp):
    1. movingObject.transform.position = Input.MousePosition;
    The mouse position is a 2D position relative to the screen, and will hold no semblance to the position in the world. Your best bet would be to use the raycast again, and either cast ScreenToWorldPoint again, or to cast onto the floor in the 3D world. Depending on your setup :).
     
  3. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    Care to elaborate more on how to put that into code?
    My game is 2D btw
     
  4. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Something similar to this. In this example I've smoothed the movement a little.

    Code (CSharp):
    1.     Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    2.     target.z = movingObject.transform.position.z;
    3.     movingObject.transform.position = Vector3.MoveTowards(movingObject.transform.position, target, speed * Time.deltaTime);
     
    JoeStrout likes this.
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,840
    And you've done it with MoveTowards, rather than the common mistake of using Lerp! Kudos.
     
    Nigey likes this.