Esempio n. 1
0
    public void SetDestination(Vector2 dest)
    {
        //Cancel path if existing
        if (seeker.GetCurrentPath() != null)
        {
            seeker.CancelCurrentPathRequest();
        }

        if (target != null)
        {
            target = null;
        }
        if (oldTarget != null)
        {
            oldTarget = null;
        }

        this.oldDestination = this.destination;
        this.destination    = dest;

        if (this.destination != this.oldDestination)
        {
            atDestination = false;
            canMove       = true;
        }

        InvokeRepeating("UpdatePath", 0f, 0.5f);
    }
    void Update()
    {
        isPathDone = seeker.IsDone();

        Vector3 dirToTarget = player.transform.position - transform.position;
        float   angle       = Vector3.SignedAngle(dirToTarget, transform.forward, Vector3.up);

        //if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
        //{

        if (currentAction == Action.Attack && isPathDone)
        {
            seeker.GetCurrentPath().Error();
            seeker.StartPath(transform.position, player.transform.position, OnPathComplete);
            playWalk(angle);
        }

        if (currentPath != null && !PathUtilities.IsPathPossible(currentPath.path))
        {
            richAI.SearchPath();
            Debug.Log("get back here!");
        }

        if (!richAI.pathPending && richAI.reachedEndOfPath && isPathDone)
        {
            playIdle(angle);
            if (!isCoroutineRunning)
            {
                if (currentAction == Action.Seeking)
                {
                    StartCoroutine(seekWait(angle));
                    isCoroutineRunning = true;
                }
                else if (currentAction == Action.Patrolling)
                {
                    if (points[(int)nfmod(destPoint - 1, points.Length)].CompareTag("Finish"))
                    {
                        alerted       = true;
                        currentAction = Action.Seeking;
                    }
                    else
                    {
                        StartCoroutine(patrollWait(angle));
                        isCoroutineRunning = true;
                    }
                }
            }
        }
        else
        {
            playWalk(angle);
        }

        //}
        //else
        //{
        //    nav.enabled = false;
        //}
    }
	public void OnDisable()
	{
		if (seeker != null && !seeker.IsDone()) seeker.GetCurrentPath().Error();
		
		if (path != null) path.Release(this);
		path = null;
		
		seeker.pathCallback -= OnPathComplete;
	}
Esempio n. 4
0
        public void UpdatePath(Seeker seeker)
        {
            Path path = seeker.GetCurrentPath();

            if (path != null)
            {
                Debug.Log("Path Count: " + path.vectorPath.Count);
            }
        }
