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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

2d - sprite following sprite

Discussion in '2D' started by Andrey2323, Oct 10, 2015.

  1. Andrey2323

    Andrey2323

    Joined:
    Oct 10, 2015
    Posts:
    6
    Can someone help me how can i make an object(sprite) to follow another sprite in unity?
    What i want exactly:
    if the first sprite goes up, then the second follow it, if it's going down, the same.

    thanks,
    Andrei
     
  2. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    You could just add the two into the scene and drag one (the one following) under the object of the other in the Hierachy

    Or use a script to make it more fluid and smooth have a look into Vector3.Lerp()
     
    Andrey2323 likes this.
  3. petresco

    petresco

    Joined:
    Aug 24, 2015
    Posts:
    3
  4. Prototypetheta

    Prototypetheta

    Joined:
    May 7, 2015
    Posts:
    122
    Code (CSharp):
    1.  
    2. Public GameObject target;
    3.  
    4. Public float smoothing;
    5.  
    6. Private Vector3 initialPosition;
    7.  
    8. Private Vector3 targetPosition;
    9.  
    10. Void Start(){
    11. initialPosition = target.transform.position;
    12. }
    13.  
    14. Void Update(){
    15.  
    16. targetPosition = new Vector3(transform.position.x + (target.transform.position.x - initialPosition.x), transform.position.y + (target.transform.position.y - initialPosition.y), transform.position.z);
    17.  
    18. transform.position = Vector3.Lerp(transform.position, targetPosition, smoothing);
    19.  
    20. }
    21.  
    Set your target to whatever GameObject you want to follow, set your smoothing between 1 and 0 (1 is no smoothing, 0 is no movement). When the first GameObject moves, this should move the second one by the same amount in the same direction.

    This code isn't perfect, but should give you and idea of how this works.