MonoGame
MonoGame 上手教程
MonoGame 是代码驱动的游戏框架,上手路径很清晰:装 SDK → 建项目 → 理解 Game1.cs → 画精灵 → 处理输入 → 管理资源 → 发布。
一、准备环境
Windows 上推荐这样装:
- 安装 .NET SDK,推荐 .NET 9;.NET 8 也仍可用。
- 安装 Visual Studio 2022 17.8+,并勾选“使用 C# 的游戏开发”。
- 在 VS 扩展管理器里安装 MonoGame Framework C# project templates。
- 如果做 WindowsDX 平台,额外装 DirectX June 2010 运行时,否则音频和手柄可能不正常。
- 也可以用命令行装模板:
dotnet new install MonoGame.Templates.CSharp二、创建项目
在 Visual Studio 里选择:
MonoGame Cross-Platform Desktop Application
命令行方式:
dotnet new mgdesktopgl -o MyFirstGame
cd MyFirstGame
dotnet run项目里最重要的文件:
| 文件 | 作用 |
|---|---|
| Game1.cs | 游戏主循环 |
| Program.cs | 启动入口 |
| Content/ | 资源目录 |
| Content.mgcb | 内容管线配置 |
| .config/dotnet-tools.json | MGCB Editor 工具配置 |
三、理解 Game1.cs
MonoGame 的核心就是这四个方法:
protected override void Initialize()
{
// 初始化变量、相机、状态
base.Initialize();
}
protected override void LoadContent()
{
// 加载纹理、字体、音效
_spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void Update(GameTime gameTime)
{
// 处理输入、移动、碰撞、AI
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
// 清屏、绘制精灵、UI
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}注意:Update 和 Draw 都会传入 GameTime,移动时要乘 ElapsedGameTime,否则帧率不同速度会不一样。
四、画一个可移动的方块
在 Game1.cs 顶部加上字段:
private Texture2D _pixel;
private Vector2 _playerPos = new Vector2(400, 300);
private float _speed = 200f;在 LoadContent 里生成一个 1x1 白色像素:
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_pixel = new Texture2D(GraphicsDevice, 1, 1);
_pixel.SetData(new[] { Color.White });
}在 Update 里处理输入:
protected override void Update(GameTime gameTime)
{
var kb = Keyboard.GetState();
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (kb.IsKeyDown(Keys.W) || kb.IsKeyDown(Keys.Up))
_playerPos.Y -= _speed * dt;
if (kb.IsKeyDown(Keys.S) || kb.IsKeyDown(Keys.Down))
_playerPos.Y += _speed * dt;
if (kb.IsKeyDown(Keys.A) || kb.IsKeyDown(Keys.Left))
_playerPos.X -= _speed * dt;
if (kb.IsKeyDown(Keys.D) || kb.IsKeyDown(Keys.Right))
_playerPos.X += _speed * dt;
if (kb.IsKeyDown(Keys.Escape))
Exit();
base.Update(gameTime);
}在 Draw 里绘制:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(new Color(30, 30, 40));
_spriteBatch.Begin();
_spriteBatch.Draw(_pixel, new Rectangle((int)_playerPos.X, (int)_playerPos.Y, 32, 32), Color.CornflowerBlue);
_spriteBatch.End();
base.Draw(gameTime);
}运行后,你会看到一个蓝色方块,可用 WASD 或方向键移动。
五、加载图片资源
- 把图片放进
Content/,例如Content/player.png。 - 双击
Content.mgcb打开 MGCB Editor。 - 右键项目节点,选择 Add → Existing Item,添加图片。
- 选中文件,确认 Processor 为
TextureProcessor。 - 点击 Build,生成
.xnb。 - 代码中加载:
private Texture2D _playerTexture;
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_playerTexture = Content.Load<Texture2D>("player");
}绘制时改成:
_spriteBatch.Draw(_playerTexture, _playerPos, Color.White);