//The rectangle, described around the first object:
Rectangle cheeseRectangle;
//The rectangle, described around the second object:
Rectangle breadRectangle;
private void Form1_Paint(object sender, PaintEventArgs e)
{
//We load into objects of class System.Drawing.Image
//the image files of the set format, added to the project
//by means of ResourceStream:
cheeseImage =
new Bitmap(myAssembly.GetManifestResourceStream(
myName_of_project + "." + "cheese.JPG"));
breadImage =
new Bitmap(myAssembly.GetManifestResourceStream(
myName_of_project + "." + "bread.JPG"));
//We initialize the rectangles, described around objects:
cheeseRectangle = new Rectangle(cx, cy,
cheeseImage.Width, cheeseImage.Height);
breadRectangle = new Rectangle(bx, by,
breadImage.Width, breadImage.Height);
//If it is necessary, we create the new buffer:
if (backBuffer == null)
{
backBuffer = new Bitmap(this.ClientSize.Width,
this.ClientSize.Height);
}
//We createobject of the Graphics class from the buffer:
using (Graphics g = Graphics.FromImage(backBuffer))
{
//We clear the form:
g.Clear(Color.White);
//We draw the image in backBuffer:
g.DrawImage(cheeseImage, cx, cy);
g.DrawImage(breadImage, bx, by);
}
//We draw the image on Form1:
e.Graphics.DrawImage(backBuffer, 0, 0);
//We turn on the timer:
timer1.Enabled = true;
} //End of the method Form1_Paint.
А вместо приведённого выше метода updatePositions для изменения координат записываем следующий метод, дополненный кодом для обнаружения столкновения объектов.
Листинг 5.2. Метод для изменения координат и обнаружения столкновения объектов.
private void updatePositions()
{
if (goingRight)
{
cx += xSpeed;
}
else
{
cx -= xSpeed;
}
if ((cx + cheeseImage.Width) >= this.Width)
{
goingRight = false;
//At the time of collision,
//the sound signal Beep is given:
Microsoft.VisualBasic.Interaction.Beep();
}
if (cx <= 0)
{
goingRight = true;
//At the time of collision,
//the sound signal Beep is given:
Microsoft.VisualBasic.Interaction.Beep();
}
if (goingDown)
{
cy += ySpeed;
}
else
{
cy -= ySpeed;
}
//That cheese did not come for the button3.Location.Y:
if ((cy + cheeseImage.Height) >= button3.Location.Y)
{
goingDown = false;
//At the time of collision,
//the sound signal Beep is given:
Microsoft.VisualBasic.Interaction.Beep();
}
if (cy <= 0)
{
goingDown = true;
//At the time of collision,
//the sound signal Beep is given:
Microsoft.VisualBasic.Interaction.Beep();
}
//We set to rectangles of coordinates of objects:
cheeseRectangle.X = cx;
cheeseRectangle.Y = cy;
breadRectangle.X = bx;
breadRectangle.Y = by;
//We check the collision of objects:
if (cheeseRectangle.IntersectsWith(breadRectangle))
{
//We СКАЧАТЬ