예제 #1
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
예제 #2
0
    def __init__(self, verts, color=(1, 1, 1), draw=True, friction=None):
        self.indexes = earcut(verts)

        if draw:
            size = len(verts) // 2
            self.dl = self.batch.add_indexed(
                size,
                gl.GL_TRIANGLES,
                self.group,
                self.indexes,
                ('v2f/static', np.array(verts) / SPACE_SCALE),
                ('t2f/static', np.array(verts) / (512 * SPACE_SCALE * 2)),
                ('c3f/static', [c for _ in range(size) for c in color]),
            )
        else:
            self.dl = None

        self.shapes = []
        verts = np.array(verts)
        tris = verts.reshape(-1, 2)[self.indexes].reshape(-1, 3, 2)
        for tri in tris:
            shp = Poly(space.static_body, tri)
            shp.friction = friction or self.FRICTION
            shp.elasticity = self.ELASTICITY
            space.add(shp)
            self.shapes.append(shp)
    def __createRectangleShape(self, info: 'Dict[str, Any]',
                               default_elasticity: float = None,
                               default_friction: float = None) \
                                   -> 'pymunk.Shape':

        pos_x = info.get('x')
        pos_y = info.get('y')

        if pos_x is None or pos_y is None:
            raise ValueError('Both \'x\' and \'y\' position of a rectangle '
                             'shape must be provided')

        width = info.get('width')
        height = info.get('height')

        if width is None or height is None:
            raise ValueError('Both \'width\' and \'height\' of a rectangle '
                             'shape must be provided')

        shape = Poly(None, (
            (pos_x, pos_y), (pos_x + width, pos_y),
            (pos_x + width, pos_y + height), (pos_x, pos_y + height)))

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

        return shape
예제 #4
0
def init_space():
    sp = Space()

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

    # Cria margens
    line = Body(body_type=Body.STATIC)
    lines = [
        Segment(line, (-30, -30), (270, -30), 2),
        Segment(line, (-30, 210), (270, 210), 2),
        Segment(line, (-30, -30), (-30, 210), 2),
        Segment(line, (270, -30), (270, 210), 2),
    ]
    for line in lines:
        line.elasticity = 1.0

    # Adiciona elementos ao espaço
    sp.add(player, shape, *lines)
    sp.player = player
    return sp
예제 #5
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
예제 #6
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
예제 #7
0
 def __init__(self, world, x=0, y=0, w=16, h=16):
     x, y = int(x), int(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("ground"),
                                      x,
                                      y,
                                      batch="objects")
예제 #8
0
    def __init__(self, x, y, car, mass=1):
        super().__init__()
        self.position = car.position + (x - 25, y)
        self.wheel = Wheel(-8, -8, self, mass=mass * 0.1, radius=10)
        self.car = car

        self.shape = Poly(self, [(-20, -8), (35, -8), (-10, 20)], radius=2)
        self.shape.visible = True
        self.shape.color = pyxel.COLOR_CYAN
        self.shape.mass = mass
예제 #9
0
def __createPolyShape(info: 'Dict[str, Any]') -> 'Poly':

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

    shape.mass = info['mass']
    shape.elasticity = info.get('elasticity', 0.5)
    shape.friction = info.get('friction', 0.5)

    return shape
예제 #10
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 __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
예제 #12
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
예제 #13
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")
예제 #14
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
예제 #15
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()
예제 #16
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
예제 #17
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()
예제 #18
0
    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))
예제 #19
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
예제 #20
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
예제 #21
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
예제 #22
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
예제 #23
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
예제 #24
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
예제 #25
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]