从零开发游戏需要学习的c#模块,第十七章(显示真正的图片——精灵绘制)

从零开发游戏需要学习的c#模块,第十七章(显示真正的图片——精灵绘制) 第一步准备图片先用一张简单的来做测试。把你准备好的图片命名为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.LoadTexture2D(文件名不带后缀)playerTexture Content.LoadTexture2D(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.LoadTexture2D(player);其中Content.LoadT()是 MonoGame 的资源加载器player是文件名不带后缀图片必须放在Content文件夹里_spriteBatch.Draw(playerTexture, playerPosition, Color.White);第一个参数纹理你的图片第二个参数位置Vector2第三个参数颜色滤镜Color.White 原样显示注意一下本节课要准备的东西准备一张你喜欢的32*32的图片可以用piskel制作好了本节课的内容到此结束关注我下期更精彩。