2011-08-02 53 views
0

我會在深入解釋之後。因此,這裏是我的代碼,我們有一個海拔[]變量,每個高程得到一個隨機數:在XNA中不能使用另一種方法的變量

public void elevation() 
    { 
     for (x = (int)Width - 1; x >= 0; x--) 
     { 
      for (y = (int)Width - 1; y >= 0; y--) 
      { 
       y = rand.Next((int)MaxElevation); //random number for each y. 
       Elevation[x] = y; //each Elevation gets a random number. 
      } 
     } 
    } 

這之後我嘗試在抽籤方法這樣使用該隨機數:

public void Draw(SpriteBatch spriteBatch) 
    { 
     for (x = (int)Width - 1; x >= 0; x--) 
     { 
      spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[x], 1, (int)Height), Color.White); 
      //HERE, I try to acces the random number for each Elevation (y value). But I get 0 everywhere. 
     } 
    } 

如何訪問此隨機數?

如果我這樣做:

public void Draw(SpriteBatch spriteBatch) 
    { 
     for (x = (int)Width - 1; x >= 0; x--) 
     { 
      for (y = (int)Width - 1; y >= 0; y--) 
      { 
       y = rand.Next((int)MaxElevation); 
       spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[y], 1, (int)Height), Color.White); 
      } 
     } 
    } 

我就能存取權限的隨機數,但它會更新每幀的隨機數會發生變化。所以我需要計算一次然後使用它們。

這裏是所有代碼:

namespace procedural_2dterrain 
{ 
    class Terrain 
{ 
    Texture2D Pixel; 
    Vector2 Position; 
    Random rand; 

    int[] Elevation; 

    float MaxElevation; 
    float MinElevation; 

    float Width; 
    float Height; 

    int x; 
    int y; 


    public void Initialize(ContentManager Content, float maxElevation, float minElevation, float width, float height, Vector2 position) 
    { 
     Pixel = Content.Load<Texture2D>("pixel"); 
     rand = new Random(); 

     Elevation = new int[(int)width]; 

     MaxElevation = maxElevation; 
     MinElevation = minElevation; 

     Width = width; 
     Height = height; 

     Position = position; 

     elevation(); 

    } 

    public void Update() 
    { 
    } 

    public void elevation() 
    { 
     for (x = (int)Width - 1; x >= 0; x--) 
     { 
      for (y = (int)Width - 1; y >= 0; y--) 
      { 
       y = rand.Next((int)MaxElevation); 
       Elevation[x] = y; 
      } 
     } 
    } 

    public void Draw(SpriteBatch spriteBatch) 
    { 
     for (x = (int)Width - 1; x >= 0; x--) 
     { 
      spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[x], 1, (int)Height), Color.White); 
     } 
    } 

} 

}

+0

顯示您的海拔聲明。它在哪裏宣佈? – BlackBear

回答

1

問題是與你的elevation()方法。您正在使用y作爲內部循環索引器,並在循環內爲其分配一個值。所以循環開始,y被分配一個隨機值。當它繼續循環時,它會遞減,然後測試爲>=0。此循環唯一的退出時間是y被指定爲隨機數0。所以這就是爲什麼你所有的Elevation都是零。

我有點困惑,爲什麼你認爲你需要一個內部循環。請嘗試:

public void elevation() 
{ 
    for (x = (int)Width - 1; x >= 0; x--) 
    {    
     Elevation[x] = rand.Next((int)MaxElevation);    
    } 
} 
相關問題