private void CheckCollision() { // ball and paddle Rect rect = ball.GetRect(); rect.Intersect(paddle.GetRect()); if (!rect.IsEmpty) { // paddle 100 px // ball position 0-100 double ballPosition = ball.LocationX - paddle.LocationX; // -0.5 <-> 0.5 double hitPercent = (ballPosition / paddle.Width) - 0.5; // set ball speed ball.SetSpeed(hitPercent); } // ball and blocks foreach (Block block in blocks) { Rect ballRect = ball.GetRect(); ballRect.Intersect(block.GetRect()); if (!ballRect.IsEmpty) { // remove from List collection blocks.Remove(block); // remove from Canvas canvas.Children.Remove(block); // ball SpeedX and SpeedY? double ballCenter = ball.LocationX + (ball.Width) / 2; if (ballCenter < block.LocationX || ballCenter > (block.LocationX + block.Width)) { ball.SpeedX *= -1; } else { ball.SpeedY *= -1; } // break break; } } }
void tmr_Tick(object sender, EventArgs e) { Point res; for (int iBall = 0; iBall < _NumBalls; iBall++) { // first we see if the ball will collide // with the frame, the paddle or the blocks var ball = _balls[iBall]; if (!ball.IsDead) { // first see if it hits the walls res = WillCollide( ball, ClientRectangle, // rect of whole frame fShouldBeInside: true); if (res.X == 0 && res.Y == 0) //didn't hit { // see if it hits paddle res = WillCollide( ball, _paddle.GetRect(), // rect of paddle fShouldBeInside: false); if (res.X == 0 && res.Y == 0) //didn't hit { // see if it hits any block if (_numBlocksAlive == 0) { _nLevels++; _nBlocksY++; // reward: bring back some balls int nBallsToBringBackToLife = 0; for (int i = 0; i < _NumBalls; i++) { if (_balls[i].IsDead) { _balls[i].IsDead = false; _balls[i]._pos.X = 100 + 10 * i; _balls[i]._pos.Y = 100 + 10 * i; _NumBallsAlive++; Invalidate(_balls[i].GetRect()); if (++nBallsToBringBackToLife == 3) { break; } } } MakeBlocks(); } else { for (int i = 0; i < _nBlocksX; i++) { for (int j = 0; j < _nBlocksY; j++) { if (!_blocks[i, j].IsDead) { res = WillCollide( ball, _blocks[i, j].GetRect(), fShouldBeInside: false); if (res.X != 0 || res.Y != 0) { Beep(100, 10); _blocks[i, j].IsDead = true; _numBlocksAlive--; _Score++; Invalidate(_blocks[i, j].GetRect()); } } } } } } else {// hit paddle Beep(400, 10); } } else { // did hit frame edge if (res.Y == -1) { // hit bottom of frame ball.IsDead = true; Invalidate(ball.GetRect()); _NumBallsAlive--; } } // now we can move the ball Invalidate(ball.GetRect()); ball._pos.X += ball._velocity.X; ball._pos.Y += ball._velocity.Y; Invalidate(ball.GetRect()); } } if (_NumBallsAlive == 0) { this._timer.Enabled = false; } this.Text = string.Format( "Blocks by Calvin Hsia. Score = {0} # Levels = {1} # of balls left = {2}", _Score, _nLevels, _NumBallsAlive); }