Beispiel #1
0
    def __init__(self, world, position, width=1.6, length=4.0, tire_width=.25, tire_length=.8, skidmarks=None, body_density=1.0):
        mass = width * length * body_density
        inertia = moment_for_box(mass, width, length)
        self.world = world
        body = Body(mass, inertia, )
        body.position = position
        shape = Poly.create_box(body, size=(width, length))
        super(Car, self).__init__(world, body, shape)

        slot_density = .01
        slot_radius = .1
        slot_mass = slot_density * (slot_radius ** 2) * pi
        slot_inertia = moment_for_circle(slot_mass, 0.0, slot_radius)
        #self.slot = Body(slot_mass, slot_inertia)


        flpos = position[0] - width / 2.0 - tire_width * 2, position[1] + length / 2.0
        self.front_left = Tire(self, flpos, tire_width, tire_length, skidmarks=skidmarks, powered=False, density=body_density)


        frpos = position[0] + width / 2.0 + tire_width * 2, position[1] + length / 2.0
        self.front_right = Tire(self, frpos, tire_width, tire_length, skidmarks=skidmarks, powered=False, density=body_density)
        
        rlpos = position[0] - width / 2.0 - tire_width * 2, position[1] - length / 2.0
        self.rear_left = Tire(self, rlpos, tire_width * 1.5, tire_length, steerable=False, skidmarks=skidmarks, density=body_density)

        rrpos = position[0] + width / 2.0 + tire_width * 2, position[1] - length / 2.0
        self.rear_right = Tire(self, rrpos, tire_width * 1.5, tire_length, steerable=False, skidmarks=skidmarks, density=body_density)
        self.tires = [self.front_left, self.front_right, self.rear_left, self.rear_right]
Beispiel #2
0
def generate_stars(space):
    for i in range(0, 5):
        star = Body(mass=0.00000001, moment=1)
        star_shape = Star(star, 5)

        x = random.randrange(400, 1600)
        y = random.randrange(0, 180)
        star.position = (x, y)
        star.velocity_func = zero_gravity

        v = random.randrange(-90, -50)
        star.velocity = (v, 0)
        star_shape.collision_type = 3

        # Setup the collision callback function Cat and Star
        g = space.add_collision_handler(1, 3)
        g.begin = boost

        # Setup the collision callback function Star and Star
        s = space.add_collision_handler(3, 3)
        s.begin = same_elem_collision

        # Setup the collision callback function Star and Pickle
        s = space.add_collision_handler(2, 3)
        s.begin = same_elem_collision

        # Setup the collision callback function Star and Pickle under boost
        pb = space.add_collision_handler(3, 6)
        pb.begin = same_elem_collision

        space.add(star, star_shape)
Beispiel #3
0
    def __init__(self, center, road, side):

        # setup shape
        mass = 90
        radius = 2.5
        inertia = moment_for_circle(mass, 0, radius * 2, (0, 0))
        body = Body(mass, inertia)
        body.position = center
        self.shape = Circle(body, radius * 2, (0, 0))
        self.shape.color = (0, 255, 255)
        self.shape.collision_type = CollisionType.Pedestrian
        self.shape.elasticity = 0.05

        # Walk parameter
        self.lenRange = road.length
        self.widthRange = (road.nLanes + 1) * road.width * 2
        self.side = side

        # Bool flags
        self.dead = False

        # Move parameters
        self.moving = 0
        self.direction = road.direction
        self.normal = road.normal
        self.speed = random.randint(3, 6)

        # Flags for crossing
        self.crossing = False
        self.beginCrossing = False
Beispiel #4
0
    def load(self, obj_info: 'MutableMapping[str, Any]', space: 'pymunk.Space',
             prefixes: 'Sequence[str]' = ()) -> 'ObjectInfo':

        config_content = obj_info.get('Config', {})

        if config_content is None:
            is_static = False
        else:
            is_static = config_content.get('static', False)

        shapes = self.__shape_loader.load(obj_info['Shape'])

        if is_static is True:

            body = Body(body_type=Body.STATIC)

            for shape in shapes:
                shape.body = body

            space.add(shapes)

        else:
            mass = sum(shape.mass for shape in shapes)
            moment = sum(shape.moment for shape in shapes)

            body = Body(mass, moment)

            for shape in shapes:
                shape.body = body

            space.add(body, shapes)

        return ObjectInfo(body, loadImages(obj_info.get('Image', ()),
                                           prefixes=prefixes))
Beispiel #5
0
def generate_pickles(space):
    for i in range(0, 10):
        pickle = Body(mass=1, moment=1)
        pickle_shape = Pickle(pickle, 6)
        pickle_shape.elasticity = 1

        x = random.randrange(260, 800)
        y = random.randrange(0, 180)
        pickle.position = (x, y)
        pickle.velocity_func = zero_gravity

        v = random.randrange(-200, -70)
        pickle.velocity = (v, 0)

        # Set collison type for pickle
        pickle_shape.collision_type = 2

        # Setup the collision callback function Cat and Pickle
        h = space.add_collision_handler(1, 2)
        h.begin = dead

        # Setup the collision callback function Pickle and Pickle
        p = space.add_collision_handler(2, 2)
        p.begin = same_elem_collision

        # Setup the collision callback function Pickle and Pickle under boost
        pb = space.add_collision_handler(2, 6)
        pb.begin = same_elem_collision

        space.add(pickle, pickle_shape)
