你需要一個graphicsDevice,但是創建很多GraphicsDevices和其他東西可能會非常麻煩。所以一個非常簡單的方法可以在你的遊戲周圍傳遞任何你想要的東西(比如你的屏幕寬度)的值,就是創建一個「GlobalVariable」,你可以在任何你想要的類中使用它。這是如何完成這個簡單的技巧。
首先創建一個新的類,並調用它GlobalClass像這樣:
class GlobalClass
{
}
現在添加一個私有變量與訪問它的公開方式。這裏我創建了兩個變量,一個用於屏幕高度,另一個用於寬度。
class GlobalClass
{
private static float screenWidth;
private static float screenHeight;
public static float ScreenWidth
{
get { return screenWidth; }
set { screenWidth = value; }
}
public static float ScreenHeight
{
get { return screenHeight; }
set { screenHeight = value; }
}
}
然後你就完成了!通過這個課程,你可以在遊戲的任何地方傳遞這兩個變量。所以回到你的本金類(game1.cs),並在更新了Methode更新論文變量與屏幕的高度和屏幕寬度這樣的值:
GlobalClass.ScreenWidth = graphics.PreferredBackBufferWidth;
GlobalClass.ScreenHeight = graphics.PreferredBackBufferHeight;
現在回到你的自定義類通過更換代碼這個:
int TextureHeight = GlobalClass.ScreenWidth;
它已經完成,這樣你就可以在任何地方傳遞任何值。只要確保在使用其值之前更新GlobalClass.ScreenWidth。
看看[這個答案](http://gamedev.stackexchange.com/questions/8687/how-to-find-the-window-size-in-xna/8694#8694)的解釋你的選擇是獲取屏幕尺寸來渲染(通常你需要'Viewport')。 –