How to make a limited follow script?

Hi there,

I’m currently trying to make a script for two characters. The characters will follow the player, but only along a certain direction and but they’re limited to only follow them in a certain area. For example, in the following image, the pink area is, for example the area in which the player would mostly explore while the red rectangle shows the strict range of movement that they could follow the player, only in that one direction, however I would want it limited to that stretch of the rectangle. In addition, I’d like the LookAt function of the animator functioning to make the later animated character models look towards the player at all times.

I imagine that it would mostly involve programming their transform.position.z, since that is the axis that direction is on, but I don’t know how to properly code that. I am, unfortunately, more of an artist than a programmer so I’m not exactly sure how I’d program my characters to do that. I’d really appreciate some in depth help on how I could code this following behaviour.

Hi,
It’s not my best code but you can do something like that :

public GameObject Player;
public float      Speed = 5f;
public float      MaxZ = 40f;
public float      MinZ = 0f;


void Update() {
    if (Player.transform.position.z > transform.position.z) {
         transform.position = new Vector3(transform.position.x, transform.position.y, Mathf.Clamp(transform.position.z + Time.deltaTime * Speed, MinZ , MaxZ ));
    } else {
        transform.position = new Vector3(transform.position.x, transform.position.y, Mathf.Clamp(transform.position.z - Time.deltaTime * Speed, MinZ , MaxZ ));
    }
    transform.LookAt(Player.transform.position);
}

I hope this help…

Hello, you can use Mathf.Max for restricting the enemies movement to the minimum z direction and Mathf.Min for restricting in max z direction.

    Vector3 currentPos = character.transform.position;
    currentPos.z = Mathf.Min(currentPos.z, 20f);
    currentPos.z = Mathf.Max(currentPos.z, -20f);
    character.transform.position = currentPos;

OR, you can use Mathf.Clamp…

    Vector3 currentPos = character.transform.position;
    currentPos.z = Mathf.Clamp(currentPos.z, -20f, 20f);
    character.transform.position = currentPos;