Beispiel #6
0
    def __init__(self, space, rect, playfield=None):
        super(PlungerAssembly, self).__init__()
        self.chute_counter = 0
        self.rect = Rect(0, 0, 1, 1)

        spring_strength = 100 * plunger_mass
        chute_opening = playfield.position + rect.center - (rect.width / 2. -
                                                            ball_radius * 4, 0)
        plunger_rect = Rect(0, 0, rect.width * .2, ball_radius / 2.)
        anchor0 = chute_opening - playfield.position - (ball_radius * 3., 0)
        anchor1 = anchor0 + (rect.width * .8, 0)
        anchor2 = -plunger_rect.width / 2., 0

        plunger_body = Body(plunger_mass, pymunk.inf)
        plunger_shape = Poly.create_box(plunger_body, plunger_rect.size)
        plunger_shape.layers = 1
        plunger_shape.friction = 0.1
        plunger_shape.elasticity = 1.0
        plunger_shape.collision_type = plunger_type
        plunger_body.position = chute_opening + (plunger_rect.width / 2., 0)

        j0 = GrooveJoint(playfield, plunger_body, anchor0, anchor1, anchor2)
        j1 = DampedSpring(playfield, plunger_body, anchor0, anchor2, 0,
                          spring_strength, 5)

        s0 = Circle(Body(), ball_radius / 2.)
        s0.layers = 1
        s0.sensor = True
        s0.collision_type = sensor0_type
        s0.body.position = chute_opening + (ball_radius * 4., 0.0)

        s1 = Circle(Body(), ball_radius * 3.)
        s1.layers = 1
        s1.sensor = True
        s1.collision_type = sensor1_type
        s1.body.position = chute_opening

        def inc_counter(space, arbiter):
            self.chute_counter += 1
            return True

        def dec_counter(space, arbiter):
            self.chute_counter -= 1

        f = space.add_collision_handler
        f(sensor1_type, plunger_type, begin=inc_counter, separate=dec_counter)

        self.playfield = playfield
        self.plunger_offset = playfield.position - plunger_body.position + (
            ball_radius * 3, 0)
        self.spring = j1
        self.spring_length = rect.width / 2.
        self.spring_strength = spring_strength
        self.plunger_body = plunger_body
        self.ball_chute = Rect(0, 0, ball_radius * 2., ball_radius * 2.)
        self.ball_chute.center = chute_opening
        self._original_image = pygame.Surface(plunger_rect.size)
        self._original_image.fill((192, 255, 255))
        self.shapes = [plunger_shape, s0, s1, j0, j1]
        self.visible = 0
Beispiel #7
0
def loadObject(obj_info: str, space: 'pymunk.Space',
               prefixes: 'Sequence[str]' = ()) \
    -> 'Tuple[Structure, Sequence[QWidget]]':

    config_content = obj_info.get('Config', {})

    if config_content is None:
        is_static = False
    else:
        is_static = config_content.get('static', False)

    shapes = loadShapes(obj_info['Shape'])

    if is_static is True:

        body = Body(body_type=Body.STATIC)

        for shape in shapes:
            shape.body = body

        space.add(shapes)

    else:
        mass = sum(shape.mass for shape in shapes)
        moment = sum(shape.moment for shape in shapes)

        body = Body(mass, moment)

        for shape in shapes:
            shape.body = body

        space.add(body, shapes)

    return ObjectInfo(body,
                      loadImages(obj_info.get('Image', ()), prefixes=prefixes))
Beispiel #8
0
 def add_polygon(self, x, y, *vertices, dynamic=True):
     body = Body(body_type=(Body.STATIC, Body.DYNAMIC)[int(dynamic)])
     body.position = x, y
     poly = Poly(body, vertices)
     poly.density = Environment.DEFAULT_DENSITY
     self.space.add(body, poly)
     self.bodies.append(body)
     return body
Beispiel #9
0
 def add_rect(self, x, y, w, h, dynamic=True):
     body = Body(body_type=(Body.STATIC, Body.DYNAMIC)[int(dynamic)])
     body.position = x, y
     poly = Poly.create_box(body, size=(w, h))
     poly.density = Environment.DEFAULT_DENSITY
     self.space.add(body, poly)
     self.bodies.append(body)
     return body
Beispiel #10
0
 def add_circle(self, x, y, r, dynamic=True):
     body = Body(body_type=(Body.STATIC, Body.DYNAMIC)[int(dynamic)])
     body.position = x, y
     circle = Circle(body, r)
     circle.density = Environment.DEFAULT_DENSITY
     self.space.add(body, circle)
     self.bodies.append(body)
     return body
Beispiel #11
0
 def __init__(self, components=[]):
     Body.__init__(self)
     for c in components:
         c.body = self
     self.components = components
     self.thrusters = filter(lambda c: type(c) == Thruster, self.components)
     self.SASmodules = filter(lambda c: type(c) == SAS, self.components)
     self.angular_velocity_limit = 400000
