Ejemplo n.º 1
0
    private void OnPathRequest(Event <PathRequestEventPayload> eventArg)
    {
        if (searchSpace == null)
        {
            return;
        }

        PathRequestEventPayload request = eventArg.EventData;

        if (request.gameObject != searchSpace.gameObject)
        {
            return;             // request not for us
        }

        MovingEntity movingEntity        = request.gameObject.GetComponent <MovingEntity>();
        Vector2      requestorPosition2D = (movingEntity != null && movingEntity.enabled) ? movingEntity.Position2D : request.gameObject.transform.position.To2D();

        int source = searchSpace.GetClosestNodeToPosition(requestorPosition2D);

        if (source != Node.INVALID_NODE_INDEX)
        {
            // Requestor may be inside or too close to obstruction
            // so let's find the closest node to warp to
            source = searchSpace.GetClosestNodeToPosition(requestorPosition2D, true);
            if (source == SearchSpace.NO_CLOSEST_NODE_FOUND)
            {
                return; // screwed
            }
        }

        int target = searchSpace.GetClosestNodeToPosition(request.destination);

        if (target == SearchSpace.NO_CLOSEST_NODE_FOUND)
        {
            ////TODO: should we instead move the target to closest valid node??
            return;
        }

        var currentSearch = new AStarSearch(searchSpace.Graph, source, target);

        var path = new Path(
            this,
            searchSpace.gameObject,
            requestorPosition2D,
            request.destination,
            currentSearch.GetPathToTarget(),
            searchSpace.Graph);

        PathReadyEventPayload result =
            new PathReadyEventPayload(request.gameObject, path);

        EventManager.Instance.Enqueue <PathReadyEventPayload>(Events.PathReady, result);
    }