Explosions
I will be adapting this to change particle to a class instead of a struct, to allow for a particle texture instead of just a block.
Code from internet
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace Explosion
{
class Explosion
{
double drag = 0.8;
Color particleColor = new Color(255, 230, 128, 255);
double maxAge = 3;
double age = 0;
struct particle
{
public double x;
public double y;
public double vx;
public double vy;
}
particle[] particles = new particle[100];
Random rnd = new Random(127);
Texture2D pixel;
public Explosion (GraphicsDevice graph, int locx, int locy, float speed, Random rndm)
{
double angle;
double radius;
pixel = new Texture2D(graph, 1, 1);
pixel.SetData<Color>(new Color[] { Color.White });
if (speed == 0) speed = 2;
rnd = rndm; // Remove this line to give each explosion the same animation
for (int tel= 0; tel < 100; tel++)
{
particles[tel] = new particle();
angle = rnd.NextDouble() * 2 * Math.PI;
radius = Math.Pow(rnd.NextDouble(), 0.5);
particles[tel].x = locx;
particles[tel].y = locy;
particles[tel].vx = speed * radius * Math.Sin(angle);
particles[tel].vy = speed * radius * Math.Cos(angle);
}
}
public bool Update(GameTime gametime)
{
double timeChange = gametime.ElapsedGameTime.TotalSeconds;
double localDrag = Math.Pow(drag, timeChange);
age += gametime.ElapsedGameTime.TotalSeconds;
if (age > maxAge) return false;
for (int tel =0;tel < 100; tel++)
{
particles[tel].vx *= localDrag;
particles[tel].vy *= localDrag;
particles[tel].x += particles[tel].vx * localDrag;
particles[tel].y += particles[tel].vy * localDrag;
}
return true;
}
public void Draw (SpriteBatch spriteBatch)
{
Rectangle destination;
for (int tel = 0; tel < 100; tel++)
{
destination = new Rectangle((int)particles[tel].x, (int)particles[tel].y, 5, 5);
spriteBatch.Draw(pixel, destination, particleColor);
}
}
}
}
Using
Declare variables
double timer;
List<Explosion> explosions = new List<Explosion>();
Random rnd = new Random(101);
Update additions
List<int> delList = new List<int>();
timer += gameTime.ElapsedGameTime.TotalSeconds;
if (timer > 0.6)
{
timer = 0;
Explosion newExplosion = new Explosion(GraphicsDevice, rnd.Next(GraphicsDevice.Viewport.Width),
rnd.Next(GraphicsDevice.Viewport.Height), rnd.Next(21)+1, rnd);
explosions.Add(newExplosion);
}
foreach (Explosion expl in explosions)
{
if (expl.Update(gameTime)) continue;
delList.Add(explosions.IndexOf(expl));
}
for (int tel = explosions.Count; tel >= 0; tel--)
if (delList.Exists(x => x == tel)) { explosions.RemoveAt(tel); }
Draw additions
spriteBatch.Begin();
foreach(Explosion expl in explosions)
{
expl.Draw(spriteBatch);
}
spriteBatch.End();