Example #1
0
    public static NavMeshPath FindPath(Vector3 from, Vector3 to)
    {
        NavMeshPath path = new NavMeshPath();

        if (NavMesh.CalculatePath(from, to, 1, path))
        {
            return(path);
            //return path[0];
        }
        else
        {
            Debug.Log("Path to " + " does not exist");
            return(null);
            //return from;
        }
    }
Example #2
0
    protected bool findPathToClosestGate(Gate g, out NavMeshPath path)
    {
        bool output = false;

        path = null;

        int         mask = 1 << NavMesh.GetAreaFromName("Walkable");
        NavMeshPath p    = new NavMeshPath();

        if (NavMesh.CalculatePath(transform.position, g.transform.position, mask, p))
        {
            output = true;
            path   = p;
        }
        return(output);
    }
        private Vector3[] FindPath(Vector3 origin, Vector3 destination)
        {
            NavMeshPath navMeshPath = new NavMeshPath();

            GetNearestPointInNavMesh(ref origin);
            GetNearestPointInNavMesh(ref destination);

            if (NavMesh.CalculatePath(origin, destination, NavMesh.AllAreas, navMeshPath))
            {
                return(navMeshPath.corners);
            }
            else
            {
                return(null);
            }
        }
    private void MoveToNewPoint(bool requireLineOfSight)
    {
        //Calculate and visualize the target position.
        Vector3 targetPosition = GetEnemyNextDestination(requireLineOfSight);

        //Calculate a path to the player's next frame position.
        NavMeshPath path = new NavMeshPath();

        NavMesh.CalculatePath(transform.position, targetPosition, NavMesh.AllAreas, path);

        //Update the destination.
        if (path.status == NavMeshPathStatus.PathComplete)
        {
            agent.SetPath(path);
        }
    }
Example #5
0
    // I search a valid position, if it cannot create it, probably the enemy is not positioned on a nav mesh area
    public static Vector3 GenerateRandomPosition(Vector3 origin, float dist, int layermask)
    {
        bool        find;
        Vector3     position;
        NavMeshPath path = new NavMeshPath();

        do
        {
            Vector3 randDirection = Random.insideUnitSphere * dist;
            randDirection += origin;
            find           = NavMesh.SamplePosition(randDirection, out NavMeshHit navHit, dist, layermask);
            position       = navHit.position;
        } while (!find || !NavMesh.CalculatePath(origin, position, layermask, path));

        return(position);
    }
        public void SetDestination(Vector3 pos)
        {
            NavMeshHit hit;

            NavMesh.SamplePosition(pos, out hit, 100, 255);
            NavMesh.CalculatePath(transform.position, pos, 255, navPath);
            path.Clear();

            foreach (Vector3 v in navPath.corners)
            {
                path.Enqueue(v);
            }

            state.ChangeState("Run", pos);
            //    navAgent.SetDestination(hit.position);
        }
Example #7
0
    private void Update()
    {
        //For drawing the NavMeshPath
        _pathElapsed += Time.deltaTime;

        if (_pathElapsed > 1.0f)
        {
            _pathElapsed -= 1.0f;
            NavMesh.CalculatePath(gameObject.transform.position, _lastKnownPos, NavMesh.AllAreas, _navMeshPath);
        }

        for (var i = 0; i < _navMeshPath.corners.Length - 1; i++)
        {
            Debug.DrawLine(_navMeshPath.corners[i], _navMeshPath.corners[i + 1], Color.red);
        }
    }
    void PerformPathfinding()
    {
        //Pathfind from spawn point to leak point, storing the result in GroundEnemy.path:
        NavMesh.CalculatePath(spawnPoint.position, leakPoint.position, NavMesh.AllAreas, GroundEnemy.path);

        if (GroundEnemy.path.status == NavMeshPathStatus.PathComplete)
        {
            //If the path was successfully found, make sure the lock panel is inactive:
            sellButtonLockPanel.SetActive(false);
        }
        else //If the path is blocked,
        {
            //Activate the lock panel:
            sellButtonLockPanel.SetActive(true);
        }
    }
