public virtual void LatencyAdjustment(GameTime gameTime, long messageTimeStamp)
        {
            this.secondsUntilUpdateMessage = this.SecondsBetweenUpdateMessage;
            this.lastMessageTimeStamp      = messageTimeStamp;

            TimeSpan deltaSpan = new TimeSpan(gameTime.TotalGameTime.Ticks - this.lastMessageTimeStamp);

            averageLatency.AddValue((float)(deltaSpan.TotalSeconds));
            float timeDeviation = (float)(deltaSpan.TotalSeconds) - averageLatency.AverageValue;

            if (timeDeviation > 0)
            {
                GameObjectField.SetModeSimulation();
                this.SubclassUpdate(timeDeviation);
                this.SimulationStateOnlyUpdate(timeDeviation);
                this.Smooth(timeDeviation);
            }
        }
Example #2
0
        public Obstacle PerformSpawn()
        {
#if DEBUG
            var screen = FlatRedBall.Screens.ScreenManager.CurrentScreen;
            LastTwoSpawnTimes[0] = LastTwoSpawnTimes[1];
            LastTwoSpawnTimes[1] = screen.PauseAdjustedCurrentTime;

            SpawnRollingAverage.AddValue((float)(LastTwoSpawnTimes[1] - LastTwoSpawnTimes[0]));
#endif
            var newObstacle = ObstacleFactory.CreateNew();

            if (FlatRedBallServices.Random.Between(0, 1) < RatioOfGold)
            {
                newObstacle.CurrentBonusCategoryState = Obstacle.BonusCategory.Bonus;
            }

            int repositionsSoFar = 0;
            while (repositionsSoFar <= NumberOfTimesToRepositionCrates)
            {
                PositionNewObstacle(newObstacle);

                var distanceFromCenterOfPath = Math.Abs(newObstacle.X - pathX) - newObstacle.Width;

                bool isOnPath = distanceFromCenterOfPath < PathWidth / 2.0f;

                if (!isOnPath)
                {
                    break;
                }

                repositionsSoFar++;
            }



            lastSpawnY = this.Y;

            return(newObstacle);
        }
