コード例 #1
0
    //Update any objects with input here
    void Update()
    {
        controller.UpdateController();

        if (Input.GetKeyDown(KeyCode.L))
        {
            waypointGraph.ShortestPath(waypointA, waypointB);
        }
    }
コード例 #2
0
    IEnumerator ReturnToPatrol()
    {
        state = EnemyState.RETURNING;

        RaycastHit2D[] hitArray;
        string[]       layers = { "Enemy", "LightWalls" };
        LayerMask      mask   = LayerMask.GetMask(layers);

        Transform closestWaypoint = null;

        for (int i = 0; i < waypointGraph.waypoints.childCount; i++)
        {
            Transform current = waypointGraph.waypoints.GetChild(i);
            Vector2   rayDir  = this.transform.position - current.position;
            hitArray = Physics2D.RaycastAll(current.position, rayDir, 1000, mask);


            for (int j = 0; j < hitArray.Length && hitArray[j].transform.tag != "Wall"; j++)
            {
                if (hitArray[j].transform == this.transform)
                {
                    if (closestWaypoint == null)
                    {
                        closestWaypoint = current;
                    }
                    else
                    {
                        float currentDistance = (current.position - this.transform.position).magnitude;
                        float closestDistance = (closestWaypoint.position - this.transform.position).magnitude;

                        if (currentDistance < closestDistance)
                        {
                            closestWaypoint = current;
                        }
                    }
                }
            }
        }

        while ((Vector2)this.transform.position != (Vector2)closestWaypoint.position && state == EnemyState.RETURNING)
        {
            WalkTowards(closestWaypoint.position);

            yield return(null);
        }

        Transform targetNode = patrolPath[0];
        LinkedList <Transform> shortestPath = waypointGraph.ShortestPath(closestWaypoint, targetNode);

        while (shortestPath.Count > 0 && state == EnemyState.RETURNING)
        {
            Vector2 toPosition = shortestPath.First.Value.position;

            while ((Vector2)this.transform.position != toPosition && state == EnemyState.RETURNING)
            {
                WalkTowards(toPosition);

                yield return(null);
            }

            shortestPath.RemoveFirst();

            if (shortestPath.Count > 0)
            {
                toPosition = shortestPath.First.Value.position;
            }
        }

        if ((Vector2)this.transform.position == (Vector2)targetNode.position)
        {
            StartCoroutine("Patrol");
        }
    }