Example #9
0
 public void Run()
 {
     path = new NavMeshPath();
     NavMesh.CalculatePath(startTransform.position, endTransform.position, 1 << 4, path);
     pathCorners = new Vector3[path.corners.Length];
     pathCorners = path.corners;
     if (debugMode)
     {
         if (GetComponent <LineRenderer>() != null)
         {
             line = GetComponent <LineRenderer>();
         }
         StartCoroutine("DrawPath");
     }
     Init();
 }
Example #10
0
 protected void UpdateNavMesh()
 {
     // Update the way to the goal every second.
     elapsed += Time.deltaTime;
     if (elapsed > 0.1f)
     {
         elapsed -= 1.0f;
         NavMesh.CalculatePath(transform.position, target.position, NavMesh.AllAreas, path);
         //Debug.Log(gameObject.name);
         agent.SetPath(path);
     }
     for (int i = 0; i < path.corners.Length - 1; i++)
     {
         Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.red);
     }
 }
Example #11
0
        private void CalculatePath()
        {
            var nextWaypoint = NextWaypoint + 1;

            if (nextWaypoint >= Waypoints.Length)
            {
                nextWaypoint = 0;
            }

            NavMesh.CalculatePath(
                transform.position,
                Waypoints[nextWaypoint].transform.position,
                NavMesh.AllAreas,
                _path
                );
        }
    public void GeneratePath(Cell targetCell)
    {
        if (targetCell == null)
        {
            return;
        }

        NavMeshPath path = new NavMeshPath();

        NavMesh.CalculatePath(transform.position, targetCell.GetPosition(), NavMesh.AllAreas, path);
        pathGenerated = path.corners.ToList();
        if (pathGenerated.Count > 0)
        {
            pathGenerated.RemoveAt(0);
        }
    }
Example #13
0
 public bool CalculatePath(Vector3 startPos, Vector3 targetPos, out Vector3[] vPath)
 {
     vPath = null;
     if (calculationsPrFrame <= 0)
     {
         return(false);
     }
     if (NavMesh.CalculatePath(startPos, targetPos, NavMesh.AllAreas, path))
     {
         calculationsPrFrame--;
         timeAtLastCalculate = Time.time;
         vPath = path.corners;
         return(true);
     }
     return(false);
 }
Example #14
0
 // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
 override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
 {
     if (playerController.state == MinifigControllerWTH.State.Idle)
     {
         currentPath = new NavMeshPath();
         NavMesh.CalculatePath(player.transform.position, targetPlayer.transform.position, NavMesh.AllAreas, currentPath);
         if (currentPath.corners.Length < 2)
         {
             animator.SetBool("PlayerInSight", false);
         }
         else
         {
             playerController.MoveTo(currentPath.corners[1]);
         }
     }
 }
Example #15
0
        public bool CanMoveTo(Vector3 destination)
        {
            NavMeshPath path    = new NavMeshPath();
            bool        hasPath = NavMesh.CalculatePath(transform.position, destination, NavMesh.AllAreas, path);

            if (!hasPath || path.status != NavMeshPathStatus.PathComplete)
            {
                return(false);
            }
            if (GetPathLength(path) > maxNavPathLength)
            {
                return(false);
            }

            return(true);
        }