Example #3
0
        public static string ForceGetMemoryInformation()
        {
            string memoryInformation;

            long currentUsage;

#if WINDOWS_PHONE
            currentUsage      = (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
            memoryInformation = DeviceExtendedProperties.GetValue("DeviceTotalMemory") + "\n" +
                                currentUsage + "\n" +
                                DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
#else
            currentUsage      = GC.GetTotalMemory(false);
            memoryInformation = "Total Memory: " + currentUsage;
#endif

#if DEBUG
            if (mLastMemoryUse >= 0)
            {
                long difference = currentUsage - mLastMemoryUse;

                if (difference >= 0)
                {
                    mAllocationAverage.AddValue((float)(difference / mMemoryUpdateFrequency));
                }
            }
            memoryInformation += "\nAverage Growth per second: " +
                                 mAllocationAverage.Average.ToString("0,000");
#endif

            LastCalculationTime = TimeManager.CurrentTime;
#if DEBUG
            mLastMemoryUse = currentUsage;
#endif


            return(memoryInformation);
        }
        /// <summary>
        /// Incoming network packets tell us where the tank was at the time the packet
        /// was sent. But packets do not arrive instantly! We want to know where the
        /// tank is now, not just where it used to be. This method attempts to guess
        /// the current state by figuring out how long the packet took to arrive, then
        /// running the appropriate number of local updates to catch up to that time.
        /// This allows us to figure out things like "it used to be over there, and it
        /// was moving that way while turning to the left, so assuming it carried on
        /// using those same inputs, it should now be over here".
        /// </summary>
        private void ApplyPrediction(GameTime gameTime, TimeSpan latency, float packetSendTime)
        {
            // Work out the difference between our current local time
            // and the remote time at which this packet was sent.
            float localTime = (float)gameTime.TotalGameTime.TotalSeconds;

            float timeDelta = localTime - packetSendTime;

            // Maintain a rolling average of time deltas from the last 100 packets.
            clockDelta.AddValue(timeDelta);

            // The caller passed in an estimate of the average network latency, which
            // is provided by the XNA Framework networking layer. But not all packets
            // will take exactly that average amount of time to arrive! To handle
            // varying latencies per packet, we include the send time as part of our
            // packet data. By comparing this with a rolling average of the last 100
            // send times, we can detect packets that are later or earlier than usual,
            // even without having synchronized clocks between the two machines. We
            // then adjust our average latency estimate by this per-packet deviation.

            float timeDeviation = timeDelta - clockDelta.AverageValue;

            latency += TimeSpan.FromSeconds(timeDeviation);

            TimeSpan oneFrame = TimeSpan.FromSeconds(1.0 / 60.0);

            // Apply prediction by updating our simulation state however
            // many times is necessary to catch up to the current time.
            while (latency >= oneFrame)
            {
                ApplyInputToPlayer(ref simulationState, _updatePacket.Input, (float)latency.TotalSeconds);
                Update(ref simulationState, (float)latency.TotalSeconds);

                latency -= oneFrame;
            }
        }
Example #5
0
    void Update()
    {
        if (_rb.IsSleeping())
        {
            _rb.WakeUp();
        }

        if (transform.position.y <= _minY)
        {
            ResetLocation();
            return;
        }

        RaycastHit hit;
        Ray        ray = new Ray(transform.position, Vector3.down);

        if (Physics.Raycast(ray, out hit, 1.05f))
        {
            _grounded = true;
        }

        float MoveH = Input.GetAxis("Move H " + _indexStr);
        float MoveV = Input.GetAxis("Move V " + _indexStr);

        Helpers.CleanupAxes(ref MoveH, ref MoveV);

        if (ValveInteractingWith &&
            Mathf.Abs(ValveInteractingWith.GetMostRecentStickRotationSpeed()) > 0.1f)
        {
            MoveH = 0;
            MoveV = 0;
        }

        Vector3 translation = Vector3.zero;

        if (_blockRiding)
        {
            translation         = (_blockRiding.transform.position - _blockRidingPrevPos);
            _blockRidingPrevPos = _blockRiding.transform.position;
        }

        Vector3 moveVec = new Vector3(MoveH, 0, MoveV);

        if (moveVec.sqrMagnitude > 1.0f)
        {
            moveVec.Normalize();
        }
        moveVec *= MoveSpeed;
        if (!_grounded)
        {
            moveVec *= 0.5f;
        }

        transform.Translate(translation + moveVec, Space.World);


        if (moveVec.magnitude > 0.01f)
        {
            transform.rotation = Quaternion.RotateTowards(_pRot, Quaternion.LookRotation(moveVec.normalized), Time.deltaTime * _turnSpeed);
            _pRot = transform.rotation;
        }
        else
        {
            transform.rotation = _pRot;
        }

        if (ValveInteractingWith)
        {
            _pAiming = false;
            _trajectoryPlane.SetActive(false);
            _averageInteractStickLength.Clear();
        }
        else
        {
            float horizontal = Input.GetAxis("Interact H " + _indexStr);
            float vertical   = Input.GetAxis("Interact V " + _indexStr);

            Helpers.CleanupAxes(ref horizontal, ref vertical);

            float   minimumExtensionLength = 0.2f;
            Vector2 stickExtension         = new Vector2(horizontal, vertical);
            float   extensionLength        = stickExtension.magnitude;

            _averageInteractStickLength.AddValue(extensionLength);

            if (extensionLength > minimumExtensionLength)
            {
                float currentAverageStickDir = _averageInteractDirection.CurrentAverage;
                float currentStickDir        = Mathf.Atan2(vertical, horizontal) + Mathf.PI;
                if (_pAiming)
                {
                    // When stick is closer to center weight less heavily
                    currentStickDir = Mathf.Lerp(currentAverageStickDir, currentStickDir, extensionLength);
                    _averageInteractDirection.AddValue(currentStickDir);
                }
                else
                {
                    _trajectoryPlane.SetActive(true);
                    // This prevents the plane from always starting with a rotation of 0 rad
                    _averageInteractDirection.SetAllValues(currentStickDir);
                }

                _trajectoryPlaneMatOffset += _trajectoryPlaneOffsetSpeed * Time.deltaTime;
                _trajectoryPlaneMesh.material.SetTextureOffset("_MainTex", new Vector2(0, -_trajectoryPlaneMatOffset));
                float textureScaleV = Mathf.Lerp(0.1f, _maxProjectilePlaneTilingV, _averageInteractStickLength.CurrentAverage);
                _trajectoryPlaneMesh.material.SetTextureScale("_MainTex", new Vector2(1.0f, textureScaleV));

                _trajectoryPlane.transform.position = transform.position;
                _trajectoryPlane.transform.rotation = Quaternion.LookRotation(
                    Quaternion.AngleAxis(Mathf.Rad2Deg * (3.0f * Mathf.PI / 2.0f - _averageInteractDirection.CurrentAverage - Mathf.PI), Vector3.up)
                    * Vector3.forward, Vector3.up);

                Vector3 trajectoryPlaneScale = new Vector3(1.0f, 1.0f, _averageInteractStickLength.CurrentAverage);
                _trajectoryPlane.transform.localScale = trajectoryPlaneScale;

                _pAiming = true;
            }
            else
            {
                _trajectoryPlane.SetActive(false);
                _pAiming = false;

                // If the average is still high then the player quickly released the stick
                // Treat as fire command
                if (_averageInteractStickLength.CurrentAverage > 0.2f)
                {
                    Vector3 forceDir = Quaternion.AngleAxis(Mathf.Rad2Deg * (3.0f * Mathf.PI / 2.0f - _averageInteractDirection.CurrentAverage - Mathf.PI), Vector3.up) * Vector3.forward;
                    forceDir.y += _projectileHeightAddition;
                    forceDir.Normalize();
                    Vector3 force = forceDir * _projectileForceMagnitude * _averageInteractStickLength.CurrentAverage;

                    Vector3    projectilePos      = transform.position + forceDir * 0.6f;
                    GameObject projectileInstance = Instantiate(ProjectilePrefab, projectilePos, Quaternion.identity);
                    projectileInstance.GetComponent <Rigidbody>().AddForce(force);

                    AudioManager.Instance.PlaySoundRandomized("whoosh");

                    _averageInteractDirection.Clear();
                    _averageInteractStickLength.Clear();
                }
            }
        }
    }