您的位置:首页 > 编程语言

《XNA高级编程:Xbox 360和Windows》1-3

2010-05-11 20:59 375 查看
1.3从头开始 您已经准备好了一切,现在就让我们开始编码吧!本节您将在XNA Studio模板的帮助下创建一个简单的游戏项目,然后在Update和Draw方法中添加少量代码以实现一些小功能。在下一小节学习了SpriteBatch类之后,您将创建您的第一个游戏。

您的第一个项目

打开XNA Game Studio Express,在菜单栏中选择“文件→新建项目”,在弹出的新窗口中选择“Windows Game”模板,然后在项目名称处输入新项目的名称,比如“HelloWorld”或者就使用默认的名称“WindowsGame1”,在位置处输入新项目的保存位置,最后点击“确定”按钮。另外,在该窗口中还可以创建基于初学者工具包的游戏项目,比如“Spacewar Windows Starter Kit”。如下图1-10所示:

static void Main(string[] args)

// Allows the game to exit

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

this.Exit();

Draw方法主要执行一个操作,将游戏窗口的背景色设置成一个特定的颜色,如下所示:

graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

现在按下键盘上的F5键,或者选择菜单栏上的“调试→启动调试”命令运行游戏,此时将弹出如图1-11-(1)所示的窗口,它的了蓝色背景就是在Draw方法中设置的。

[align=center]graphics.GraphicsDevice.Clear(Color.Green);[/align]

[align=center]graphics.GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Green, 1, 0);[/align]

参数ClearOptions的默认值是ClearOptions.Target | ClearOptions.DepthBuffer,意思是背景色和Depth缓存都被清除。

修改代码



现在,您可以想一想如何修改您的代码来实现一些操作。比如,按下键盘上的Escape键可以退出游戏。之前说过,XNA默认的会在Update方法中检查Xbox 360控制器上的Back按钮是否被按下来决定是否退出游戏,代码如下:

// Allows the game to exit

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

this.Exit();

在“第三章-辅助类”中您将学习到Input类的使用,不过现在您可以使用一种快速的方法来操作键盘,下面的代码演示了当您按下Escape键时也能退出程序:

// Get current gamepad and keyboard states

GamePadState gamePad = GamePad.GetState(PlayerIndex.One);

KeyboardState keyboard = Keyboard.GetState();

// Back or Escape exits our game on Xbox 360 and Windows

if (gamePad.Buttons.Back == ButtonState.Pressed ||

keyboard.IsKeyDown(Keys.Escape))

private Texture2D backgroundTexture;

private SpriteBatch sprites;

protected override void Initialize()

protected override void Draw(GameTime gameTime)

protected override void Update(GameTime gameTime)

protected override void Draw(GameTime gameTime)

{

{

{

Vector2 position = new Vector2(

x * this.backgroundTexture.Width,

y * this.backgroundTexture.Height +

((int)this.scrollPosition) % this.backgroundTexture.Height);

this.sprites.Draw(this.backgroundTexture, position, Color.White);

}

}

this.sprites.End();

base.Draw(gameTime);

}

现在运行您的游戏就可以上下来回移动,这对于您的第一个小应用是不是很酷?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: