Exemple #1
0
    private void OnSceneGUI()
    {
        PatrolPath path = (PatrolPath)target;

        Handles.color = Color.yellow;
        if (path.NumPoints > 0)
        {
            for (int i = 0; i < path.NumPoints; i++)
            {
                Vector2 newPos = Handles.FreeMoveHandle(path.pathPoints[i], Quaternion.identity, 0.25f, Vector2.zero, Handles.CylinderHandleCap);
                if (path[i] != newPos)
                {
                    Undo.RecordObject(path, "Move Path Point");
                    path[i] = newPos;
                }
            }
        }


        if (path.NumPoints > 1)
        {
            Handles.color = Color.green;
            for (int i = 1; i < path.NumPoints; i++)
            {
                Handles.DrawLine(path[i - 1], path[i]);
            }

            if (path.loopPath)
            {
                Handles.DrawLine(path[path.NumPoints - 1], path[0]);
            }
        }
    }
Exemple #2
0
        new public PatrolPath getShortestPath(IPoint src, IPoint dest, List <IPoint> availableTiles)
        {
            DistanceMap   distMap            = getDistanceMap(src);
            PatrolPath    reverse            = new PatrolPath();
            valuePoint    vPrevious          = new valuePoint();
            List <IPoint> availableTilesCopy = availableTiles.GetRange(0, availableTiles.Count);

            if (isPointInList(availableTiles, dest))
            {
                //Get last point, add to path,get next, add, etc
                reverse.MyWaypoints.Add(dest);
                vPrevious.p = dest;
                while (!vPrevious.p.equals(src))
                {
                    vPrevious = getPreviousInPath(getValuePoint(distMap.MyPoints, vPrevious.p),
                                                  availableTilesCopy, distMap.MyPoints);
                    if (vPrevious != null && vPrevious.p != null)
                    {
                        reverse.MyWaypoints.Add(vPrevious.p);
                        availableTilesCopy.Remove(availableTilesCopy.Find(delegate(IPoint p) { return(p.equals(vPrevious.p)); }));
                    }
                    else //Ran out of available points before reaching end
                    {
                        return(null);
                    }
                }
                //Reverse path
                reverse.MyWaypoints.Reverse();
            }
            return(reverse);
        }
