// updates navigation towards designated point
    void UpdateNavigation()
    {
        agent.nextPosition = transform.position;
        agent.SetDestination(targetPos);

        NavMeshHit hit;

        agent.SamplePathPosition(NavMesh.AllAreas, 0.3f, out hit);

        navNextPoint = hit.position;
        //navRemainDist = hit.distance;
        navRemainDist = agent.remainingDistance;

        if (Vector3.Distance(transform.position, targetPos) < 1e-3f)
        {
            navNextPoint  = transform.position;
            navRemainDist = 0;
        }

        Vector3 delta = (navNextPoint - transform.position);

        navMoveDir   = delta.normalized;
        navMoveDir2  = delta.SetY(0).normalized;
        navMoveDir.y = 0;
    }
    // Update is called once per frame
    void Update()
    {
        durationSpentInCurrentState += Time.deltaTime;
        if (durationSpentInCurrentState >= signalStateDuration)
        {
            durationSpentInCurrentState = 0.0f;
            stop = !stop;

            //Fetch the Renderer from the GameObject
            Renderer rend = GameObject.Find("TrafficSignal").GetComponent <Renderer>();

            //Set the main Color of the Material to green
            Color c = stop ? Color.red : Color.green;
            rend.material.shader = Shader.Find("_Color");
            rend.material.SetColor("_Color", c);

            //Find the Specular shader and change its Color to red
            rend.material.shader = Shader.Find("Specular");
            rend.material.SetColor("_SpecColor", c);
        }


        NavMeshHit lookAheadPosition, currentPosition;

        agent.SamplePathPosition(~zebraCrossPathMask, 1.0f, out lookAheadPosition);
        agent.SamplePathPosition(~zebraCrossPathMask, 0.01f, out currentPosition);

        zebraCrossAhead = lookAheadPosition.hit;
        alreadyCrossing = currentPosition.hit;

        if (stop && zebraCrossAhead && !alreadyCrossing)
        {
            lastAgentVelocity = agent.velocity;
            lastAgentPath     = agent.path;
            waitingOnSignal   = true;
            agent.velocity    = Vector3.zero;
            agent.ResetPath();
        }

        if (!stop && waitingOnSignal)
        {
            waitingOnSignal = false;
            agent.velocity  = lastAgentVelocity;
            agent.SetPath(lastAgentPath);
        }

        if (Vector3.Distance(transform.position, positions[targetIndex]) < 0.9f)
        {
            targetIndex       = (targetIndex + 1) % positions.Length;
            agent.destination = positions[targetIndex];
        }
    }
Exemplo n.º 3
0
    //return current mouse Area
    public int getCurrentArea()
    {
        NavMeshHit hit;

        agent.SamplePathPosition(agent.areaMask, 0.01f, out hit);
        return(hit.mask);
    }
        void DoSamplePath()
        {
            if (_agent == null)
            {
                return;
            }

            NavMeshHit _NavMeshHit;
            bool       _reachedBeforeMaxDistance = _agent.SamplePathPosition(passableMask.Value, maxDistance.Value, out _NavMeshHit);

            reachedBeforeMaxDistance.Value = _reachedBeforeMaxDistance;

            position.Value = _NavMeshHit.position;
            normal.Value   = _NavMeshHit.normal;
            distance.Value = _NavMeshHit.distance;
            mask.Value     = _NavMeshHit.mask;
            hit.Value      = _NavMeshHit.hit;

            if (_reachedBeforeMaxDistance)
            {
                if (!FsmEvent.IsNullOrEmpty(reachedBeforeMaxDistanceEvent))
                {
                    Fsm.Event(reachedBeforeMaxDistanceEvent);
                }
            }
            else
            {
                if (!FsmEvent.IsNullOrEmpty(reachedAfterMaxDistanceEvent))
                {
                    Fsm.Event(reachedAfterMaxDistanceEvent);
                }
            }
        }
Exemplo n.º 5
0
    /**
     * Only returns a value when a path is set. The NavMesh mask is a bitset representing the current area
     * 8 = Stairs / 16 = Elevator
     */
    private void ProcessCurrentArea()
    {
        NavMeshHit navMeshHit;
        int        currentMask  = -1;
        var        currentFloor = _PoseEstimation.GetCurrentFloor();

        // Hide the map above the users floor so that its not in the way
        //Debug.Log("Current Floor: " + currentFloor);
        _ModelDatabase.HideFloorsUntil(currentFloor);

        if (_PoseEstimation.GetCurrentFloor() == destinationFloor)
        {
            return;
        }
        // Check if the navmesh agent is on the mesh
        if (!_NavMeshAgent.SamplePathPosition(NavMesh.AllAreas, 0f, out navMeshHit))
        {
            currentMask = navMeshHit.mask;
        }
        // Check if the user is on stairs
        if (currentMask == stairsMask)
        {
            PauseNavigation();

            _NavigationPresenter.SendObstacleMessage(currentFloor, destinationFloor, PoseEstimation.NewPosReason.EnteredStairs);
            _PoseEstimation.RequestNewPosition(PoseEstimation.NewPosReason.EnteredStairs);
        }
        // Check if the user is on the elevator
        else if (currentMask == elevatorMask)
        {
            PauseNavigation();
            _NavigationPresenter.SendObstacleMessage(currentFloor, destinationFloor, PoseEstimation.NewPosReason.EnteredElevator);
            _PoseEstimation.RequestNewPosition(PoseEstimation.NewPosReason.EnteredElevator);
        }
    }
