NPC that follows me tilts backwards as he get too close to me.

Hi guys!

Hope someone can help me out. I have a C# script that allows an NPC to follow me around and stop at a certain distance.

If the NPC gets too close he will tilt back until horizontal. I have a feeling i need to set y axis to 0 but not entirely sure at what point or how in the script. Below is a sample of my code, if anyone can help that would be great!

public class NPCFollow : MonoBehaviour
    public GameObject player;
    public GameObject npc;
    public float followspeed;
    public int alloweddistance = 1;
    public float targetdistance;
    public RaycastHit Shot;
    private Animator anim;

    // Start is called before the first frame update
    // Update is called once per frame
    void Update()

        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
            targetdistance = Shot.distance;
            if (targetdistance >= alloweddistance)

                followspeed = 0.02f;
                npc.GetComponent<Animator>().SetBool("isIdle", false);
                npc.GetComponent<Animator>().SetBool("isWalking", true);
                transform.position = Vector3.MoveTowards(transform.position, player.transform.position, followspeed);
                followspeed = 0;
                npc.GetComponent<Animator>().SetBool("isIdle", true);
                npc.GetComponent<Animator>().SetBool("isWalking", false);

Since you’re doing all this in Update you could set the x and z rotation to 0 which I think should fix your problem. However I think it would be a much better way to remove the origign of the rotation instead of adding something to work against it, but I can’t see anything causing this, the only thing I could think about is that there might be something wrong with your Idle Animation because you say that the NPC tilts if he gets too close which seems to be around the time when the Idle Animation is set to true.

@Compii I found that if I added

var rot = transform.eulerAngles;
        rot.x = 0;
        transform.eulerAngles = rot;

It sorted it right out for me! Thanks for your input!