Ejemplo n.º 1
0
        private void Update()
        {
            if (!photonView.isMine)
            {
                return;
            }

            //Move along path
            if (path.corners.Length > 0)
            {
                Vector3 corner = path.corners[currentCorner];
                transform.position = Vector3.MoveTowards(transform.position, corner, moveSpeed * Time.deltaTime);

                //Turn the agent
                Vector3 direction = (corner - transform.position).normalized;
                if (direction.magnitude > 0f)
                {
                    Quaternion targetDir = Quaternion.LookRotation(direction);
                    transform.rotation = Quaternion.Slerp(transform.rotation, targetDir, Time.deltaTime * rotationSpeed);
                }

                //Update corner
                if (Vector3.Distance(transform.position, corner) < 0.05f)
                {
                    transform.position = corner;
                    currentCorner++;
                }

                if (currentCorner >= path.corners.Length)
                {
                    path.ClearCorners();
                }
            }
        }
Ejemplo n.º 2
0
        public void Reset()
        {
            _controllable = true;
            _grounded     = false;

            speedPercent          = 1;
            _speed                = 0;
            _velocity             = Vector3.zero;
            _fall_start           = 0;
            _last_position        = Vector3.zero;
            _wanted_position      = Vector3.zero;
            _last_wanted_position = Vector3.zero;
            select                = null;

            canBack = true;

            if (path != null)
            {
                path.ClearCorners();
            }
            pathIndex         = 0;
            curPathDistance   = 0;
            _isMovingToTarget = false;
            _isNavJumping     = false;

            prevCalculateY = GetLayerCollisionY(m_transform.position) + 0.1f;
        }
Ejemplo n.º 3
0
        // 计算寻路轨迹 add by TangJian 2017/11/08 12:44:22
        public Vector3[] CalculPath(Vector3 position)
        {
            // 捕获异常, 防止无限计算路径 add by TangJian 2018/11/20 15:57
            try
            {
                navMeshPath.ClearCorners();

                NavMeshAgentEnable();

                if (navMeshAgent.isActiveAndEnabled)
                {
                    if (navMeshAgent.isOnNavMesh)
                    {
                        navMeshAgent.updatePosition = false;
                        navMeshAgent.updateRotation = false;
                        navMeshAgent.updateUpAxis   = false;

                        navMeshAgent.Warp(selfController.transform.position);

                        if (navMeshAgent.CalculatePath(position, navMeshPath))
                        {
                            return(navMeshPath.corners);
                        }
                    }
                    else
                    {
                        NavMeshHit hit;
                        if (NavMesh.SamplePosition(transform.position, out hit, 5, NavMesh.AllAreas))
                        {
                            return(new Vector3[] { hit.position });
                        }
                    }
                }

#if UNITY_EDITOR
                // 绘制寻路轨迹 add by TangJian 2017/11/08 12:44:05
                DebugManager.Instance.AddDrawGizmos(gameObject.GetInstanceID() + "CalculPath", () =>
                {
                    for (int i = 0; i < navMeshPath.corners.Length; i++)
                    {
                        if (i > 0)
                        {
                            var from = navMeshPath.corners[i - 1];
                            var to   = navMeshPath.corners[i];
                            Gizmos.DrawLine(from, to);
                        }
                    }
                });
#endif
            }
            catch (System.Exception e)
            {
                Debug.LogWarning(e);
            }

            return(navMeshPath.corners);
        }
Ejemplo n.º 4
0
Archivo: Animal.cs Proyecto: okoz/ld32
    private void AngryIdle(StateMachine machine)
    {
        path.ClearCorners();
        if (lineRenderer != null)
        {
            lineRenderer.SetVertexCount(0);
        }

        machine.SetState("Angry");
    }
Ejemplo n.º 5
0
    private void Update()
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo))
        {
            Debug.Log("true");
            if (Input.GetMouseButtonDown(0))
            {
                //m_Agent.Stop();
                _lineRenderer.gameObject.SetActive(true);
                if (!IsCalulatePath)
                {
                    Vect3.Clear();
                    _lineRenderer.positionCount = 0;
                    path.ClearCorners();
                    StartPoint = m_HitInfo.point;
                }
                else
                {
                    EndPoint = m_HitInfo.point;
                    CalculatePath(StartPoint, EndPoint);
                }
                IsCalulatePath = !IsCalulatePath;
            }
        }
    }