Exemplo n.º 6
0
    /**
     * Only returns a value when a path is set. The NavMesh mask is a bitset representing the current area
     * 8 = Stairs / 16 = Elevator
     */
    private void ProcessCurrentArea()
    {
        NavMeshHit navMeshHit;
        int        currentMask = -1;

        if (_PoseEstimation.GetCurrentFloor() == destinationFloor)
        {
            return;
        }
        // Check if the navmesh agent is on the mesh
        if (!_NavMeshAgent.SamplePathPosition(NavMesh.AllAreas, 0f, out navMeshHit))
        {
            currentMask = navMeshHit.mask;
        }
        // Check if the user is on stairs
        if (currentMask == stairsMask)
        {
            PauseNavigation();
            var currentFloor = _PoseEstimation.GetCurrentFloor();
            _NavigationPresenter.SendObstacleMessage(currentFloor, destinationFloor, PoseEstimation.NewPosReason.EnteredStairs);
            _PoseEstimation.RequestNewPosition(PoseEstimation.NewPosReason.EnteredStairs);
        }
        // Check if the user is on the elevator
        else if (currentMask == elevatorMask)
        {
            PauseNavigation();
            var currentFloor = _PoseEstimation.GetCurrentFloor();
            _NavigationPresenter.SendObstacleMessage(currentFloor, destinationFloor, PoseEstimation.NewPosReason.EnteredElevator);
            _PoseEstimation.RequestNewPosition(PoseEstimation.NewPosReason.EnteredElevator);
        }
    }
Exemplo n.º 7
0
    /// <summary>
    /// Gets the member predicted position, using the group set up
    /// </summary>
    /// <returns>The member predicted position.</returns>
    /// <param name="member">Member.</param>
    public Vector3 getMemberPredictedPosition(GroupMemberMovement member)
    {
        int index = m_groupMembers.IndexOf(member);

        Transform[] formation = getCurrentFormation().Positions;

        if (index != -1)
        {
            //Get member position in formation and tranlate it into local space
            Vector3 currentMemberPos = formation [index].position;
            Vector3 localMemberPos   = m_transform.InverseTransformPoint(currentMemberPos);

            //Calculate distance for prediction using the current speed and a the time interval used to update the positions
            float predictionDist = m_groupSpeed * m_positionUpdateInterval;
            predictionDist += localMemberPos.magnitude;

            //Calculate a path
            NavMeshHit prediction;
            m_navigationAgent.SamplePathPosition(m_navigationAgent.areaMask, predictionDist, out prediction);


            //Get the predicted position of the group leader and translate it into localspace
            Vector3 localPredictedPos = m_transform.InverseTransformPoint(prediction.position);


            //Add the predicted leader position and the local member position, add them, and translating it into a world space position
            //the result is the World Space predicted position of the group member
            return(m_transform.TransformPoint(localPredictedPos + localMemberPos));
        }
        else
        {
            return(new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity));
        }
    }
Exemplo n.º 8
0
        private int GetCurrentNavArea()
        {
            NavMeshHit navHit;

            _nav.SamplePathPosition(-1, 0.0f, out navHit);

            return(navHit.mask);
        }
Exemplo n.º 9
0
    private int CheckCurrentNavMeshLayer()
    {
        // We get the mask where the agent is on at the current time
        _agent.SamplePathPosition(NavMesh.AllAreas, 0f, out NavMeshHit hit);

        // Get the index of the navMesh from the mask
        int index = IndexFromMask(hit.mask);

        return(index);
    }
Exemplo n.º 10
0
    /// <summary>
    /// 바닥으로 레이를 쏴서 착륙상태인지 확인
    /// 불가능하면 return false
    /// 상태 및 네비게이션 재설정
    /// </summary>
    /// <returns></returns>
    protected bool LandingAndStatusCheck(AIController.AIState state)
    {
        // Debug.DrawRay(transform.position, -transform.up * 0.2f, Color.green, 2f);
        if (Physics.Raycast(transform.position, -transform.up, groundHeight * 2, groundLayer))
        {
            ConditionRegulate(state, false);
            NavMeshHit hit;
            nav.SamplePathPosition(groundLayer, 2f, out hit);
            nav.nextPosition = hit.position;
            //NavMesh.CalculatePath(transform.position, targetTr.transform.position, NavMesh.AllAreas, nav.path);
            // Debug.Log("되돌아오기:"+nav.nextPosition);
            // col.radius = 0.5f;

            nav.avoidancePriority = lowProperty;
            nav.acceleration      = 12;

            return(true);
        }

        return(false);
    }
