Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

2d Spring joint...did not work for a sprite to follow my guy...while moving.

Discussion in 'Physics' started by codejoy, Feb 1, 2015.

  1. codejoy

    codejoy

    Joined:
    Aug 17, 2012
    Posts:
    203
    I was trying to build a character like a ghost follower dude that hovers around my player and follows him as he moves through the level. I wanted sorta random hovering movement around the 2d sprite...I thought a spring joint 2d would be good place to start but it seems that the fact it needs a rigid body it really wonks with the other character as he moves (and changes his behavior and physics and forces a lot)...I even set the mass of the follower around to 0 on the rigid body ... no go. So is the wrong tree to bark up? Think of a fairy hovering around the head of the player ..that is basically what i want (with it having semi random movement or movement that is reactive to what the player is doing).

    As I type this, sounds like I am going to have to script this myself and I have no idea where to start.
     
  2. Uberpete

    Uberpete

    Joined:
    Jan 16, 2014
    Posts:
    78
    Yep, you'll have to script yourself an AI. I'd recommend something like this:

    Code (CSharp):
    1. public Transform player;
    2. public Vector2 nextPoint;
    3.  
    4. void Start (){
    5.  
    6. NewPoint ();
    7.  
    8. }
    9.  
    10. void Update (){
    11.  
    12.    if (Vector2.Distance (transform.position, nextPoint.position) > 0.1){
    13.  
    14.    Vector2 direction =transform.position - nextPoint;
    15.  
    16.    //TODO: Move to the next point either by translating the sprite or using Rigidbody forces.
    17.  
    18.  
    19.     }
    20.  
    21. else
    22.  
    23.  
    24. {
    25.  
    26. NewPoint ();
    27.  
    28. }
    29.  
    30. }
    31.  
    32. void NewPoint (){
    33.  
    34. nextPoint = player.position + new Vector3 (Random.Range (-1,1), Random.Range (-1,1), Random.Range (-1,1));
    35.  
    36. //Or something likewise.
    37.  
    38. }
    You'd probably want to add some animations/delays but these are the bare bones.
     
  3. codejoy

    codejoy

    Joined:
    Aug 17, 2012
    Posts:
    203
    Thanks for the response, i was also investigating a simple ai steering algorithm.