第一步:准备图片
先用一张简单的来做测试。把你准备好的图片命名为player.png。
第二步:把图片加入项目
在 Visual Studio 右侧“解决方案资源管理器”里,找到
Content文件夹右键
Content→添加→现有项选择你的
player.png文件选中刚添加的
player.png,在下方属性窗口里,确认:生成操作=
Content复制到输出目录=
如果较新则复制
第三步:完整代码
打开Game1.cs,完整替换为:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace MY_FIRST_GAME
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private Texture2D playerTexture;
private Vector2 playerPosition;
private float playerSpeed = 200f;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
_graphics.PreferredBackBufferWidth = 800;
_graphics.PreferredBackBufferHeight = 600;
_graphics.ApplyChanges();
playerPosition = new Vector2(400, 300);
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// ★ 加载图片:用 Content.Load<Texture2D>("文件名不带后缀")
playerTexture = Content.Load<Texture2D>("player");
}
protected override void Update(GameTime gameTime)
{
KeyboardState keyboard = Keyboard.GetState();
float speed = playerSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (keyboard.IsKeyDown(Keys.W) || keyboard.IsKeyDown(Keys.Up))
playerPosition.Y -= speed;
if (keyboard.IsKeyDown(Keys.S) || keyboard.IsKeyDown(Keys.Down))
playerPosition.Y += speed;
if (keyboard.IsKeyDown(Keys.A) || keyboard.IsKeyDown(Keys.Left))
playerPosition.X -= speed;
if (keyboard.IsKeyDown(Keys.D) || keyboard.IsKeyDown(Keys.Right))
playerPosition.X += speed;
if (keyboard.IsKeyDown(Keys.Escape))
Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
// ★ 画图片:纹理, 位置, 颜色(Color.White = 原色)
_spriteBatch.Draw(playerTexture, playerPosition, Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
其中新知识
playerTexture = Content.Load<Texture2D>("player");其中
Content.Load<T>()是 MonoGame 的资源加载器"player"是文件名不带后缀图片必须放在
Content文件夹里
_spriteBatch.Draw(playerTexture, playerPosition, Color.White);第一个参数:纹理(你的图片)
第二个参数:位置(
Vector2)第三个参数:颜色滤镜(
Color.White= 原样显示)
注意一下本节课要准备的东西
准备一张你喜欢的32*32的图片,可以用piskel制作
好了,本节课的内容到此结束,关注我,下期更精彩。