Exemplo n.º 11
0
    public void CheckMask()
    {
        NavMeshHit hit = new NavMeshHit();

        nav.SamplePathPosition(NavMesh.AllAreas, 0.0f, out hit);
        int ll = LayerMask.GetMask("Human");

        if (hit.mask != ll)
        {
            Accroupi();
        }
    }
Exemplo n.º 12
0
    static int SamplePathPosition(IntPtr L)
    {
        LuaScriptMgr.CheckArgsCount(L, 4);
        NavMeshAgent obj  = LuaScriptMgr.GetNetObject <NavMeshAgent>(L, 1);
        int          arg0 = (int)LuaScriptMgr.GetNumber(L, 2);
        float        arg1 = (float)LuaScriptMgr.GetNumber(L, 3);
        NavMeshHit   arg2 = LuaScriptMgr.GetNetObject <NavMeshHit>(L, 4);
        bool         o    = obj.SamplePathPosition(arg0, arg1, out arg2);

        LuaScriptMgr.Push(L, o);
        LuaScriptMgr.PushValue(L, arg2);
        return(2);
    }
Exemplo n.º 13
0
    void Update()
    {
        //check the areas the player hit
        navAgent.SamplePathPosition(-1, 0.0f, out navHit); //when player is moving

        if (navHit.mask == 8)                              //NavMeshArea Mud
        {
            navAgent.speed = speed * 0.5f;                 //set speed to half the speed
        }
        else
        {
            navAgent.speed = speed;
        }
    }
Exemplo n.º 14
0
        private void ManuallyUpdateAgent()
        {
            //   Debug.Log(MyLog.Format("ManuallyUpdateAgent"));
            Vector3    velocitySetted = default;
            NavMeshHit pathHit;

            objectAgent.SamplePathPosition(NavMesh.AllAreas, objectAgent.speed * DeltaTime, out pathHit);
            if (DeltaTime > 0)
            {
                objectAgent.velocity = (pathHit.position - objectAgent.transform.position) / DeltaTime;
            }

            objectAgent.nextPosition = pathHit.position;
        }
    private void CheckGround()
    {
        int        rockMask = 1 << NavMesh.GetAreaFromName("Rock");
        NavMeshHit hit;

        agent.SamplePathPosition(-1, 0.0f, out hit);
        if (hit.mask == rockMask)
        {
            agent.speed = 3;
        }
        else
        {
            agent.speed = 10;
        }
    }
Exemplo n.º 16
0
    // Update is called once per frame
    void Update()
    {
        sliderHP.value = health;
        UpdateHpPosition();
        if (Time.timeScale > 1.0f && agent.hasPath)
        {
            NavMeshHit hit;
            float      maxAgentTravelDistance = Time.deltaTime * agent.speed;

            //If at the end of path, stop agent.
            if (
                agent.SamplePathPosition(NavMesh.AllAreas, maxAgentTravelDistance, out hit) ||
                agent.remainingDistance <= agent.stoppingDistance
                )
            {
                Debug.Log("Stopping agent!");
                //Stop agent
            }
            //Else, move the actor and manually update the agent pos
            else
            {
                transform.position = hit.position;
                agent.nextPosition = transform.position;
            }
        }

        if (agent.pathStatus != NavMeshPathStatus.PathComplete)
        {
            Debug.Log(agent.pathStatus);
            if (GameMaster.Master.player1_PathAvailable && !fixingPath)
            {
                fixingPath = true;
                GameMaster.Master.player1_PathAvailable = false;
                StartCoroutine("WaitForPath");
            }
            else
            {
                if (!invulnerable)
                {
                    StartCoroutine("GetInvulnerability");
                }
            }
        }
    }
Exemplo n.º 17
0
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray.origin, ray.direction, out hitInfo))
            {
                agent.destination = hitInfo.point;
            }
        }
        float   h         = Input.GetAxisRaw("Horizontal");
        float   v         = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(h, 0, v).normalized;

        if (direction.magnitude > 0)
        {
            float inputDirectionAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
            float targetAngle         = inputDirectionAngle + camera.transform.eulerAngles.y;

            Quaternion angleone = Quaternion.Euler(0, targetAngle, 0);
            Quaternion anlgeTow = Quaternion.Euler(0, transform.eulerAngles.y, 0);
            float      final    = Quaternion.Angle(angleone, anlgeTow);
            if (final > 60 && agent.speed - agent.velocity.magnitude < 6)
            {
                agent.destination = transform.position;
            }
            else if (!stopping)
            {
                float      smoothedAngle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
                Quaternion newRotation   = Quaternion.Euler(0, smoothedAngle, 0);
                transform.rotation = newRotation;
                Vector3 cameraAdjustedDirection = newRotation * Vector3.forward;
                //   characterController.SimpleMove(cameraAdjustedDirection.normalized * speed);
                if (agent.enabled)
                {
                    agent.destination = transform.position + cameraAdjustedDirection.normalized * speed;
                }
            }
        }
        agent.SamplePathPosition(agent.areaMask, 0.5f, out NavMeshHit hit);
        Debug.Log((hit.mask & 1 << 3) == 1 << 3);
    }
