Developing Game-Themed Applications with XNA
Day 1 - Section III: The Block Breaker
Game
c. The Ball class
back to Day-1 main page
References:
- Pre-requisite: this is the
example (Section IIIb. Simple Circle) we are building off from and here
is the source code we
will begin working with.
- Here is the result source code from this
example.
Goals: In this tutorial we want to experience:
- Define the look and behavior of the main object in the game: The Ball.
- Verify behavior:
- Shot out per A-button pressed.
- Bounces off the window boundaries.
- Invalided when moved lower than the window
Library functions to notice:
-
Application window bounds:
Please refer to the
library documentation for more details.
XNACS1Base.World.ClampAtWorldBound(m_Circle)
-
Memory allocation: memory are allocated during initialization.
Implementation:
-
Create a new file: Ball.cs. Here is the link to
the file.
Interesting features of this class includes:
- Instance variables:
-
m_Circle: 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.
- Update:
- Update ball position by velocity.
- Bouncing with the bounds of the application bounds
- Notice we set the expiration to true when the ball is below
the window.
- DeleteBall: remove the ball from the AutoDrawSet.
- 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.
Lesson Learned:
For each object in our application, we should pay attention to two
attributes: appearance and behavior. These two attributes maps perfectly to the
InitializeWorld() and the UpdateWorld() functions. In general, we
should define object to encapsulate our objects. The constructor should define
appearance and we should define an Update() function for the class to implement
the behavior.
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.