Ejemplo n.º 6
0
    public int FindNextClosest()
    {
        GameObject[] gameArr = null;
        agent.ResetPath();
        int         chosen        = 0;
        NavMeshPath path          = new NavMeshPath();
        float       minPathLength = 99999.0f;

        switch (targetObject.tag)
        {
        case "CoffeMachine":
            gameArr = coffeeMachines;
            break;

        case "Workstation":
            gameArr       = workStations;
            chosen        = (int)(UnityEngine.Random.value * (workStations.Length));
            minPathLength = -1;
            //workStations[(int))].transform;
            break;

        case "Toilet":     //TODO not implemented yet
            gameArr = toiletPosistions;
            break;

        case "Sink":     //TODO not implemented yet
            gameArr = sinks;
            break;
        }

        //Loop trough all objects
        for (int i = 0; i < gameArr.Length; i++)
        {
            if (gameArr[i].transform != targetObject.transform)
            {
                path.ClearCorners();
                float pathL = 0.0f;
                //Calculate the path
                agent.CalculatePath(GetObjectFront(gameArr[i].transform), path);

                //If path is valid
                if (true || path.status == NavMeshPathStatus.PathComplete)
                {
                    //Calc the leght of the path
                    for (int j = 1; j < path.corners.Length; ++j)
                    {
                        pathL += Vector3.Distance(path.corners[j - 1], path.corners[j]);
                    }
                    //If this path is shorter than the current min set it as the current destiantion
                    if (pathL < minPathLength)
                    {
                        minPathLength = pathL;
                        chosen        = i;
                    }
                }
            }
        }
        targetObject = gameArr[chosen];
        return(chosen);
    }
Ejemplo n.º 7
0
    public int FindClosest(GameObject[] gameArr)
    {
        agent.ResetPath();
        int         chosen        = 0;
        NavMeshPath path          = new NavMeshPath();
        float       minPathLength = 99999.0f;

        //Loop trough all objects
        for (int i = 0; i < gameArr.Length; i++)
        {
            path.ClearCorners();
            float pathL = 0.0f;
            //Calculate the path
            agent.CalculatePath(GetObjectFront(gameArr[i].transform), path);

            //If path is valid
            if (true || path.status == NavMeshPathStatus.PathComplete)
            {
                //Calc the leght of the path
                for (int j = 1; j < path.corners.Length; ++j)
                {
                    pathL += Vector3.Distance(path.corners[j - 1], path.corners[j]);
                }
                //If this path is shorter than the current min set it as the current destiantion
                if (pathL < minPathLength)
                {
                    minPathLength = pathL;
                    chosen        = i;
                }
            }
        }

        return(chosen);
    }
Ejemplo n.º 8
0
        public static Vector3 GetNavPoint(Vector3 current, Vector3 target, float range, int area, out int count, Vector3[] points)
        {
            Vector3 tgt    = target;
            var     random = MovementDictionary.RandomCount;

            for (var i = 0; i < random; i++)
            {
                path.ClearCorners();
                if (NavMesh.CalculatePath(current, tgt, area, path))
                {
                    if (points != null)
                    {
                        count = path.GetCornersNonAlloc(points);
                    }
                    else
                    {
                        count = 0;
                    }

                    return(tgt);
                }

                var circle = UnityEngine.Random.insideUnitCircle;
                tgt += new Vector3(circle.x, 0, circle.y) * range;
            }

            count = 0;
            return(current);
        }