Exemplo n.º 18
0
    private void CheckGround()
    {
        int        waterMask = 1 << NavMesh.GetAreaFromName("Rock");
        NavMeshHit hit;

        agent.SamplePathPosition(-1, 0.0f, out hit);
        if (hit.mask == waterMask)//changed line
        {
            if (hasAxe == false)
            {
                agent.speed = 3;
            }
            else
            {
                agent.speed = 10;
            }
        }
        else
        {
            agent.speed = 10;
        }
    }
Exemplo n.º 19
0
    void Update()
    {
        navAgent.SamplePathPosition(-1, 0.0f, out navHit); //when player is moving

        //check the areas the player hit
        if (navHit.mask == 8)              //NavMeshArea Mud
        {
            navAgent.speed = speed * 0.5f; //set speed to half the speed
        }
        else
        {
            navAgent.speed = speed;
        }


        if (selected)
        {
            if (Input.GetMouseButtonDown(0))                                //if left mouse button is pressed
            {
                Ray        ray = cam.ScreenPointToRay(Input.mousePosition); //get mouse position
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit)) //if raycast hits something
                {
                    //TO DO...
                    //so you can select another player instead
                    //or so you can select multiple players

                    selector.SetSelectable(false); //not possible to select other players

                    cameraManager.ChangeMovable(); //make the camera able to follow the player
                    cameraManager.StartCoroutine("FollowPlayer", gameObject);

                    StartCoroutine("MovePlayer", hit.point); //begin movement
                }
            }
        }
    }
Exemplo n.º 20
0
    void Update()
    {
        if ((m_targetPosition - transform.position).sqrMagnitude < m_nextPointDst /*|| m_agent.velocity.sqrMagnitude < m_nextPointDst*/)
        {
            m_targetPosition = PlayerLoop.inst.GetNextPoint(true);
            m_agent.SetDestination(m_targetPosition);
            LoopEditor.inst.SetPinPosition(m_targetPosition);
        }
        UpdateTravelDst();

        NavMeshHit navMeshHit;

        m_agent.SamplePathPosition(NavMesh.AllAreas, 0f, out navMeshHit);
        if (navMeshHit.mask == m_dirtMaskId)
        {
            m_agent.speed = m_baseAgentSpeed * m_dirtMultiplier;
            SoundManager.inst.PlayMud();
        }
        else
        {
            SoundManager.inst.StopMud();
            m_agent.speed = m_baseAgentSpeed;
        }
    }
    // Update is called once per frame
    void Foo()
    {
        agent.transform.localPosition = new Vector3();
        agent.transform.rotation      = new Quaternion();

        TrafficState state = TrafficState.Green;

        Collider[] colliders = Physics.OverlapSphere(agent.transform.position, 20.0f);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].tag == "TrafficSignal")
            {
                state  = colliders[i].gameObject.GetComponent <TrafficSignal>().state;
                signal = colliders[i].gameObject;
                break;
            }
        }

        waitingOnSignal = state == TrafficState.Red;
        if (signal && Vector3.Dot(signal.transform.position - car.transform.position, car.transform.forward) < 0.0f)
        {
            waitingOnSignal = false;
        }

        NavMeshHit currentPosition;

        agent.SamplePathPosition(~zebraCrossPathMask, 0.01f, out currentPosition);
        bool alreadyCrossing = currentPosition.hit;

        if (alreadyCrossing)
        {
            waitingOnSignal = false;
        }


        if (waitingOnSignal || Vector3.Distance(car.transform.position, destination.position) <= agent.stoppingDistance)
        {
            steering  = 0.0f;
            speed     = 0.0f;
            handbrake = 1.0f;
        }
        else
        {
            Vector2 to   = new Vector2(agent.transform.forward.x, agent.transform.forward.z);
            Vector2 from = new Vector2(agent.desiredVelocity.x, agent.desiredVelocity.z);
            from = from.normalized;
            to   = to.normalized;

            turningFactor = Vector2.Dot(from, to);
            turningFactor = Mathf.Sign(turningFactor) * Mathf.Clamp(Mathf.Abs(turningFactor), 0.35f, 1.0f);

            speed = agent.desiredVelocity.magnitude * turningFactor;
            speed = speed / agent.speed;

            steeringAngle = Vector2.SignedAngle(from, to);
            steering      = RemapRange(-carController.m_MaximumSteerAngle, carController.m_MaximumSteerAngle, -1, 1, steeringAngle);
            if (turningFactor < 0.0f)
            {
                steering = steering * -1.0f;
            }
            handbrake = 0.0f;
        }

        car.GetComponent <CarController>().Move(steering, speed, speed, handbrake);

        if (draw)
        {
            DebugDrawPath(agent.path);
            Debug.DrawRay(agent.transform.position, agent.desiredVelocity, Color.cyan, 0.0f, false);
            Debug.DrawRay(agent.transform.position, agent.transform.forward * Vector3.Magnitude(agent.desiredVelocity), Color.yellow, 0.0f, false);
        }
    }
