For my Space Invaders game in C# WinForms I have this code which moves the player's cannon depending on their arrow key input:
void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 100; i++)
{
if (Form1.lives != 0)
{
if (e.KeyCode == Keys.Left)
{
cannonBox.Location = new Point(cannonBox.Left -= 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
else
if (e.KeyCode == Keys.Right)
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
}
}
}
However, when the cannonBox reaches the form's boundaries it just keeps going and I would like to make it bounce off and go towards the other direction. I thought and tried of using something like this but it would be really difficult to find the precise location from where it intersects with:
if (cannonBox.Location == new Point(763, 50))
{
for (int i = 0; i < 50; i++)
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top);
}
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}