我正在嘗試創建雞蛋生成器,但出現了這個錯誤。
試圖修復這個錯誤,但不幸的是我不能。
我知道 XNA 框架已經過時,但我用它來學習。
有人會幫助我嗎?
謝謝。
代碼:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
int screenWidth;
int screenHeight;
List<Eggs> eggList = new List<Eggs>();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = false;
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
screenWidth = GraphicsDevice.Viewport.Width;
screenHeight = GraphicsDevice.Viewport.Height;
}
public class Eggs
{
public Texture2D texture;
public Vector2 position;
public Vector2 velocity1;
public bool isVisible = true;
Random random = new Random();
int randX;
public Eggs(Texture2D newTexture, Vector2 newPosition)
{
texture = newTexture;
position = newPosition;
randX = random.Next(0, 400);
velocity = new Vector2(randX, 0);
}
public void Update(GraphicsDevice graphic)
{
position = velocity;
if(position.Y < 0 - texture.Height);
isVisible = false;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
float spawn = 0;
protected override void Update(GameTime gameTime)
{
spawn = (float)gameTime.ElapsedGameTime.TotalSeconds;
foreach(Eggs eggList in eggList)
eggList.Update(graphics.GraphicsDevice);
LoadEggs();
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
Exit();
base.Update(gameTime);
}
public void LoadEggs()
{
if(spawn >= 1)
{
spawn = 0;
if(eggList.Count() < 4)
eggList.Add(new Eggs(Content.Load<Texture2D>("Images/egg"), new Vector2(50, 0)));
}
for(int i = 0; i < eggList.Count; i )
if(!eggList[i].isVisible)
{
eggList.RemoveAt(i);
i--;
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.LightYellow);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
foreach(Eggs eggList in eggList)
{
Eggs.Draw(spriteBatch);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
為什么會出現這個錯誤?
錯誤 CS0120:非靜態欄位、方法或屬性“Game1.E ggs.Draw(SpriteBatch)”需要物件參考
uj5u.com熱心網友回復:
似乎從最后的第 6 行開始出現問題。
Eggs.Draw(SpriteBatch)不能這樣稱呼。由于 Eggs 不是靜態類,Draw 也不是靜態方法,這意味著您需要 Eggs 型別的物件來呼叫方法 Draw。
所以需要這樣的東西:
var egg = new Eggs();
egg.Draw(SpriteBatch);
此外,foreach 回圈沒有意義,不要為 item 使用相同的名稱,因為它是您正在回圈的集合的名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457625.html
