Hello i am working on 2.5d game in which player just moves in 2 direction and the enemy who follows the player also have to move in 2 directions to catch the player. I have applied nav mesh agent on the enemy but I couldn’t figure it out that how to apply constraints on a nav mesh agent so it can move along only 2 axis x and y. Can someone please help me out ?
If you baking a NavMesh on a xy plane and setting target point for NavMeshAgent on that plane, agent should move only in XY coordinates.
However, if you still need some custom path adjusting, you can put NavMeshAgent script on a different invisible object and move your enemy like this:
class EnemyMovement: MonoBehavior {
[SerializedField]
NavMeshAgent agent; //reference to an object with NavMeshAgent agent, set it in inspector, for example
void FixedUpdate() {
Vector3 nextPos = agent.nextPosition;
Vector3 correctPos = ....; // do all modifications you need for nextPos
transform.position = correctPos;
}
}
My own approach worked for this problem was as following, Just posting this as an answer so maybe it would be useful for someone else.
public class PlayerFollow : MonoBehaviour {
private NavMeshAgent agent;
private GameObject player;
Vector3 startPos;
bool enemyPowerEnd = false;
bool iam = false;
bool your = false;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
// Use this for initialization
void Start ()
{
player = GameObject.FindGameObjectWithTag ("Player");
startPos = new Vector3(46.9f, 0.5f, 7.5f);
}
// Update is called once per frame
void Update ()
{
Vector3 enemyPos = this.transform.position;
Vector3 playerPos = player.transform.position;
if(!BirdMove.isGameOver && !enemyPowerEnd && !BirdMove.isWin && !MainMenu.asCatcher)
{
if(this.transform.position.x != player.transform.position.x && !iam)
{
agent.SetDestination(new Vector3(player.transform.position.x, this.transform.position.y, this.transform.position.z));
Debug.Log("awais here also");
Debug.Log(iam);
}
if(this.transform.position.x == player.transform.position.x)
{
iam = true;
}
if(iam == true)
{
Debug.Log("awais here");
your = false;
agent.SetDestination(new Vector3(this.transform.position.x, this.transform.position.y, player.transform.position.z));
}
if(this.transform.position.z == player.transform.position.z)
{
your = true;
iam = false;
}
this.transform.rotation = Quaternion.Euler(0,0,0);
}
else
if(BirdMove.isWin)
{
agent.enabled = false;
}
else
if(MainMenu.asCatcher)
{
agent.enabled = false;
transform.position -= transform.right*10f*Time.deltaTime;
}
if(Vector3.Distance(agent.transform.position, player.transform.position) <= 2)
{
agent.enabled = false;
GameObject.Find("BirdTest").SendMessage("GameOver");
}
}