Reputation: 285
As I am still new to programming, I'm trying to come up with some basic programs simply to help me understand coding and learn.
I am trying to create an object that shoots small particles upward using pygame. It all works fine, but I can't find a way to control the rate at which the objects creates those particles. I have a Launcher and Particle class, and a launchers and particles lists. Do you need all the lines of the program? Here is the basic setup:
particles = []
launchers = []
class Particle:
def __init__(self, x, y):
self.pos = np.array([x, y])
self.vel = np.array([0.0, -15])
self.acc = np.array([0.0, -0.5])
self.colors = white
self.size = 1
def renderParticle(self):
self.pos += self.vel
self.vel += self.acc
pygame.draw.circle(mainscreen, self.colors, [int(particles[i].pos[0]), int(particles[i].pos[1])], self.size, 0)
class Launcher:
def __init__(self, x):
self.width = 10
self.height = 23
self.ypos = winHeight - self.height
self.xpos = x
def drawLauncher(self):
pygame.draw.rect(mainscreen, white, (self.xpos, self.ypos, self.width, self.height))
def addParticle(self):
particles.append(Particle(self.xpos + self.width/2, self.ypos))
while True :
for i in range(0, len(launchers)):
launchers[i].drawLauncher()
launchers[i].addParticle()
# threading.Timer(1, launchers[i].addparticle()).start()
# I tried that thinking it could work to at least slow down the rate of fire, it didn't
for i in range(0, len(particles)):
particles[i].renderParticle()
I use the mouse to add new launchers to the array and the while loop to render everything. Like I said, I would like to find a way to control the rate at which my Launcher spit out those particles, while the program is still running (so sleep() can't work)
Upvotes: 1
Views: 346
Reputation: 8853
The PyGame time
module contains what you'll need. get_ticks()
will tell you how many milliseconds into your code you are. By keeping track of it's value the last time particles were spawned, you can control the release frequency. Something like:
particle_release_milliseconds = 20 #50 times a second
last_release_time = pygame.time.get_ticks()
...
current_time = pygame.time.get_ticks()
if current_time - last_release_time > particle_release_milliseconds:
release_particles()
last_release_time = current_time
Upvotes: 1