Exemplo n.º 22
0
    // Update is called once per frame
    void Update()
    {
        TimeElapsed += Time.deltaTime;
        if (agent.speed != 0 && agent.remainingDistance != 0)
        {
            hasBegunRoute = true;
        }

        NavMeshPath path = new NavMeshPath();

        agent.CalculatePath(currentDestination.position, path);

        // if destination is blocked, then stop the agent
        if (!isStopped && path.status != NavMeshPathStatus.PathComplete)
        {
            agent.ResetPath();
            isStopped = true;
            Debug.Log("Destination Blocked");
        }

        // if destination has become unblocked, then start the agent
        else if (isStopped && path.status == NavMeshPathStatus.PathComplete)
        {
            agent.destination = currentDestination.position;
            //agent.SetPath(path);
            Debug.Log("Destination Found");
            isStopped = false;
        }

        float dist = agent.remainingDistance;



        float timeToWait = 4f;

        if (hasBegunRoute && dist != Mathf.Infinity && agent.pathStatus == NavMeshPathStatus.PathComplete && dist == 0)
        {
            hasBegunRoute = false;
            currentDestinationIndex++;
            if (currentDestinationIndex < destinationList.Count)
            {
                // TODO use expected time for each destination type

                if (!IsInTransition)
                {
                    Debug.Log("Waiting " + timeToWait + " seconds, time elapsed: " + TimeElapsed);
                    IsInTransition      = true;
                    TransitionStartTime = TimeElapsed;
                }
            }
            else
            {
                Debug.Log("Path complete, stations visited: " + currentDestinationIndex);
            }
        }


        if (IsInTransition && (TimeElapsed < (TransitionStartTime + timeToWait / 4f)))
        {
            //agent.destination = agent.transform.position + 0.1f*(agent.transform.right + agent.transform.forward);
            head.transform.Rotate(transform.up, 100f * Time.deltaTime);
        }
        else if (IsInTransition && (TimeElapsed < (TransitionStartTime + 3 * timeToWait / 4)))
        {
            //agent.destination = agent.transform.position + 0.1f * (agent.transform.right - agent.transform.forward);
            head.transform.Rotate(transform.up, -100f * Time.deltaTime);
        }
        else if (IsInTransition && (TimeElapsed < (TransitionStartTime + timeToWait)))
        {
            //agent.destination = agent.transform.position + 0.1f * (-agent.transform.forward);
            head.transform.Rotate(transform.up, 100f * Time.deltaTime);
        }
        if (IsInTransition && (TimeElapsed >= (TransitionStartTime + timeToWait)))
        {
            transitionPhase    = 0;
            IsInTransition     = false;
            currentDestination = destinationList[currentDestinationIndex];
            agent.destination  = currentDestination.position;
            Debug.Log("Pathing to Next Destination (Destination " + destinationList[currentDestinationIndex].name + ")");
            isStopped = false;
        }

        NavMeshHit navHit;

        agent.SamplePathPosition(NavMesh.AllAreas, 0.0f, out navHit);

        if (!isStopped || IsInTransition)
        {
            character.Move(agent.desiredVelocity, false, false);
        }
        else if (!IsInTransition)
        {
            character.Move(Vector3.zero, false, false);
        }

        // sets the speed based on the cost of the terrain beneath agent
        //agent.speed = baseSpeed * 2 / agent.GetAreaCost(GetAreaListFromNavMeshHit(navHit)[0]);
    }
    /// <summary>
    /// Update method.
    /// </summary>
    void Update()
    {
        // Check if the flash pedestrian is paused
        if (globalParam != null)
        {
            if (globalParam.flashPedestriansPaused && !isPause)
            {
                navAgent.speed = 0;
                isPause        = true;
            }
            else if (!globalParam.flashPedestriansPaused && isPause)
            {
                navAgent.speed = profile.speed;

                if (goingBikingToDestination)
                {
                    navAgent.speed += 3;
                }

                isPause = false;
            }
        }

        if (!isPause)
        {
            // Check the weather and update pedestrian behaviour accordingly
            if (currentWeather != flashInformer.globalParam.currentWeatherCondition)
            {
                ChangePedestrianBehaviourOnWeather(flashInformer.globalParam.currentWeatherCondition);
            }

            // If going to station, check if pedestrian has arrived to station
            if (goingToStation && Vector3.Distance(this.transform.position, nextPoint.position) < 4.0f)
            {
                // Arrives at the station
                goingToStation = false;
                FSM.SetBool("OnStation", true);
            }

            // If going to destination, check if pedestrian has arrived to destination
            if (goingToDestination && Vector3.Distance(this.transform.position, routing.destinationPoint.transform.position) < 4.0f)
            {
                // Arrives at the destination
                goingToDestination = false;
                FSM.SetBool("OnDestination", true);
            }

            // If going to take a bike, check if pedestrian has arrived to bike station
            if (takingABike && Vector3.Distance(this.transform.position, targetedBikeStation.transform.position) < 4.0f)
            {
                // Arrives at the bike station
                takingABike = false;
                FSM.SetBool("OnBikeStation", true);
            }

            // If going to take a bike an arrived and there is no bike station there, bike station has moved
            if (takingABike && (navAgent.remainingDistance < 3.0f || navAgent.isPathStale))
            {
                navAgent.ResetPath();
                navAgent.SetDestination(targetedBikeStation.transform.position);
            }

            // If going to destination biking, check if pedestrian has arrived to destination
            if (goingBikingToDestination && Vector3.Distance(this.transform.position, routing.destinationPoint.transform.position) < 4.0f)
            {
                // Arrives at the destination
                goingBikingToDestination = false;
                FSM.SetBool("OnDestination", true);
            }

            // If car awareness is active and pedestrian is walking or cycling, check if it is on a road
            if (profile.carAwareness && (goingToStation || goingToDestination || takingABike || goingBikingToDestination))
            {
                if (carAwarenessTimer > carAwarenessFrequency)
                {
                    NavMeshHit navHit;
                    if (navAgent.enabled && navAgent.hasPath && !navAgent.SamplePathPosition(-1, 2.0f, out navHit))
                    {
                        if ((navHit.mask & roadMask) != 0)
                        {
                            // Send message to the cars around
                            InformVehiclesAround();
                        }
                    }

                    carAwarenessTimer = 0.0f;
                }

                carAwarenessTimer += Time.deltaTime;
            }

            // If bikes are enabled, check if there are bike stations around
            if (flashInformer.globalParam.bikesEnabled && (!takingABike || !goingBikingToDestination))
            {
                // If the pedestrian is willing to take a bike, it will look for bike stations nearby.
                if ((goingToStation || goingToDestination) && bikeAwarenessTimer > bikeAwarenessFrequency &&
                    profile.chanceOfTakingABike + flashInformer.globalParam.percOfPedTakingBikes * profile.weatherFactorOnTakingBikes > 1.0f)
                {
                    targetedBikeStation = flashInformer.FindBikeStationNearby(this.transform.position);

                    if (targetedBikeStation != null && targetedBikeStation.capacityNumber > 0)
                    {
                        navAgent.enabled = false;
                        GoToBikeStation();
                    }

                    bikeAwarenessTimer = 0.0f;
                }

                bikeAwarenessTimer += Time.deltaTime;
            }
        }
    }
