技术开发 频道

XNA Framework Game Studio开发WP游戏

  开始编码

  现在我们粗略地知道了XNA Framework应用程序如何运行,并且创建了一些可用于构建应用程序的纹理,终于可以开始编写程序代码了。

  1、首先将CrossPlatformXNA FrameworkGame项目包含的Game1.cs重命名为“GolfGameMain.cs”;

  2、然后打开GolfGameMain.cs文件,定义下面的变量,它们将用于我们的两个纹理,位置和速度信息:

// Textures
Texture2D ball;
Texture2D target;
// Location information
Vector2 ballPt;
Vector2 targetPt;
// normalized velocity vector
Vector2 ballVelocity;
// Used to multiply on the velocity vector
float velocityMultiplier;

  3、在Initialize()方法内添加下面的代码,设置高尔夫球的速度:

  velocityMultiplier = 13.0f;

  4、自己动手写一个名为ResetGame()的函数,初始化高尔夫球的速度和位置值,函数内容如下,我们指定高尔夫球的初始位置为左上角稍微靠右的位置,目标在右下角稍微靠左的位置,高尔夫球的速度从0开始:

private void ResetGame()
{
    ballVelocity
= Vector2.Zero;
    ballPt
= new Vector2(target.Width, target.Height);
    targetPt
= new Vector2(graphics.GraphicsDevice.Viewport.Width - 2*target.Width, graphics.GraphicsDevice.Viewport.Height - 2*target.Height);
}

  5、向LoadContent()函数添加下面的代码,加载我们导入到内容管理器的纹理,完成后,调用ResetGame()指定对象的位置:

  ball = Content.Load("ball_small");

  target = Content.Load("target_small");

  ResetGame();

  6、现在我们已将内容载入到内容管理器,接下来让我们根据描述的位置绘制加载到屏幕的纹理,修改Draw()函数,修改后内容如下:

protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);
            spriteBatch.Begin();
            
// Draw our objects to the screen
            spriteBatch.Draw(target, targetPt, Color.White);
            spriteBatch.Draw(ball, ballPt, Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }

  7、至此,我们应该可以运行这个程序,看到高尔夫球和目标绘制到屏幕上,看起来的效果应该和下图差不多:

开始编码
▲图 5 程序运行效果

  8、下一步要为做碰撞检查添加一个函数,当高尔夫球完全包含在目标内时,这个函数开始执行。

private bool CheckForCollision()
{
    Rectangle ballRect
= new Rectangle((int)ballPt.X, (int)ballPt.Y, ball.Width, ball.Height);
    Rectangle targetRect
= new Rectangle((int)targetPt.X, (int)targetPt.Y, target.Width, target.Height);
    return targetRect.Contains(ballRect);
}

  9、有了碰撞检测逻辑后,我们可以给高尔夫球移动到目标的过程也添加上逻辑,将下面的代码添加到Update()函数即可,检测到碰撞后,我们可以通过调用前面创建的函数ResetGame()重置游戏:

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;
    }
ballPt
+= ballVelocity;
if (CheckForCollision())
    ResetGame();

  10、测试一下游戏运行时的状况,现在你应该可以使用键盘上的箭头控制高尔夫球的移动,当高尔夫球移动到目标时,游戏应该被重置。至此,你已经完成了主要的工作,从下一步开始,我们将修改代码,使其支持Windows Phone 7和Xbox平台。

0
相关文章