Beispiel #12
0
    def __init__(self, space, rect, playfield=None):
        super(PlungerAssembly, self).__init__()
        self.chute_counter = 0
        self.rect = pygame.Rect(0, 0, 0, 0)

        spring_strength = 100 * plunger_mass
        chute_opening = playfield.position + rect.center - (rect.width / 2 - ball_radius * 4, 0)
        plunger_rect = pygame.Rect(0, 0, rect.width * .2, ball_radius / 2)
        anchor0 = chute_opening - playfield.position - (ball_radius * 3, 0)
        anchor1 = anchor0 + (rect.width * .8, 0)
        anchor2 = -plunger_rect.width / 2, 0

        plunger_body = Body(plunger_mass, pymunk.inf)
        plunger_shape = Poly.create_box(plunger_body, plunger_rect.size)
        plunger_shape.layers = 1
        plunger_shape.friction = 0
        plunger_shape.elasticity = 1.0
        plunger_shape.collision_type = plunger_type
        plunger_body.position = chute_opening + (plunger_rect.width / 2, 0)

        j0 = GrooveJoint(playfield, plunger_body, anchor0, anchor1, anchor2)
        j1 = DampedSpring(playfield, plunger_body, anchor0, anchor2, 0, spring_strength, 5)

        s0 = Circle(Body(), ball_radius / 2)
        s0.layers = 1
        s0.sensor = True
        s0.collision_type = sensor0_type
        s0.body.position = chute_opening + (ball_radius * 4, 0)

        s1 = Circle(Body(), ball_radius * 3)
        s1.layers = 1
        s1.sensor = True
        s1.collision_type = sensor1_type
        s1.body.position = chute_opening

        def inc_counter(space, arbiter):
            self.chute_counter += 1
            return True

        def dec_counter(space, arbiter):
            self.chute_counter -= 1

        f = space.add_collision_handler
        f(sensor1_type, plunger_type, begin=inc_counter, separate=dec_counter)

        self.playfield = playfield
        self.plunger_offset = playfield.position - plunger_body.position + (ball_radius * 3, 0)
        self.spring = j1
        self.spring_length = rect.width / 2
        self.spring_strength = spring_strength
        self.plunger_body = plunger_body
        self.ball_chute = pygame.Rect(0, 0, ball_radius * 2, ball_radius * 2)
        self.ball_chute.center = chute_opening
        self._original_image = pygame.Surface(plunger_rect.size)
        self._original_image.fill((192, 255, 255))
        self.shapes = [plunger_shape, s0, s1, j0, j1]
        self.visible = 0
Beispiel #13
0
 def __init__(self, x, y, side, dir):
     body = Body(0, 0, Body.STATIC)
     body.position = x, y
     self.side = side
     self.dir = dir
     self.shape = Circle(body, self.radius * 2, (0, 0))
     self.shape.color = (0, 0, 255, 0)
     self.shape.elasticity = 0.95
     self.shape.collision_type = CollisionType.Goalpost
Beispiel #14
0
class Bough(GameRect):

    def __init__(self, branch):
        self.branch = branch
        x, y = branch.tip()
        width = branch.height
        height = width / 4
        GameRect.__init__(self, x, y, width, height)
        self.color = (0, 255, 0)
        self.role = "Bough"
        self.status = None
        #self.image = [image.load("data/art/leaves/leaf1_small_0.png").convert_alpha()]
        self.image = spritesheet.load_strip('leaves-rotating-88.png', 88, colorkey = None)[0]

        # bough collides with ground and woger
        self.layers = LayerType.ITEMS | LayerType.PLAYER
        self.group = GroupType.BOUGH


    def get_verts(self):
        return [
            (- self.width / 2, - self.height / 2), # left top
            (+ self.width / 2, - self.height / 2), # right top
            (               0, + self.height / 2), # bottom
        ]


    def create_body(self):
        verts = self.get_verts()

        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        self.body.position = self.branch.tip()

        self.shape = Poly(self.body, verts)

        # platforms should only collide with other platforms and woger
        self.shape.layers =  self.layers
        self.shape.group = self.group
        self.shape.collision_type = CollisionType.BOUGH
        self.shape.parent = self


    def add_to_space(self, space):
        space.add(self.body)
        space.add(self.shape)
        
        
        self.pivot = PivotJoint(self.body, self.branch.body, self.branch.tip())
        space.add(self.pivot)

    def remove_from_tree(self, space):
        space.remove(self.pivot)

    def destroy(self):
        self.status = "Collided"
        self.body.reset_forces()
Beispiel #15
0
    def _create_poly(self):
        """
        Create the polygon used for ray-casting. (Ultrasonic sensor)
        :return: a Pymunk Poly object.
        """

        body = Body(body_type=Body.STATIC)
        body.position = Vec2d(self.center_x, self.center_y)

        return Poly.create_box(body, (self.width, self.height))
Beispiel #16
0
    def _create_poly(self) -> Circle:
        """
        Create the polygon used for ray-casting. (Ultrasonic sensor)
        :return: a Pymunk Circle object.
        """

        body = Body(body_type=Body.STATIC)
        body.position = Vec2d(self.center_x, self.center_y)

        return Circle(body, self.radius)
Beispiel #17
0
    def __init__(
            self,
            space: Space,
            shape_type: str,
            pos: Tuple[float, float],
            scale: float = 1.,
            mass: float = 1,
            static: bool = False,
            friction: float = 1.,
            color: Tuple[float, float, float] = (1., 1., 1.),
    ):
        self.space = space
        self.shape_type = shape_type
        self.static = static
        self._scale = scale
        self.color = color

        padding = 0.03

        if not static:
            if self.shape_type == "box":
                moment = pymunk.moment_for_box(mass, (self.scale, self.scale))
            elif self.shape_type == "circle":
                moment = pymunk.moment_for_circle(mass, 0, self.scale / 2.)
            else:
                raise ValueError(f"Invalid shape_type '{self.shape_type}'")

            self.mass = mass
            self.body = Body(mass, moment)
            self.body.position = pos
            self._static_position = None
            if self.shape_type == "box":
                self.shape = Poly.create_box(self.body, (1, 1))
            elif self.shape_type == "circle":
                self.shape = Circle(self.body, self.scale / 2. - padding)

        # static
        else:
            self.mass = 0
            self.body = self.space.static_body
            self._static_position = Vec2d(*pos)

            if self.shape_type == "box":
                self.shape = Poly(
                    self.space.static_body,
                    [(pos[0] + p[0] * scale, pos[1] + p[1] * scale)
                     for p in SHAPE_TYPES[self.shape_type]["polygon"]])
                self.shape.get_vertices()
            elif self.shape_type == "circle":
                self.shape = Circle(self.space.static_body,
                                    self.scale / 2. - padding,
                                    offset=pos)

        self.shape.friction = friction
