2011-11-27 58 views
1

我正在嘗試編寫一些代碼,用於在文本中顯示我的播放器的X值。 它告訴我,Microsoft.Xna.Framework.Graphics.SpriteBatch.DrawString行需要一個對象引用。有任何想法嗎?這裏是我的代碼:我該如何解決「非靜態字段,方法或屬性需要對象引用...」

public void Effects(Player player) 
{ 
    string compassString = ""; 
    int playerY = (int) (((player.position.X + player.width) * 2f)/16f); 
    if (playerY > 0) 
    { 
     compassString = "Distance: " + playerY + " feet left"; 
     if (playerY == 1) 
     { 
     compassString = "Distance: " + playerY + " foot left"; 
     } 
    } 
    else if (playerY < 0) 
    { 
     playerY *= -1; 
     compassString = "Distance: " + playerY + " feet right"; 
     if (playerY == 1) 
     { 
      compassString = "Distance: " + playerY + " foot right"; 
     } 
    } 
    else 
    { 
     compassString = "Distance: Level"; 
    } 
    Color black; 
    black.R = (byte)((0xff + black.R)/2); 
    black.G = (byte)((0xff + black.R)/2); 
    black.B = (byte)((0xff + black.R)/2); 
    Microsoft.Xna.Framework.Graphics.SpriteBatch.DrawString(Main.fontMouseText, compassString, new Vector2((float) (0x16), (float) ((0x4a + (0x16)) + 0x30)), black, 0f, new Vector2(), (float) 1f, SpriteEffects.None, 0f); 

} 
+5

您需要在SpriteBatch的實例上調用DrawString。 –

+0

喜歡這個?:\t spriteBatch = new Microsoft.Xna.Framework.Graphics.SpriteBatch(GraphicsDevice graphicsDevice); –

回答

1

如果你想顯示你的座標在XNA字符串:

  1. 在您的應用程序定義一個新SpriteFont
  2. 在您的Game.Draw()方法中(而不只是在您的代碼中的某處!)使用默認的spriteBatch實例使用剛剛定義的SprinteFont繪製座標。

Here是從MSDN網頁上的這些步驟很好的教程。

下面是上面鏈接頁面報價:

protected override void Draw(GameTime gameTime) // <- do it here, not somewhere else! 
{ 
    GraphicsDevice.Clear(Color.CornflowerBlue); 

    spriteBatch.Begin(); // <-- before you start to draw 

    spriteBatch.DrawString(Font1, output, FontPos, Color.LightGreen, 
     0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f); 

    spriteBatch.End(); // <-- after you draw 
    base.Draw(gameTime); 
} 
+0

我修改了我的代碼,然後編譯。它拒絕吸引他們。我現在擁有的是[this](http://pastebin.com/msMpMdy9) –

+0

您是否閱讀過本教程?你做錯了方式。我添加了一個擴展的代碼示例如何操作 - 但請閱讀教程! –

0

你得到這個錯誤,因爲SpriteBatch不是一個靜態類。它必須像int i = 0那樣被實例化;你不能做int.i = 0;

轉到game1.cs。找到「SpriteBatch spriteBatch」聲明。要麼使這一個公共靜態或使另一個全球類(或單身),有一個公共參考這個變量。 將在Draw方法game1.cs你叫

spriteBatch.Begin(); 
yourClass.Draw(); 
spriteBatch.End(); 
在YourClass.Draw

然後()提出:在spitebatch在game1.cs分配給

所以經過
<yourGlobalClass>.SpriteBatch.DrawString(..); 

你可以把一條線:

<yourGlobalClass>.SpriteBatch = spritebatch; 
相關問題