Hey Folks,
I’m having some trouble figuring this out so hopefully someone can help!
In the game i’m making I’ve got characters who, when touched by the player, begin to follow him (something this forum helped me work out!).
This all works fine, but as the movespeed is defined by a public int for the followers, the character falling / being moved at a higher speed than theirs means a large gap is created between them which they then slowly catch up over.
Ideally what i’d like to happen is for them to match the characters speed as it increases, i’ve looked into using rigidbody2D.velocity, but as the player characters rigidbody is kinematic I believe it doesn’t have a velocity for them to match?
Any suggestions would be fantastic, thanks in advance guys!
Quick Edit: I don’t want to make the followers children of the player as their movement becomes more rigid and locked to the players! If anyone could tell me how to make it so the followers could move more freely as children (e.g. moving up when the player jumps down a hole etc), then I would consider that as well.
Code Below:
using UnityEngine;
using System.Collections;
public class EnemyAi : MonoBehaviour {
//------------Variables----------------//
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance;
public int minDistance;
private Transform myTransform;
public GameObject detonate;
public AudioClip Explosion;
AudioSource boulderBoom;
//------------------------------------//
void Awake()
{
myTransform = transform;
EnemyAi otherScript = GetComponent<EnemyAi>();
otherScript.enabled = false;
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Player") {
EnemyAi otherScript = GetComponent<EnemyAi> ();
otherScript.enabled = true;
}
}
void Start ()
{
boulderBoom = GetComponent<AudioSource> ();
}
void Update ()
{
if (Vector3.Distance (target.position, myTransform.position) > minDistance) {
Vector3 dir = target.position - myTransform.position;
// Normalize it so that it's a unit direction vector
dir.Normalize();
}
else if (Vector3.Distance(target.position, myTransform.position) > maxDistance)
{
Vector3 dir = target.position - myTransform.position;
dir.Normalize();
myTransform.position += dir * moveSpeed * Time.deltaTime;
}
}
}