Developing Game-Themed Applications with XNA Game Studio
Section III: The Block Breaker
Game
b. The Ball class
back to workshop main page
References:
Goals: In this tutorial we want to experience:
- Creation and bouncing animation of a circle (the ball class).
- Validity of object: remove when out of bound.
Library functions to notice:
Implementation:
-
Game1.cs:
add in the following code in the beginning of the file. This is the
general utility for generating random number for our application.
|
#region
__CODE_ADDED__ random number support
private
static
Random m_Rand = new
Random();
static
public float RandomNumber() {
return (float)m_Rand.NextDouble();
}
#endregion |
-
Create a new file: Ball.cs. Here is the link to
the file.
Interesting features of this class includes:
- Instance variables:
-
m_Position: position of
the ball
- m_Velocity: velocity
of the ball
- m_BounceCount: number
of bounce (for fun).
- m_Expired: is the ball
still valid? This will be determined by if the ball is still within the
bounds of the application window.
- Constructor: Notice the randomness in initial velocity of the
ball.
- Bounds:
-
MinBound: lower-left
corner of the ball.
- MaxBound: upper-right
corner of the ball.
- Update:
- Update ball position by velocity.
- Bouncing with the bounds of the application bounds (notice
the XnaAssignmentBase.WorldMax, and XnaAssignmentBase.WorldMin).
- Notice we set the expiration to true when the ball is below
the window.
- Draw: draws a circle.
- Changes to: Game1.cs
- Instance variable:
- InitializeWorld: set
m_Ball to
null. No ball until we press the "A"-button.
- UpdateWorld:
- Create ball: allocate memory for a ball if button-A is
pressed.
- Update Ball: if there is a ball, calls the update function,
and check to remove the ball if already expired.
- DrawWorld: Draws the ball if not null.
Lesson Learned:
Most classes we create will have the following two functions:
- Update: this function should update the state of the object,
typically changing position, or colliding with another object.
- Draw: draws the object.
This document and the related materials are developed with support from
Microsoft Research Computer Gaming Initiative under the Computer Gaming
Curriculum in Computer Science RFP, Award Number 15871, and 16531.