Exemplo n.º 24
0
    // Update is called once per frame
    void Update()
    {
        agent.updateRotation = false;
        NavMeshHit hit;

        if (!agent.SamplePathPosition(0, 1f, out hit))
        {
            //goidle
            //cycle Position

            agent.speed = 0f;
        }
        else
        {
            //Keep going to current Target

            agent.SetDestination(targetPosition.position);
            float axis = Input.GetAxis("Vertical");
            if (agent.remainingDistance < idleRange)
            {
                agent.speed = speed * axis;

                anim.SetFloat("Speed", 1 * axis);
            }
            else
            {
                agent.speed = speed * catchUpMultiplier;
                anim.SetFloat("Speed", 1);
            }
        }
        if (enemyTarget != null)
        {
            RotateTowardsTarget();
            if (enemyTarget.GetComponent <NPCHealthMC>().dead)
            {
                anim.SetBool("Shooting", false);
                enemyTarget = null;
            }
        }
        if (enemyTarget == null)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, origRotation, 0.5f);
        }
        CheckDestinationAngle();
        if (enemies.Count > 0)
        {
            CheckClosestEnemy();
        }
        if (enemies.Count <= 0)
        {
            if (enemyTarget != null)
            {
                enemyTarget = null;
            }
            List <Transform> _list = NPCSWATControl.instance.TryGetEnemy();
            if (_list != null)
            {
                enemies = _list;
            }
        }
        agent.SetDestination(targetPosition.position);
    }
    // Update is called once per frame
    void Update()
    {
        agent.transform.localPosition = new Vector3();
        agent.transform.rotation      = new Quaternion();

        // Check whether there is a traffic signal at front
        signalToStop = false;
        RaycastHit hit;

        //Debug.DrawRay(car.transform.position, car.transform.forward * 5.0f, Color.white, 0.0f, false);
        if (Physics.Raycast(car.transform.position, car.transform.forward, out hit, 5.0f))//, DefaultRaycastLayers, QueryTriggerInteraction.Collide))
        {
            //Debug.Log(this.name + " detected " + hit.collider.name + " having tag " + hit.collider.tag);
            if (hit.collider.tag == "TrafficSignal")
            {
                GameObject trafficSignal = hit.collider.gameObject;

                NavMeshHit currentPosition;
                agent.SamplePathPosition(~zebraCrossPathMask, 0.01f, out currentPosition);
                bool alreadyCrossing = currentPosition.hit;

                signalToStop = alreadyCrossing ? false : trafficSignal.GetComponent <TrafficSignal>().state == TrafficState.Red;
            }
        }

        //Check whether there is any collider too close to the car
        somethingTooClose = collidersInTrigger > 0;

        //Check whether the car has reached destination
        reachedDestination = Vector3.Distance(car.transform.position, destination.position) <= agent.stoppingDistance;

        if (signalToStop)
        {
            BrakeOnTheSpot();
        }
        else if (somethingTooClose)
        {
            BrakeOnTheSpot();
        }
        else if (reachedDestination)
        {
            BrakeOnTheSpot();
        }
        else // Free to move
        {
            Vector2 to   = new Vector2(agent.transform.forward.x, agent.transform.forward.z);
            Vector2 from = new Vector2(agent.desiredVelocity.x, agent.desiredVelocity.z);

            from = from.normalized;
            to   = to.normalized;

            turningFactor = Vector2.Dot(from, to);

            // Don't allow turning factor to be 0 or very small
            turningFactor = Mathf.Sign(turningFactor) * Mathf.Clamp(Mathf.Abs(turningFactor), 0.35f, 1.0f);

            // If turning factor magnitude is greater than 0.5,
            // and it is negative, it means that we need to go in
            // reverse as we cannot take such a sharp turn.
            // Else the turning factor is kept positive, meaning
            // that we'll try to make that turn without going into reverse
            if (Mathf.Abs(turningFactor) < 0.5f)
            {
                turningFactor = Mathf.Abs(turningFactor);
            }

            //Sharper the turn, smaller the speed.
            speed = agent.desiredVelocity.magnitude * turningFactor;
            speed = speed / agent.speed; // normalize

            steeringAngle = Vector2.SignedAngle(from, to);
            steering      = RemapRange(-carController.m_MaximumSteerAngle, carController.m_MaximumSteerAngle, -1, 1, steeringAngle); // normalize

            if (turningFactor < 0.0f)
            {
                steering = steering * -1.0f;                       //if steering in reverse
            }
            handbrake = 0.0f;

            carController.Move(steering, speed, speed, handbrake);
            pausePosition = car.transform.position;
        }


        // Update the position of threat detection depending on whether we are going forward or reverse
        Vector3 safetyCushionPos = car.transform.Find("SafetyCushion").localPosition;

        car.transform.Find("SafetyCushion").localPosition = new Vector3(safetyCushionPos.x, safetyCushionPos.y, Mathf.Sign(turningFactor) * Mathf.Abs(safetyCushionPos.z));

        if (drawVisualInfo)
        {
            DebugDrawPath(agent.path);
            Debug.DrawRay(agent.transform.position, agent.desiredVelocity, Color.cyan, 0.0f, false);
            Debug.DrawRay(agent.transform.position, agent.transform.forward * Vector3.Magnitude(agent.desiredVelocity), Color.yellow, 0.0f, false);
        }
    }
