예제 #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]
예제 #2
0
파일: items.py 프로젝트: mjs/ldnpydojo
class Platform(object):

    def __init__(self, x, y, width=400, height=50):
        self.width = width
        self.height = height

        verts = [
            (- self.width / 2, - self.height / 2),# left top
            (- self.width / 2, + self.height / 2),# left bottom
            (+ self.width / 2, + self.height / 2),# right bottom
            (+ self.width / 2, - self.height / 2),# right top
        ]
        verts = map(Vec2d, verts)
        self.mass = self.width * self.height * 1
        self.body = Body(
            self.mass, moment_for_poly(self.mass, verts))
        self.body.position = (x, y)
        self.start_pos = Vec2d(x, y)
        self.shape = Poly(self.body, verts, (0, 0))


    @property
    def verts(self):
        return self.shape.get_points()        

    @property
    def centre(self):
        verts = self.verts
        return (verts[0] + verts[2]) / 2
예제 #3
0
파일: Entity.py 프로젝트: DomNomNom/Jumpy2D
  def createShape(self, verticies):
    assert len(verticies) >= 2
    
    verticies = self.verticies = map(Vec2d, verticies)
    if is_clockwise(verticies): # fix it if it is clockwise
      average = sum(verticies) / len(verticies)
      verticies.sort(key=lambda v: (average-v).get_angle())

    assert not is_clockwise(verticies), 'OMG, my code is wrong! the poly points are still clockwise'
    assert is_convex(verticies), 'Shape verticies must be convex!'

    if len(verticies) in self.specialPolyTypes:
      self.polyType = self.specialPolyTypes[len(verticies)]
    else:
      self.polyType = pg.GL_POLYGON

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


    # note: collisionLayers and collisionType get created by physics.py
    self.shape.layers = self.collisionLayers
    self.shape.collision_type = self.collisionType
    self.shapes = [self.shape]

    bb = self.shape.cache_bb()
    self.size = Vec2d(bb.right-bb.left, bb.top-bb.bottom)
예제 #4
0
파일: items.py 프로젝트: mjs/ldnpydojo
 def create_body(self):
     verts = map(Vec2d, self.get_verts())
     self.body = Body(self.mass, moment_for_poly(self.mass, verts))
     self.body.position = (self.x, self.y)
     self.shape = Poly(self.body, verts, (0, 0))
     self.shape.layers = self.layers
     # this is so you can get to it from collision handlers.
     #     eg. arbiter.shapes[0].parent 
     self.shape.parent = self
예제 #5
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
예제 #6
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))
예제 #7
0
def init_space():
    sp = Space()
    sp.gravity = (0, 50)

    chain = make_pivot_chain(sp, (0, 0), (240, 30), 30)
    sp.add(constraint.PivotJoint(chain[0], sp.static_body, chain[0].position))

    # Cria quadrado
    L = 25
    player = Body(mass=1, moment=100)
    shape = Poly(player, [(-L, -L), (L, -L), (L, L), (-L, L)])
    player.position = (90, 60)
    player.velocity = (-25, 25)
    shape.elasticity = 1.0
    shape.color = pyxel.COLOR_RED
    shape.collision_type = 42

    ball = Body(mass=1, moment=200)
    ball_shape = Circle(ball, 20)
    ball.position = (player.position.x, 130)
    ball_shape.elasticity = 1.0
    shape.color = pyxel.COLOR_NAVY
    ball_shape.collision_type = 42

    joint1 = constraint.DampedSpring(player, ball, (0, 0), (20, 0), 20, 3, 0.5)
    joint2 = constraint.PivotJoint(sp.static_body, player, (65, 35))
    joint1.collide_bodies = False
    sp.add(joint1, joint2)

    body2 = Body(1, 100)
    sp.add(body2)
    sp.add(Poly(body2, [(-3, 3), (3, 3), (3, -3), (-3, -3)]))
    body2.position = 220, 50
    sp.add(constraint.DampedRotarySpring(body2, ball, 0, 2, 1))
    sp.body2 = body2

    # Cria margens
    line = Body(body_type=Body.STATIC)
    e = 0
    lines = [
        Segment(line, (-e, -e), (240 + e, -e), 2),
        Segment(line, (-e, 180 + e), (240 + e, 180 + e), 2),
        Segment(line, (-e, -e), (-e, 180 + e), 2),
        Segment(line, (240 + e, -e), (240 + e, 180 + e), 2),
    ]
    for line in lines:
        line.elasticity = 1.0
    lines = []

    # Adiciona elementos ao espaço
    sp.add(player, shape, ball, ball_shape, *lines)
    sp.player = player

    #handler = sp.add_collision_handler(42, 42)
    #handler.begin = lambda *args: False
    return sp
    def __createPolyShape(self, info: 'Dict[str, Any]',
                          default_elasticity: float = None,
                          default_friction: float = None) -> 'pymunk.Shape':

        points = tuple((point.get('x', 0), point.get('y', 0))
                       for point in info['Point'])
        shape = Poly(None, points)

        self.__setGeneralProperties(shape, info,
                                    default_elasticity=default_elasticity,
                                    default_friction=default_friction)

        return shape