Ejemplo n.º 9
0
 // Получение случайной точки на Navmesh
 void GetRandomPoint(Vector3 center, float maxDistance)
 {
     for (int c = 0; c < 100; c++)
     {
         // случайная точка внутри окружности, расположенной в center с радиусом maxDistance
         Vector3 randomPos = new Vector3(Random.Range(center.x - maxDistance, center.x + maxDistance), 0, Random.Range(center.z - maxDistance, center.z + maxDistance));
         // вычисляем путь до randomPos по Navmesh сетке
         NavMesh.CalculatePath(transform.position, randomPos, NavMesh.AllAreas, path);
         // если путь построен
         if (path.status == NavMeshPathStatus.PathComplete)
         {
             // вычисляем длину пути
             if (path.corners.Length >= 2)
             {
                 for (int i = 0; i < path.corners.Length - 1; i++)
                 {
                     pathDist += (path.corners[i + 1] - path.corners[i]).magnitude;
                 }
             }
             // если длина пути достаточная
             if (pathDist >= maxDistance * 2f / 3f)
             {
                 return;
             }
         }
     }
     path.ClearCorners();
 }
        /*
         *  Grabs a random triangle in the mesh (connected to p),
         *  weighted by size so random point distribution is even
         */
        static int GetRandomConnectedTriangleOnNavMesh(Vector3[] vertices, int[] triangles, Vector3 p)
        {
            // Check for triangle connectivity and calculate total area of all *connected* triangles
            int         nTriangles         = triangles.Length / 3;
            float       tArea              = 0.0f;
            List <int>  connectedTriangles = new List <int>();
            NavMeshPath path = new NavMeshPath();

            for (int i = 0; i < nTriangles; i++)
            {
                path.ClearCorners();
                if (NavMesh.CalculatePath(p, vertices[triangles[3 * i + 0]], NavMesh.AllAreas, path))
                {
                    if (path.status == NavMeshPathStatus.PathComplete)
                    {
                        tArea += GetTriangleArea(vertices, triangles, i);
                        connectedTriangles.Add(i);
                    }
                }
            }

            float rnd = UnityEngine.Random.Range(0, tArea);

            foreach (int i in connectedTriangles)
            {
                rnd -= GetTriangleArea(vertices, triangles, i);
                if (rnd <= 0)
                {
                    return(i);
                }
            }
            return(0);
        }
Ejemplo n.º 11
0
        void MoveCheck(Ray screenRay)
        {
            if (m_CalculatedPath.status == NavMeshPathStatus.PathComplete)
            {
                m_Agent.SetPath(m_CalculatedPath);
                m_CalculatedPath.ClearCorners();
            }

            if (Physics.RaycastNonAlloc(screenRay, m_RaycastHitCache, 1000.0f, m_LevelLayer) > 0)
            {
                Vector3 point = m_RaycastHitCache[0].point;
                //avoid recomputing path for close enough click
                if (Vector3.SqrMagnitude(point - m_LastRaycastResult) > 1.0f)
                {
                    NavMeshHit hit;
                    if (NavMesh.SamplePosition(point, out hit, 0.5f, NavMesh.AllAreas))
                    {//sample just around where we hit, avoid setting destination outside of navmesh (ie. on building)
                        m_LastRaycastResult = point;
                        //m_Agent.SetDestination(hit.position);

                        m_Agent.CalculatePath(hit.position, m_CalculatedPath);
                    }
                }
            }
        }
Ejemplo n.º 12
0
    public void SetDestPos(Vector3 dest)
    {
        RVO.Simulator.Instance.setAgentMaxNeighbors(m_agentHandle, m_agentMaxNeighbors);

        Vector3 from = transform.position + (dest - transform.position).normalized * 0.1f;

        NavMeshHit hit;

        if (!NavMesh.SamplePosition(from, out hit, 1.1f, WALKABLE))
        {
            return;
        }

        if (NavMesh.CalculatePath(hit.position, dest, WALKABLE, path))
        {
            Vector3 dist = dest - path.corners[path.corners.Count() - 1];
            if (dist.sqrMagnitude >= 0.01f)
            {
                path.ClearCorners();
                return;
            }

            m_havValidPath = true;
            m_cornerIndex  = 1;
            m_destPos      = path.corners[m_cornerIndex];
            GetComponent <NavMeshObstacle>().carving = false;
            if (m_animator != null)
            {
                m_animator.Play("Run", 0);
            }
        }
    }
Ejemplo n.º 13
0
    static int ClearCorners(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 1);
        NavMeshPath obj = LuaScriptMgr.GetNetObject <NavMeshPath>(L, 1);

        obj.ClearCorners();
        return(0);
    }