Exemplo n.º 26
0
    // Update is called once per frame

    void Update()
    {
        TrafficState state = TrafficState.Red;
        RaycastHit   hit;

        //Debug.DrawRay(agent.transform.position, agent.transform.forward, Color.yellow, 0.0f, false);
        if (Physics.Raycast(agent.transform.position, agent.transform.forward, out hit, 1.0f))//, DefaultRaycastLayers, QueryTriggerInteraction.Collide))
        {
            //Debug.Log(this.name + " detected " + hit.collider.name + " having tag " + hit.collider.tag);
            if (hit.collider.tag == "TrafficSignal")
            {
                lastSeenTrafficSignal = hit.collider.gameObject;
                state = lastSeenTrafficSignal.GetComponent <TrafficSignal>().state;
            }
        }

        if (waitingOnSignal && lastSeenTrafficSignal.GetComponent <TrafficSignal>().state == TrafficState.Red)
        {
            waitingOnSignal = false;
            agent.velocity  = lastAgentVelocity;
            agent.SetPath(lastAgentPath);
        }
        else
        {
            NavMeshHit lookAheadPosition, currentPosition;
            agent.SamplePathPosition(~zebraCrossPathMask, 1.0f, out lookAheadPosition);
            agent.SamplePathPosition(~zebraCrossPathMask, 0.01f, out currentPosition);

            bool zebraCrossAhead = lookAheadPosition.hit;
            bool alreadyCrossing = currentPosition.hit;

            if (state == TrafficState.Green && zebraCrossAhead && !alreadyCrossing)
            {
                lastAgentVelocity = agent.velocity;
                lastAgentPath     = agent.path;
                waitingOnSignal   = true;
                agent.velocity    = Vector3.zero;
                agent.ResetPath();
            }
        }

        Color c = Color.white;

        if (waitingOnSignal && state == TrafficState.Red)
        {
            c = Color.red;
        }
        else if (waitingOnSignal && state == TrafficState.Green)
        {
            c = Color.blue;
        }
        else if (!waitingOnSignal && state == TrafficState.Red)
        {
            c = Color.yellow;
        }
        else if (!waitingOnSignal && state == TrafficState.Green)
        {
            c = Color.green;
        }


        //Color c = waitingOnSignal ? Color.red : Color.green;
        color.material.shader = Shader.Find("_Color");
        color.material.SetColor("_Color", c);

        //Find the Specular shader and change its Color to red
        color.material.shader = Shader.Find("Specular");
        color.material.SetColor("_SpecColor", c);
    }
