Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't use a variable in another method in XNA
    text
    copied!<p>I will explain in depth after. So here is my code, we have an Elevation[] variable and each Elevation gets a random number:</p> <pre><code>public void elevation() { for (x = (int)Width - 1; x &gt;= 0; x--) { for (y = (int)Width - 1; y &gt;= 0; y--) { y = rand.Next((int)MaxElevation); //random number for each y. Elevation[x] = y; //each Elevation gets a random number. } } } </code></pre> <p>After this I try to use this random number in the draw method like this:</p> <pre><code>public void Draw(SpriteBatch spriteBatch) { for (x = (int)Width - 1; x &gt;= 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. } } </code></pre> <p>How can I acces this random number? </p> <p>If I do that:</p> <pre><code>public void Draw(SpriteBatch spriteBatch) { for (x = (int)Width - 1; x &gt;= 0; x--) { for (y = (int)Width - 1; y &gt;= 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); } } } </code></pre> <p>I will be able to acces the random numbers, but it will update every frame and the random numbers will change. So I need to calculate them once and then use them.</p> <p>Here is all the code:</p> <pre><code>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&lt;Texture2D&gt;("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 &gt;= 0; x--) { for (y = (int)Width - 1; y &gt;= 0; y--) { y = rand.Next((int)MaxElevation); Elevation[x] = y; } } } public void Draw(SpriteBatch spriteBatch) { for (x = (int)Width - 1; x &gt;= 0; x--) { spriteBatch.Draw(Pixel, new Rectangle((int)Position.X + x, (int)Position.Y - Elevation[x], 1, (int)Height), Color.White); } } } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload