Hi all, for example each 5 seconds, a enemy will spawn at random position, after another 5 seconds a new enemy will spawn at random position, but without the previous one change their position, and so on.
This is my code:
using System;using System.Collections.Generic;using SFML.Graphics;using SFML.System;using SFML.Window;namespace sfml_array_sprites
{ class Program
{ public static RenderWindow rw
; public static Clock tmpcl
; public static List
<Sprite
> lst_sprt
; public static Texture txtr
; public static Random rndm
; public static int l_size
=0; public static List
<float> lst_posx
; public static List
<float> lst_posy
; public static void Main
(string[] args
) { rndm
= new Random
(); rw
= new RenderWindow
(new VideoMode
(700,
500),
"..."); rw
.SetActive(true); bool state
=rw
.IsOpen(); txtr
= new Texture
(@"c:\assets\player.png"); Clock clck
= new Clock
(); Time timeSinceLastUpdate
=Time
.Zero; Time timePerFrame
=Time
.FromSeconds(1
.0f
/60
.0f
); tmpcl
= new Clock
(); lst_sprt
=new List
<Sprite
>(); lst_posx
= new List
<float>(); lst_posy
= new List
<float>(); while(state
==true) { timeSinceLastUpdate
+=clck
.Restart(); while(timeSinceLastUpdate
>timePerFrame
) { timeSinceLastUpdate
-=timePerFrame
; update
(timePerFrame
); } render
(); } } public static void update
(Time deltaTime
) { if(tmpcl
.ElapsedTime.AsSeconds()>4
.0f
) { spawnEnemy
(); l_size
+=1; tmpcl
.Restart(); } } public static void render
() { rw
.Clear(Color
.White); rw
.DispatchEvents(); for(int p
=0;p
<lst_sprt
.Count;p
++) { rw
.Draw(lst_sprt
[p
]); } rw
.Display(); } public static void spawnEnemy
() { Sprite obj
; lst_sprt
= new List
<Sprite
>(l_size
); lst_posx
= new List
<float>(l_size
); lst_posy
= new List
<float>(l_size
); for(int dd
=0;dd
<lst_posx
.Capacity;dd
++) { lst_posx
.Add((float)Rndm_pX
()); lst_posy
.Add((float)Rndm_pY
()); } for(int u
=0;u
<lst_sprt
.Capacity;u
++) { obj
= new Sprite
(txtr
); lst_sprt
.Add(obj
); lst_sprt
[u
].Scale = new SFML
.Window.Vector2f(0
.5f,0
.5f
); lst_sprt
[u
].Position=new SFML
.Window.Vector2f(lst_posx
[u
],lst_posy
[u
]); } } public static int Rndm_pX
() { return rndm
.Next(0,
625); } public static int Rndm_pY
() { return rndm
.Next(0,
404); } }} If I comment these lines I get an NullReferenceException:
lst_sprt
=new List
<Sprite
>();lst_posx
= new List
<float>();lst_posy
= new List
<float>(); I am aware that after resetting the clock a new position will be generated for each sprite. I do not know how to prevent that from happening, neither do I know where in the code that method should be implemented. That's why I need your help.
P.S. I do not know if it is allowed to upload videos from a specific platform, but here is the video:
Thanks, problem solved ^^
The new spawnEnemy code:
Sprite obj=new Sprite(txtr);
rndm=new Random();
obj.Position=new SFML.Window.Vector2f((float)rndm.Next(0,500),(float)rndm.Next(0,700));
lst_sprt.Add(obj);