iPhone Game Programming – Tutorial 8 – Particle Emitter
Finally I’ve managed to finish the Particle Emitter tutorial. I got seriously side tracked with other fun things like sound etc on the iPhone, but I’ve managed to focus back on this and get it finished.
This tutorial will go through the creation of a particle emitter. This is a class which can generate a large number of objects, particles, on screen and control them in an organic way. This is normally used to generate effects such as fire, smoke, sparks etc.
The code and design of this are very much based on the work done by Cocos2D and so I owe them thanks for having their code open and available to check out. I’ve learnt a lot from looking at how they do things.
This particle emitter is not as complex as the Cocos2D one as I wanted to make is as easy to understand as I could, one so I could learn and two as I think people can take the basics and build up from that at their own pace.
As usual the video and source is available below, so I hope you enjoy it and join me next time when I’ll be running through the Sound Manager.
Mike
P.S. If you want to design particle effects in realtime, check out our Particle Designer desktop app. This allows you to design particle effects in realtime and then export them for use in Cocos2D iPhone or our latest version of the ParticleEmitter class.
66 Comments
mike on May 25th, 2009
Hi DennisVR, explosions were why I wanted to get a Particle System up and running. Its been fun to learn with a lot of it coming from looking inside Cocos2D.
I’d be interested in any feedback you have when you’ve watched it.
Cheers
Mike
Tony on May 25th, 2009
Awesome, Mike! After being thrown into iPhone game development overnight (for work), these tutorials have cleared up/explained so many things that reading two books and numerous blogs/articles could not. They are clear and well-structured. I managed to watch all of them this weekend in between my husband-duties (gardening, etc.). I’m going to work late as I watched Tutorial 8 in the comfort of my living room. Thank you very much for your efforts. I’m impressed that you can be so lively at two in the morning. :o) I look forward to the Sound Manager tutorial.
Many thanks,
Tony
iamflimflam1 on May 25th, 2009
Another awesome tutorial. I’m just putting the finishing touches to my game (the last 10% long slog). But I’m tempted to revisit my explosions and fire effects now.
Also looking forward to the sound tutorial. Keep up the good work!
mike on May 25th, 2009
Thanks iamflimflam1. The particle emitter was fun to do and I kept thinking of all sorts of things it could be used for. Your right that the last 10% can be a slog. In my days as a full time dev that seemed to be the last 10% of any project :O)
I hope the game goes well and I’m looking forward to getting a glimpse of the finished product when its done.
I’m off to get some sleep now but I’m leaving the Sound Manager tutorial uploading, so I’ll get it posted first thing tomorrow morning.
Mike
mike on May 25th, 2009
Thanks Tony. Sounds like a bit of deep end swimming for a while given when you started all this. I’m glad the tutorials are helping and please post any questions you have. Can’t say I’ll always have the answer but I’ll certainly do my best :o)
Mike
RoberRM on May 25th, 2009
I couldn’t resist it! Even though I’m in tutorial 7 now, I had to take a look at what you have done with the particles… The results are awesome! But what has made me write this post is that I’ll be able to finally click the screen and the game will do something (yeah, I know: it’s just implementing one method! But I didn’t know where to implement it, and now I’ll know!!). Thank you again Mike, thank you very much! :)
iamflimflam1 on May 25th, 2009
Been doing some work on the graphics side of things as a break from the coding. I’ve got an icon – just need to finish game now.
mike on May 26th, 2009
@RoberRM, I’m glad you liked it and that you were able to get your touches working. I’ll be doing more on touches and controlling things in the coming tutorials :)
Mike
Eskema on May 26th, 2009
Im thinking mike, we are using point sprites to gain performance, because its much faster than draw a quad, so maybe we can do the same with fonts and other sprites, isn’t?
Maybe this doesnt makes any sense, but if we draw a point and attach a texture, why are we loosing time rendering quads?
iamflimflam1 on May 26th, 2009
@Eskema, I think the problem with point sprites is that you can only render whole texture so to draw multiple different point sprites you have to keep binding different textures.
With the quads method you can bind one texture that contains multiple sprites so you avoid the cost of having to rebind the texture.
Eskema on May 26th, 2009
Aja, so we can draw our “explosions” because its only one texture, but the spritesheet draws the whole texture, interesting stuff :)
mike on May 26th, 2009
iamflimflam1 got there first :o)
As he says, when you use a texture with a point sprite it uses the whole thing, you cant specify texture coordinates so bitmap fonts would mean LOADS of texture bindings and lots of textures.
Mike
Eskema on May 26th, 2009
nevermind, this is one of those strange days when you start thinking nonsense things ;)
my app finally reach the store, time to take a breath and start another project
mike on May 26th, 2009
@Eskema, I have lots of those days :o)
What is the name of the app, I’d like to go have a look.
Mike
Eskema on May 26th, 2009
TheNovice its a puzzle-action game
Tenchy on May 27th, 2009
Thanks for this mike, is just awesome. I’can’t wait to go home and play with it for hours. The possibilities are just infinite.
Thanks to all of your tutorials my project is becoming a reality
ricky on May 29th, 2009
Hey Mike, thanks a lot for putting this up.. the tutorial is a huge help.
mazebr on May 30th, 2009
Have you seen the Stanford lessons site recently?
They had a guy down from ngmoco who spoke on open gl.
He posted source code for a particle emitter on his company blog. Check it out:
http://gamemakers.ngmoco.com/p.....-enough-to
mike on May 30th, 2009
Thanks mazebr, I’m going to check out both the lecture and the source code as both look really interesting :o)
Thanks for the info
Mike
iamflimflam1 on May 30th, 2009
Interesting, I had a quick look at the posted code – he’s not actually using point sprites for his particles.
What might be quite useful to look at is that he is rotating his sprites in code rather than using the gltranslate and glrotate commands. This lets him batch up his draw calls even though he he has rotated sprites – something that I’ve been looking to do in my code.
RoberRM on May 31st, 2009
Well, now I’ve finished tutorial 8. I had to add one change that was somewhere in your code but I missed it in the tutorials: at the end of the -renderParticles method I’ve added:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_BLEND);
I’ve seeing you’ve got it in the -renderScene method inside EAGLView.m, but for some reason I didn’t. I prefer to add it at the end of the -renderParticles though, because you always say that if a class messes something it’s the class that should fix it (or something like that, but that’s the idea I’ve gotten so far). ;)
Anyway, Mike, this one was really, really good. And thanks to you I’m starting to lose the fear of coding for the iPhone. Please, keep up with your tutorials (but you can take more time between them, we will understand :D ).
mike on May 31st, 2009
Hi RoberRM. You are right that I always try to switch of things at the end of rendering something which I switch on in the same method. I’ve had a few odd things happen in the past which was down to not doing that.
I’m glad you liked this tutorial and appreciate your comments on not needing to post tutorials so quickly :) . The particle one had been hanging around for a while so I was eager to get it out and the Sound one just kinda grew out of playing with OpenAL.
I do try to keep them as regular as I can as I know how frustrating it can be when you are following something and there is a big gap between updates, but its good to know people are not expecting too much in terms of speed of posting with these :o) it does give me some time to get them as good as possible.
Mike
RoberRM on May 31st, 2009
Hi Mike!
Just a final note: I appreciate your work a lot. That’s why I told you not to stress yourself, not because I want your tutorials to be perfect (they are awesome as they are) but because I do want you to end this series of tutorials and not to feel so much stressed that you abandon them or something like that.
Also, your status news now and then are welcome too. They help to let us know that you haven’t forgotten us (because THAT would be frustrating). :D
I felt compelled to write this post because of your comment: “… its good to know people are not expecting too much in terms of …”. I don’t know how others feel, but I’m not in the position to expect anything from you (meaning that who am I to require you to do anything?). I am extremely grateful for your tutorials and comments, but I would also understand if you could not continue the work. (Not that I like the idea, though :D ). But in that case, please, warn us!
I hope this didn’t sound too stupid (because I’m making too much of a fuss over your comment). In that case sorry, my english is not that good yet. :)
Cheers!
Róber
A Person on June 1st, 2009
Hey mike great tutorials, I noticed that in one of the older tutorials you mentitioned collision detection. I’ve been writing one myself but I’m not sure if it’s right. Are you making any tutorials on collision detection.
mike on June 1st, 2009
Hi A Person, yes is the answer to that :o)
I’m just refactoring my code at the moment and I’m then going to be covering off more on touch and accelerometer as well as collision detection. I’m not planning on doing anything too sophisticated but I will cover AABB (Axis Aligned Bounding Boxes).
Mike
A Person on June 1st, 2009
Sounds good thanks for the fast reply
penguins on June 10th, 2009
Wow, Best tutorial yet. I Love the particle system. Its totally awesome. Thank you so much for sharing.
Mr Speaker on June 12th, 2009
That. Is. So. COoool! No more sprites for me… just particles!
But I was trying (unsuccessfully) to update parameters mid-particle effect. As everything is configured and calculated in the init function, how can you change say, the x and y position of the centre of the whole effect? For example, if you wanted the particle cloud to float across the screen. Or have the particles become larger over time etc?
Mr Speaker on June 12th, 2009
Ha ha! oops. I just was doing some gesture stuff with the touch api, and was doing my particle cloud updating only after you do a horizontal swipe… so I thought it wasn’t working.
Updating the particles mid-effect is tres cool ;)
mike on June 13th, 2009
Excellent, I am pleased that you have managed to get that working. I love particle systems as they are so flexible and just fun to play with. I’d also like to thank you for the coffee, its much appreciated :o)
Mike
Dennis S. Sedov on July 11th, 2009
Really great tutorial! I have finished building my particle system for a game using it! One problem I found instantly is that particle simmulaton looks different on device and on simulator. There are few things I’ve done that helped me solve this problem.
Not everything in you simmulation is dependant on delta in update loop. Things like distance a particle should travel and amount of particle emitted should really depend on it.
Here is what I’ve done:
Assuming that emission rate is given in particles per second we change update loop to this:
if(active && emissionRate > 0.0f) {
emitCounter += emissionRate * delta;
while(particleCount 0.0f) {
[self emitParticle];
emitCounter -= 1.0f;
}
elapsedTime += delta;
if(duration != -1 && duration position = Vector2fAdd(currentParticle->position, Vector2fMultiply(currentParticle->direction, delta));
}
jadetree on August 5th, 2009
Mike,
I love the work you are doing! Amazing stuff!! You are really good at keeping things as simple as possible, but without sacrificing features that are necessary. Your work is valuable and inspiring. This is a personal thanks for all your hard work! Also, is it okay to use your classes in a game I am making? When finished, I want to submit it to the App store. Is your code protected or can I use it legally? Thanks again. Either way, your tutorials are amazing!!
-Joshua
mike on August 6th, 2009
@Dennis, thanks for spotting the missing delta usage. That is something I’ll put back in :o)
@Joshua, I appreciate the great comments. I do really believe that keeping it simple is the best way to learn. There are always more complex ways to do things but its much harder to explain how something is working when using them.
All the iPhone code on the blog is under the MIT license. I keep meaning to add it to the source code as I should have done from the start. Basically you are free to use the code as necessary with an MIT license. I’m just about to post about using code in your own projects and it will contain the license details.
Mike
Early on August 9th, 2009
These Tutorials have really been incredible for me I wrote my first game without OpenGL and the methods you have walked us through are so much cleaner and more efficient than what I was using before so thanks for that. I have learned a lot from these and I really appreciate you sharing your knowledge.
One of the things I’ve noticed with the particle emitter is that the particles always render as the top layer even if I render sprites or animations after the renderParticles. I can imagine scenarios where I might like to have the sprites or characters in front of the particles. Is this possible?
mike on August 9th, 2009
Hi Early, I’m glad your finding these tutorials useful :o)
As for the particles always being on top, I think you have just found a bug :O)
If you are using additive blending on the particles its not being switch off which causes anything drawn next to merge with the particles making it look the particles are on top. If you add the following line to the end of the renderParticles method
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
It puts OpenGL back into the normal blending we have be using when rendering our images. That should then cause things drawn after the particles to render on top of them.
If this is not the problem let me know.
Mike
mike on August 9th, 2009
There are of course cleaner ways to do that such as only changing the blend function of additive has been used etc.
I should be putting up new particle emitter code soon which I’ve debugged further and cleaned up. I’ll also be putting put a debugged and cleaner sound manager as well.
Mike
Early on August 9th, 2009
Thanks Mike!
That was the problem. I couldn’t figure out why the particle code was changing the alpha of my sprite but the blending explains that as well.
Thanks again for all your help.
Seth A. Robinson on August 27th, 2009
Nice work!
Quick note, I believe the line glDisableClientState(GL_POINT_SPRITE_OES); should be removed… glGetError reports an error with it in for me.
(Should be a glDisable(), which is there also)
iPhone Game Programming – Tutorial 8 – Particle Emitter | 71² … | IPhoneMate on September 7th, 2009
[...] from: iPhone Game Programming – Tutorial 8 – Particle Emitter | 71² … Share and [...]
hugo on September 10th, 2009
Excellent tutorial Mike! Thanks a lot!
I think there is only one thing missing – a maxParticles setter so you could set it dynamicly (increasing or decreasing in time)…
Its my version – seems to work fine
- (void)setMaxParticles:(GLuint)aMaxParticles{
maxParticles = aMaxParticles;
particles = realloc(particles, sizeof(Particle) * maxParticles);
vertices = realloc(vertices, sizeof(PointSprite) * maxParticles);
colors = realloc(colors, sizeof(Color4f) * maxParticles);
}
Once again thanks for all!
mike on September 10th, 2009
Hi hugo, nice idea :o) I’ll have to give that a go
Could you post about what you have done in the community forum for this tutorial. It will make it easier for others to see your post and what you have done.
Let me know if you have any problems.
Thanks
Mike
zibba on September 10th, 2009
Thanks for your tutorials very useful. There’s a small problem in the ParticleEmitter.m. At the end of renderParticles it does this
glDisableClientState(GL_POINT_SPRITE_OES);
It should actually be
glDisableClientState(GL_POINT_SIZE_ARRAY_OES);
mike on September 10th, 2009
Thanks zibba. That was a fix I’d put into Tutorial 10 but forgot to go back and change the other tutorial projects. I’ve now done that.
Thanks
Mike
MrGando on October 1st, 2009
Hello there! thanks for making this tutorials!
I have been struggling to understand how did you manage to get such a good frame-rate with 64×64 gl point sprites!, I am working on a project and I’m doing my drawing in your EXACT same way. ( VBO ) , but instead of using two buffers I only use one for one Vertex Struct that contains color + x,y + size. It renders but when displaying 500 particles at a time I seem to get like 18 FPS, you seem to be getting a lot more. is it because you are not really displaying the 500 particles at once and your emitter is regulating the emittion rate so there are actually less than 500 particles on screen ? or something ?
If you need code examples or anything and you are willing to help me , please, let me know.
Thanks
mike on October 1st, 2009
Hi MrGando
I’m not sure why you are getting such a slow frame rate. Using a single VBO should work well. Have you done any work using instruments to see where the bottleneck is i.e. CPU or GPU.
If you have any code you can provide then send it over and I’ll have a look. My email is mike@71squared.co.uk
Mike
brianb on November 25th, 2009
When I run the sample code (and my copy) in the simulator, all I see is a colorful glowing white circle. Mine doesn’t blowup like it should. Thoughts?
brianb on November 25th, 2009
When I run the sample code (and my version) in 2.2 & 3.0 simulator, all I see is a colorful glowing white circle. I should be seeing the explosion. Any ideas?
Trevor Newsome on February 15th, 2010
Wow, speechless Mike, fantastic tutorial.
Andy on March 28th, 2010
Ive been going through your tutorials over the last couple of months and just started testing my game on the device and i get a weird problem when i use the particle emitter i get a secondary much larger explosion in the top right corner. It appears to be related to particleLifeSpan if its 50 it works fine, but much lower values cause the problem. It never happens on the simulator. Any help would be much appriated. Its about my last bug!
_explosionEmitter = [[ParticleEmitter alloc] initParticleEmitterWithImageNamed:@”texture.png”
position:Vector2fMake(160, 240)
sourcePositionVariance:Vector2fMake(5, 5)
speed:1.0f
speedVariance:0.5f
particleLifeSpan:0.5f
particleLifespanVariance:0.8f
angle:0.0f
angleVariance:360
gravity:Vector2fMake(0.0f, -0.00f)
startColor:Color4fMake(1.0f, 0.4f, 0.0f, 1.0f)
startColorVariance:Color4fMake(0.1f, 0.0f, 0.0f, 0.5f)
finishColor:Color4fMake(0.8f, 0.8f, 0.8f, 0.5f)
finishColorVariance:Color4fMake(0.1f, 0.1f, 0.1f, 0.0f)
maxParticles:500
particleSize:16
particleSizeVariance:20
duration:0.025f
blendAdditive:YES];
mike on March 29th, 2010
Hi Andy
I think I do know what your problem is. During beta testing of SLQ it was noticed that on iPhone 3GS devices you would get this large secondary artefact somewhere on the screen. This was traced back to the partile size going below zero, which it can do if you have a size on the variance.
The fix is to make sure the particle size does not go below zero as shown below.
vertices[particleIndex].size = MAX(0, currentParticle->particleSize);
Let me know if that solves your problem.
Mike
Andy on March 29th, 2010
Hi Mike
Thanks for that, yep this was testing on a 3GS and your fix solves the problem. Many thanks saved me a lot of time! I will hopefully have my game in the app store very soon, another spectrum classic i may add.
Many thanks Andy
Saliom on April 2nd, 2010
Hi mike, i’m doing a little game on iPhone, and need an explosion effect, as i’m using cocos2d i use their Particle System, but i can’t get somehow the same explosion effect than you (in the video at 74:25 )
even with the same settings… in fact the problem is that the texture doesn’t take the colors i put… every particle gets a different color (Green Red or Blue) and it’s quite ugly…
any idea on what should i do?
Saliom on April 2nd, 2010
if it helps you to see hat i mean, my textures ( when not blending ) looks like the multi color balls you got at 79h40 … and i don’t know why …
Saliom on April 2nd, 2010
oups i meant 79:40 not79h xD sorry
Danegraphics on April 10th, 2010
I’ve been using your classes and have found memory leaks in you Image.m file at the following places:
subImage = [[Image alloc] initWithTexture:texture scale:subImageScale];
and
texCoords = malloc( sizeof(texCoords[0]) * totalQuads);
Both give me leaks when tested with the leak monitor tool.
Danegraphics on April 10th, 2010
Actually I just retested and found that all three mallocs are memory leaks of some kind.
texCoords = malloc( sizeof(texCoords[0]) * totalQuads);
vertices = malloc( sizeof(vertices[0]) * totalQuads);
indices = malloc( sizeof(indices[0]) * totalQuads * 6);
iPhone Game Programming Tutorial 1 | Hardblog Cafe on October 6th, 2010
[...] iphone-game-programming-tutorial-7-singleton-class iphone-game-programming-tutorial-8-particle-emitter iphone-game-programming-tutorial-9-sound-manager iphone-game-programming-tutorial-10-game-structure [...]
Daniel on November 18th, 2010
Hi Mike, first of all thanks for this great tutorial.
I’ve only got one problem, that i haven’t been able to solve:
If i use the EAGLEView as a normal UIVIew (inside another UIVIew) everything works fine and as expected, but if i re-instantiate it a second time (having released the first EAGLView before), the particles do NOT get rendered on-screen.
I’m rather new to OpenGLES, so forgive me if this is a dumb question.
thanks
Colourclash on May 16th, 2011
Hi Mike, thanks for the tutorial. Great stuff as always.
I just wanted to point you in the direction of a cool open source tool that you might find useful. It’s a realtime debug variable tweaker that lets you change variables in realtime of your iPhone/iPad app.
It requires you to add some code to your iPhone projet but the code is lightweight and can be integrated in 10 minutes and once the code is integrated the tool just needs the iPhone’s ip address to communicate.
You can expose variables by declaring them in your code with a special macro and once exposed you will get a slider bar in the tool for each one. It even supports colours with a colour picker.
Check it out:
mike on May 16th, 2011
Thanks for the pointer Colourclash. That is a really interesting project and may well help us get the live particle editing we have wanted to put in Particle Designer sorted out.
We wrote our own network code to remotely control a particle emitter on one or more real devices direct from Particle Designer. It was working great but we could not get rid of some stability issues and ran out of time to get it working.
We are working on Particle Designer 2.0 at the moment and this project may well be able to help out.
Cheers
Mike
Colourclash on May 16th, 2011
No problem Mike.
ps I can’t take any credit for the DebugScope tool. It was written by another ex Bizarre Creations guy who now runs PixelBalloon (www.pixelballoon.com).
Generate Particles Along A Path | ClingMarks on September 17th, 2011
[...] 71squared’s tutorial, which in my opinion is the one of the best tutorials in this category (link to tutorial). Their “Particle Designer” is also a great tool to simplify the process to create [...]
Peter on September 23rd, 2011
Hi Mike,
Firstly let me just say your tutorials are amazing – keep up the awesome work!
I have a question regarding particle systems -more specifically about your point sprite implementation. Is it possible for point sprites to be drawn at a rotated angle? For some particle effects like smoke it looks cooler if the particles are rotated!
If this is possible could you help me out with it?
Thanks in advance,
Peter
Peter on September 23rd, 2011
So I got my hands on Tim Omernick’s particle system and his particles do rotate. After examining his code it appears as though he has done the rotations manually (by specifying the corners of the quad (or rather two triangles)). I think someone has already posted this above actually.
Anyway, so my question is this: could a similar approach (manually specify corners of quad) be used in combination with your approach (sprite points)?
Or maybe there is a ‘better’ way to do it perhaps?
Joshua Simeon Narins on January 26th, 2012
I am pretty sure you want the gravity to be multiplied by delta, too.





DennisVR on May 25th, 2009
Great, did some particle stuff myself this weekend. Mainly for explosions and missle trails. Curious to see how you tackled it. Will watch it when i find some time.