// on updates do animations and controls protected override void Update(double deltaTime) { // if user click 'exit' action, exit game if (Input.Down("exit")) { Game.Exit(); } // skip frames with too much delta if (deltaTime > 1) { return; } // get window size var windowSize = Gfx.WindowSize; // move ball _ballPosition.AddSelf(_ballSpeed.Multiply((float)deltaTime * 235f)); if (_ballPosition.X < 0) { _ballSpeed.X = Math.Abs(_ballSpeed.X); } if (_ballPosition.X > windowSize.X) { _ballSpeed.X = -Math.Abs(_ballSpeed.X); } if (_ballPosition.Y < 0) { _ballSpeed.Y = Math.Abs(_ballSpeed.Y); } if (_ballPosition.Y > windowSize.Y + 250) { _ballSpeed.Y = -Math.Abs(_ballSpeed.Y); } _isBallOut = _ballPosition.Y > windowSize.Y; // if ball out, reset speed if (_isBallOut && Math.Abs(_ballSpeed.X) > 1f) { _ballSpeed.X = 1; } // update explosions foreach (Explosion exp in _explosions) { if (exp.Radius > 10) { exp.Color.A -= (float)deltaTime * 1.25f; } exp.Radius += (float)deltaTime * 150f; } _explosions.RemoveAll(x => x.Color.A < 0); // player movement speed var playerSpeed = 350f; float playerVelocity = 0f; // do player movement if (!_isBallOut) { // move player left if (_player.Left > 0 && Input.Down("left")) { playerVelocity -= (float)deltaTime * playerSpeed; } // move player right if (_player.Right < windowSize.X && Input.Down("right")) { playerVelocity += (float)deltaTime * playerSpeed; } } // update player position _player.X += playerVelocity; // test collision with blocks Block collidedBlock = null; foreach (var block in _blocks) { // check collision with block + some extra margin var rect = block.Rectangle; rect.X -= 5; rect.Width += 10; rect.Y -= 5; rect.Height += 10; // ball hit block if (rect.Contains(_ballPosition)) { AddExplosion(_ballPosition, block.Color); collidedBlock = block; if ((_ballPosition.Y < block.Rectangle.Top + 6) || (_ballPosition.Y > block.Rectangle.Bottom - 6)) { _ballSpeed.Y *= -1; } if ((_ballPosition.X < block.Rectangle.Left + 5) || (_ballPosition.X > block.Rectangle.Right - 5)) { _ballSpeed.X *= -1; } break; } } if (collidedBlock != null) { _blocks.Remove(collidedBlock); } // test collision with player paddle if (_ballSpeed.Y > 0) { // create a slightly larger rect for player collision var playerCollision = _player; playerCollision.X -= 10; playerCollision.Width += 10; playerCollision.Y -= 10; playerCollision.Height += 15; // check if hit ball if (playerCollision.Contains(_ballPosition)) { // update ball speed _ballSpeed.Y = -_ballSpeed.Y; _ballSpeed.X += playerVelocity * 0.1f; // special case for corners if (_ballPosition.X < _player.Left + 10) { if (_ballSpeed.X > 0) { _ballSpeed.X = 0f; } _ballSpeed.X -= 0.65f; AddExplosion(_ballPosition, new Color(1f, 0.5f, 0f, 1f)); } else if (_ballPosition.X > _player.Right - 10) { if (_ballSpeed.X < 0) { _ballSpeed.X = 0f; } _ballSpeed.X += 0.65f; AddExplosion(_ballPosition, new Color(1f, 0.5f, 0f, 1f)); } } } }