Exemplo n.º 27
0
    //update is called once per frame
    private void Update()
    {
        //if the agent is crossing a road, they can choose a random faster speed - to simulat a human running
        NavMeshHit hit;

        if (!agent.SamplePathPosition(NavMesh.AllAreas, 0.0f, out hit))
        {
            if ((hit.mask & crossingMask) != 0)
            {
                int random = UnityEngine.Random.Range(8, 15);
                agent.speed = random; //run across roads
            }
            else
            {
                agent.speed = 5; //walk around the paths
            }
        }

        //if the agent is close to their waypoint, choose another at random
        if (agent.remainingDistance < 0.5)
        {
            int d = UnityEngine.Random.Range(0, wps.Length);
            agent.SetAreaCost(4, 20);
            agent.SetDestination(wps[d].transform.position);
        }
        //change the acceleration if the agent is turning corners to help navigate
        else if (agent.hasPath)
        {
            agent.isStopped = false;

            Vector3 toTarget  = agent.steeringTarget - this.transform.position;
            float   turnAngle = Vector3.Angle(this.transform.forward, toTarget);
            agent.acceleration = turnAngle * agent.speed;
        }

        // Simple dead reckoning algorithm below; checking to see if distance moved since last espdu (change) > threshold value
        change[0]      += Mathf.Abs(this.agent.transform.position.x - prev_location.x);
        prev_location.x = this.agent.transform.position.x;
        change[1]      += Mathf.Abs(this.agent.transform.position.y - prev_location.y);
        prev_location.y = this.agent.transform.position.y;

        if ((change[0] > threshold) | (change[1] > threshold))
        {
            change[0]         = 0;
            change[1]         = 0;
            this.sendNewEspdu = true;
        }
        else
        {
            this.sendNewEspdu = false;
        }

        // Sending the new Espdu if necessary (if Dead Reckoning threshold passed)
        if (this.sendNewEspdu)
        {
            // Declaring the position of the Bot (in WSP - World Space Position)
            Vector3Double loc = espdu.EntityLocation;                                   // Issues here

            loc.X = this.agent.transform.position.x;
            loc.Y = this.agent.transform.position.y;
            loc.Z = 0.0;


            if (espdu.EntityLocation.X.Equals(null) | espdu.EntityLocation.Y.Equals(null))
            {
                Debug.LogError("Espdu's location value is NULL!!!");
            }

            // Declaring the Bot's velocity
            Vector3Float vel = espdu.EntityLinearVelocity;

            vel.X = this.agent.velocity.x;
            vel.Y = this.agent.velocity.y;
            vel.Z = 0.0f;

            if (espdu.EntityLinearVelocity.X.Equals(null) | espdu.EntityLinearVelocity.Y.Equals(null))
            {
                Debug.LogError("Espdu's linear velocity value is NULL!!!");
            }

            // Declaring the DeadReckoning Algorithm to be used (R, P, W)
            espdu.DeadReckoningParameters.DeadReckoningAlgorithm = (byte)2;

            // Sending the Espdu
            espdu.Timestamp = DisTime.DisRelativeTimestamp;

            // Prepare output
            DataOutputStream dos = new DataOutputStream(Endian.Big);
            espdu.MarshalAutoLengthSet(dos);

            // Transmit broadcast messages
            Sender.SendMessages(dos.ConvertToBytes());
            string mess = string.Format("Message sent with TimeStamp [{0}] Time Of[{1}]", espdu.Timestamp, (espdu.Timestamp >> 1));
            Debug.Log(mess);
            this.sendNewEspdu = false;
        }
    }