Yytsi
Yytsi

Reputation: 424

Check if Picturebox touches any object on screen C#

I have a problem with my game that is coded on C#. I've tried searching all over the forums for this problem but none has worked for this case :/

I'm trying to check if Picturebox hits ANY other Picturebox in screen.

I've tried this, but this might be too slow when I add more objects.

if (!square.Bounds.IntersectsWith(grass.Bounds) && !square.Bounds.IntersectsWith(grMiddle.Bounds) && !square.Bounds.IntersectsWith(grRight.Bounds) && !square.Bounds.IntersectsWith(middle.Bounds) && !square.Bounds.IntersectsWith(sideRight.Bounds) && !square.Bounds.IntersectsWith(topPanel.Bounds))

This method doesn't work since player movement increases 100x and I die instantly, somehow...

foreach (PictureBox pic in this.Controls.OfType<PictureBox>())
        {
            if (pic != square)  // exclude square PictureBox from the test
            {
                if (!square.Bounds.IntersectsWith(pic.Bounds))
                {
                    if (!square.Bounds.IntersectsWith(rightGoal.Bounds))
                    {
                        if (Right) { square.Left += 5; }
                        if (Left) { square.Left -= 5; }
                        if (Up) { square.Top -= 5; }
                        if (Down) { square.Top += 5; }
                    }
                    else
                    {
                        pally.points++;
                        rightPoints.Text = pally.points.ToString();
                        square.Location = new Point(690, 533);
                    }
                }
                else
                {
                    square.Location = new Point(690, 533);
                }
            }
        }

I'm out of ideas, some help would be nice :)

Upvotes: 1

Views: 1136

Answers (1)

The Vermilion Wizard
The Vermilion Wizard

Reputation: 5395

                    if (Right) { square.Left += 5; }
                    if (Left) { square.Left -= 5; }
                    if (Up) { square.Top -= 5; }
                    if (Down) { square.Top += 5; }

Are these testing keyboard inputs or something? You're moving your square with this code. And you're doing it for each picturebox on your form. That's why your square moves too far. Separating your position updating code from your intersection code should solve your problem.

Upvotes: 2

Related Questions