Example #16
0
    // IEnumerator move( AnimCallBack onEnd)
    // {


    //     yield return null;
    // }

    IEnumerator CheckIfOnPlace(AnimCallBack onEnd)
    {
        Vector3 target = points[0];

        while (Vector3.Distance(target, go1.transform.position) > 2f)
        {
            yield return(new WaitForSeconds(0.1f));

            NavMeshHit hit;
            if (NavMesh.SamplePosition(points[0], out hit, 2.0f, NavMesh.AllAreas))
            {
                NavMeshPath path = new NavMeshPath();
                if (NavMesh.CalculatePath(go1.transform.position, hit.position, NavMesh.AllAreas, path))
                {
                    agent.path = path;
                }
                else
                {
                    animator.speed = startAnimSpeed;
                    agent.speed    = startAgentSpeed;
                    onEnd.Invoke();
                    Debug.Log("Invalid Path. End Animate");
                    break;
                }


                // agent.destination = hit.position;
            }
            else
            {
                onEnd.Invoke();
                Debug.Log("Invalid Path. End Animate");
                break;
            }
        }
        go1.GetComponent <UChanVoice>().PlayLaught();
        animator.speed  = startAnimSpeed;
        agent.speed     = startAgentSpeed;
        agent.isStopped = true;
        animator.SetBool("walk", false);
        yield return(new WaitForSeconds(1));

        onEnd.Invoke();
        Debug.Log("End Animate");

        yield return(null);
    }
Example #17
0
    void Update()
    {
        // Игнорируем координату y, чтобы двигаться вдоль XOZ
        var targetPointWithoutZ  = new Vector3(this.targetPoint.x, 0, this.targetPoint.z);
        var targetCornerWithoutZ = new Vector3(this.targetCorner.x, 0, this.targetCorner.z);
        var enemyWithoutZ        = new Vector3(characterController.transform.position.x, 0, characterController.transform.position.z);

        // Проверяем смотрит ли Enemy на Point
        Quaternion direction = Quaternion.LookRotation(targetPointWithoutZ - enemyWithoutZ);

        if (Quaternion.Angle(characterController.transform.rotation, direction) <= stoppingAngle)
        {
            // Проверяем находится ли Enemy вблизи целевого Corner
            if (Vector3.Distance(enemyWithoutZ, targetCornerWithoutZ) <= stoppingDistance)
            {
                // Проверяем является ли целевой Corner последним в NavMeshPath
                if (targetCornerIndex == path.corners.Length - 1)
                {
                    // Простраиваем путь к следующей Point
                    targetPointIndex = (targetPointIndex + 1) % points.Length;
                    targetPoint      = points[targetPointIndex].position;
                    NavMesh.CalculatePath(characterController.transform.position, targetPoint, NavMesh.AllAreas, path);

                    // Фиксируем первый Corner из NavMeshPath как целевой, чтобы двигаться к нему
                    targetCornerIndex = 0;
                    this.targetCorner = path.corners[targetCornerIndex];
                }
                else
                {
                    // Фиксируем соедующий Corner из NavMeshPath как целевой, чтобы двигаться к нему
                    targetCornerIndex++;
                    this.targetCorner = path.corners[targetCornerIndex];
                }
            }
            else
            {
                // Передвигаем Enemy к corner
                var movement = (targetCornerWithoutZ - enemyWithoutZ).normalized;
                characterController.SimpleMove(movement * speedMove);
            }
        }
        else
        {
            // Поворачиваем Enemy, чтобы смотрел на point
            characterController.transform.rotation = Quaternion.Lerp(characterController.transform.rotation, direction, Time.deltaTime * speedTurn);
        }
    }