예제 #9
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
예제 #10
0
파일: items.py 프로젝트: mjs/ldnpydojo
    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
예제 #11
0
 def __init__(self, world, x=0, y=0, w=16, h=16, sprite="block"):
     # x, y = int(x), int(y)
     x, y = int(x - w / 2), int(y - h / 2)
     # print(x, y)
     shape = Poly(world.phys_space.static_body,
                  world.shapes.rect(w, h, x=x, y=y))
     super().__init__(world, shape, x=x, y=y)
     self.spriteobject = SpriteObject(world.get_texture(sprite),
                                      x,
                                      y,
                                      w=w,
                                      h=h,
                                      batch="objects")
예제 #12
0
파일: robot.py 프로젝트: gavincangan/alvin
    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()
예제 #13
0
    def poly(self, vertices, *, radius=0, **kwargs):
        """
        Creates polygon from the given list of vertices.
        """
        cm = center_of_mass(vertices)
        vertices = [v - cm for v in vertices]

        body = self._make_body(**kwargs)
        shape = Poly(body, vertices, radius=radius)
        shape = self._make_shape(shape, **kwargs)

        body.position = cm
        self.space.add(body, shape)
        return body
예제 #14
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()
예제 #15
0
def create_triangle(p1=(0, 0),
                    p2=(1, 0),
                    p3=(.5, .866),
                    x=0,
                    y=0,
                    m=1,
                    scalar=1,
                    bt=Body.DYNAMIC):
    '''
    given points (p1..p3), mass (m), x-position (x), y-position (y),
          scalar <to augment default equilateral triangle>, body_type (bt),
    The default values for p1,p2,p3 make an approx. equilateral triangle.
    return (body, shape) tuple for a triangle
    '''
    vertices = (p1, p2, p3)  # equilateral
    vertices = tuple((v[0] * scalar, v[1] * scalar) for v in vertices)
    shape = Poly(body=None, vertices=vertices)  # will set body later
    vertices = shape.get_vertices()  # because Vec2d of vertices is needed
    moment = moment_for_poly(mass=m, vertices=vertices)
    body = Body(mass=m, moment=moment)
    body.position = (x, y)
    shape.body = body  # set body here because init None above
    return body, shape
예제 #16
0
def create_pentagon(p1=(0, 0),
                    p2=(2, 0),
                    p3=(3, 2),
                    p4=(1, 4),
                    p5=(-1, 2),
                    x=0,
                    y=0,
                    m=1,
                    scalar=1,
                    bt=Body.DYNAMIC):
    '''
    given points (p1..p5), mass (m), x-position (x), y-position (y),
          scalar <to augment default points>, body_type (bt),
    return (body, shape) tuple for a pentagon
    '''
    vertices = (p1, p2, p3, p4, p5)
    vertices = tuple((v[0] * scalar, v[1] * scalar) for v in vertices)
    shape = Poly(body=None, vertices=vertices)  # will set body later
    vertices = shape.get_vertices()  # because Vec2d of vertices is needed
    moment = moment_for_poly(mass=m, vertices=vertices)
    body = Body(mass=m, moment=moment)
    body.position = (x, y)
    shape.body = body  # set body here because init None above
    return body, shape
예제 #17
0
def init_space():
    sp = Space()

    h = 20 * sqrt(2)
    player = Body(mass=1, moment=400)
    shape = Poly(player, [(-20, -h / 3), (20, -h / 3), (0, 2 / 3 * h)])
    player.position = (90, 90)
    shape.elasticity = 1.0
    shape.color = pyxel.COLOR_YELLOW

    line = Body(body_type=Body.STATIC)
    lines = [
        Segment(line, (0, 1), (240, 1), 2),
        Segment(line, (0, 179), (240, 179), 2),
        Segment(line, (1, 0), (1, 180), 2),
        Segment(line, (239, 0), (239, 180), 2),
    ]
    for line in lines:
        line.elasticity = 1.0
        line.color = pyxel.COLOR_PEACH

    sp.add(player, shape, *lines)
    sp.player = player
    return sp
