Search code examples
c#labelcollision

Check Collision between Label and Rectangle?


i have a question: If a label is moving with a timer from left to right and after a while is meeting a rectangle. How can i get the collision between them?

Here is the rectangle:

e.Graphics.FillRectangle(Brushes.LightCyan, new Rectangle(Pipe1[0], 0, PipeWidth, Pipe1[1]));
e.Graphics.FillRectangle(Brushes.LightCyan, new Rectangle(Pipe1[2], Pipe1[3], PipeWidth, this.Height - Pipe1[3]));

Some ideas?


Solution

  • Label myLabel = new Label();
    
    myLabel.Text = "BOB";
    Rectangle rec = myLabel.Bounds;
    Rectangle rec2 = new Rectangle(30, 10, 20, 40);
    Rectangle intersect = Rectangle.Intersect(rec, rec2);
    if (intersect != Rectangle.Empty)
    {
       MessageBox.Show("Intersection!");
    }
    

    You'd substitute for "rec2" the rectangle you built above. Obviously, you'd want to build it and assign it to a Rectangle reference and then refer to it in both places by that variable.