/// <summary>Creates a 800x600 window with the specified title.</summary> public Game() : base(WindowWidth, WindowHeight, GraphicsMode.Default, "Funny PongGL") { //Increase speed as time goes by _timer.Elapsed += (sender, args) => { _dx += 0.002f * Math.Sign(_dx); }; VSync = VSyncMode.On; _ballCenterX = (float)_randomClass.NextDouble(); _ballCenterY = (float)_randomClass.NextDouble(); _dx = BallSpeedX; _dy = BallSpeedY; _sprites = new Sprite[2]; _sprites[PlayerOne] = new Sprite(2); _sprites[PlayerTwo] = new Sprite(2); _sprites[PlayerOne].Vertices[Bottom].X = -0.025f + 0.8f; _sprites[PlayerOne].Vertices[Bottom].Y = -0.15f; _sprites[PlayerOne].Vertices[Top].X = 0.025f + 0.8f; _sprites[PlayerOne].Vertices[Top].Y = 0.15f; _sprites[PlayerTwo].Vertices[Bottom].X = -0.025f - 0.8f; _sprites[PlayerTwo].Vertices[Bottom].Y = -0.15f; _sprites[PlayerTwo].Vertices[Top].X = 0.025f - 0.8f; _sprites[PlayerTwo].Vertices[Top].Y = 0.15f; _timer.Start(); }
private void SetBallSpeed(Sprite player) { var currentVelocity = Math.Sqrt(_dx * _dx + _dy * _dy); var localHitLoc = _ballCenterY - player.Vertices[Bottom].Y + 0.15f; // Where did the ball hit, relative to the paddle's center? var angleMultiplier = Math.Abs(localHitLoc / 0.15f); // Express local hit loc as a percentage of half the paddle's height // Use the angle multiplier to determine the angle the ball should return at, from 0-65 degrees. Then use trig functions to determine new x/y velocities. Feel free to use a different angle limit if you think another one works better. var xVelocity = Math.Cos(85.0f * angleMultiplier * Math.PI / 180) * currentVelocity; var yVelocity = Math.Sin(85.0f * angleMultiplier * Math.PI / 180) * currentVelocity; // If the ball hit the paddle below the center, the yVelocity should be flipped so that the ball is returned at a downward angle if (localHitLoc < 0) { yVelocity = -yVelocity; } // If the ball came in at an xVelocity of more than 0, we know the ball was travelling right when it hit the paddle. It should now start going left. if (_dx < 0) { xVelocity = -xVelocity; } _dx = (float)xVelocity; _dy = (float)yVelocity; }