def __init__(self, x, y, radius=15): self.sprite = scene.layers[0].add_sprite( 'steel', scale=radius / 32, ) self.refl = scene.layers[1].add_sprite('lens_fresnel', scale=radius / 100, color=(1, 1, 1, 0.5)) self.velocity = v2(0, 0) self.radius = radius self.mass = radius * radius dr = v2(radius, radius) self.rect = Rect(0, 0, *(dr * 2)) self.pos = v2(x, y)
def apply_impact(a, b): """Resolve the collision between two balls. Calculate their closing momentum and apply a fraction of it back as impulse to both objects. """ ab = b.pos - a.pos try: ab.normalize_ip() except ValueError: ab = v2(1, 0) rel_momentum = ab.dot(a.velocity) * a.mass - ab.dot(b.velocity) * b.mass if rel_momentum < 0: return rel_momentum *= ELASTICITY a.velocity -= ab * rel_momentum / a.mass b.velocity += ab * rel_momentum / b.mass
def separate(a, b, frac=0.5): """Move a and b apart. Return True if they are now separate. """ ab = a.pos - b.pos sep = ab.length() overlap = a.radius + b.radius - sep if overlap <= 0: return if sep == 0.0: ab = v2(1, 0) else: ab /= sep masses = a.mass + b.mass if overlap > 1: overlap *= frac a.pos += ab * (overlap * b.mass / masses) b.pos -= ab * (overlap * a.mass / masses)
rect = pg.Rect(0, 0, 0, 0) def __init__(self): super().__init__() self.image = pg.Surface((50, 50)) self.image.set_colorkey((0, 0, 0)) self.image.fill((0, 0, 255)) self.rect = self.image.get_rect() self.rect.topleft = (350, 300) self.mask = pg.mask.from_surface(self.image) player = Player() loop = True acceleration = v2(0, 1) velocity = v2(0, 0) vx, vy = 5, 5 double = True while loop: keyboard = pg.key.get_pressed() for event in pg.event.get(): if event.type == pg.QUIT: loop = False elif event.type == pg.KEYDOWN: if event.key == pg.K_w and (player.rect.bottom == HEIGHT): velocity.y = -20 jump.play() elif event.key == pg.K_w and double: velocity.y = -20 double = False
scene = w2d.Scene(1280, 720) scene.chain = [ w2d.chain.LayerRange(stop=0), w2d.chain.DisplacementMap(displacement=w2d.chain.Layers([1]), paint=w2d.chain.LayerRange(stop=0), scale=-100) ] scene.layers[0].set_effect('dropshadow', offset=(3, 3)) cursor = scene.layers[0].add_sprite('cursor', anchor_x='left', anchor_y='top') scene.layers[-1].add_sprite('wood', anchor_x='left', anchor_y='top') GRAVITY = v2(0, 1) BALL_RADIUS = 15 BALL_COLOR = (34, 128, 75) ELASTICITY = 0.3 SEPARATION_STEPS = [1.0] * 10 BALL_COUNT = 20 class Ball: def __init__(self, x, y, radius=15): self.sprite = scene.layers[0].add_sprite( 'steel', scale=radius / 32, ) self.refl = scene.layers[1].add_sprite('lens_fresnel',