• 15
• 15
• 11
• 9
• 10

# Explosion code

This topic is 3621 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello all. I've created a simple function a long time ago that could create an explosion of particles in 2D. In order to calculate the velocity in x and y directions from an angle, I used this code:
    velx = velocity * cos(torad(angle));
vely = velocity * sin(torad(angle));
In order to create the explosion, I'd provide a random angle (float) and a random velocity (float) capped at a maximum. How would I tackle the maths if I want to do a similar explosion in 3D? I guess I need two random angles, since one won't cut it for all three dimensions. But how would I combine them?

##### Share on other sites
http://en.wikipedia.org/wiki/Spherical_coordinates

You are correct that you would need 2 angles, azimuth and elevation (or zenith depending on what you want your 0 to mean).

##### Share on other sites
I'm just gonna put this one out there, as i'm just thinking on my feet here.

You could pick a random point, then work out the vector between that and the center of the explosion, normalise it to give you the direction then apply a random magnitude to it.

##### Share on other sites
You can use spherical coordinates with rho == 1 (what you did there in 2D was actually use polar coordinates). Converting from spherical to cartesian is pretty easy, the equations are listed on the wikipedia entry. However there's a trick: simply generating two random angles (for phi and theta) won't get you a uniform distribution on a sphere. this page and this page talk about what happens with the naive approach. The easiest way to get around this is to do what the second page suggests:

// Assume that RandFloat returns a random floating-point number within the specified rangefloat phi = RandFloat(0, 2 * pi);float theta = acos(1 - RandFloat(0, 2));velx = velocity * sin(phi) * cos(theta);vely = velocity * sin(phi) * sin(theta);velz = velocity * cos(phi);

##### Share on other sites
You need two angles. I would also use vectors rather than holding 3 separate scalars.

void ParticleSystem::addExplosion( const Particle& ptcl, float maxvel, int magnitude ){    for( int i = 0; i < magnitude; i++ ) {        // Velocity is between maxvel/2 and maxvel        float random_vel = (float)rand()/RAND_MAX * (maxvel/2) + (maxvel/2);        // Create a random point - rand()-rand() also creates negative numbers        Vector random_point( rand()-rand(), rand()-rand(), rand()-rand() );        // Take the unit vector and multiply it times the random velocity        random_point = random_point.unit() * random_vel;        // Add the particle and set its velocity        system.push_back( ptcl );        system.back().vel = random_point;    }}