NPC walking on air when targeting player

So, i was making this code and it happens to me. I have one NPC on my scene called CatLite, and he’s following me as it should, but he’s not fixed on y axis, he starts walking on the air. If anyone could tell me where i’m missing i would be thankful.

Here’s the entire code.

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

public class NPCFollow : MonoBehaviour
    public GameObject Player;
    public float TargetDistance;
    public float AllowedDistance = 5;
    public GameObject CatLite;
    public float FollowSpeed;
    public RaycastHit Shot;

    void Update()
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
            TargetDistance = Shot.distance;
            if (TargetDistance >= AllowedDistance)
                FollowSpeed = 0.02f;
                transform.position = Vector3.MoveTowards(transform.position, Player.transform.position, FollowSpeed);
                FollowSpeed = 0;

btw, i’m using Navigation Static, don’t know if i’m getting it too complex for something that maybe is simple, so that’s it :slight_smile:

First, as a general advice, the first letter of your variable should not be capitalized.

Second you are not actually using any navigation library in this script. This line will always move an object towards the target with no respect of colliders, gravity or animation:

transform.position = Vector3.MoveTowards(transform.position, Player.transform.position, FollowSpeed);

If you want the cat to navigate correctly by hand, I suggest a CharacterController. The SimpleMove call will apply gravity by itself simply by giving it a normalized direction towards the player.

The cat would likely get stuck quite easily if you do so, so I would suggest actually using a NavMesh Agent or equivalent.