Ejemplo n.º 14
0
 public void CreatePath(Vector3 pos)
 {
     current_point = 1;
     if (path != null)
     {
         path.ClearCorners();
     }
     NavMesh.CalculatePath(transform.position, pos, (1 << NavMesh.GetAreaFromName("Walkable")), path);
 }
Ejemplo n.º 15
0
        private void clearNavMeshPath()
        {
            _currPathIndex = 0;

            if (_currCanMoveNavMeshPath != null)
            {
                _currCanMoveNavMeshPath.ClearCorners();
            }
        }
Ejemplo n.º 16
0
 public override EBTTaskState OnTaskTick(BehaviourTreeRunner btree, float deltaTime)
 {
     if (mAbort)
     {
         return(EBTTaskState.faild);
     }
     mTimer += deltaTime;
     if (mTimer >= mUpdateInterval)
     {
         if (mTargetTrans != null)
         {
             Transform trans = mTargetTrans.Value;
             if (trans == null)
             {
                 return(EBTTaskState.faild);
             }
             mTargetPos = trans.position;
         }
         else
         {
             mTargetPos = mTarget.Value;
         }
         mPath.ClearCorners();
         NavMesh.CalculatePath(mPlayer.transform.position, mTargetPos, 1, mPath);
         mCornnerPtr = 1;
         mTimer      = 0;
     }
     Vector3[] points = mPath.corners;
     if (mCornnerPtr < points.Length)
     {
         Vector3 p   = points[mCornnerPtr];
         Vector3 dir = p - mPlayer.transform.position;
         mPlayer.Move(dir.normalized * mSpeedPercentage * Mathf.Min(1, dir.magnitude * 3));
         float rad;
         if (mCornnerPtr == points.Length - 1 && mPath.status == NavMeshPathStatus.PathComplete)
         {
             rad = mStopDistance * mStopDistance;
         }
         else
         {
             rad = 0.009f;
         }
         if (dir.sqrMagnitude < rad)
         {
             mCornnerPtr++;
         }
         return(EBTTaskState.running);
     }
     else
     {
         if (mPath.status == NavMeshPathStatus.PathPartial)
         {
             mPlayer.Move(mPlayer.transform.forward * mSpeedPercentage);
         }
         return(mPath.status == NavMeshPathStatus.PathComplete ? EBTTaskState.success : EBTTaskState.running);
     }
 }
