Bouncing Ball - Source Code
Background
.NET Framework 2.0A while ago, I offered the source code to my simple physics (gravity) demo I made using Microsoft’s XNA Game Studio Beta. This was a simple change to the default Microsoft XNA Game Studio demo program. Don’t get too excited because the code is pretty basic.
The Trouble Begins
I was all ready to post the code when I thought it would be nice to include the binaries for your immediate gratification. It was then when I fired up fresh copy of XP SP2 running in virtual machine using Microsoft’s free Virtual PC software.
This is when the trouble started. The executable didn’t run. I immediately figured I needed some kind of XNA runtime and sure enough I did. However, the game still didn’t run after I installed the runtime. It looks as if I had compiled by binaries with the first public beta of XNA, but the latest redistributable was for Beta 2.
So, I uninstalled Beta 1 on my desktop and re-installed Beta 2. Then my project didn’t compile. You would not believe the amount of framework changes made between these two betas. At this point, I had to completely rewrite my code just so it would work on Beta 2.
Ok, I thought I was ready so I tried the new binaries on my clean XP virtual machijne. No dice! I had everything installed:
- .NET Framework 2.0
- DirectX 9.0c
- XNA Game Studio Redistributable Beta 2
At this point, I plain give up. I’ll NEVER post this code if I try and figure this out. I can’t believe that I’m that stupid so I’ll just assume it’s a problem with the SDK. In short, you’ll need to install the full XNA Game Studio SDK if you want to run this code.
Code Overview
I basically tweaked these variables until the bouncing looked realistic:
//coordinates to draw the sprite atdouble gravityAccel = 3.0;
double frictionDecelY = 1.003;
double frictionDecelX = 1.0075;
Then, we have the UpdateSprite function, which does all of the motion calculations:
void UpdateSprite()
{
//move the sprite by speed
spriteX += m_dSpriteHorizSpeed;
spriteY += m_dSpriteVertSpeed;
double MaxX = Window.ClientWidth - myTexture.Width;
double MinX = 0.0;
double MaxY = Window.ClientHeight - myTexture.Height;
double MinY = 0.0;
//check for bounce
if (spriteX >= MaxX)
{
m_dSpriteHorizSpeed = -m_dSpriteHorizSpeed;
spriteX = MaxX;
}
else if (spriteX <= MinX)
{
m_dSpriteHorizSpeed = -m_dSpriteHorizSpeed;
spriteX = MinX;
}
if (spriteY >= MaxY)
{
m_dSpriteVertSpeed = -m_dSpriteVertSpeed;
spriteY = MaxY;
}
else if (spriteY <= MinY)
{
m_dSpriteVertSpeed = -m_dSpriteVertSpeed;
spriteY = MinY;
}
m_dSpriteVertSpeed += gravityAccel - 1.0;
m_dSpriteVertSpeed /= frictionDecelY;
m_dSpriteHorizSpeed /= frictionDecelX;
}
Please find the attached zip file which contains the entire source tree, with all temporary and final binaries.
Enjoy!
UPDATE: This code drop seems to work with the released version of the SDK.