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()
{
transform.LookAt(Player.transform);
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
{
TargetDistance = Shot.distance;
if (TargetDistance >= AllowedDistance)
{
FollowSpeed = 0.02f;
CatLite.GetComponent<Animator>().Play("Walk");
transform.position = Vector3.MoveTowards(transform.position, Player.transform.position, FollowSpeed);
}
else
{
FollowSpeed = 0;
CatLite.GetComponent<Animator>().Play("Idle_B");
}
}
}
}
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 :)
Answer by lgarczyn · Dec 06, 2019 at 07:03 PM
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.
Thank u, i did the tips you said and it worked, and thanks for the capitalized too, i doesn't know that this could do problems in my code.
Capitalisation won't ever cause problems in your code, but the difference helps differentiate Types and variables for yourself and other programmeurs.