第2步:修改代码,使其支持Windows Phone 7
11、为Windows Phone 7创建一个CrossPlatformXNA FrameworkGame项目副本,在项目名称上点击右键,选择“为Windows Phone创建项目副本”,第二个项目应该就这样创建好了,项目名称应该是“Windows Phone 7 copy of CrossPlatformXNA FrameworkGame”。
12、在“引用”上点击右键,选择“添加引用”,为你的项目添加一个引用,如下图所示,然后选择“Microsoft.Devices.Sensors”,点击“添加”。

▲图 6 添加引用
13、现在关闭所有打开的文件,选择并打开“Windows Phone 7 copy of Cross PlatformXNA FrameworkGame”项目下的GolfGameMain.cs文件。
14、在项目顶部添加下面的命名空间,通过宏“#if WINDOWS_PHONE”批量导入命名空间,这样可以告诉编译器忽略“#if…#endif”内的代码,除非它是为Windows Phone 7编译,后面我们会使用“if XBOX… #endif”为Xbox做同样的处理。
#if WINDOWS_PHONE
using Microsoft.Devices.Sensors;
#endif
15、添加一个类级变量,增加加速计支持
Accelerometer accelerometer;
#endif
16、在构造器中添加下面的代码,帮助修改设置,处理游戏如何显示,以及游戏运行在什么分辨率下。
// Hides the battery and signal strength bar
graphics.IsFullScreen = true;
#else
// Code to support changing the resolution of the game for the Xbox to handle high def screens
graphics.IsFullScreen = false;
graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
#endif
17、修改前面编写的Initialize()函数,初始化加速计,根据平台的不同为高尔夫球设置不同的速度。
if (accelerometer == null)
{
// Instantiate the accelerometer sensor
accelerometer = new Accelerometer();
accelerometer.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(accelerometer_ReadingChanged);
accelerometer.Start();
}
velocityMultiplier = 10.0f;
#elif WINDOWS
velocityMultiplier = 13.0f;
#else
velocityMultiplier = 20.0f;
#endif
18、添加一个函数处理我们在上一步注册的事件,这个函数将处理加速计读数变化,我们基于此设置高尔夫球的速度,这与在Windows版本中处理不同按键事件的代码是等效的。
void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
ballVelocity.X = -velocityMultiplier*(float)e.Y;
ballVelocity.Y = -velocityMultiplier*(float)e.X;
}
#endif
19、修改LoadContent()函数,使其可以根据平台的不同加载不同的纹理,对Windows Phone和Windows平台,我们将加载低分辨率图像,对于Xbox,我们将加载高分辨率图像。
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load our game content to the ContentManager
#if WINDOWS_PHONE || WINDOWS
ball = Content.Load<Texture2D>("ball_small");
target = Content.Load<Texture2D>("target_small");
#else
ball = Content.Load<Texture2D>("ball");
target = Content.Load<Texture2D>("target");
#endif
ResetGame();
20、修改Update()函数,如果我们是为Windows版本编译的话,我们只能看到键盘输入。
KeyboardState kState = Keyboard.GetState(PlayerIndex.One);
Keys[] pressedKeys = kState.GetPressedKeys();
ballVelocity = Vector2.Zero;
foreach (Keys k in pressedKeys)
switch (k)
{
case Keys.Right:
ballVelocity.X = velocityMultiplier;
break;
case Keys.Left:
ballVelocity.X = -velocityMultiplier;
break;
case Keys.Down:
ballVelocity.Y = velocityMultiplier;
break;
case Keys.Up:
ballVelocity.Y = -velocityMultiplier;
break;
}
#endif
21、很好,现在在解决方案资源管理器中的“Windows Phone 7 copy of CrossPlatformXNA FrameworkGame”项目上点击右键,运行“调试”*“运行新实例”,这时应该会启动Windows Phone 7模拟器,如下图所示,但遗憾的是,不能在模拟器中测试加速计功能,除非你将应用程序部署到一台真实的Windows Phone 7手机上。

▲图 7 在Windows Phone 7模拟器上运行的效果