Exemple #3
0
    public void OnSceneGUI()
    {
        PatrolPath path = target as PatrolPath;

        if ((path.pathNodes == null) || (path.pathNodes.Length <= 0))
        {
            return;
        }

        Vector3[] worldPts = new Vector3[path.pathNodes.Length];

        for (int i = 0; i < path.pathNodes.Length; i++)
        {
            worldPts[i] = path.transform.TransformPoint(path.pathNodes[i]);
            worldPts[i] = Handles.FreeMoveHandle(worldPts[i], Quaternion.identity,
                                                 1.0f, Vector3.one, Handles.DotCap);

            path.pathNodes[i] = path.transform.InverseTransformPoint(worldPts[i]);
        }

        Handles.DrawAAPolyLine(10.0f, worldPts);

        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
Exemple #4
0
    protected void Awake()
    {
        _navMeshAgent = GetComponent <NavMeshAgent>();
        _animator     = GetComponent <Animator>();
        _enemySight   = GetComponent <EnemySight>();
        _patrolPath   = transform.parent.Find("Patrol Path")?.GetComponent <PatrolPath>();

        StateData = new StateData
        {
            Animator                    = _animator,
            Npc                         = gameObject,
            EnemySight                  = _enemySight,
            PatrolPath                  = _patrolPath,
            NavMeshAgent                = _navMeshAgent,
            WalkSpeed                   = walkSpeed,
            RunSpeed                    = runSpeed,
            AccelerationFactor          = accelerationFactor,
            DecelerationFactor          = decelerationFactor,
            DestinationDistanceAccuracy = destinationDistanceAccuracy,
            IsInDebugMode               = debug,
            IdleAtWaypoint              = idleAtWaypoint,
            MinIdleTime                 = minIdleTime,
            MaxIdleTime                 = maxIdleTime,
            CheckLastKnownPosition      = checkLastKnownPosition
        };

        InitCustomStateMachineData();
    }
    public void DrawEnemyPatrol(PatrolPath path)
    {
        List <LineRenderer> patrolPathLines = new List <LineRenderer>();

        for (int i = 0; i < path.pathPatrolGraphNode.Count - 1; i++)
        {
            PatrolManager.PatrolGraphNode node = path.pathPatrolGraphNode[i];
            Vector3 from = new Vector3(path.pathPatrolGraphNode[i].pos.x, 3.0f, path.pathPatrolGraphNode[i].pos.z);
            Vector3 to   = new Vector3(path.pathPatrolGraphNode[i + 1].pos.x, 3.0f, path.pathPatrolGraphNode[i + 1].pos.z);
            patrolLine[0].material = enemyPatrolMat;
            patrolLine[0].enabled  = true;
            patrolLine[0].SetPosition(0, from);
            patrolLine[0].SetPosition(1, to);
            patrolPathLines.Add(patrolLine[0]);
            patrolLine.RemoveAt(0);

            if (!hasInPatrol.ContainsKey(path.pathPatrolGraphNode[i].pos))
            {
                hasInPatrol.Add(path.pathPatrolGraphNode[i].pos, new List <Vector3>());
            }
            hasInPatrol[path.pathPatrolGraphNode[i].pos].Add(path.pathPatrolGraphNode[i + 1].pos);

            if (!hasInPatrol.ContainsKey(path.pathPatrolGraphNode[i + 1].pos))
            {
                hasInPatrol.Add(path.pathPatrolGraphNode[i + 1].pos, new List <Vector3>());
            }
            hasInPatrol[path.pathPatrolGraphNode[i + 1].pos].Add(path.pathPatrolGraphNode[i].pos);
        }
        patrolPathLineDic.Add(path, patrolPathLines);
    }
Exemple #6
0
    // Use this for initialization
    protected void Start()
    {
        enemiesSituation = GameObject.FindGameObjectWithTag("EnemyHandler").GetComponent <EnemiesSituation>();
        health           = GetComponent <Health>();
        stateAction      = Patrol;

        patrolPath = GetComponent <PatrolPath>();
        pathfinder = GetComponent <EnemyPathfinder>();
    }
Exemple #7
0
    public override void OnInspectorGUI()
    {
        PatrolPath path = target as PatrolPath;

        if ((path.pathNodes == null) || (path.pathNodes.Length <= 0))
        {
            path.pathNodes = new Vector3[2];
        }

        List <Vector3> ptList     = new List <Vector3>(path.pathNodes);
        List <Vector3> removeList = new List <Vector3>();

        if (GUILayout.Button("Reset Rotation & Scale"))
        {
            for (int i = 0; i < ptList.Count; ++i)
            {
                ptList[i] = path.transform.TransformPoint(ptList[i]);
            }

            path.transform.localScale    = Vector3.one;
            path.transform.localRotation = Quaternion.identity;

            for (int i = 0; i < ptList.Count; ++i)
            {
                ptList[i] = path.transform.InverseTransformPoint(ptList[i]);
            }
        }

        for (int i = 0; i < ptList.Count; ++i)
        {
            EditorGUILayout.BeginHorizontal();
            ptList[i] = EditorGUILayout.Vector3Field("" + 1, ptList[i]);
            if (GUILayout.Button("-", GUILayout.Width(20)))
            {
                removeList.Add(ptList[i]);
            }
            EditorGUILayout.EndHorizontal();
        }

        if (GUILayout.Button("Add Point"))
        {
            Vector3 newPt = ptList[ptList.Count - 1] + Vector3.one;
            ptList.Add(newPt);
        }

        while (removeList.Count > 0)
        {
            ptList.Remove(removeList[0]);
            removeList.RemoveAt(0);
        }

        if (GUI.changed)
        {
            path.pathNodes = ptList.ToArray();
            EditorUtility.SetDirty(target);
        }
    }
 private void Start()
 {
     if (m_canMove)
     {
         m_path        = GetComponent <PatrolPath>();
         m_destination = m_path.GetPathNodeByIndex(0);
         StartCoroutine(UpdateDestination());
     }
 }
Exemple #9
0
        private static void OnDrawGizmo(PatrolPath path, GizmoType gizmoType)
        {
            var start = path.transform.TransformPoint(path.startPosition);
            var end   = path.transform.TransformPoint(path.endPosition);

            Handles.color = Color.yellow;
            Handles.DrawDottedLine(start, end, 5);
            Handles.DrawSolidDisc(start, path.transform.forward, 0.1f);
            Handles.DrawSolidDisc(end, path.transform.forward, 0.1f);
        }
Exemple #10
0
    public Enemy SpawnEnemyInPatrol(PatrolPath path, PatrolManager patrolManager)
    {
        Debug.Log("spppppppppppppppppawn  ");
        Enemy enemy = freeEnemy[0];

        freeEnemy.RemoveAt(0);
        usedEnemy.Add(enemy);
        enemy.SetPatrolPath(path, patrolManager);
        return(enemy);
    }
Exemple #11
0
    // Start is called before the first frame update
    void Start()
    {
        fov  = GetComponent <FieldOfView>();
        path = GetComponent <PatrolPath>();

        initialPosition = transform.position;
        initialAngle    = transform.eulerAngles.z;

        Reset();
    }
Exemple #12
0
    public void UpdateWaypoints(PatrolPath patrol)
    {
        patrol.waypoints = new Transform[patrol.transform.childCount];
        int i = 0;

        foreach (Transform t in patrol.transform)
        {
            patrol.waypoints[i++] = t;
        }
    }
Exemple #13
0
        static public List <Guard> getGuards(XmlDocument myDoc)
        {
            XmlNode positionNode, positionXNode, positionYNode,
                    patrolNode, wpXNode, wpYNode, orientationNode;
            XmlNodeList guardNodes = myDoc.SelectNodes("Character"),
                        waypointNodes;
            List <Guard> guards = new List <Guard>();
            Guard        _cGuard;
            PatrolPath   _cPath;

            #region READ GUARDS TO LIST
            if (guardNodes != null)
            {
                foreach (XmlNode g in guardNodes)
                {
                    _cGuard = new Guard();
                    _cPath  = new PatrolPath();
                    //Read Position
                    _cGuard.fromXml(g);
                    positionNode  = ((XmlElement)g).SelectNodes("Position")[0];
                    positionXNode = ((XmlElement)positionNode).SelectNodes("X")[0];
                    positionYNode = ((XmlElement)positionNode).SelectNodes("Y")[0];


                    _cGuard.MyPosition = new PointObj(Int32.Parse(positionXNode.InnerText),
                                                      Int32.Parse(positionYNode.InnerText),
                                                      0);
                    //Read Patrol
                    //First, put guard position as first waypoint
                    _cPath.MyWaypoints.Add(_cGuard.MyPosition);

                    //Add rest of waypoints
                    patrolNode = ((XmlElement)g).SelectNodes("Patrol")[0];
                    if (patrolNode != null)
                    {
                        waypointNodes = ((XmlElement)patrolNode).SelectNodes("Waypoint");
                        foreach (XmlElement wp in waypointNodes)
                        {
                            wpXNode = wp.SelectNodes("X")[0];
                            wpYNode = wp.SelectNodes("Y")[0];
                            _cPath.MyWaypoints.Add(new PointObj(Int32.Parse(wpXNode.InnerText),
                                                                Int32.Parse(wpYNode.InnerText),
                                                                0));
                        }
                    }
                    //save patrol in guard
                    _cGuard.getNPCBehavior().setPatrol(_cPath);

                    //Add guard to list
                    guards.Add(_cGuard);
                }
            }
            #endregion
            return(guards);
        }
Exemple #14
0
    public override void OnInspectorGUI()
    {
        PatrolPath myTarget = target as PatrolPath;

        if (GUILayout.Button("Rebuild Path"))
        {
            myTarget.RebuildPath();
        }
        addNodeMode = EditorGUILayout.Toggle("Add Nodes Mode", addNodeMode);
        this.DrawDefaultInspector();
    }
Exemple #15
0
 public static PatrolWalkConfig Default(PatrolPath path, Transform trans)
 {
     return(new PatrolWalkConfig
     {
         path = path,
         trans = trans,
         circular = true,
         forward = true,
         nearDistance = 0.1f,
     });
 }
Exemple #16
0
 private void ShowPath(PatrolPath p, bool show)
 {
     foreach (var ob in p.waypoints)
     {
         if (ob == null)
         {
             continue;
         }
         ob.gameObject.SetActive(show);
     }
 }
Exemple #17
0
    private void DrawPatrol(PatrolPath p)
    {
        var waypoints = p.waypoints;

        if (waypoints == null)
        {
            return;
        }

        Handles.color = p.color;
        GUIStyle style = new GUIStyle();

        style.normal.textColor = p.color;

        var len = waypoints.Length;

        if (len < 2)
        {
            return;
        }

        for (int i = 0; i < waypoints.Length; i++)
        {
            var next = i == len - 1 ? waypoints[0] : waypoints[i + 1];
            var curr = waypoints[i];

            if (curr != null && next != null)
            {
                string text;
                if (showNames)
                {
                    text = $" {i.ToString() } :: {curr.name}";
                }
                else
                {
                    text = i.ToString();
                }

                Handles.DrawLine(curr.transform.position, next.transform.position);
                Handles.SphereHandleCap(i, curr.transform.position, Quaternion.identity, 0.35f, EventType.Repaint);
                if (showLabels)
                {
                    Handles.BeginGUI();
                    Vector3 pos   = curr.transform.position;
                    Vector2 pos2D = HandleUtility.WorldToGUIPoint(pos);
                    var     rect  = new Rect(pos2D.x + labelOffset.x, pos2D.y + labelOffset.y, 100, 100);
                    GUI.Label(rect, text, style);
                    Handles.EndGUI();
                }
            }
        }
    }
    public PatrolState(Enemy owner, StateMachine <Enemy> fsm, PatrolPath patrolPath, float pauseTime = 0.0f)
        : base(owner, fsm)
    {
        this.path               = patrolPath;
        this.seekStates         = null;
        this.currentTargetIndex = -1;
        this.pauseTime          = pauseTime;
        this.patrolPauseTimer   = pauseTime;

        this.rotationSpeed   = DEFAULT_ROTATION_SPEED;
        this.rotationFov     = DEFAULT_FOV;
        this.stopped         = false;
        this.targetDirection = Owner.transform.forward;
    }
Exemple #19
0
 // Start is called before the first frame update
 void Start()
 {
     agent            = GetComponent <NavMeshAgent>();
     patrol           = GetComponent <PatrolPath>();
     fow              = GetComponent <FieldOfView>();
     line             = GetComponent <LineRenderer>();
     actions          = GetComponent <Actions>();
     animator         = GetComponent <Animator>();
     playerController = GetComponent <PlayerController>();
     playerController.SetArsenal("AK-74M");
     player = GameObject.Find("Player");
     characterController = player.GetComponent <CharacterController>();
     allEnemies          = GameObject.FindGameObjectsWithTag("Enemy");
 }
Exemple #20
0
 public PatrolPointArgs(
     WhatHappenedType wht,
     ActorData ad,
     WayPoint pp,
     int index,
     PatrolPath inPath,
     bool dwo)
 {
     whatHappened           = wht;
     characterActor         = ad;
     patrolPoint            = pp;
     patrolPointIndex       = index;
     patrolPath             = inPath;
     destinationWasOccupied = dwo;
 }
        public override void OnEnter()
        {
            base.OnEnter();
            _waitTimer = new Timer(WaitTime.Value);
            if (UsePath)
            {
                //if(PatrolPathGameObject.Value)
                if (PatrolPathGameObject == null)
                {
                    Finish();
                    return;
                }

                _path = PatrolPathGameObject.Value.GetComponent <PatrolPath>();
            }
        }
Exemple #22
0
    public PatrolWalk(PatrolWalkConfig c)
    {
        if (c.trans == null && c.IsNear == null)
        {
            Debug.LogError("Patrol walk needs transform or IsNear function");
        }

        last       = c.path.waypoints.Length - 1;
        startIndex = Mathf.Clamp(c.startIndex, 0, last);
        IsNear     = c.IsNear ?? DefaultIsNear;
        wayIndex   = startIndex;

        path         = c.path;
        trans        = c.trans;
        nearDistance = c.nearDistance;
        circular     = c.circular;
        forward      = c.forward;
    }
Exemple #23
0
        protected override void Initialize()
        {
            capsule      = GetComponent <CapsuleCollider>();
            patrol       = GetComponent <PatrolPath>();
            agent        = GetComponent <DungeonNavAgent>();
            lastSighting = GetComponent <LastPlayerSighting>();

            State startState = null;

            if (hasPatrolling)
            {
                startState = new AIStatePatrol(this);
            }
            else
            {
                startState = new AIStateIdle(this);
            }

            stateMachine.MoveTo(startState);
        }
    public void initFromSpawner(Spawner spawner)
    {
        endCondition   = BehaviorChangeConditions.NA;
        mySpawner      = spawner;
        currTgtWpIndex = 1;
        isPostPath     = false;

        //Positionning enemy at the first waypoint's coordinates
        if (mySpawner != null)
        {
            path        = mySpawner.path;
            rb.position = transform.position = path.wayPoints[0].position;
        }

        //Orienting enemy in the direction of the path, if there are more than one waypoints
        //if (path.Length > 1)
        //{
        //	transform.LookAt(path[currTargetIndex]);
        //	rb.rotation = transform.eulerAngles.z;
        //}
    }
Exemple #25
0
    public void OnSceneGUI()
    {
        Event current   = Event.current;
        int   controlID = GUIUtility.GetControlID(this.GetHashCode(), FocusType.Passive);

        switch (current.GetTypeForControl(controlID))
        {
        case EventType.MouseDown:
            if (addNodeMode && current.button == 0)
            {
                GUIUtility.hotControl = controlID;
                PatrolPath myTarget = target as PatrolPath;
                Ray        worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                RaycastHit hitInfo;

                if (Physics.Raycast(worldRay, out hitInfo))
                {
                    Vector3    loc  = new Vector3(hitInfo.point.x, Mathf.Round(hitInfo.point.y), hitInfo.point.z);
                    PatrolNode node = Instantiate(myTarget.nodeType, loc, Quaternion.identity) as PatrolNode;
                    node.name             = "Patrol Node (" + myTarget.Path.Count + ")";
                    node.transform.parent = myTarget.transform;
                }
                current.Use();
            }
            break;

        case EventType.MouseUp:
            if (addNodeMode && current.button == 0)
            {
                GUIUtility.hotControl = 0;
                current.Use();
            }
            break;
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
Exemple #26
0
    public override void OnInspectorGUI()
    {
        PatrolPath path = (PatrolPath)target;

        //Add a button that will add new waypoints
        if (GUILayout.Button("Add Waypoint"))
        {
            //Call Start() on the path so its waypoint data is initialised
            path.Start();

            //Create the new object to house our waypoint
            GameObject newWaypoint = new GameObject();
            newWaypoint.name                    = "Waypoint" + path.Size();
            newWaypoint.transform.parent        = path.transform;
            newWaypoint.transform.localPosition = Vector3.zero;
            //Create the waypoint component instance
            PatrolPathWaypoint waypoint = newWaypoint.AddComponent <PatrolPathWaypoint>();
            waypoint.orderInSequence = path.Size();
            //Add it to the path!
            path.AddWaypoint(waypoint);
        }
    }
Exemple #27
0
    // Use this for initialization
    void Start()
    {
        // Get access to the unit we are controlling
        unit = GetComponent <Unit>();

        // Install an on death function to remove all logic from the unit
        unit.installDeathListener(delegate() { root = new Leaf(delegate() { return(BehaviorReturnCode.Success); }); });

        ////////////////////////////////////////////////////////////////////
        /////////////////////   PATROLLING/IDLE   //////////////////////////
        ////////////////////////////////////////////////////////////////////

        Leaf checkIsPatrolling = new Leaf(delegate()
        {
            if (unit.patrolling == false)
            {
                return(BehaviorReturnCode.Failure);
            }

            return(BehaviorReturnCode.Success);
        });

        Leaf patrolPath = new Leaf(delegate()
        {
            // Check if we have a patrol path to make use of
            PatrolPath path = unit.GetComponent <PatrolPath>();
            if (path != null)
            {
                unit.setDestination(path.patrolPointHolder.transform.GetChild(path.nextPatrolPoint()).position);
                unit.patrolling = true;
                return(BehaviorReturnCode.Success);
            }
            return(BehaviorReturnCode.Failure);
        });

        Leaf patrolArea = new Leaf(delegate()
        {
            // If we have a patrol area use that to find our random position
            PatrolArea area = unit.GetComponent <PatrolArea>();
            if (area == null)
            {
                return(BehaviorReturnCode.Failure);
            }

            // Generate our patrol position
            Vector3 newTargetPosition = Vector3.zero;
            Vector3 patrolPosition    = area.patrolAreaObject.transform.position;
            float patrolRange         = area.patrolAreaObject.transform.localScale.x;
            if (unit.findRandomPointOnNavMesh(patrolPosition, patrolRange, out newTargetPosition))
            {
                // Start moving towards our new random point
                unit.setDestination(newTargetPosition);
                unit.patrolling = true;
                return(BehaviorReturnCode.Success);
            }
            return(BehaviorReturnCode.Failure);
        });

        Leaf manualPatrol = new Leaf(delegate()
        {
            // Check to see if the unit manually patrols
            ManualPatrol manualPatrolling = unit.GetComponent <ManualPatrol>();
            if (manualPatrolling == null)
            {
                return(BehaviorReturnCode.Failure);
            }

            // If the unit manually patrols wait for a new patrol position
            if (manualPatrolling.getPatrolConsumed())
            {
                return(BehaviorReturnCode.Running);
            }

            // If we have a new patrol position consume it
            unit.setDestination(manualPatrolling.getPatrolPosition());
            unit.patrolling = true;
            return(BehaviorReturnCode.Success);
        });

        Leaf patrolFollowLeader = new Leaf(delegate()
        {
            // Check to see if the unit has a leader to follow
            FollowLeader leaderToFollow = unit.GetComponent <FollowLeader>();
            if (leaderToFollow == null)
            {
                return(BehaviorReturnCode.Failure);
            }

            // If the unit has a leader follow it but don't start patrolling.  This allows
            // the unit to continuously follow the leader as it moves.
            unit.setDestination(leaderToFollow.getFollowPosition());
            return(BehaviorReturnCode.Success);
        });

        Leaf patrolRandom = new Leaf(delegate()
        {
            // If we don't have a defined path generate a random position
            Vector3 patrolCenterPosition = transform.position;
            float patrolRange            = unit.patrolSearchRange;
            Vector3 newTargetPosition    = Vector3.zero;

            // Generate our patrol position
            if (unit.findRandomPointOnNavMesh(patrolCenterPosition, patrolRange, out newTargetPosition))
            {
                // Start moving towards our new random point
                unit.setDestination(newTargetPosition);
                unit.patrolling = true;
                return(BehaviorReturnCode.Success);
            }
            return(BehaviorReturnCode.Failure);
        });

        Selector selectPatrolPath = new Selector(checkIsPatrolling, patrolPath, patrolArea, manualPatrol, patrolFollowLeader, patrolRandom);

        Leaf sendPatrolToSquad = new Leaf(delegate()
        {
            SquadLeader squad = unit.GetComponent <SquadLeader>();
            if (squad == null)
            {
                return(BehaviorReturnCode.Success);
            }

            // If the unit is part of a squad inform the subordinates of a new patrol position
            squad.issueNewTroopMovement();
            return(BehaviorReturnCode.Success);
        });

        Leaf waitToReachDestination = new Leaf(delegate()
        {
            if (unit.isMovingNavMesh() && unit.patrolling)
            {
                return(BehaviorReturnCode.Running);
            }
            // If the unit is a follower then don't bother waiting to reach a destination
            else if (unit.GetComponent <FollowLeader>() != null)
            {
                return(BehaviorReturnCode.Failure);
            }
            else
            {
                return(BehaviorReturnCode.Success);
            }
        });

        Leaf stopRunning = new Leaf(delegate()
        {
            unit.anim.SetBool("Running", false);
            unit.agent.isStopped = true;
            return(BehaviorReturnCode.Success);
        });

        Leaf playIdleAnim = new Leaf(delegate()
        {
            unit.anim.SetTrigger("PatrolIdleAnim1Trigger");
            return(BehaviorReturnCode.Success);
        });

        RandomBehavior idleRand = new RandomBehavior(.1f, playIdleAnim);

        Timer playIdleAnimTimer = new Timer(1.0f, idleRand);

        Leaf stopPatrolling = new Leaf(delegate()
        {
            unit.patrolling = false;
            return(BehaviorReturnCode.Success);
        });

        Timer stopPatrollingTimer = new Timer(unit.patrolWaitTime, stopPatrolling);

        StateSequence patrolLogic = new StateSequence(selectPatrolPath, sendPatrolToSquad, waitToReachDestination, stopRunning, playIdleAnimTimer, stopPatrollingTimer);

        ////////////////////////////////////////////////////////////////////
        /////////////////////   AGGRO/ATTACKING   //////////////////////////
        ////////////////////////////////////////////////////////////////////

        Leaf dropTargetLogic = new Leaf(delegate()
        {
            // If we don't have a target continue
            if (unit.target == null)
            {
                return(BehaviorReturnCode.Success);
            }

            // If our target is dying search for a new one
            if (unit.target.isUnitDying())
            {
                unit.target = null;
            }
            // If our target it outside of our aggro radius clear it
            if (unit.distanceToTarget() > unit.enemySearchRadius)
            {
                unit.target = null;
            }

            return(BehaviorReturnCode.Success);
        });

        Leaf acquireTarget = new Leaf(delegate()
        {
            // If we already have a living target just return success
            if (unit.target != null)
            {
                return(BehaviorReturnCode.Success);
            }

            // Search for the closest enemy
            IUnit foundTarget = unit.findClosestTarget();

            // If we were able to find a target return success, otherwise we failed
            if (foundTarget != null)
            {
                // If we find a new target stop patrolling
                unit.patrolling = false;
                unit.target     = foundTarget;
                return(BehaviorReturnCode.Success);
            }
            else
            {
                return(BehaviorReturnCode.Failure);
            }
        });

        Leaf checkToAttack = new Leaf(delegate()
        {
            // If we are already attacking continue
            if (unit.attacking)
            {
                return(BehaviorReturnCode.Success);
            }

            // Check if our target is within the attack radius and isn't already dying
            if (unit.distanceToTarget() <= unit.attackRadius)
            {
                // Face the target
                Quaternion lookRot      = Quaternion.LookRotation(unit.target.getGameObject().transform.position - unit.transform.position);
                unit.transform.rotation = Quaternion.Euler(0, lookRot.eulerAngles.y, 0);

                // Stop the navmesh agent
                unit.agent.isStopped = true;
                // Stop running
                unit.anim.SetBool("Running", false);
                // Play our attack animation
                unit.anim.SetTrigger("AttackTrigger");
                unit.attacking = true;
            }
            else
            {
                unit.attacking = false;
            }
            return(BehaviorReturnCode.Success);
        });

        Leaf moveToTarget = new Leaf(delegate()
        {
            // If we're still attacking wait to finish
            if (unit.attacking == true)
            {
                return(BehaviorReturnCode.Success);
            }

            // Start moving towards our target
            unit.setDestination(unit.target.getGameObject().transform.position);
            return(BehaviorReturnCode.Success);
        });

        Sequence attackSequence = new Sequence(dropTargetLogic, acquireTarget, checkToAttack, moveToTarget);

        ////////////////////////////////////////////////////////////////////
        //////////////////////////   ROOT   ////////////////////////////////
        ////////////////////////////////////////////////////////////////////

        root = new Selector(attackSequence, patrolLogic);
    }
Exemple #28
0
 void MoveNodesOnTransformChange(PatrolPath pp)
 {
     Vector3 delta = pp.transform.position - lastPosition;
     for (int i = 0; i < pp.points.Count; i++)
     {
         pp.points[i].position = pp.points[i].position + delta;
     }
     lastPosition = pp.transform.position;
 }
Exemple #29
0
 public void setPatrol(PatrolPath _patrol)
 {
     throw new NotImplementedException();
 }
Exemple #30
0
 public override void InitializePatrolPath()
 {
     PatrolPath = _algorithm.CalculatePath(StartCell, _level.Map[8, 27], _level.Map);
     PatrolPath.AddRange(_algorithm.CalculatePath(_level.Map[8, 27], _level.Map[12, 30], _level.Map));
     PatrolPath.AddRange(_algorithm.CalculatePath(_level.Map[12, 30], StartCell, _level.Map));
 }
Exemple #31
0
 public Mover(PatrolPath path, float speed)
 {
     this.path      = path;
     this.duration  = (path.endPosition - path.startPosition).magnitude / speed;
     this.startTime = Time.time;
 }
Exemple #32
0
 public void Restart()
 {
     currentStep = 1;
     linkedSpawnPath = null;
 }