Home > Back-end >  My C# Unity code for AI enemy movement doesnt work
My C# Unity code for AI enemy movement doesnt work

Time:06-22

Im trying to make an AI enemy in Unity. Im writing the code for the AI movement. So the AI is supposed to start at a starting point, then its supposed to move until it reaches a certain point and come back but my code doesnt work for some reason.

Code:

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

public class EnemyMoveAround : MonoBehaviour
{
    public Vector3 start;
    public Vector3 startOrientation;
    public Vector3 end;
    public int speed;
    public int moveMode;


    // Start is called before the first frame update
    void Start()
    {
        transform.position = start;
        transform.localScale = startOrientation;

    }

    // Update is called once per frame
    void Update()
    {
        transform.position  = new Vector3(startOrientation * speed, 0);
        if (transform.position > end || transform.postion < start)
        {
            startOrientation = startOrientation * -1;
        }


    }
}

CodePudding user response:

you can use unity built in navmesh system

basicaly you check the distance between the end position and you current position

and you set the NavMeshAgent destination to the end positon like : (whatever you name the variable).SetDestination(end);

then as the dstBetween the end position and current position get small then you can switch the destination to start Position and set a boolean to true like isReturning to true.

you can watch tutorials of NavMesh in youtube if my answer confuses you

Hope that helps!

  • Related