Exemplo n.º 1
0
    void Update()
    {
        if (!_moving)
        {
            return;
        }

        // Stop the car if there is an obstacle
        if (ObstacleExists())
        {
            StopCar(true);
            return;
        }

        if (_switchingLanes)
        {
            // Set target
            Vector3 targetPos;
            if (_intersectionOffset > 0f)   // turning into the middle of a lane
            {
                var straight = _intersectionFrom.GetComponent <IntersectionStraight>();
                targetPos = straight.MainRoad.GetPointInPath(straight.IntersectionOffset);
            }
            else
            {
                targetPos = _hitCenter ? _targetLane.GetStartPoint() : _intersectionFrom.transform.position;
            }

            // Move our position a step closer to the target.
            float step = Speed * Time.deltaTime; // calculate distance to move
            transform.position = Vector3.MoveTowards(transform.position, targetPos, step);

            // Look towards movement direction
            Vector3 targetDirection = targetPos - transform.position;
            Vector3 newDirection    = Vector3.RotateTowards(transform.forward, targetDirection, step, 0.0f);
            transform.rotation = Quaternion.LookRotation(newDirection);

            // Check if the position are approximately equal.
            if (Vector3.Distance(transform.position, targetPos) < 0.001f)
            {
                if (_hitCenter)
                {
                    PutCarOnLaneFromIntersection(_targetLane, _intersectionOffset);
                }
                else
                {
                    _hitCenter = true;
                }
            }
        }
        else     // Car is moving forward
        {
            if (_currentLane == null)
            {
                Debug.LogWarning("No lane"); return;
            }

            if (_shouldTurnOff)
            {
                if (!IsAtTurnoff())
                {
                    return;
                }
                _shouldTurnOff = false;
                StopCar();
                GetOffLane();
                MoveToLane(_intersectionStraight.LaneEntrances.First(), _intersectionStraight);
            }
            else
            {
                // Check for the end of the path
                if (!IsAtEnd())
                {
                    return;
                }
                StopCar();
                PlaceCarInQueue();
            }
        }
    }