Heres the main part of the code with comments. Download the source for the rest:
Vector3 accelerometer = Accelerometer.GetState().Acceleration;
for (int i = 0; i < snowflakes.Count; i++)
{
//get the object out of the collection
GameObjects go = (GameObjects)snowflakes[i];
//work out the new acceleration. We add its random weight times the tilt to the current acc.
//it has random weight so they all move seperately else they will all go into one big blob ;)
float newXAcc = (go.acceleration.X + (accelerometer.X * (float)(go.weight)));
float newYAcc = (go.acceleration.Y + (-(accelerometer.Y * (float)(go.weight))));
//stop them speeding up too much
newXAcc = MathHelper.Clamp(newXAcc, -5, 5);
newYAcc = MathHelper.Clamp(newYAcc, -5, 5);
//works out their new x and y positions
float newX = go.position.X + newXAcc;
float newY = go.position.Y + newYAcc;
//does some bounds checking so they dont go off the screen.
if (((newX > (viewportRect.Left + 1)))
&& (newX < (viewportRect.Left + viewportRect.Width - go.rectangle.Width)))
{
//if its still inside the screen, then give it the new acceleration(remember we factored in
//its old acc above
go.acceleration.X = newXAcc;
}
else
{
//else make it bounce, and lose some momentum. It should be lower than 0.9 but
//this looks nicer than if it was realistic
go.acceleration.X = -(go.acceleration.X * 0.9f);
}
//same for y
if ((newY > (viewportRect.Top + 1))
&& (newY < (viewportRect.Top + viewportRect.Height - go.rectangle.Height)))
{
go.acceleration.Y = newYAcc;
}
else
{
go.acceleration.Y = -(go.acceleration.Y * 0.9f);
}
go.UpdatePosition();
}