def run_gravity(body_1: pymunk.Body, body_2: pymunk.Body, g):
    """Function that can be called to apply gravitational impulses between two bodies.
    g is the gravitational constant"""
    distance = 2 * math.sqrt((body_1.position[0] - body_2.position[0])**2 +
                             (body_1.position[1] - body_2.position[0])**2)
    force = body_1.mass * body_2.mass / (distance**2) * g
    impulse = Vec2d(force, 0)
    impulse = impulse.rotated((body_1.position - body_2.position).angle)
    if distance >= 5:
        body_1.apply_impulse_at_world_point(impulse.rotated(math.pi),
                                            body_2.position)
        body_2.apply_impulse_at_world_point(impulse, body_2.position)
Beispiel #19
0
 def __init__(self, rect):
     super(Ball, self).__init__()
     radius = rect.width / 2
     body = Body()
     body.position = rect.center
     self.shape = Circle(body, radius)
     self.shape.mass = ball_mass
     self.shape.elasticity = .25
     self.shape.friction = 1
     self.rect = Rect(0, 0, rect.width, rect.width)
     self.original_image = resources.gfx("yarnball.png", convert_alpha=True)
     self.pymunk_shapes = (body, self.shape)
Beispiel #20
0
def generate_cat(space):
    cat = Body(mass=1, moment=1)
    cat_shape = Cat(cat, 15)
    cat_shape.elasticity = 1
    cat.position = (50, 120)
    cat_shape.collision_type = 1

    # Setup the collision callback function Cat and Pickle under boost
    g = space.add_collision_handler(1, 6)
    g.begin = same_elem_collision

    space.add(cat, cat_shape)
Beispiel #21
0
 def check_win(self, container : pymunk.Body) -> bool:
     points = [container.local_to_world((-3,-12)), container.local_to_world((3,-12)), container.local_to_world((3,12)), container.local_to_world((-3,12))]
     won = True
     (dx, dy) = (10, 26) if self.vertical else (26,-10)
     limits = {'x': (min(self.position.x, self.position.x + dx), 
                     max(self.position.x, self.position.x + dx)), 
               'y': (min(self.position.y, self.position.y + dy), 
                     max(self.position.y, self.position.y + dy))}
     for point in points:
         if (point.x < limits['x'][0] or point.x > limits['x'][1]) or (point.y < limits['y'][0] or point.y > limits['y'][1]):
             won = False
     return won;
Beispiel #22
0
class Bough(GameRect):
    def __init__(self, branch):
        self.branch = branch
        x, y = branch.tip()
        width = branch.height
        height = width / 4
        GameRect.__init__(self, x, y, width, height)
        self.color = (0, 255, 0)
        self.role = "Bough"
        self.status = None
        #self.image = [image.load("data/art/leaves/leaf1_small_0.png").convert_alpha()]
        self.image = spritesheet.load_strip('leaves-rotating-88.png',
                                            88,
                                            colorkey=None)[0]

        # bough collides with ground and woger
        self.layers = LayerType.ITEMS | LayerType.PLAYER
        self.group = GroupType.BOUGH

    def get_verts(self):
        return [
            (-self.width / 2, -self.height / 2),  # left top
            (+self.width / 2, -self.height / 2),  # right top
            (0, +self.height / 2),  # bottom
        ]

    def create_body(self):
        verts = self.get_verts()

        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        self.body.position = self.branch.tip()

        self.shape = Poly(self.body, verts)

        # platforms should only collide with other platforms and woger
        self.shape.layers = self.layers
        self.shape.group = self.group
        self.shape.collision_type = CollisionType.BOUGH
        self.shape.parent = self

    def add_to_space(self, space):
        space.add(self.body)
        space.add(self.shape)

        self.pivot = PivotJoint(self.body, self.branch.body, self.branch.tip())
        space.add(self.pivot)

    def remove_from_tree(self, space):
        space.remove(self.pivot)

    def destroy(self):
        self.status = "Collided"
        self.body.reset_forces()
Beispiel #23
0
 def __init__(self, space, rect):
     super(Ball, self).__init__()
     radius = rect.width / 2
     body = Body(ball_mass, moment_for_circle(ball_mass, 0, radius))
     body.position = rect.center
     self.shape = Circle(body, radius)
     self.shape.elasticity = .5
     self.shape.friction = 0
     self.shape.layers = 1
     self.shape.collision_type = ball_type
     self.rect = pygame.Rect(0, 0, rect.width, rect.width)
     image = smoothscale(prepare.GFX.get('ball-bearing'), self.rect.size)
     self._original_image = image.convert_alpha()
Beispiel #24
0
 def __init__(self, space, rect):
     super(Ball, self).__init__()
     radius = rect.width / 2
     body = Body(ball_mass, moment_for_circle(ball_mass, 0, radius))
     body.position = rect.center
     self.shape = Circle(body, radius)
     self.shape.elasticity = .5
     self.shape.friction = 0
     self.shape.layers = 1
     self.shape.collision_type = ball_type
     self.rect = pygame.Rect(0, 0, rect.width, rect.width)
     image = smoothscale(prepare.GFX.get('ball-bearing'), self.rect.size)
     self._original_image = image.convert_alpha()
