Игрок не перемещается на все путевые точки. - PullRequest
0 голосов
/ 23 ноября 2018

Вражеский персонаж не двигается к 3-й путевой точке.После перемещения к путевой точке 2 он просто останавливается и воспроизводится бездействующая анимация.У персонажа есть агент NavMeshAgent, и похоже, что событие, достигнутое пунктом назначения, не вызывается, когда он добирается до путевой точки.Если бы у кого-то была такая ситуация, я был бы признателен за любую возможную информацию.Я пытался выяснить, что не так в течение нескольких часов, и начинаю думать, что это может быть не один из сценариев.

вот контроллер путевых точек

using UnityEngine;
using UnityEngine.AI; 

public class WaypointController : MonoBehaviour {

    Waypoints[] waypoints;
    public Transform target; 
    //NavMeshPath path; 
    int currentWaypointIndex = -1;
    //private NavMeshAgent agent;
    //EnemyCharacter enemy; 

    public event System.Action<Waypoints> OnWaypointChanged;

    // Use this for initialization
    void Awake () {

        waypoints = GetWaypoints();

    }

    public void SetNextWaypoint() {

        if (currentWaypointIndex != waypoints.Length)
            currentWaypointIndex++;

        if (currentWaypointIndex == waypoints.Length)
            currentWaypointIndex = 0;

        if (OnWaypointChanged != null)
            OnWaypointChanged(waypoints[currentWaypointIndex]);
        //Debug.Log("OnWaypointChanged == null: " + (OnWaypointChanged == null));
        //Debug.Log("OnWaypointChanged != null: " + (OnWaypointChanged != null));

    }
    Waypoints[] GetWaypoints()
    {
        return GetComponentsInChildren<Waypoints>();

    }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;

        Vector3 previousWaypoint = Vector3.zero;
        foreach (var waypoint in GetWaypoints())
        { 
            Vector3 waypointPosition = waypoint.transform.position; 
            Gizmos.DrawWireSphere(waypointPosition, .2f);
            if (previousWaypoint != Vector3.zero)
                Gizmos.DrawLine(previousWaypoint, waypointPosition);
            previousWaypoint = waypointPosition;
        }
    }
}

вот скрипт EnemyPatrolPoints

using UnityEngine;

[RequireComponent(typeof(AI_PathFinder))]
public class EnemyPatrolPoints : MonoBehaviour {

    [SerializeField]
    WaypointController waypointController;

    [SerializeField]
    float waitTimeMin;

    [SerializeField]
    float waitTimeMax;

    AI_PathFinder pathfinder;

    private void Start()
    {
        waypointController.SetNextWaypoint(); 
    }

    private void Awake()
    {
        pathfinder = GetComponent<AI_PathFinder>();
        pathfinder.OnDestinationReached += Pathfinder_OnDestinationReached;
        waypointController.OnWaypointChanged += WaypointController_OnWaypointChanged;
    }
    private void WaypointController_OnWaypointChanged(Waypoints waypoint)
    {
        pathfinder.SetTarget(waypoint.transform.position);
        print("waypoint changed"); 
    }
    private void Pathfinder_OnDestinationReached()
    {
        SealForce_GameManager.Instance.Timer.Add(waypointController.SetNextWaypoint, Random.Range(waitTimeMin, waitTimeMax));
        print("destination reached"); 
    }   
}

вот скрипт AI Pathfinder`

using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class AI_PathFinder : MonoBehaviour
{

    [HideInInspector]
    public NavMeshAgent agent;
    public EnemyPatrolPoints enemyPatrolPoints;

    [SerializeField] float distanceRemainingThreshold;

    bool m_destinationReached;
    bool destinationReached
    {
        get
        { return m_destinationReached; }

        set
        {
            m_destinationReached = value;

            if (m_destinationReached)
            {
                if (OnDestinationReached != null)
                    OnDestinationReached();
            }
        }
    }

    public event System.Action OnDestinationReached;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        //enemyPatrolPoints = GetComponent<EnemyPatrolPoints>();
    }
    public void SetTarget(Vector3 target)
    {
        agent.SetDestination(target);
    }

    void Update()
    {
        if (destinationReached)
            return;

        if (agent.remainingDistance < distanceRemainingThreshold)
            destinationReached = true;


    }
}

1 Ответ

0 голосов
/ 23 ноября 2018

Линии

if (agent.remainingDistance < distanceRemainingThreshold)
    destinationReached = true;

никогда не достигаются, пока destinationReached равно true из-за

if (destinationReached)
    return;

Вы устанавливаете его на true после первой путевой точкидостигается, а затем никогда не сбрасывается в false, поэтому ваш Update всегда пропускается в будущем.

Вы должны добавить его, например, к

public void SetTarget(Vector3 target)
{
    agent.SetDestination(target);
    destinationReached = false;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...