I'm using pymunk and I'm trying to create a "container" for the other objects. I'm generating a circle shape which I'm adding to the space using add_static. When I create smaller circles inside this circle they accelerate left or right (their x position is randomly generated) until they reach the edge of the static circle. Then they drop vertically down.
The code I'm using:
Code: Select all
import sys, random
import pygame
from pygame.locals import *
from pygame.color import *
import pymunk as pm
def add_ball(space):
mass = 1
radius = 14
inertia = pm.moment_for_circle(mass, 0, radius, (0, 0))
body = pm.Body(mass, inertia)
x = random.randint(250, 350)
body.position = x, 300
shape = pm.Circle(body, radius, (0, 0))
space.add(body, shape)
return shape
def draw_ball(screen, ball):
p = int(ball.body.position.x), 600 - int(ball.body.position.y)
pygame.draw.circle(screen, THECOLORS['blue'], p, int(ball.radius), 2)
def main():
pygame.init()
screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
running = True
pm.init_pymunk()
space = pm.Space()
space.gravity = (0.0, -900.0)
balls = []
ticks_to_next_ball = 10
#static ball
mass = pm.inf
radius = 300
inertia = pm.inf
body = pm.Body(mass, inertia)
body.position = 300, 300
shape = pm.Circle(body, radius, (0, 0))
space.add_static(shape)
balls.append(shape)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN and event.key == K_ESCAPE:
running = False
ticks_to_next_ball -= 1
if ticks_to_next_ball <=0:
ticks_to_next_ball = 25
ball_shape = add_ball(space)
balls.append(ball_shape)
screen.fill(THECOLORS['white'])
x = 0
for ball in balls:
x += 1
if ball.body.position.y < 0:
space.remove(ball)
balls.remove(ball)
else:
draw_ball(screen, ball)
print x
space.step(1/50.0)
pygame.draw.circle(screen, THECOLORS['black'], (450, 450), 2)
pygame.display.flip()
clock.tick(50)
if __name__== '__main__':
sys.exit(main())