| XNA Game-Themed CS1 Examples (XGC1) | |
|
Release 2.0 (XNA V3.1) |
|
Need (library reference):
References:
Goals:
1. Obtain the example code
When the game starts, you'll see a screen that looks similar to this:

The game behaves in a manner that is identical to the what was described for the previous tutorial, with two new changes:
If the soccer ball reaches the left edge of the screen, it will 'bounce off' that edge, meaning that it will reverse it's horizontal direction.
If the soccer ball collides with the right paddle, it will 'bounce off' that paddle, meaning that it will reverse it's horizontal direction. We will also play a sound, in order to provide audio feedback to the user that the player has successfully bounced the ball
Let's examine the
C# source code that produces the behavior we see on-screen. Since the code
is nearly identical to the program that was presented in the previous tutorial,
we'll leave out everything, except for code that has changed, or code that is
new. That leaves us with:
UpdateWorld():
|
protected
override
void
UpdateWorld() { <code omitted, for clarity> // This is the if condition! if (m_TheSoccer.CenterX > 100.0f) { m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX; } if (m_TheSoccer.CenterX < 0.0f) { m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX; } if (m_RightPaddle.Collided(m_TheSoccer)) { m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX; PlayACue("Bounce"); } EchoToTopStatus("Left Paddle Center=" + m_LeftPaddle.Center + " Right Paddle Center=" + m_RightPaddle.Center); EchoToBottomStatus("Soccer Ball position: " + m_TheSoccer.Center); } |
{
m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX;
PlayACue("Bounce");
}
Let's break this out into separate parts:
FURTHER EXERCISES::
| Line # | Source Code |
| 69 | if (m_TheSoccer.CenterX < 0.0f) |
| 70 | { |
| 71 | m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX; |
| 72 | } |
| 73 | |
| 74 | if (m_RightPaddle.Collided(m_TheSoccer)) |
| 75 | { |
| 76 | m_TheSoccer.VelocityX = -m_Soccer.VelocityX; |
| 77 | PlayACue("Bounce"); |
| 78 | } |