Beispiel #25
0
    def create_body(self):
        verts = self.get_verts()

        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        self.body.position = self.branch.tip()

        self.shape = Poly(self.body, verts)

        # platforms should only collide with other platforms and woger
        self.shape.layers = self.layers
        self.shape.group = self.group
        self.shape.collision_type = CollisionType.BOUGH
        self.shape.parent = self
Beispiel #26
0
    def __init__(self, center, width, height):

        # Create body
        body = Body(0, 0, Body.STATIC)
        body.position = center
        points = [Vec2d(width,height),Vec2d(-width,height),-Vec2d(width,height),Vec2d(width,-height)]
        self.width = width
        self.height = height
        self.points = [p+center for p in points]
        self.shape = Poly(body,points)
        self.shape.color = (200, 200, 200)
        self.shape.elasticity = 0.05
        self.shape.collision_type = CollisionType.Obstacle
Beispiel #27
0
    def __init__(self):
        self.mass = 1  # 1 kg

        # 0.1 meter radius, converted to pixels for display
        #self.radius = 0.05 * M_TO_PIXELS

        # Bupimo: 0.111 meter radius, converted to pixels for display
        self.radius = 0.111 * M_TO_PIXELS

        # moment of inertia for disk
        rob_I = moment_for_circle(self.mass, 0, self.radius)

        self.body = Body(self.mass, rob_I)
        self.body.position = 0, 0
        self.body.angle = 0
        self.body.velocity = 0, 0
        self.body.angular_velocity = 0

        """
        self.shape = Circle(self.body, self.radius)
        self.shape.color = 127, 0, 255  # a pinkish blue
        self.shape.filter = ShapeFilter(categories = ROBOT_MASK)
        """

        """
        r = self.radius
        p = self.radius / 2.0 # Amount the wedge part pokes out.
        vertices = [(r+p, r),
                    (-r/3, r),
                    (-r, 0),
                    (-r/3, -r),
                    (r/3, -r) ]
        """
        r = self.radius
        d = self.radius * 1.5 # Amount the wedge part pokes out.
        vertices = [(0, -r),
                    (d, 0),
                    (0, r)]
        # Now add the semicircular back part
        n = 3
        angles = [pi/2 + i*(pi/n) for i in range(1, n)]
        for a in angles:
            vertices.append((r*cos(a), r*sin(a)))

        vertices = vertices[::-1]

        self.shape = Poly(self.body, vertices)
        self.shape.color = 127, 0, 255  # a pinkish blue
        self.shape.filter = ShapeFilter(categories = ROBOT_MASK)

        self.command = Twist()
Beispiel #28
0
    def __init__(self):
        self.mass = 1  # 1 kg

        # e-puck: 0.037 meter radius, converted to pixels for display
        #self.radius = 3.7 * CM_TO_PIXELS

        # Bupimo: 9 cm radius, converted to pixels for display
        self.radius = 9 * CM_TO_PIXELS

        self.circular = False;

        if self.circular:
            rob_I = moment_for_circle(self.mass, 0, self.radius)
            self.body = Body(self.mass, rob_I)
            self.shape = Circle(self.body, self.radius)
        else:
            r = self.radius
            d = self.radius * 1.5 # Amount the wedge part pokes out.
            vertices = [(0, -r),
                        (d, 0),
                        (0, r)]
            #vertices = [(0, -r),
            #            (d/4, 0),
            #            (d/2, r)]
            # Now add the semicircular back part
            n = 5
            angles = [pi/2 + i*(pi/n) for i in range(1, n)]
            for a in angles:
                vertices.append((r*cos(a), r*sin(a)))

            rob_I = moment_for_poly(self.mass, vertices)
            self.body = Body(self.mass, rob_I)
            self.shape = Poly(self.body, vertices)

            # EXPERIMENTAL: Add bristles to robot
#            rest_length = 100
#            stiffness = 500
#            damping = 10
#            self.bristle_body = pymunk.DampedSpring(self.body, body, \
#                                  (0,0), (0,0), rest_length, stiffness, damping)
#                self.sim.env.add(self.spring_body)

        self.body.position = 0, 0
        self.body.angle = 0
        self.body.velocity = 0, 0
        self.body.angular_velocity = 0
        self.shape.color = 0, 255, 0
        self.shape.filter = ShapeFilter(categories = ROBOT_MASK)

        self.command = Twist()
