using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace CSharpGameExample
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private Texture2D _playerTexture;
private Vector2 _playerPosition;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
// 初始化玩家位置
_playerPosition = new Vector2(400, 300);
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// 加载玩家纹理
_playerTexture = Content.Load<Texture2D>("player");
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// 玩家输入处理
var keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.Up))
_playerPosition.Y -= 5;
if (keyboardState.IsKeyDown(Keys.Down))
_playerPosition.Y += 5;
if (keyboardState.IsKeyDown(Keys.Left))
_playerPosition.X -= 5;
if (keyboardState.IsKeyDown(Keys.Right))
_playerPosition.X += 5;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
_spriteBatch.Draw(_playerTexture, _playerPosition, Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
这段代码是一个简单的C#游戏开发示例,使用了XNA框架(或MonoGame)。它创建了一个基本的游戏循环,其中包含一个可以移动的玩家角色。
Game1
类继承自 Game
,这是XNA/MonoGame中的基础游戏类。Initialize
方法中,我们设置了玩家的初始位置。LoadContent
方法用于加载游戏资源,如玩家的纹理图像。Update
方法处理游戏逻辑和用户输入。这里我们根据键盘输入来移动玩家。Draw
方法负责绘制游戏画面,包括背景颜色和玩家角色。通过这个示例,你可以看到如何使用C#和XNA/MonoGame框架来创建一个简单的2D游戏。
上一篇:c#网络编程
下一篇:.net和c#
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站