Random textures in XNA

Okay, so I have this game I'm working on, I'm new to XNA (I use 4.0), and what I want to do is have a different texture every time the enemy spawns.

So, I have these images "image1.png", "image2.png" etc. I want him to use different textures every time a new enemy appears, while he downloads only a random image when the game starts, so the problem should be that the random method is not updated for each caviar, but is set at the beginning of the game. I searched a lot on the Internet and tried solutions that, although I would work, but did not hope ... So, my code

In LoadContent() , I have this code:

 Random textureRandom = new Random(); int skinRandom = textureRandom.Next(1, 4); string lamp = string.Concat("image", skinRandom.ToString()); enemyTex = Content.Load<Texture2D>(lamp) as Texture2D; 
+4
source share
1 answer

If I remember correctly, the Game.LoadContent () method is called only once during initialization (Game.Initialize ()) to load game resources. You can force the game to reload these resources, but since you do not want to reload all your resources, I would suggest loading all the images that you need in the LoadContent () method, for example:

 List<Texture2D> texturePool = new List<Texture2D>(); Random rng = new Random(); protected override void LoadContent() { for(int i = 0; i < 4; i++) texturePool.Add(Content.Load<Texture2D>("image" + i.ToString())); } 

And then, before the enemy starts, you will change the texture used, choosing one from the loaded pool.

 enemyTex = texturePool[rng.NextInt(texturePool.Count)]; 

And maybe you can change the name to "Random Textures in XNA" or something like that, since you want to change the texture on each spawn, and not on every draw, and this method can be used in many other situations.

+3
source

Source: https://habr.com/ru/post/1446162/


All Articles