Example #18
0
    // Use this for initialization
    void Start()
    {
        flockers     = new List <GameObject>();
        flockerComps = new List <Flocker>();
        temp         = new GameObject[GameObject.FindGameObjectsWithTag("Flocker").Length];
        temp         = GameObject.FindGameObjectsWithTag("Flocker");
        foreach (GameObject g in temp)
        {
            flockers.Add(g);
            flockerComps.Add(g.GetComponent <Flocker>());
        }

        originalPositions = new Vector3[flockers.Count];
        for (int index = 0; index < flockers.Count; index++)
        {
            originalPositions[index] = flockers[index].transform.position;
        }

        this.target = GameObject.FindGameObjectWithTag("Target");

        avgDirection = Vector3.zero;
        avgPosition  = Vector3.zero;

        terrain = GameObject.Find("Terrain").GetComponent <Terrain>();
        endGoal = GameObject.Find("EndGoal");

        path = new NavMeshPath();


        NavMesh.CalculatePath(flockers[0].transform.position, endGoal.transform.position, 1 << NavMesh.GetAreaFromName("Walkable"), path);

        cornerIndex = 0;
        target.transform.position = path.corners[cornerIndex];


        temp      = new GameObject[GameObject.FindGameObjectsWithTag("Obstacle").Length];
        temp      = GameObject.FindGameObjectsWithTag("Obstacle");
        obstacles = new List <GameObject>();
        foreach (GameObject g in temp)
        {
            obstacles.Add(g);
        }
        foreach (GameObject g in flockers)
        {
            g.GetComponent <Flocker>().target = target;
        }
    }
Example #19
0
    public void CalculatePath(Entity entity)
    {
        //reading of the start and end positions and generation of the path to provide it to the
        //entity that is related later
        Translation ballposEnemy = manager.GetComponentData <Translation>(entity);

        startPosition = ballposEnemy.Value;
        NavMeshPath path = new NavMeshPath();

        targetPosition = AppManager.instance.playerPosition;
        NavMesh.CalculatePath(startPosition, targetPosition, NavMesh.AllAreas, path);

        // set nodeindex to 0 so the Job does not run during update
        ActiveNodeIndexData nodeIndex = manager.GetComponentData <ActiveNodeIndexData>(entity);
        ActiveNodeIndexData tempNode  = nodeIndex;

        tempNode.nodeInPath = 0;
        manager.SetComponentData(entity, tempNode);

        //when you do not reload the buffer directly from the entity but rather try to cach it then
        //you get spammed by errors telling you the native array has been deallocated and cant be accessed
        DynamicBuffer <Float3BufferElement> float3Buffer = manager.GetBuffer <Float3BufferElement>(entity);

        float3Buffer.Clear();

        for (int i = 0; i < path.corners.Length; i++)
        {
            convertPlaceholder = path.corners[i];
            float3Buffer.Add(new Float3BufferElement {
                Value = convertPlaceholder
            });
        }

        //reset the variables since they could have bneen changed by other operations in the mean time
        //by another script
        nodeIndex           = manager.GetComponentData <ActiveNodeIndexData>(entity);
        tempNode            = nodeIndex;
        tempNode.nodeInPath = 1;
        manager.SetComponentData(entity, tempNode);

        OJO_RequestRecalculationData recalc = manager.GetComponentData <OJO_RequestRecalculationData>(entity);

        recalc.requestState = MyCode.RequestState.NoRequest;
        manager.SetComponentData(entity, recalc);

        return;
    }