Beispiel #29
0
 def __init__(self, space, rect):
     super(Handle, self).__init__()
     color = (192, 192, 220)
     radius = rect.width / 2
     body = Body()
     body.position = rect.center
     shape = Circle(body, radius)
     rect2 = pygame.Rect(0, 0, rect.width, rect.width)
     image = pygame.Surface(rect2.size, pygame.SRCALPHA)
     pygame.draw.circle(image, color, rect2.center, int(radius // 4))
     pygame.draw.line(image, (0, 0, 255), rect2.center, rect2.midtop, 8)
     self.shapes = [shape]
     self.rect = rect
     self._original_image = image
Beispiel #30
0
def create_circle(r=1, x=0, y=0, m=1, bt=Body.DYNAMIC):
    '''
    given radius (r), x-position (x), y-position (y), mass (m), body_type (bt)
    return the (body, shape) tuple for a circle
    '''
    given_bt = bt
    bt = Body.DYNAMIC if given_bt == 'dynamic' else Body.DYNAMIC
    bt = Body.STATIC if given_bt == 'static' else Body.DYNAMIC
    bt = Body.KINEMATIC if given_bt == 'kinematic' else Body.DYNAMIC
    moment = moment_for_circle(mass=m, inner_radius=0, outer_radius=r)
    body = Body(mass=m, moment=moment, body_type=bt)
    shape = Circle(body=body, radius=r)
    body.position = (x, y)
    return body, shape
Beispiel #31
0
 def __init__(self, world, x=0, y=0):
     self.movable = Movable()
     self.spriteobject = SpriteObject(
         world.get_texture("player"), x, y, batch="player"
     )
     self.directionalsprite = DirectionalSprite(world, "player")
     phys_body = Body(5, inf)
     phys_body.position = x, y
     shape = Circle(phys_body, 8, (8, 8))
     self.physicsbody = PhysicsBody(shape)
     world.phys_space.add(self.physicsbody.body, self.physicsbody.shape)
     self.groundingobject = GroundingObject()
     self.jumpobject = JumpObject()
     self.inputobject = InputObject("kb")
Beispiel #32
0
 def __init__(self, space, rect):
     super(Handle, self).__init__()
     color = (192, 192, 220)
     radius = rect.width / 2
     body = Body()
     body.position = rect.center
     shape = Circle(body, radius)
     rect2 = pygame.Rect(0, 0, rect.width, rect.width)
     image = pygame.Surface(rect2.size, pygame.SRCALPHA)
     pygame.draw.circle(image, color, rect2.center, int(radius//4))
     pygame.draw.line(image, (0, 0, 255), rect2.center, rect2.midtop, 8)
     self.shapes = [shape]
     self.rect = rect
     self._original_image = image
Beispiel #33
0
class Explosion(PhysicsEntity):

  radius = 20
  size = Vec2d(radius, 0) # size.x is our radius
  explosionImpact = 3000

  lifeSpan = 0.2 # in seconds

  def __init__(self, level, pos, player):
    self.level = level
    self.pos = Vec2d(pos)
    self.player = player
    self.startTime = game.engine.levelTime
    self.hasCollided = False


    self.body = Body(self.mass, self.moment)
    self.body.position = Vec2d(pos)
    self.body.apply_force(-self.mass*self.level.space.gravity) # make it not be affected by gravity
    self.shape = Circle(self.body, self.radius)
    self.shape.layers = self.collisionLayers
    self.shape.collision_type = self.collisionType
    self.shape.sensor = True
    self.shapes = [self.shape]

  def update(self, dt):
    lifeRatio = (game.engine.levelTime - self.startTime) / self.lifeSpan
    self.size = lifeRatio * Explosion.size
    if lifeRatio > 1:
      game.engine.removeEntity(self)  # Suicide D:


  def onPlayerCollide(self, player):
    if self.hasCollided: return
    self.hasCollided = True
    toPlayer = self.player.body.position - self.pos # the vector from our center to the player
    if toPlayer == Vec2d(0,0): # when in doubt, go upwards
      toPlayer = Vec2d(0,1)
    impulse = toPlayer.normalized() * self.explosionImpact # TODO: falloff curve
    self.player.body.apply_impulse(impulse)

  def draw(self):
    r = self.size.x
    gl.glColor3f(1.0, .7, 0.0)
    with shiftView(self.body.position):
      gl.glBegin(gl.GL_LINE_LOOP)
      for angle in xrange(0, 360, 360/12):
        gl.glVertex2f(*self.size.rotated_degrees(angle))
      gl.glEnd()
Beispiel #34
0
 def __init__(self, world, x=0, y=0):
     self.movable = Movable()
     self.spriteobject = SpriteObject(world.get_texture("player"),
                                      x,
                                      y,
                                      batch="player")
     self.directionalsprite = DirectionalSprite(world, "player")
     phys_body = Body(5, inf)
     phys_body.position = x, y
     shape = Circle(phys_body, 8, (8, 8))
     self.physicsbody = PhysicsBody(shape)
     world.phys_space.add(self.physicsbody.body, self.physicsbody.shape)
     self.groundingobject = GroundingObject()
     self.jumpobject = JumpObject()
     self.inputobject = InputObject("kb")
Beispiel #35
0
    def add_body(self, body: pymunk.Body):
        body.id = self.__body_count
        self.__body_count = self.__body_count + 1

        self.__space.add(body)
        for shape in body.shapes:
            self.add_shape(shape)
Beispiel #36
0
def init_space():
    sp = Space()

    player = Body(mass=1, moment=1)
    shape = Circle(player, 10)
    player.position = (20, 90)
    player.velocity = (5, 0)
    shape.color = pyxel.COLOR_YELLOW

    line = Body(body_type=Body.STATIC)
    line_shape = Segment(line, (0, 1), (240, 1), 2)
    line_shape.color = pyxel.COLOR_RED

    sp.add(player, shape, line, line_shape)
    sp.player = player
    return sp
Beispiel #37
0
    def __init__(self, mask):
        self.body = Body(0, 0, Body.STATIC)
        self.body.position = 0, 0
        self.body.angle = 0
        self.body.velocity = 0, 0
        self.body.angular_velocity = 0

        #self.radius = 9 * CM_TO_PIXELS
        self.radius = 6 * CM_TO_PIXELS

        self.shape = Circle(self.body, self.radius)

        self.mask = mask
        self.shape.filter = ShapeFilter(mask=ShapeFilter.ALL_MASKS ^
                                        (ANY_PUCK_MASK | ROBOT_MASK),
                                        categories=mask)
        if mask == ARC_LANDMARK_MASK:
            self.shape.color = 255, 0, 255
        elif mask == ENTER_ARC_LANDMARK_MASK:
            self.shape.color = 0, 255, 0
        elif mask == EXIT_ARC_LANDMARK_MASK:
            self.shape.color = 255, 0, 0
        elif mask == POLE_LANDMARK_MASK:
            self.shape.color = 0, 0, 255
        elif mask == BLAST_LANDMARK_MASK:
            self.shape.color = 255, 255, 255
        else:
            sys.exit("Unknown landmark mask: " + str(mask))
Beispiel #38
0
 def __init__(self, space, rect, playfield=None):
     super(Spinner, self).__init__()
     r, cy = rect.width / 2, rect.height / 2
     assert (r == cy)
     body = Body(.1, moment_for_circle(.1, 0, r))
     body.position = rect.center
     top = Circle(body, r)
     top.layers = 2
     rect2 = pygame.Rect((-r, -cy), rect.size)
     cross0 = Segment(body, rect2.midleft, rect2.midright, 1)
     cross1 = Segment(body, rect2.midtop, rect2.midbottom, 1)
     j0 = PivotJoint(playfield, body, body.position)
     j1 = SimpleMotor(playfield, body, 0)
     j1.max_force = 200
     self.shapes = [top, cross0, cross1, j0, j1]
     self.rect = pygame.Rect(rect)
     self._original_image = prepare.GFX['pachinko-spinner']
Beispiel #39
0
	def __init__(self, x, y, batch, group, space):
		self.speed = 10
		self.group = PhysicsBodyGroup(group, self)
		self.sprite = sprite.Sprite(centre_image(resource.image("pushing.png")), 0, 0, batch=batch, group=self.group)
		self.body = Body(2, moment_for_circle(2, 5, 14))
		self.body.position = x, y
		self.shape = Circle(self.body, 15)
		self.shape.elasticity = 0
		self.shape.friction = 0.5
		self.old = (0, 0)
		self.target = (x, y)
		space.add(self.body, self.shape)
Beispiel #40
0
    def create_body(self):
        verts = self.get_verts()

        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        self.body.position = self.branch.tip()

        self.shape = Poly(self.body, verts)

        # platforms should only collide with other platforms and woger
        self.shape.layers =  self.layers
        self.shape.group = self.group
        self.shape.collision_type = CollisionType.BOUGH
        self.shape.parent = self
Beispiel #41
0
    def __init__(self, car, position, width=10.0, length=20.0, steerable=True, skidmarks=None, powered=True, density=1.0):
        world = car.world
        self.steerable = steerable
        self.powered = powered
        self.skidding = False

        mass = width * length * density
        inertia = moment_for_box(mass, width, length)
        self.world = world
        body = Body(mass, inertia, )
        body.position = position
        shape= Poly.create_box(body, size=(width, length))
        super(Tire, self).__init__(world, body, shape)
        
        ## self.bodyDef = box2d.b2BodyDef()
        ## self.bodyDef.position = position

        
        ## body = world.CreateBody(self.bodyDef)
        ## super(Tire, self).__init__(world, body)

        ## self.shapeDef = box2d.b2PolygonDef()
        ## self.shapeDef.density = 1
        ## self.shapeDef.SetAsBox(width, length)
        ## self.shap = self.body.CreateShape(self.shapeDef)
        ## self.body.SetMassFromShapes()

        # our joint
        joint = PivotJoint(self.body, car.body, self.position)
        joint.error_bias = pow(1.0 - 0.1, 60.0) * 10
        self.world.add(joint)


        #joint = PinJoint(self.body, car.body)
        #self.world.add(joint)

        self.rot_joint = RotaryLimitJoint(self.body, car.body, 0, 0)
        self.world.add(self.rot_joint)
Beispiel #42
0
class Person(object):
	def __init__(self, x, y, batch, group, space):
		self.speed = 10
		self.group = PhysicsBodyGroup(group, self)
		self.sprite = sprite.Sprite(centre_image(resource.image("pushing.png")), 0, 0, batch=batch, group=self.group)
		self.body = Body(2, moment_for_circle(2, 5, 14))
		self.body.position = x, y
		self.shape = Circle(self.body, 15)
		self.shape.elasticity = 0
		self.shape.friction = 0.5
		self.old = (0, 0)
		self.target = (x, y)
		space.add(self.body, self.shape)

	@classmethod
	def populate(cls, world_size, batch, group, space):
		return[Person(0, 0, batch, group, space) for _ in range(20)]

	def update(self):
		angle = -maths.atan2(*Vector(*self.target)-Vector(*self.body.position))
		self.body.angle = angle
		x, y = self.body.position
		self.body.apply_impulse((20*maths.sin(angle), -20*maths.cos(angle)))
Beispiel #43
0
  def __init__(self, level, pos, player):
    self.level = level
    self.pos = Vec2d(pos)
    self.player = player
    self.startTime = game.engine.levelTime
    self.hasCollided = False


    self.body = Body(self.mass, self.moment)
    self.body.position = Vec2d(pos)
    self.body.apply_force(-self.mass*self.level.space.gravity) # make it not be affected by gravity
    self.shape = Circle(self.body, self.radius)
    self.shape.layers = self.collisionLayers
    self.shape.collision_type = self.collisionType
    self.shape.sensor = True
    self.shapes = [self.shape]
Beispiel #44
0
	def load(self):
		self.world_size = Size(3000, 3000)

		self.camera = Camera(self.size, self.world_size, 1000, 10)

		self._tool = None
		self.tool = None

		self.batch = graphics.Batch()
		self.background = CameraGroup(graphics.OrderedGroup(0), self.camera)
		self.foreground = CameraGroup(graphics.OrderedGroup(1), self.camera)
		self.playerg = CameraGroup(graphics.OrderedGroup(2), self.camera)
		self.world_ui = CameraGroup(graphics.OrderedGroup(3), self.camera)
		self.ui = graphics.OrderedGroup(2)

		self.space = Space()
		self.space.gravity = (0.0, 0.0)
		buffer = 100
		borders = Body()
		borders.position = (0, 0)
		left = Segment(borders, (-buffer, -buffer), (-buffer, self.world_size.height+buffer), buffer)
		bottom = Segment(borders, (-buffer, -buffer), (self.world_size.width+buffer, -buffer), buffer)
		right = Segment(borders, (self.world_size.width+buffer, self.world_size.height+buffer),
			(self.world_size.width+buffer, -buffer), buffer)
		top = Segment(borders, (self.world_size.width+buffer, self.world_size.height+buffer),
			(-buffer, self.world_size.height+buffer), buffer)
		self.space.add_static(left, bottom, right, top)

		self.stars = Stars(self.world_size, self.batch, self.background)

		self.asteroids = Asteroid.populate(50, 100, self.world_size, self.batch, self.foreground, self.space)

		if not self.asteroids:
			print("None of a particular resource on this asteroid belt, that'd be unfair. Trying again.")
			self.end(Main())
			return

		self.home_world = choice([asteroid for asteroid in self.asteroids if asteroid.position.y > self.world_size.height/4*3])
		self.home_world.type = "home"
		self.home_world.populated = True

		x, y = self.home_world.position
		self.camera.move(Vector(x-self.size.width/2, y-self.size.height/2))

		# Let's make stuff a bit more interesting.
		for asteroid in self.asteroids:
			if not asteroid.type == "home":
				asteroid.body.apply_impulse((triangular(-20000, 20000, 0), triangular(-20000, 20000, 0)))

		x, y = self.home_world.position
		self.player = Person(x+150, y+150, self.batch, self.playerg, self.space)
		self.mouse = x+150, y+150

		centre = Vector(self.size.width/2, self.size.height/2)
		image = centre_image(resource.image("logo.png"))
		self.logo = sprite.Sprite(image, centre.x, centre.y, batch=self.batch, group=self.ui)
		self.logo.opacity = 255
		self.fade = True
		self.faded = False

		planet = centre_image(resource.image("planet.png"))
		x = self.world_size.width/2
		y = planet.height/2
		self.planet_sprite = sprite.Sprite(planet, x, y, batch=self.batch, group=self.world_ui)
		self.win_box = BB(x-200, y-200, x+200, y+200)

		#self.tools = sorted([tool(self.space) for tool in Tool.__subclasses__()], key=attrgetter("order"), reverse=True)
		#self.buttons = {tool: Button(30, 30+number*50, tool.image, tool.description, self.use_tool(tool), self.ui, self.batch) for number, tool in enumerate(self.tools)}

		self.constraints = set()
Beispiel #45
0
class Robot(object):
    def __init__(self):
        self.mass = 1  # 1 kg

        # 0.1 meter radius, converted to pixels for display
        #self.radius = 0.05 * M_TO_PIXELS

        # Bupimo: 0.111 meter radius, converted to pixels for display
        self.radius = 0.111 * M_TO_PIXELS

        # moment of inertia for disk
        rob_I = moment_for_circle(self.mass, 0, self.radius)

        self.body = Body(self.mass, rob_I)
        self.body.position = 0, 0
        self.body.angle = 0
        self.body.velocity = 0, 0
        self.body.angular_velocity = 0

        """
        self.shape = Circle(self.body, self.radius)
        self.shape.color = 127, 0, 255  # a pinkish blue
        self.shape.filter = ShapeFilter(categories = ROBOT_MASK)
        """

        """
        r = self.radius
        p = self.radius / 2.0 # Amount the wedge part pokes out.
        vertices = [(r+p, r),
                    (-r/3, r),
                    (-r, 0),
                    (-r/3, -r),
                    (r/3, -r) ]
        """
        r = self.radius
        d = self.radius * 1.5 # Amount the wedge part pokes out.
        vertices = [(0, -r),
                    (d, 0),
                    (0, r)]
        # Now add the semicircular back part
        n = 3
        angles = [pi/2 + i*(pi/n) for i in range(1, n)]
        for a in angles:
            vertices.append((r*cos(a), r*sin(a)))

        vertices = vertices[::-1]

        self.shape = Poly(self.body, vertices)
        self.shape.color = 127, 0, 255  # a pinkish blue
        self.shape.filter = ShapeFilter(categories = ROBOT_MASK)

        self.command = Twist()

    def control_step(self, dt):
        """Execute one control step for robot.

        control_step should be called regularly and at high frequency
        to ensure propper execution.

        :param dt: time since last control step execution
        :type dt: float
        """

        self.body.angular_velocity = self.command.angular

        self.body.apply_impulse_at_local_point((self.command.linear, 0), (0,0))

    def set_command(self, twist):
        """Set robot velocity command.

        :param twist: command to send
        :type twist: roboticsintro.common.Twist
        """
        if twist is None:
            raise ValueError("Command may not be null. Set zero velocities instead.")
        self.command = twist

    def stop(self):
        """Stop robot motion."""
        self.set_command(Twist())

    def get_pose(self):
        return (self.body.position.x,
                self.body.position.y,
                normalize_angle_0_2pi(self.body.angle))