예제 #18
0
파일: items.py 프로젝트: mjs/ldnpydojo
class GameRect(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.mass = self.width * self.height / 10000
        self.layers = LayerType.EVERYTHING # collide with everything
        self.status = None


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


    def create_body(self):
        verts = map(Vec2d, self.get_verts())
        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        self.body.position = (self.x, self.y)
        self.shape = Poly(self.body, verts, (0, 0))
        self.shape.layers = self.layers
        # this is so you can get to it from collision handlers.
        #     eg. arbiter.shapes[0].parent 
        self.shape.parent = self


    def update(self):
        pass


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

    def remove_from_space(self, space):
        space.remove(self.body)
        space.remove(self.shape)

    @property
    def verts(self):
        "This is the position of the item's verts as calculated by pymunk"
        return self.shape.get_points()        
예제 #19
0
파일: items.py 프로젝트: mjs/ldnpydojo
    def __init__(self, x, y, width=400, height=50):
        self.width = width
        self.height = height

        verts = [
            (- self.width / 2, - self.height / 2),# left top
            (- self.width / 2, + self.height / 2),# left bottom
            (+ self.width / 2, + self.height / 2),# right bottom
            (+ self.width / 2, - self.height / 2),# right top
        ]
        verts = map(Vec2d, verts)
        self.mass = self.width * self.height * 1
        self.body = Body(
            self.mass, moment_for_poly(self.mass, verts))
        self.body.position = (x, y)
        self.start_pos = Vec2d(x, y)
        self.shape = Poly(self.body, verts, (0, 0))
예제 #20
0
파일: Entity.py 프로젝트: DomNomNom/Jumpy2D
class PhysicsEntity(GameEntity):

  # PLEASE NOTE: every PhysicsEntity should be listed in
  #              game/physics.py ==> physicsEntities

  groups = {'all', 'updating', 'game', 'physics'}

  mass = 10.
  moment = 30. # pymunk.moment_for_poly(mass, verticies)
  level = None # The level that contains the physics Space
  
  # this is for the following funciton
  specialPolyTypes = {
    2 : gl.GL_LINES,
    3 : gl.GL_TRIANGLES,
    4 : gl.GL_QUADS,
  }

  # creates a shape for the Entities physics body with the given verticies
  def createShape(self, verticies):
    assert len(verticies) >= 2
    
    verticies = self.verticies = map(Vec2d, verticies)
    if is_clockwise(verticies): # fix it if it is clockwise
      average = sum(verticies) / len(verticies)
      verticies.sort(key=lambda v: (average-v).get_angle())

    assert not is_clockwise(verticies), 'OMG, my code is wrong! the poly points are still clockwise'
    assert is_convex(verticies), 'Shape verticies must be convex!'

    if len(verticies) in self.specialPolyTypes:
      self.polyType = self.specialPolyTypes[len(verticies)]
    else:
      self.polyType = pg.GL_POLYGON

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


    # note: collisionLayers and collisionType get created by physics.py
    self.shape.layers = self.collisionLayers
    self.shape.collision_type = self.collisionType
    self.shapes = [self.shape]

    bb = self.shape.cache_bb()
    self.size = Vec2d(bb.right-bb.left, bb.top-bb.bottom)
예제 #21
0
파일: items.py 프로젝트: mjs/ldnpydojo
    def create_body(self):
        verts = self.get_verts()

        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        root = Vec2d(0, 0)
        if isinstance(self.parent, Branch):
            root = self.parent.tip()
        self.body.position = root - self.tail(verts)

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

        # branch should not collide with other branches, which will
        # overlap slightly at the joints
        self.shape.group = GroupType.BRANCH

        # branches should collide only with ground
        self.shape.layers = LayerType.BACKGROUND
        self.collision_type = CollisionType.BRANCH
예제 #22
0
def create_rect(w=1, h=1, scalar=1, m=1, x=0, y=0, bt=Body.DYNAMIC):
    '''
    given the width (w), height (h), mass (m), x-position (x), y-position (y),
        scalar <to augment default square>, and the body_type (bt).
    returns a `rigid body` which is a shapeless object that
    has physical properties (mass, position, rotation, velocity, etc)
    ALSO returns a Poly which is the Shape that really gets drawn
    '''
    poly_size = (w * scalar, h * scalar)
    poly = Poly.create_box(body=None, size=poly_size)
    # moment depends on mass and size.
    # bigger poly >> bigger moment.
    # more massive >> bigger moment
    moment_of_inertia = moment_for_poly(m, poly.get_vertices())
    body = Body(mass=m, moment=moment_of_inertia, body_type=bt)
    body.position = (x, y)
    poly.body = body
    return body, poly
예제 #23
0
파일: items.py 프로젝트: mjs/ldnpydojo
class GameRect(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.mass = self.width * self.height / 10000
        self.layers = LayerType.EVERYTHING  # collide with everything
        self.status = None

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

    def create_body(self):
        verts = map(Vec2d, self.get_verts())
        self.body = Body(self.mass, moment_for_poly(self.mass, verts))
        self.body.position = (self.x, self.y)
        self.shape = Poly(self.body, verts, (0, 0))
        self.shape.layers = self.layers
        # this is so you can get to it from collision handlers.
        #     eg. arbiter.shapes[0].parent
        self.shape.parent = self

    def update(self):
        pass

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

    def remove_from_space(self, space):
        space.remove(self.body)
        space.remove(self.shape)

    @property
    def verts(self):
        "This is the position of the item's verts as calculated by pymunk"
        return self.shape.get_points()
예제 #24
0
def init_space():
    sp = Space()
    sp.gravity = (0, 50)
    sp.damping = 1.0

    floor = Body(body_type=Body.STATIC)
    stick = Body(mass=100, moment=100 * 50**2)
    L = 20
    shapes = [
        Poly(stick, [(-L, -L), (L, -L), (L, L), (0, L + L / 2), (-L, L)],
             radius=3),
        Segment(floor, (1, 179), (239, 179), 1),
        Segment(floor, (1, 1), (239, 1), 1),
        Segment(floor, (1, 1), (1, 179), 1),
        Segment(floor, (239, 1), (239, 179), 1),
    ]
    stick.position = (120, L)

    bodies = []
    for _ in range(L):
        r = random.uniform(2, 6)
        mass = pi * r**2
        body = Body(mass=mass, moment=mass * r**2 / 2)
        circle = Circle(body, r)

        x = random.uniform(r, 240 - r)
        y = random.uniform(r, 180 - r)
        body.position = (x, y)

        vx = random.uniform(-L, L)
        vy = random.uniform(-L, L)
        body.velocity = (vx, vy)

        bodies.append(body)
        shapes.append(circle)
        circle.color = random.randint(1, 15)

    for shape in shapes:
        shape.elasticity = 1.0

    sp.add(floor, stick, *bodies, *shapes)
    return sp
예제 #25
0
 def __init__(self, space, rect, playfield=None, win=False, returns=False):
     super(Pocket, self).__init__()
     color = (220, 100, 0)
     inside = rect.inflate(-10, -10)
     cover = Poly.create_box(playfield, inside.size, rect.center)
     self.shapes = [cover]
     if win:
         self.shapes.extend((
             Segment(playfield, rect.topleft, rect.bottomleft, 1),
             Segment(playfield, rect.bottomleft, rect.bottomright, 1),
             Segment(playfield, rect.bottomright, rect.topright, 1)))
     self._original_image = pygame.Surface(rect.size, pygame.SRCALPHA)
     pygame.draw.rect(self._original_image, color, rect)
     self.rect = pygame.Rect(rect)
     if win:
         self.shape.collision_type = pocket_win_type
     elif returns:
         self.shape.collision_type = pocket_return_type
     else:
         self.shape.collision_type = pocket_fail_type
예제 #26
0
 def __init__(self, space, rect, playfield=None, win=False, returns=False):
     super(Pocket, self).__init__()
     color = (220, 100, 0)
     inside = rect.inflate(-10, -10)
     cover = Poly.create_box(playfield, inside.size, rect.center)
     self.shapes = [cover]
     if win:
         self.shapes.extend(
             (Segment(playfield, rect.topleft, rect.bottomleft, 1),
              Segment(playfield, rect.bottomleft, rect.bottomright, 1),
              Segment(playfield, rect.bottomright, rect.topright, 1)))
     self._original_image = pygame.Surface(rect.size, pygame.SRCALPHA)
     pygame.draw.rect(self._original_image, color, rect)
     self.rect = pygame.Rect(rect)
     if win:
         self.shape.collision_type = pocket_win_type
     elif returns:
         self.shape.collision_type = pocket_return_type
     else:
         self.shape.collision_type = pocket_fail_type
예제 #27
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)
예제 #28
0
    def __init__(self,center,angle,type,team,goal):

        # Params based on vehicle type
        self.width = self.widths[type]
        self.height = self.lengths[type]
        mass = self.masses[type]
        self.points = [Vec2d(self.height,self. width), Vec2d(-self.height, self.width),
                       -Vec2d(self.height, self.width), Vec2d(self.height, -self.width)]
        inertia = moment_for_poly(mass,self.points)

        # Basic params
        self.type = type
        self.team = team
        self.goal = goal

        # Flags
        self.finished = False
        self.crashed = False

        # Direction
        self.direction = Vec2d(1,0)
        self.direction.rotate(angle)

        # Position
        self.position = LanePosition.OffRoad

        # For reward
        self.prevPos = center

        # Create body
        body = Body(mass, inertia, Body.DYNAMIC)
        body.position = center
        body.angle = angle
        body.velocity_func = friction_car
        self.shape = Poly(body, self.points)
        self.shape.color = (0, 255, 0)
        self.shape.elasticity = 0.05
        self.shape.collision_type = CollisionType.Car
예제 #29
0
    def __init__(self,
                 arm_anchor_points,
                 arm_segment_lengths,
                 target_position,
                 target_rotation=0,
                 do_render=False,
                 sparse=True,
                 object_size=OBJECT_SIZE):
        super().__init__(do_render, sparse, MAX_MOTOR_FORCE)
        self.target_size = TARGET_SIZE
        self.target_position = target_position
        self.target_rotation = target_rotation
        self.space.gravity = (0.0, -900.0)

        floor = pymunk.Segment(self.space.static_body,
                               (int(-5 * ENV_SIZE), int(0.17 * ENV_SIZE)),
                               (int(5 * ENV_SIZE), int(0.17 * ENV_SIZE)),
                               0.017 * ENV_SIZE)
        floor.elasticity = 0.1
        floor.friction = 0.5
        floor.collision_type = NO_COLLISION_TYPE
        self.space.add(floor)

        for i, anchor_point in enumerate(arm_anchor_points):
            self.add_arm(arm_segment_lengths[i], anchor_point)

        self.object_size = (object_size, object_size)
        object_mass = TARGET_MASS
        object_moment = pymunk.moment_for_box(object_mass, self.object_size)
        self.object_body = Body(object_mass, object_moment)
        self.object_body.position = ENV_SIZE / 2, object_size / 2 + int(
            0.187 * ENV_SIZE)
        self.object_shape = Poly.create_box(self.object_body, self.object_size)
        self.object_shape.elasticity = 0.1
        self.object_shape.friction = 1.0
        self.space.add(self.object_body, self.object_shape)
예제 #30
0
    def __init__(self, x, y, mass=1):
        super().__init__()

        self.position = (x, y)
        self.motors = []

        self.shape = Poly(self, [(-30, -5), (+40, -5), (+30, +5), (-30, +10)],
                          radius=2)
        self.shape.mass = mass
        self.shape.visible = True
        self.shape.color = pyxel.COLOR_RED

        self.front_wheel = Wheel(+25, -6, self, mass=1 / 10)
        self.back_wheel = Wheel(-20, -6, self, mass=1 / 10, radius=12)
        self.motor_wheel = self.back_wheel

        ref = self
        self.carts = []
        for _ in range(1):
            ref = cart = Cart(-50, 10, ref)
            self.carts.append(cart)

        self.gear = 1
        self.gear_ratios = [-1, 1, 2, 3, 5, 7]
예제 #31
0
파일: physics.py 프로젝트: tartley/pyong
 def create_shape(self):
     shape = Poly(self.body, self.item.geometry.verts, (0, 0))
     shape.elasticity = 1.0
     shape.friction = 0.0
     return shape
예제 #32
0
파일: loop.py 프로젝트: tartley/sole-scion
 def get_shape(self, body):
     shape = Poly(body, self.verts, (0, 0))
     shape.elasticity = 0.5
     shape.friction = 10.0
     return shape
예제 #33
0
 def draw_shape_polygon(self,
                        body: pymunk.Body,
                        poly: pymunk.Poly,
                        color,
                        filled: bool = False) -> None:
     self.draw_polygon_on_body(body, color, filled, poly.get_vertices())