Bhagya
Bhagya

Reputation: 53

Using IntersectsWith() Method to a drawn triangle

I am making a snake game using C#. I draw four shapes(Circle, Square, Rectangle, Triangle) same time. If I pass the target as Square, snake has to reach to the Square. If user move the snake to the target and hit,then Win otherwise Fail.

For rectangle, circle, square IntersectsWith() works fine. But for triangle it is not working.Is there any help me? Here is my code

if (snakes.SnakeRec[i].IntersectsWith(food.foodSquare))
{
   Win();
}
 if ((snakes.SnakeRec[i].IntersectsWith(food.foodCircle))||    (snakes.SnakeRec[i].IntersectsWith(food.foodRec)))
{
    restart();
}

Works fine But this won't work

if (snakes.SnakeRec[i].IntersectsWith(food.foodTrianglePoints))
 {
       //cannot convert from 'System.Drawing.Point[]' to 'System.Drawing.Rectangle'                                       
 }

Upvotes: 0

Views: 391

Answers (1)

TaW
TaW

Reputation: 54433

IntersectsWith certainly will only work between Rectangles, not triangles nor circles nor ellispis, unless the happen to overlap at the bounds..

However there is a trick to find intersections of pretty much arbitrarily complex shapes, as long as they can be assigned to a Region. One simple way to create a Region is using a GraphicsPath..

You can add all sorts of shapes to a GraphicsPath, pretty much like you would draw them..

When you have got Regions for both of your shapes you can Intersect them and then test if the Region is Empty.

Here is an example using your shapes; it needs to know on which control or form the shapes are being drawn; let's call it Control surface..:

using (Graphics g = surface.CreateGraphics())
{
    GraphicsPath gp1 = new GraphicsPath();
    GraphicsPath gp2 = new GraphicsPath();
    GraphicsPath gp3 = new GraphicsPath();
    GraphicsPath gp4 = new GraphicsPath();

    gp1.AddRectangle(fsnakes.SnakeRec[i]);
    gp2.AddPolygon(food.foodTrianglePoints);
    gp3.AddEllipse(food.foodCircle);
    gp4.AddRectangle(food.foodRec);

    Region reg1 = new Region(gp1);
    Region reg2 = new Region(gp2);
    Region reg3 = new Region(gp3);
    reg2.Intersect(reg1);
    reg3.Intersect(reg1);
    reg4.Intersect(reg1);

    if (!reg2.IsEmpty(g)) Win();
    if (!reg3.IsEmpty(g) || !reg4.IsEmpty(g)) restart();
}

Upvotes: 1

Related Questions