Search code examples
c#wpfcollision-detection

Detecting collision between two rectangles on a WPF Canvas


I am extremely new to programming, and I have started off with C#. I am now trying to make my first game, I decided on snake. So far I have been trying to research this question, but all of the answers I see are ones that pertain to people who are using a different method of moving their snake around.

My program uses two doubles (left and top) in order to store where the snake is on the Canvas. My program also uses two doubles for the "food" in the game, called randomFoodSpawnLeft and randomFoodSpawnTop.

My question is this. How does one detect collision between two rectangular objects with just a left and top value? I am rather confused.

snakeWindow is the Window, snakeHead is the rectangle that represents a snake, left is the left value of the snake, top is the top value of the snake.

void timer_Tick(object sender, EventArgs e)
    {
        double left = Canvas.GetLeft(snakeHead);
        double top = Canvas.GetTop(snakeHead);

        if (keyUp)
        {
            top -= 3;
        }
        else if (keyDown)
        {
            top += 3;
        }
        else if (keyLeft)
        {
            left -= 3;
        }

        else if (keyRight)
        {
            left += 3;
        }
        // These statements see if you have hit the border of the window, default is 1024x765
        if (left < 0)
        {
            left = 0;
            gameOver = true;
        }
        if (top < 0)
        {
            top = 0;
            gameOver = true;
        }
        if (left > snakeWindow.Width)
        {
            left = 0;
            gameOver = true;
        }
        if (top > snakeWindow.Height)
        {
            top = 0;
            gameOver = true;
        }
        // Statements that detect hit collision between the snakeHead and food
        //
        if (foodEaten == true)
        {
            spawnFood();
            textBlockCurrentScore.Text += 1;
        }

            // If gameOver were to be true, then the game would have to end. In order to accomplish this I display to the user that the game is over
            // and the snakeHead is disabled, and should restart.
            if (gameOver == true)
        {
            keyRight = false;
            keyLeft = false;
            keyUp = false;
            keyDown = false;
            top = 0;
            left = 0;

            textBlockGameOver.Text = "GAME OVER!";
            snakeCanvas.Background = Brushes.Blue;
        }


        Canvas.SetLeft(snakeHead, left);
        Canvas.SetTop(snakeHead, top);
    }

Solution

  • You can use System.Windows.Rect.IntersectsWith. Try it like this:

    Rect rect1 = new Rect(left1, top1, widht1, height1);
    Rect rect2 = new Rect(left2, top2, widht2, height2);
    
    bool intersects = rect1.IntersectsWith(rect2);
    

    Of course you will have to check the snake's head against all it's parts.