gpt4 book ai didi

c# - 我在 XNA 的第一个游戏(小问题)

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:34 25 4
gpt4 key购买 nike

到目前为止,这是我的代码:Game1.cs 类:

 public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player MyPlayer;
Texture2D Ball;
int GraphicsWidth,GraphicsHeight;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

protected override void Initialize()
{
GraphicsWidth = graphics.PreferredBackBufferWidth;
GraphicsHeight= graphics.PreferredBackBufferHeight;
MyPlayer = new Player(Ball, new Vector2(100, 100), Vector2.Zero);
base.Initialize();
}

protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Ball = Content.Load<Texture2D>("Images/ball");

}

protected override void UnloadContent()
{
}

protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();


base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);

MyPlayer.Draw(spriteBatch);

base.Draw(gameTime);
}
}

球员类(球):

class Player
{
Texture2D Texture;
Vector2 Positon,Velocity;
public int Height
{
get { return this.Texture.Height; }
}
public int Width
{
get { return this.Texture.Width; }
}


public Player(Texture2D tex, Vector2 position,Vector2 velocity)
{
this.Texture = tex;
this.Positon = position;
this.Velocity = velocity;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(Texture, Positon, Color.White);
spriteBatch.End();
}
}

当我尝试调试游戏时出现以下错误:

此方法不接受此参数为 null。参数名称:纹理在那个部分:

public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(Texture, Positon, Color.White);
spriteBatch.End();
}

顺便说一句,我想问一下我是否可以改进这段代码或类似的东西。非常感谢!

最佳答案

看起来您在加载 Ball 内容之前创建了 Player 对象,因此,播放器持有 null 而不是纹理,但是 Ball 字段在游戏才是真正的质感。

在您分配了 Ball 之后,我会将 Player 的创建移动到 LoadContent 中。

Ball = Content.Load<Texture2D>("Images/ball");
MyPlayer = new Player(Ball, new Vector2(100, 100), Vector2.Zero);

关于c# - 我在 XNA 的第一个游戏(小问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6956896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com