Esempio n. 5
0
 static int GetCurrentPath(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         Seeker           obj = (Seeker)ToLua.CheckObject <Seeker>(L, 1);
         Pathfinding.Path o   = obj.GetCurrentPath();
         ToLua.PushObject(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Esempio n. 6
0
    public void OnDisable()
    {
        // Abort calculation of path
        if (seeker != null && !seeker.IsDone())
        {
            seeker.GetCurrentPath().Error();
        }

        // Release current path
        if (path != null)
        {
            path.Release(this);
        }
        path = null;

        //Make sure we receive callbacks when paths complete
        seeker.pathCallback -= OnPathComplete;
    }
Esempio n. 7
0
    private void HandleRotation()
    {
        Path currentPath = seeker.GetCurrentPath();

        if (currentPath == null)
        {
            return;
        }
        if (currentWaypoint >= currentPath.vectorPath.Count)
        {
            RotateTo(playerController.transform.position);
            return;
        }

        RotateTo(currentPath.vectorPath[currentWaypoint]);
        if (Vector3.Distance(transform.position, currentPath.vectorPath[currentWaypoint]) < maxWaypointDistance)
        {
            currentWaypoint++;
        }
    }
Esempio n. 8
0
    public override void OnExit()
    {
        EventDispatcher.RemoveEventListener(EventID.ACTOR_PROPERTY_CHANGE, OnActorPropertyChange);
        if (_seeker == null)
        {
            return;
        }

        // 停止当前的寻路
        if (!_seeker.IsDone())
        {
            _seeker.GetCurrentPath().Error();
        }

        // 释放当前路径
        if (_path != null)
        {
            _path.Release(this);
            _path = null;
        }
    }
Esempio n. 9
0
        /// <summary>
        /// Raises the disable event.
        /// </summary>
        public void OnDisable()
        {
            // Abort calculation of path
            if (Seeker != null && !Seeker.IsDone())
            {
                Seeker.GetCurrentPath().Error();
            }

            // Release current path
            if (m_Path != null)
            {
                m_Path.Release(this);
            }

            m_Path = null;
            Seeker.pathCallback -= OnPathComplete;

            m_Controller.Creature.Move.OnTargetMovePositionReached -= OnTargetMovePositionReached;
            m_Controller.Creature.Move.OnMoveComplete       -= OnMoveComplete;
            m_Controller.Creature.Move.OnUpdateMovePosition -= OnMoveUpdatePosition;
        }
Esempio n. 10
0
    public void SetTarget(Transform t)
    {
        //Cancel path if existing
        if (seeker.GetCurrentPath() != null)
        {
            seeker.CancelCurrentPathRequest();
        }

        //destination = nullVector;
        //oldDestination = nullVector;
        this.oldTarget = this.target;
        this.target    = t;

        if (this.target != this.oldTarget)
        {
            //Debug.Log("test");
            atDestination = false;
            canMove       = true;
        }
        CancelInvoke("UpdatePath");
        InvokeRepeating("UpdatePath", 0f, 0.5f);
    }
Esempio n. 11
0
        IEnumerator WaitForPathComplete()
        {
            while (ai.pathPending)
            {
                yield return(null);
            }

            // Проверяем, не стоит ли ИИ на клетке, по которой щёлкнули.
            List <GraphNode> path    = seeker.GetCurrentPath().path;
            Vector3          pathEnd = (Vector3)path[path.Count - 1].position;

            if (Vector3.Distance(ai.position, pathEnd) > ai.endReachedDistance)
            {
                // Если не стоит, то движемся.
                ai.canMove = true;
            }
            else
            {
                // Если стоит, то удаляем путь и не движемся.
                ai.enabled            = false;
                ai.enabled            = true;
                CurrentMovementTarget = null;
                if (WentToDestination != null)
                {
                    WentToDestination.Invoke();
                }
                if (ReachedDestination != null)
                {
                    ReachedDestination.Invoke();
                }
                yield break;
            }

            if (WentToDestination != null)
            {
                WentToDestination.Invoke();
            }
            StartCoroutine(WaitForDestinationReached());
        }
Esempio n. 12
0
    public void OnDisable()
    {
        // Abort calculation of path
        if (seeker != null && !seeker.IsDone())
        {
            seeker.GetCurrentPath().Error();
        }

        // Release current path
        if (path != null)
        {
            path.Release(this);
        }
        path = null;

        mDestination = INIT_DEST;

        //Make sure we receive callbacks when paths complete
        seeker.pathCallback -= OnPathComplete;

        keepLoop = false;
        StopAllCoroutines();
    }
Esempio n. 13
0
    /// <summary>\copydoc Pathfinding::IAstarAI::SetPath</summary>
    public void SetPath(Path path)
    {
        if (path == null)
        {
            ClearPath();
        }
        else if (path.PipelineState == PathState.Created)
        {
            // Path has not started calculation yet
            lastRepath     = Time.time;
            canSearchAgain = false;
            seeker.CancelCurrentPathRequest();
            seeker.StartPath(path);
        }
        else if (path.PipelineState == PathState.Returned)
        {
            // Path has already been calculated

            // We might be calculating another path at the same time, and we don't want that path to override this one. So cancel it.
            if (seeker.GetCurrentPath() != path)
            {
                seeker.CancelCurrentPathRequest();
            }
            else
            {
                throw new System.ArgumentException("If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.");
            }

            OnPathComplete(path);
        }
        else
        {
            // Path calculation has been started, but it is not yet complete. Cannot really handle this.
            throw new System.ArgumentException("You must call the SetPath method with a path that either has been completely calculated or one whose path calculation has not been started at all. It looks like the path calculation for the path you tried to use has been started, but is not yet finished.");
        }
    }
Esempio n. 14
0
    void UpdatePosition()
    {
        float s = speed * speedMult;

        if (!canMove)
        {
            return;
        }

        if (currentState > walking || !isMoving)
        {
            return;                                        //We have to be walking!
        }
        if (seeker.IsDone())
        {
            path           = seeker.GetCurrentPath();
            wayPointNumber = 0;
        }
        if (path == null || path.error)
        {
            return;
        }

        Vector3 newPosition = Vector3.zero;

        //if we are close enough to our target or not
        if ((this.transform.position - targetPosition).magnitude <= s * Time.deltaTime + 0.001f)
        {
            newPosition = targetPosition;
            finishedPath();
        }
        //else  newPosition = this.transform.position + direction * s * Time.deltaTime;
        else
        {
            float myDist     = 0;
            int   myWayPoint = wayPointNumber;
            while (myDist < s * Time.deltaTime)
            {
                newPosition = path.vectorPath[wayPointNumber];
                float d = (transform.position - newPosition).magnitude;
                if (d < s * Time.deltaTime - myDist)
                {
                    Vector3 off = (newPosition - transform.position);
                    off.Normalize();
                    off           *= d;
                    newPosition    = newPosition += off;
                    wayPointNumber = myWayPoint;
                }
                else
                {
                    newPosition = path.vectorPath[myWayPoint];
                    myDist     += d;
                    ++myWayPoint;
                }
            }
        }
        Vector3 dir = newPosition - transform.position;

        direction = dir;
        direction.Normalize();


        //finding obstacles (collisions).
        RaycastHit2D[] hits      = Physics2D.GetRayIntersectionAll(Camera.main.ScreenPointToRay(Camera.main.WorldToScreenPoint(newPosition)));
        bool           collision = false;

        foreach (RaycastHit2D hit in hits)
        {
            if (hit.collider.gameObject.tag == "Obstacle")
            {
                collision = true;
                break;
            }
        }
        if (!collision)
        {
            this.transform.position = newPosition;           //Everything goes smoothly.
        }
        //Stop if collision of close enough to target.

        Vector3 dif = targetPosition - this.transform.position;

        if (collision || (dif.magnitude < 0.25 && Vector3.Dot(dif, direction) < Mathf.Epsilon))
        {
            isMoving = false;
            SetCurrentState(walking, false);
        }
    }
Esempio n. 15
0
    private void Update()
    {
        GameObject closestTarget = null;
        float      closestDist   = 1e5f;

        foreach (var enemy in myTargets.ToList())
        {
            if (enemy == null)
            {
                myTargets.Remove(enemy);
                continue;
            }

            var dist = Vector2.Distance(transform.position, enemy.transform.position);
            if (dist < closestDist)
            {
                closestDist   = dist;
                closestTarget = enemy;
            }
        }

        if (closestTarget != null)
        {
            var hit = Physics2D.Raycast(transform.position, closestTarget.transform.position - transform.position, 1000,
                                        myAttackComponent.CollisionMask);
            if (hit.collider != null && hit.collider.gameObject == closestTarget)
            {
                Vector2 moveDirection = closestTarget.transform.position - transform.position;
                if (moveDirection != Vector2.zero)
                {
                    float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
                    transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
                }

                if (hit.distance < myAttackComponent.Weapon.AttackRange)
                {
                    myAttackComponent.TryAttackTarget(closestTarget);
                }
                else
                {
                    Move(moveDirection.normalized);
                }
                return;
            }
        }

        if (myAttackComponent.IsAttacking)
        {
            myRigidbody2D.velocity = Vector2.zero;
            return;
        }

        if (myPath == null || myPath.vectorPath.Count == 0 || Vector2.Distance(myPath.vectorPath[myCurrentWaypoint], transform.position) > 2)
        {
            myPath = null;

            if (mySeeker.GetCurrentPath().PipelineState > PathState.Processing)
            {
                mySeeker.StartPath(transform.position, SessionManager.Instance.HQPosition, path => {
                    if (path.error)
                    {
                        Debug.Log(path.errorLog, this);
                        return;
                    }

                    myPath            = path;
                    myCurrentWaypoint = 0;
                });
            }

            var hqHit = Physics2D.Raycast(transform.position, (Vector3)SessionManager.Instance.HQPosition - transform.position, 1000,
                                          myAttackComponent.CollisionMask);
            if (hqHit.collider != null)
            {
                myAttackComponent.TryAttackTarget(hqHit.collider.gameObject);
            }

            return;
        }

        float distanceToWaypoint;

        while (true)
        {
            distanceToWaypoint = Vector3.Distance(transform.position, myPath.vectorPath[myCurrentWaypoint]);
            if (distanceToWaypoint < nextWaypointDistance)
            {
                if (myCurrentWaypoint + 1 < myPath.vectorPath.Count)
                {
                    myCurrentWaypoint++;
                }
                else
                {
                    myPath = null;
                    return;
                }
            }
            else
            {
                break;
            }
        }

        Vector2 moveDir = myPath.vectorPath[myCurrentWaypoint] - transform.position;

        var wallHit = Physics2D.Raycast(transform.position, moveDir.normalized, 2,
                                        myAttackComponent.CollisionMask);

        if (wallHit.collider != null)
        {
            myAttackComponent.TryAttackTarget(wallHit.collider.gameObject);
        }

        Move(moveDir.normalized);
    }