Ejemplo n.º 17
0
 public static bool GetPath(Vector3 fromPos, Vector3 toPos, int passableMask, NavMeshPath path)
 {
     path.ClearCorners();
     if (NavMesh.CalculatePath(fromPos, toPos, passableMask, path) == false)
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 18
0
    TestState UnityNavigateTest()
    {
        TestState state = new TestState()
        {
            Name = "UnityNavigate"
        };

        //GameObject agent = new GameObject("UnityNavigateAgent");
        //agent.transform.SetParent(transform);
        //NavMeshAgent navAgent = agent.AddComponent<NavMeshAgent>();
        //navAgent.updatePosition = false;
        //NavMesh.pathfindingIterationsPerFrame = int.MaxValue;


        Vector3 startPos = new Vector3(this.startPoint.x + 0.5f, 0, this.startPoint.y + 0.5f);
        Vector3 endPos   = new Vector3(this.endPoint.x + 0.5f, 0, this.endPoint.y + 0.5f);

        NavMeshPath path = new NavMeshPath();

        //agent.transform.position = startPos;

        System.DateTime start   = System.DateTime.Now;
        bool            success = false;
        int             safeNum = 0;

        while (++safeNum < 199)
        {
            path.ClearCorners();
            success = NavMesh.CalculatePath(startPos, endPos, NavMesh.AllAreas, path);
            if (success)
            {
                if (state.PathResult == null)
                {
                    state.PathResult = new List <Vector2Int>();
                }
                for (int i = 0; i < path.corners.Length; ++i)
                {
                    Vector3 p = path.corners[i];
                    state.PathResult.Add(new Vector2Int((int)p.x, (int)p.z));
                }

                startPos = path.corners[path.corners.Length - 1];
                if (path.status == NavMeshPathStatus.PathComplete)
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }

        state.CostTimeMS = (int)(System.DateTime.Now - start).TotalMilliseconds;
        state.extendMsg  = string.Format("success={0},status={1},safeNum={2}", success, path.status.ToString(), safeNum);
        return(state);
    }
Ejemplo n.º 19
0
 private void ResetPath()
 {
     if (m_pathCorners != null && 0 < m_pathCorners.Length)
     {
         m_path.ClearCorners();
         m_pathCorners          = null;
         m_nextPathPoint        = 0;
         m_interactionAtPathEnd = false;
     }
 }
Ejemplo n.º 20
0
    public bool GetPath(NavMeshPath path, Vector2 fromPos, Vector2 toPos, int passableMask = NavMesh.AllAreas)
    {
        path.ClearCorners();

        if (NavMesh.CalculatePath(fromPos, toPos, passableMask, path) == false)
        {
            return(false);
        }

        return(true);
    }
Ejemplo n.º 21
0
    public void ClearPath()
    {
        movePath.ClearCorners();
        movePathIndex = 1;
        DestPosition  = null != ownerTrans ? ownerTrans.position : Vector3.zero;

        if (null != NavAgent)
        {
            NavAgent.ResetPath();
        }
    }
Ejemplo n.º 22
0
 public bool FindPath(Vector3 sourcePosition, Vector3 targetPosition, ref List <Vector3> paths)
 {
     path.ClearCorners();
     if (NavMesh.CalculatePath(sourcePosition, targetPosition, NavMesh.AllAreas, path))
     {
         paths.Clear();
         paths.AddRange(path.corners);
         return(true);
     }
     return(false);
 }
Ejemplo n.º 23
0
        /// <summary>
        /// 计算路径
        /// </summary>
        public static void CalcPath(Vector3 source_pos, Vector3 target_pos, ref List <Vector3> path_nodes)
        {
            // 初始化数据
            if (path_nodes == null)
            {
                return;
            }
            path_nodes.Clear();

            //LogManager.Error("目标点为非法点:{0}", target_pos);
            // 非法目标
            NavMeshHit nav_hit;

            if (!NavMesh.SamplePosition(target_pos, out nav_hit, MovementConst.MIN_DISTANCE, UnityLayerConst.Instance.layer_nav_mask))
            {
                return;
            }

            // 最短距离
            float distance = Vector2.Distance(source_pos, target_pos);

            if (distance < MovementConst.MIN_DISTANCE)
            {
                return;
            }

            // 清除老数据,重新开始寻路
            navmesh_path.ClearCorners();
            if (!NavMesh.CalculatePath(source_pos, target_pos, -1, navmesh_path))
            {
                return;
            }
            if (navmesh_path.status != NavMeshPathStatus.PathComplete)
            {
                return;
            }

            // 添加路径节点
            path_nodes.AddRange(navmesh_path.corners);
            navmesh_path.ClearCorners();
        }
Ejemplo n.º 24
0
        //  ========================= Behaviour LifeCycle =========================
        public void OnDestroy()
        {
            hideLocaltionMask(true);

            cleanAllTweeners();

            if (_currCanMoveNavMeshPath != null)
            {
                _currCanMoveNavMeshPath.ClearCorners();
                _currCanMoveNavMeshPath = null;
            }
        }
Ejemplo n.º 25
0
 public override void MoveTo(Vector3 v, bool needToAdjustPosY = true)
 {
     speed            = 3f;
     isMovingToTarget = true;
     navAgent.speed   = 0.0f;
     navAgent.SetDestination(v);
     path.ClearCorners();
     navAgent.CalculatePath(v, path);
     cornersIdx               = 1;
     moveDirection            = (path.corners[cornersIdx] - transform.position).normalized;
     currentPathPointDistance = Vector3.Distance(transform.position, path.corners[cornersIdx]);
 }
Ejemplo n.º 26
0
    static bool GetPath(NavMeshPath path, Vector3 fromPosition, Vector3 toPosition, int mask)
    {
        path.ClearCorners();

        NavMesh.CalculatePath(fromPosition, toPosition, mask, path);

        if (path.status != NavMeshPathStatus.PathComplete)
        {
            return(false);
        }

        return(true);
    }
Ejemplo n.º 27
0
    public void GetPathTowards(Vector3 Destination)
    {
        path = new NavMeshPath();
        path.ClearCorners();
        agent.CalculatePath(GetClosestPointToNavMesh(Destination), path);

        if (path == null || path.status == NavMeshPathStatus.PathInvalid)
        {
            Debug.LogError("No path found.");
            return;
        }

        path.GetCornersNonAlloc(Path);
    }
Ejemplo n.º 28
0
        /// <summary>
        /// Move this character by sending input to the input system.
        /// </summary>
        private void HandleMovement()
        {
            // Stop the current input direction
            inputDirection *= 0.0f;

            // Try to calculate a new input direction
            if (movementPath.corners != null && movementPath.corners.Length > 0)
            {
                if (pathIndex >= movementPath.corners.Length || pathIndex < 0)
                {
                    // Clear the nav path
                    movementPath.ClearCorners();
                    pathIndex = 0;
                }
                else
                {
                    // Set the position to move to
                    targetPosition = movementPath.corners[pathIndex];

                    // Get the direction from the position
                    inputDirection = targetPosition - _transform.position;

                    // Look in the direction we are moving.
                    lookAt = new Vector3(targetPosition.x, _transform.position.y, targetPosition.z);

                    if (pathIndex == movementPath.corners.Length - 1)
                    {
                        lookAt += _transform.forward * 10;
                    }

                    lookAt = Utility.Utilities.mainCamera.WorldToScreenPoint(lookAt);

                    inputManager.HandleLook(lookAt);

                    // Check if we are close enough to stop or move on
                    if (Vector3.Distance(_transform.position, targetPosition) <= stoppingDistance)
                    {
                        // Move to the next item in the array
                        pathIndex++;
                    }
                }
            }

            // Convert the input from a vector3 into a vector2
            inputDirection.y = inputDirection.z;
            inputDirection.z = 0;

            // Feed the input to the input manager.
            inputManager.HandleMovement(inputDirection);
        }
Ejemplo n.º 29
0
    public Vector3 GetDistinationNacMech(Vector3 request)
    {
        NavMeshHit myHitik;

        if (NavMesh.SamplePosition(request, out myHitik, 100, NavMesh.AllAreas))
        {
            navPath.ClearCorners();
            NavMesh.CalculatePath(transform.position, Glavtrans.position, NavMesh.AllAreas, navPath);
            Instantiate(Glavtrans, myHitik.position, Quaternion.identity);
            if (navPath != null && navPath.corners.Length > 1)
            {
                return(navPath.corners[1]);
            }
        }

        return(myHitik.position);
    }
Ejemplo n.º 30
0
    public override void UpdateState()
    {
        //Debug.DrawLine(m_stalker.transform.position, m_activePoints.m_currentWaypoint, Color.magenta);
        if (m_stalkerMotor.TargetReached)
        {
            if (m_path.status != NavMeshPathStatus.PathInvalid && m_currentPathIndex < m_path.corners.Length)
            {
                m_stalkerMotor.SetNewTarget(m_path.corners[m_currentPathIndex++]);
            }
            else
            {
                // clear the current path
                m_path.ClearCorners();
                m_currentPathIndex = 0;

                // Find the next waypoint and find a path to it
                switch (m_stalkerMotor.CurrentSearchType)
                {
                case Motor_Stalker.SearchType.LINEAR:
                    m_stalkerAgent.CalculatePath(Navigation.FindNearestWaypoint(ref m_activePoints), m_path);
                    break;

                case Motor_Stalker.SearchType.RANDOM:
                    m_stalkerAgent.CalculatePath(Navigation.FindRandomWaypoint(ref m_activePoints), m_path);
                    break;
                }
            }
        }

        // Move to next position
        m_stalkerMotor.UpdateMotor();

        // Check for player if in range
        if (m_stalkerMotor.ShouldCheckForNearbyObjects)
        {
            // Update the sight
            m_stalkerMotor.UpdateLOS();

            if (m_stalkerMotor.CanSeePlayer)
            {
                // Enter pursuit state and set the player's location as the new target
                m_stalker.SetPursuitState(GameManager.Player.transform);
            }
        }
    }