C#开发跨平台游戏——编写第一个C#游戏
安装开发环境:
步骤:
【开始菜单】找到【Visual Studio 2017】,点击打开
窗口左上角点击【文件】【新建】【项目】
展开【已安装】【Visual C#】点击【XNA Game Studio 4.0】,选择【Windows Game (4.0)】
名称:输入【HelloWorld.XNA】
位置:可以自己自定义
解决方案名称:输入【HelloWorld】
框架:选择【.NET Framework 4.6】
点击【确定】
注:确保Windows10所有版本的用户都能运行(Windows10最低版本10240预装.net Framework 4.6)
查看右侧的解决方案管理器,Visual Studio 2017默认创建了两个项目【HelloWorld.XNA】【HelloWorldXNAContent】
HelloWorld.XNA: 编写游戏逻辑代码,默认提供了两个.cs文件【Program.cs】【Game1.cs】
- Program.cs :游戏入口,启动游戏会首先执行
using System; namespace HelloWorld.XNA { #if WINDOWS || XBOX static class Program { /// <summary> /// 1.程序(游戏)入口,打开游戏会首先执行 /// </summary> static void Main(string[] args) { //2.实例化游戏主体Game1,使用using保证当游戏关闭后立即释放内存 using (Game1 game = new Game1()) { //3.运行游戏主体 game.Run(); } } } #endif }
- Game1.cs :游戏运行主体。包括设备初始化,加载游戏资源,绘制游戏界面,检测游戏精灵碰撞,监听用户输入操作,播放音频等以及卸载释放游戏资源
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace HelloWorld.XNA { /// <summary> /// 游戏主体,可以理解为它就是一台带触控笔电脑 /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { //定义图形设备管理器,可以认为它就是你电脑的显卡 GraphicsDeviceManager graphics; //定义一个游戏精灵的画刷,可以认为它就是一支画笔 SpriteBatch spriteBatch; public Game1() { //实例化图形设备管理器,可以认为你的电脑插上了显卡并插上了显示器 graphics = new GraphicsDeviceManager(this); //定义游戏资源(图片、字体、音频、模型等)存放的路径,完整写法this.Content.RootDirectory = "Content",this表示你现在的这个游戏Game1 Content.RootDirectory = "Content"; } /// <summary> /// 初始化任何非图形资源。可以认为你的电脑插上了电源插座,键盘,鼠标等按电源之前的操作 /// </summary> protected override void Initialize() { base.Initialize(); } /// <summary> /// 加载游戏所需要的图形图片、音频等游戏资源。可以认为你的电脑已经启动正在读取硬盘内存CPU等信息 /// </summary> protected override void LoadContent() { // 实例化游戏精灵画刷。可以认为电脑的画笔装了电池 spriteBatch = new SpriteBatch(GraphicsDevice); // 加载游戏资源代码写在这里 } /// <summary> /// 当游戏关闭后,释放所有资源。可以认为电脑关机,屏幕变黑之前关闭运行的软件 /// </summary> protected override void UnloadContent() { // 释放资源代码写在这里 } /// <summary> /// 编写游戏逻辑代码。检测玩家受否触摸了屏幕、按下了键盘、点击了鼠标、使用了游戏手柄。并修改游戏精灵的状态(位置,颜色,播放音效等) /// </summary> /// <param name="gameTime">游戏时间</param> protected override void Update(GameTime gameTime) { // 判断是否按下游戏手柄的返回键,退出游戏,Windows游戏无效 if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); //游戏逻辑代码 base.Update(gameTime); } /// <summary> /// 绘制游戏资源到屏幕。可以认为在你的显示器上显示游戏的内容 /// </summary> /// <param name="gameTime">游戏时间</param> protected override void Draw(GameTime gameTime) { //使用显卡在屏幕上显示蓝色,完整写法是this.GraphicsDevice.Clear(Color.CornflowerBlue) GraphicsDevice.Clear(Color.CornflowerBlue); // 用画笔画出其他游戏资源 base.Draw(gameTime); } } }
HelloWorldXNAContent:存放游戏资源文件(图片、字体、模型、音频、视频等)
以上是对默认cs文件的解释和说明,下面我们开始编写第一个C#游戏:
选择【HelloWorld.XNAContent】项目,点击鼠标右键【添加】【新建项】
选择【Visual C#】【Sprite Font】,修改名称为【DefaultFont.spritefont】,点击【添加】
这时Visual Studio会打开DefaultFont.spritefont文件
<?xml version="1.0" encoding="utf-8"?> <!-- This file contains an xml description of a font, and will be read by the XNA Framework Content Pipeline. Follow the comments to customize the appearance of the font in your game, and to change the characters which are available to draw with. --> <XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics"> <Asset Type="Graphics:FontDescription"> <!-- 游戏的字体名称 --> <FontName>Segoe UI Mono</FontName> <!-- 游戏的字体大小 --> <Size>14</Size> <!-- 游戏字体的间距 --> <Spacing>0</Spacing> <!-- 使用字体间距调整字体的布局。如果该值为true --> <UseKerning>true</UseKerning> <!-- 游戏字体样式:常规、粗体、斜体 Regular, Bold, Italic --> <Style>Regular</Style> <!-- If you uncomment this line, the default character will be substituted if you draw or measure text that contains characters which were not included in the font. --> <!-- <DefaultCharacter>*</DefaultCharacter> --> <!-- 游戏中所使用到的字符范围,默认只能使用英文字符(从32(ASCII 空格)到126,(“~”),包括基本拉丁语字符集) --> <CharacterRegions> <CharacterRegion> <Start> </Start> <End>~</End> </CharacterRegion> </CharacterRegions> </Asset> </XnaContent>
双击打开【Game1.cs】文件,找到SpriteBatch spriteBatch;在下面输入
SpriteFont defaultFont;
选中【HelloWorld.XNAContent】项目中的【DefaultFont.spritefont】,点击鼠标右键选择【属性】
复制属性窗口中Asset Name的值【DefaultFont】
找到LoadContent()方法,在 spriteBatch = new SpriteBatch(GraphicsDevice);下面输入
defaultFont = Content.Load<SpriteFont>("DefaultFont");
“DefaultFont”就是Asset Name,这行代码的目的是加载游戏的默认字体
找到Draw(GameTime gameTime)方法,在GraphicsDevice.Clear(Color.CornflowerBlue);下面输入
spriteBatch.Begin(); spriteBatch.DrawString(defaultFont, "Hello World", Vector2.Zero, Color.White); spriteBatch.End();
前面提到spriteBatch可以认为是画笔,使用画笔绘制界面必须调用spriteBatch.Begin(),在使用完毕必须调用spriteBatch.End()。所以在绘制界面图的代码spriteBatch.DrawString(defaultFont, “Hello World”, Vector2.Zero, Color.White);必须放在Begin和End之间。
参数说明:
defaultFont:字体
Hello World:显示的内容
Vector2.Zero:显示位置
Color.White:显示白色文字
完整代码如下:
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace HelloWorld.XNA { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont defaultFont; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here defaultFont = Content.Load<SpriteFont>("DefaultFont"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here spriteBatch.Begin(); spriteBatch.DrawString(defaultFont, "Hello World", Vector2.Zero, Color.White); spriteBatch.End(); base.Draw(gameTime); } } }
点击【启动】
这时候蓝色的窗口中,显示出了【Hello World】。这就是我们编写的第一个C#游戏