Search code examples
c#xamlvisual-studio-2012windows-phone-8rect

'System.Windows.Rect' does not contain a definition for 'Intersects' for C#


I am doing a collision on Windows Phone App for Windows Phone 8 using Microsoft Visual Studio 2012. I used Rect to make a rectangle border for the ball. I received this error. 'System.Windows.Rect' does not contain a definition for 'Intersects' and no extension method 'Intersects' accepting a first argument of type 'System.Windows.Rect' could be found (are you missing a using directive or an assembly reference?) The codes are as below.

var greenBallPositionX1 = Canvas.GetLeft(this.greenBall1);
var greenBallPositionY1 = Canvas.GetTop(this.greenBall1);

Rect r1 = new Rect(greenBallPositionX1, greenBallPositionY1, greenBall1.ActualWidth, greenBall1.ActualHeight);

var blueBallPositionX1 = Canvas.GetLeft(this.blueBall1);
var blueBallPositionY1 = Canvas.GetTop(this.blueBall1);

Rect r2 = new Rect(blueBallPositionX1, blueBallPositionY1, blueBall1.ActualWidth, blueBall1.ActualHeight);

if (r1.Intersects(r2))
        {
            MessageBox.Show("Collision Detected");
        }

Solution

  • your own intersects can be written as

    public bool Intersects(Rect r1,Rect r2)
    {
      r1.Intersect(r2);
    
      if(r1.IsEmpty)
      {
        return false;
      }
      else 
      {
        return true;
      }
    }
    

    then you can use

    if(Intersects(r1,r2))
    {
      MessageBox.Show("Collison Detected");
    }