So recently i posted a question here for help in generating random objects for my “tower defense” game. I’ve got a lot of help, and actually managed to do it. The problem is the positions where “too random” and it gave me issues with object 1 being drawn above object 2 and things like that. The solution i found was to make and array with 5 different locations for each object, so this way these objects wouldn’t collide with each other.
However, i also needed to make the number of objects random, and i realized an issue. When i get, for example, 2 intances of object 2 drawn on screen, they are getting the same position, and i’m not managing to make them get different positions. I made a function that will select a random number from this “position array”, but how can i do it so it calls a different position everytime it is called? I understand the problem happens because the function is being called once and having the same value forever.
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin(this.camera);
mapa.draw(_spriteBatch, backGroundFloor);
for(int i = 0; i < control.randomNumber(); i++) { mapa.drawObjs(_spriteBatch, singlePineTree, rNX1, rNY1); }
player.anim.Draw(_spriteBatch);
_spriteBatch.End();
base.Draw(gameTime);
}
control.randomNumber is the number of times the obj will be drawn on screen. Here’s this simple function:
public int randomNumber()
{
Random rand = new Random();
return rand.Next(2,4);
}
I call the function for a random position in initialize or in the constructor ( understand the problem is here, but don’t know where to call it or how to call it to work how i want it):
protected override void Initialize()
{
_graphics.PreferredBackBufferWidth = 1920;
_graphics.PreferredBackBufferHeight = 1080;
_graphics.ApplyChanges();
this.camera = new Camera(_graphics.GraphicsDevice);
rNX1 = control.rNumberPos(15, 50, 900, 600, 700);
rNY1 = control.rNumberPos(55, 70, 500, 300, 250);
base.Initialize();
}
and the function:
public int rNumberPos(int r1, int r2, int r3, int r4, int r5)
{
Random rand = new Random();
int[] rArray = { r1, r2, r3, r4, r5 };
int rn = rand.Next(0, rArray.Length);
return rArray[rn];
}