0
votes

Hello i want to create a group of the same prefab following the player in my game. I already got the prefab intantiation to follow the player but when there is more than one they just follow the exact same path on top of each other. is there a way where they can follow the player but act like a bunch of bees moving? Thanks!

This is the script on my prefab:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KillerMovement : MonoBehaviour {


    public GameObject player;


    void FixedUpdate()
    {
        Vector2 toTarget = player.transform.position - transform.position;
        float speed = 0.5f;

        transform.Translate(toTarget * speed * Time.deltaTime);
    }
}
1
Do you have this script attached to each prefab individually? Or is it only attached to the parent component. If it is individually attached, they should all follower their own path, as long as their starting position is different - ryeMoss

1 Answers

0
votes

The best solution depends on you game logic, but you may consider having a delay before starting following (you can tweak the delay depending on the position you want to the particular object to assume in the trail.

using System.Collections;
using UnityEngine;

public class Follower : MonoBehaviour
{
  public GameObject player;
  public float delay = 0f;
  public float speed = .5f;
  bool isReady = false;

  void Start()
  {
    StartFollowing();
  }

  public void StartFollowing()
  {
    StartCoroutine(WaitThenFollow(delay));
  }

  IEnumerator WaitThenFollow(float delay)
  {
    yield return new WaitForSeconds(delay);
    isReady = true;
    Debug.Log(gameObject.name);
    Debug.Log(Time.time);
  }

  void FixedUpdate()
  {
    if (isReady && player != null)
    {
      Vector2 toTarget = player.transform.position - transform.position;
      transform.Translate(toTarget * speed * Time.deltaTime);
    }
  }
}

I've called StartFollowing in the Start method for you to test the code. You should call this method whenever approrpiate in your game logic.