Example #20
0
    public bool FindLandingSpot()
    {
        NavMeshHit navMeshHit = new NavMeshHit();

        if (NavMesh.CalculatePath(enemy.transform.position, player.transform.position, areaMask, path))
        {
            // Go through path backwards to find landing spot at desired distance (find point closest to player as possible)
            for (int i = path.corners.Length - 1; i >= 0; i--)
            {
                if ((path.corners[i] - enemy.transform.position).magnitude < jumpingDistance)
                {
                    jumpTargetPosition = path.corners[i];

                    return(true);
                }
                else if (i > 0 && (path.corners[i - 1] - enemy.transform.position).magnitude < jumpingDistance)
                {
                    float previousCornerDistance = (path.corners[i - 1] - enemy.transform.position).magnitude;
                    float deltaCornerDistance    = (path.corners[i] - path.corners[i - 1]).magnitude;
                    float cos_theta  = Mathf.Cos(Vector3.Angle(path.corners[i - 1] - enemy.transform.position, path.corners[i] - path.corners[i - 1]) * Mathf.Deg2Rad);
                    float jumpDistSq = jumpingDistance * jumpingDistance;
                    float prevDistSq = previousCornerDistance * previousCornerDistance;

                    // Because math
                    float x = (previousCornerDistance / deltaCornerDistance) * (Mathf.Sqrt(cos_theta - 1 + (jumpDistSq / prevDistSq)) - cos_theta);

                    // Protect from bugs
                    if (float.IsNaN(x))
                    {
                        x = 1f;
                    }

                    jumpTargetPosition = path.corners[i - 1] + (path.corners[i] - path.corners[i - 1]) * Mathf.Clamp01(x);

                    return(true);
                }
            }
        }
        else if (NavMesh.FindClosestEdge(enemy.transform.position, out navMeshHit, areaMask))
        {
            jumpStartPosition = navMeshHit.position;

            return(true);
        }

        return(false);
    }
        private void OnUpdate()
        {
            foreach (var npc in npcs)
            {
                var movementVector = npc.character.Direction;
                if (npc.pathProgress >= npc.path.corners.Length)
                {
                    npc.targetPosition = GetRandomPosition();
                    NavMesh.CalculatePath(npc.character.Position, npc.targetPosition, NavMesh.AllAreas, npc.path);
                    npc.pathProgress = 0;
                }

                if (npc.pathProgress < npc.path.corners.Length)
                {
                    var point = npc.path.corners[npc.pathProgress];
                    if (Vector3.Distance(point, npc.character.Position) < GameManager.Properties.npcMovementAccurancy)
                    {
                        npc.pathProgress++;
                    }
                    else
                    {
                        movementVector     = point - npc.character.Position;
                        npc.character.Move = movementVector.normalized;
                    }
                }
                else
                {
                    npc.character.Move = Vector3.zero;
                }


                var target       = GameManager.PlayerController.Target;
                var targetVector = target.Position - npc.character.Position;
                var distance     = targetVector.magnitude;
                if (!target.Dead && distance < GameManager.Properties.npcAttackDistance)
                {
                    npc.character.Direction = targetVector;
                    npc.character.Fire      = npc.character.Aiming = true;
                    npc.character.AimPoint  = target.Position + Vector3.up;
                }
                else
                {
                    npc.character.Fire      = npc.character.Aiming = false;
                    npc.character.Direction = movementVector;
                }
            }
        }
Example #22
0
    /// <summary>
    /// Creates a pin the game, hinting a specific position
    /// </summary>
    public void pin(Vector3 position)
    {
        Transform newPin = Instantiate(spawn) as Transform;

        newPin.position = position;
        newPin.parent   = transform;

        pathStart = Character.Instance.transform.position;
        pathEnd   = position;

        if (NavMesh.CalculatePath(pathStart, pathEnd, -1, navMeshPath))
        {
            DrawPath(navMeshPath.corners);
        }

        Destroy(newPin.gameObject, 1);
    }
Example #23
0
    public void Simulate()
    {
        agents.RemoveAll(i => i == null);

        foreach (GameObject agent in agents)
        {
            NavMeshPath path = new NavMeshPath();
            Vector3     dest = agent.GetComponent <AgentController>().destination;
            NavMesh.CalculatePath(agent.transform.position, dest, NavMesh.AllAreas, path);
            agentPaths.Add(path);
        }

        for (int i = 0; i < agents.Count; i++)
        {
            agents[i].GetComponent <AgentController>().Navigate(agentPaths[i]);
        }
    }
