Search code examples
python2dpygameparticles

pygame - particle effects


I'm making a 2-d game using Pygame.
I want to add particle effects into the game I'm working on. I want to do things like spawn smoke, fire, blood, etc. I'm curious is there an easy way to do this? I don't really know even where to start.
I just need a base case I could expand upon..
Pls Help.


Solution

  • You might want to just make a class made of rects that go up and randomly go to the right or left each time it is updated for the smoke. Then make a ton of them whenever you want it. I'll try to make an example code below, but I can't guarntee it will work. You can make similar classes for the other particle effects.

    class classsmoke(pygame.Rect):
        'classsmoke(location)'
        def __init__(self, location):
            self.width=1
            self.height=1
            self.center=location
        def update(self):
            self.centery-=3#You might want to increase or decrease this
            self.centerx+=random.randint(-2, 2)#You might want to raise or lower this as well
    
    #use this to create smoke
    smoke=[]
    for i in range(20):
        smoke.append(classsmoke(insert location here))
    #put this somewhere within your game loop
    for i in smoke:
        i.update()
        if i.centery<0:
            smoke.remove(i)
        else:
            pygame.draw.rect(screen, GREY, i)
    

    Another option would be to make the class just a tuple, like this:

    class classsmoke():
        'classsmoke(location)'
        def __init__(self, location):
            self.center=location
        def update(self):
            self.center[1]-=3
            self.center[0]+=random.randint(-2, 2)
    
    #to create smoke
    smoke=[]
    for i in range(20):
        smoke.append(classsmoke(insert location here))
    #put inside game loop
    for i in smoke:
        i.update()
        if i.centery<0:
            smoke.remove(i)
        else:
            pygame.draw.rect(screen, GREY, (i.center[0], i.center[1], 1, 1))
    

    Or, to avoid classes completly:

    #to create smoke:
    smoke=[]
    for i in range(20):
        smoke.append(insert location here)
    #put within your game loop
    for i in smoke:
        i[1]-=3
        i[0]+=random.randint(-2, 2)
        if i[1]<0:
            smoke.remove(i)
        else:
            pygame.draw.rect(screen, GREY, (i[0], i[1], 1, 1))
    

    Pick your preference, and do something similar for other particle effects.