Example #24
0
    private static List <Vector3> GetWorldPath(Vector3 source, Vector3 target, float distance)
    {
        NavMeshPath       path      = new NavMeshPath();
        HashSet <Vector3> finalPath = new HashSet <Vector3>();
        Vector3           moveTo    = source;

        NavMesh.CalculatePath(source, target, NavMesh.AllAreas, path);

        for (int index = 1; index < path.corners.Length; index++)
        {
            Vector3 endHere = new Vector3(Mathf.Round(path.corners[index].x), target.y, Mathf.Round(path.corners[index].z));
            finalPath.UnionWith(rasterizedLine(moveTo, endHere, distance));
            finalPath.Add(endHere);
            moveTo = endHere;
        }
        return(new List <Vector3> (finalPath));
    }
    public void SetMovePosition(Vector3 movePosition, Action onReachedMovePosition)
    {
        this.onReachedMovePosition = onReachedMovePosition;
        float sameDistancePosition = 1f;

        if (Vector3.Distance(movePosition, lastMovePosition) < sameDistancePosition)
        {
            // Position is too similar to last position
            // Has it been long enough?
            float timeToRepeatSamePath = .5f;
            if (Time.realtimeSinceStartup - lastMovePositionTime < timeToRepeatSamePath)
            {
                // Not long enough
                return;
            }
        }

        //Debug.Log("SetMovePosition " + Time.realtimeSinceStartup);
        path = new NavMeshPath();
        if (NavMesh.CalculatePath(transform.position, movePosition, NavMesh.AllAreas, path))
        {
            failCount            = 0;
            lastMovePositionTime = Time.realtimeSinceStartup;
            lastMovePosition     = movePosition;
            if (path.corners.Length > 1)
            {
                pathIndex       = 1;
                pathVectorArray = path.corners;
            }
            else
            {
                pathIndex = -1;
            }
        }
        else
        {
            //Debug.Log("Path fail " + failCount + " " + movePosition);
            pathIndex = -1;
            failCount++;
            if (failCount >= 100)
            {
                pathVectorArray = new Vector3[] { movePosition };
                pathIndex       = 0;
            }
        }
    }
Example #26
0
        void PathExistsTest()
        {
            foreach (var node in eqsNodes)
            {
                if (!node.Enabled)
                {
                    continue;
                }

                if (node == null)
                {
                    continue;
                }
                NavMeshPath path = new NavMeshPath();
                node.Enabled = NavMesh.CalculatePath(ParentPos, node.Position, NavMesh.AllAreas, path);
            }
        }
Example #27
0
 private void Start()
 {
     if (instance != null)
     {
         Destroy(gameObject);
     }
     else
     {
         instance = this;
         surfaceMesh.BuildNavMesh();
         realTimePath           = new NavMeshPath();
         preBuildPath           = new NavMeshPath();
         generateNewNavMeshPath = CalculatePaths();
         NavMesh.CalculatePath(transform.position, destination.position, preBuildAgent.areaMask, preBuildPath);
         NavMesh.CalculatePath(transform.position, destination.position, realTimeAgent.areaMask, realTimePath);
     }
 }
Example #28
0
    private void RefreshPath()
    {
        Vector3 originPos = transform.position;

        Vector3 destinationPos = destination.position;

        bool pathFound = NavMesh.CalculatePath(originPos, destinationPos, NavMesh.AllAreas, navPath);

        if (pathFound)
        {
            followPathIndex = 1;
        }
        else
        {
            Debug.Log("Path Not Found");
        }
    }
Example #29
0
 bool JumpRandomPoint(Vector3 center, float range, out Vector3 result)
 {
     while (true)
     {
         Vector3    randomPoint = center + Random.insideUnitSphere.normalized * range;
         NavMeshHit hit;
         if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
         {
             bool ok = NavMesh.CalculatePath(transform.position, randomPoint, NavMesh.AllAreas, path);
             if (path.status == NavMeshPathStatus.PathComplete)
             {
                 result = hit.position;
                 return(true);
             }
         }
     }
 }
Example #30
0
        Vector3 CalcDestinationPosition(Vector3 worldPosition)
        {
            NavMeshPath path = new NavMeshPath();

            NavMesh.CalculatePath(transform.position, worldPosition, NavMesh.AllAreas, path);

            NavMeshHit hit;

            if (NavMesh.SamplePosition(worldPosition, out hit, navMeshSampleDistance, NavMesh.AllAreas))
            {
                return(hit.position);
            }
            else
            {
                return(worldPosition);
            }
        }