Beispiel #1
0
    def __init__(self):
        self._player_maximum_thrust = 2

        self._physics_world = Box2D.b2World(gravity=(0,0), doSleep=False, contactListener=ContactDamageInflicter(self))

        self._asteroid_shape = Box2D.b2CircleShape()
        self._asteroid_shape.radius = ASTEROID_RADIUS

        self._asteroid_fixture = Box2D.b2FixtureDef()
        self._asteroid_fixture.shape = self._asteroid_shape
        self._asteroid_fixture.density = 10
        self._asteroid_fixture.restitution = 1
        self._asteroid_fixture.friction = 1
        self._asteroid_fixture.filter.categoryBits = CollisionFilterCategory.ASTEROID
        self._asteroid_fixture.filter.maskBits = CollisionFilterCategory.ASTEROID | CollisionFilterCategory.PLAYER 

        self._ship_shape = Box2D.b2CircleShape()
        self._ship_shape.radius = PLAYER_RADIUS

        ship_fixture = Box2D.b2FixtureDef()
        ship_fixture.shape = self._ship_shape
        ship_fixture.density = 5
        ship_fixture.restitution = 1
        ship_fixture.friction = 1
        ship_fixture.filter.categoryBits = CollisionFilterCategory.PLAYER
        ship_fixture.filter.maskBits = CollisionFilterCategory.ASTEROID | CollisionFilterCategory.BORDER

        self._player_base_friction = 0.02
        self._player_thrust_extra_friction = 0.02

        self._player_maximum_turn_thrust = 1
        self._thrust_extra_turn_thrust = -0.3
        self._base_rotational_friction = 0.1
        self._thrust_extra_rotational_friction = 0.05

        ship_body_def = Box2D.b2BodyDef()
        ship_body_def.position = (
            5 + random() * (RIGHT_BORDER_X - 10),
            5 + random() * (TOP_BORDER_Y - 10)
        )
        ship_body_def.angle = random() * pi * 2
        ship_body_def.linearVelocity = (0,0)
        ship_body_def.linearDamping = self._player_base_friction
        ship_body_def.angularVelocity = 0
        ship_body_def.angularDamping = self._base_rotational_friction
        ship_body_def.fixtures = [ship_fixture]
        ship_body_def.type = Box2D.b2_dynamicBody
        ship_body_def.allowSleep = False

        self._player_ship = self._physics_world.CreateBody(ship_body_def)

        self._asteroids = self._create_starting_asteroids()
        self._asteroids_to_kill = []
        self._asteroid_extra_spawn_accumulator = 0
        self._asteroids_avoided_count = 0

        self._borders = borders.add_borders(self._physics_world, LEFT_BORDER_X, RIGHT_BORDER_X, BOTTOM_BORDER_Y, TOP_BORDER_Y)
        self._asteroid_play_space = asteroid_play_space.add_asteroid_play_space(self._physics_world, LEFT_BORDER_X, RIGHT_BORDER_X, BOTTOM_BORDER_Y, TOP_BORDER_Y)

        self.player_current_health = MAX_PLAYER_HEALTH
Beispiel #2
0
    def __init__(self, fisica, pilas, x, y, radio, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False, sensor=False):

        Figura.__init__(self, fisica, pilas)

        if x is None:
            x = pilas.azar(10000, 10000 + 100000)

        if y is None:
            y = pilas.azar(10000, 10000 + 100000)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._radio = utils.convertir_a_metros(radio)
        self._escala = 1

        self.fisica = fisica

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not dinamica:
            densidad = 0

        try:
            fixture = box2d.b2FixtureDef(
                                     shape=box2d.b2CircleShape(radius=self._radio),
                                     density=densidad,
                                     friction=friccion,
                                     restitution=restitucion)
        except TypeError:
            fixture = box2d.b2FixtureDef(
                                     shape=box2d.b2CircleShape(radius=self._radio),
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)


        # Agregamos un identificador para controlarlo posteriormente en las
        # colisiones.
        self.userData = {'id': self.id, 'figura': self}
        fixture.userData = self.userData


        self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(x, y), fixtures=fixture)

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor
        self.dinamica = dinamica

        if not dinamica:
            self._cuerpo.mass = 1000000
Beispiel #3
0
def createCircle(position, r=0.3, bDynamic=True, bCollideNoOne=False, density=1, damping=0.05, restitution=0.1, friction=200, name="",categoryBits=0x0001,maskBits=0x0009):
    global world, fig, ax
    bodyDef = Box2D.b2BodyDef()
    bodyDef.position = position
    if bDynamic:
        bodyDef.type = Box2D.b2_dynamicBody
    else:
        bodyDef.type = Box2D.b2_staticBody

    if(abs(world.gravity[1]) > 1):
        bodyDef.linearDamping = damping
        bodyDef.angularDamping = damping
    else:
        bodyDef.linearDamping = 70
        bodyDef.angularDamping = 30

    body = world.CreateBody(bodyDef)
    shape = Box2D.b2CircleShape(radius=r)

    mask=maskBits
    if(bCollideNoOne):
        mask = 0x0000
    fixture = body.CreateFixture(maskBits=mask, shape=shape, density=density, restitution=restitution, friction=friction,categoryBits=categoryBits)
    body.userData = {"name": name}

    return body
Beispiel #4
0
    def _create_balls(self, balls_pose):
        """
    Creates the balls in the simulation at the given positions
    :param balls_pose: Initial pose of the ball in table RF
    :return:
    """
        ## List of balls in simulation
        self.balls = []

        for idx, pose in enumerate(balls_pose):
            pose = pose + self.tw_transform  ## move balls in world RF
            ball = self.world.CreateDynamicBody(
                position=pose,
                bullet=True,
                allowSleep=False,
                userData={'name': 'ball{}'.format(idx)},
                linearDamping=1.1,
                angularDamping=2,
                fixtures=b2.b2FixtureDef(
                    shape=b2.b2CircleShape(radius=self.params.BALL_RADIUS),
                    density=1,
                    friction=self.params.BALL_FRICTION,
                    restitution=self.params.BALL_ELASTICITY,
                ))
            self.balls.append(ball)
def createCircle(position, r=0.3, dynamic=True, bMatplotlib = True):
    global world, fig, ax
    bodyDef = Box2D.b2BodyDef()
    fixtureDef = Box2D.b2FixtureDef()
    if dynamic:
        bodyDef.type = Box2D.b2_dynamicBody
        fixtureDef.density = 1
    else:
        bodyDef.type = Box2D.b2_staticBody
        fixtureDef.density = 0

    bodyDef.position = position

    if(abs(world.gravity[1]) > 1):
        bodyDef.linearDamping = 0.1
        bodyDef.angularDamping = 0.1
    else:
        bodyDef.linearDamping = 70
        bodyDef.angularDamping = 30

    body = world.CreateBody(bodyDef)
    fixture = body.CreateFixture(shape=Box2D.b2CircleShape(radius=r), density=1.0, friction=0.3)
    
    if(bMatplotlib): 
        createGlobalFigure()
        fixture.userData = drawCircle(ax,position,r)
    
    return body
Beispiel #6
0
    def _ball(self, pos, radius, dynamic=True, density=1.0, restitution=0.16,
              friction=0.5):
        # Add a ball without correcting any settings
        # meaning, pos and vertices are in meters
        # Define the body
        x, y = pos
        bodyDef = box2d.b2BodyDef()
        bodyDef.position = (x, y)

        userData = {'color': self.parent.get_color()}
        bodyDef.userData = userData

        # Create the Body
        if not dynamic:
            density = 0
        else:
            bodyDef.type = box2d.b2_dynamicBody

        body = self.parent.world.CreateBody(bodyDef)

        self.parent.element_count += 1

        # Add a shape to the Body
        circleShape = box2d.b2CircleShape()
        circleShape.radius = radius
        circleDef = box2d.b2FixtureDef()
        circleDef.shape = circleShape
        circleDef.density = density
        circleDef.restitution = restitution
        circleDef.friction = friction

        body.CreateFixture(circleDef)

        return body
Beispiel #7
0
 def __init__(self, world, name, pos, radius=0.022, density=1.0):
     self.name = name
     self.body = world.CreateDynamicBody(position=pos, linearDamping=1,
                                         angulardamping=1)
     ps = b2.b2CircleShape(radius=radius)
     self.body.CreateFixture(shape=ps, density=density)
     self.radius = radius
     self.body
    def __init__(self,
                 fisica,
                 pilas,
                 x=0,
                 y=0,
                 radio=20,
                 dinamica=True,
                 densidad=1.0,
                 restitucion=0.56,
                 friccion=10.5,
                 amortiguacion=0.1,
                 sin_rotacion=False,
                 sensor=False,
                 interactivo=True):

        Figura.__init__(self, fisica, pilas)

        if x is None:
            x = pilas.azar(10000, 10000 + 100000)

        if y is None:
            y = pilas.azar(10000, 10000 + 100000)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._radio = utils.convertir_a_metros(radio)
        self._escala = 1
        self.interactivo = interactivo
        self.fisica = fisica

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not dinamica:
            densidad = 0

        fixture = box2d.b2FixtureDef(
            shape=box2d.b2CircleShape(radius=self._radio),
            density=densidad,
            linearDamping=amortiguacion,
            friction=friccion,
            restitution=restitucion)

        # Agregamos un identificador para controlarlo posteriormente en las
        # colisiones.
        self.userData = {'id': self.id, 'figura': self}
        fixture.userData = self.userData

        self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(x, y),
                                                           fixtures=fixture)

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor
        self.dinamica = dinamica

        if not dinamica:
            self._cuerpo.mass = 1000000
Beispiel #9
0
def create_bumper(bumper_def):
    bumper = world.CreateBody(bumper_def)
    bumperFixture = b2.b2FixtureDef()
    bumperFixture.friction = 0
    bumperFixture.restitution = 0
    bumperFixture.density = 1000000 * 1000000
    bumperFixture.shape = b2.b2CircleShape(radius=6.5)
    bumper.CreateFixture(bumperFixture)
    return bumper
Beispiel #10
0
    def __init__(self, **kwargs):
        super(Circle, self).__init__(**kwargs)
        self.hue = random()

        # Ball
        self._body = self.world.CreateDynamicBody(
            fixtures=b2d.b2FixtureDef(
                shape=b2d.b2CircleShape(radius=self.radius),
                density=1.0, friction=0.3),
            bullet=True,
            position=self.pos)
Beispiel #11
0
 def add_circle(self, pos, vel):
     pos = self.renderer.to_world_frame(pos)
     vel = (self.renderer.pixels_to_meters(vel[0]),
            -self.renderer.pixels_to_meters(vel[1]))
     circle = self.world.CreateDynamicBody(position=pos)
     fixture_def = Box2D.b2FixtureDef(shape=(Box2D.b2CircleShape(radius=5)),
                                      density=1,
                                      friction=0,
                                      restitution=1)
     circle.CreateFixture(fixture_def)
     circle.linearVelocity = vel
     circle.userData = BouncingBalls.BodyData("circle")
    def __init__(self,
                 fisica,
                 pilas,
                 x,
                 y,
                 radio,
                 dinamica=True,
                 densidad=1.0,
                 restitucion=0.56,
                 friccion=10.5,
                 amortiguacion=0.1,
                 sin_rotacion=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._radio = utils.convertir_a_metros(radio)
        self._escala = 1

        self.dinamica = dinamica
        self.fisica = fisica
        self.sin_rotacion = sin_rotacion

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not self.dinamica:
            densidad = 0

        fixture = box2d.b2FixtureDef(
            shape=box2d.b2CircleShape(radius=self._radio),
            density=densidad,
            linearDamping=amortiguacion,
            friction=friccion,
            restitution=restitucion)

        # Agregamos un identificador para controlarlo posteriormente en las
        # colisiones.
        self.userData = {'id': self.id}
        fixture.userData = self.userData

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(
                position=(x, y), fixtures=fixture)
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(
                position=(x, y), fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
Beispiel #13
0
    def __crear_fixture(self):
        fixture = box2d.b2FixtureDef(shape=box2d.b2CircleShape(radius=self._radio),
                                         density=self._cuerpo.fixtures[0].density,
                                         linearDamping=self._cuerpo.fixtures[0].body.linearDamping,
                                         friction=self._cuerpo.fixtures[0].friction,
                                         restitution=self._cuerpo.fixtures[0].restitution)                

        fixture.userData = self.userData

        self.fisica.mundo.DestroyBody(self._cuerpo)

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(self._cuerpo.position.x, self._cuerpo.position.y), angle=self._cuerpo.angle, linearVelocity=self._cuerpo.linearVelocity, fixtures=fixture)    
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(position=(self._cuerpo.position.x, self._cuerpo.position.y), angle=self._cuerpo.angle, fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
Beispiel #14
0
    def attachRobotBody(self, world, **kargs):
        robotBody = world.CreateDynamicBody(**kargs)
        robotBody.CreateFixture( shape = Box2D.b2CircleShape(pos=(0, 0),
                    radius = self.radius), density = 1.0, **kargs)

        for i, angle in enumerate(numpy.linspace(0, math.pi*2, self.nbumpers+1)[:-1]):
            c = numpy.array((self.radius * math.sin(angle),
                              self.radius * math.cos(angle)))
            robotBody.CreateFixture(shape = Box2D.b2PolygonShape(
                                                        box = (self.bumper_w/2,
                                                               self.bumper_h/2,
                                                        (c[0], c[1]),
                                                        angle)),
                                    density = 0.01,
                                    isSensor = True,
                                    userData = 'b'+ str(i))
        self.robotBody = robotBody
        return robotBody
Beispiel #15
0
 def rescale_shape(self):
     scale = self.object.scale
     bs = self._basic_shape
     if scale != self._old_scale:
         self._old_scale = scale
         if isinstance(bs, B2D.b2PolygonShape):
             vertices = []
             c = bs.centroid
             for v in bs.vertices:
                 dv = c-B2D.b2Vec2(*v)
                 dv.x *= scale[0]
                 dv.y *= scale[1]
                 vertices.append((c+dv).tuple)
             self.rescaled_shape = B2D.b2PolygonShape(vertices=vertices)
         else:
             c_scale = max(scale[0], scale[1])
             self.rescaled_shape = B2D.b2CircleShape(pos=bs.pos,
                                                   radius=c_scale*bs.radius)
     return self.rescaled_shape
Beispiel #16
0
    def attachRobotBody(self, world, **kargs):
        robotBody = world.CreateDynamicBody(**kargs)
        robotBody.CreateFixture(shape=Box2D.b2CircleShape(pos=(0, 0),
                                                          radius=self.radius),
                                density=1.0,
                                **kargs)

        for i, angle in enumerate(
                numpy.linspace(0, math.pi * 2, self.nbumpers + 1)[:-1]):
            c = numpy.array(
                (self.radius * math.sin(angle), self.radius * math.cos(angle)))
            robotBody.CreateFixture(
                shape=Box2D.b2PolygonShape(box=(self.bumper_w / 2,
                                                self.bumper_h / 2,
                                                (c[0], c[1]), angle)),
                density=0.01,
                isSensor=True,
                userData='b' + str(i))
        self.robotBody = robotBody
        return robotBody
    def __init__(self, fisica, pilas, x, y, radio, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._radio = utils.convertir_a_metros(radio)
        self._escala = 1

        self.dinamica = dinamica
        self.fisica = fisica
        self.sin_rotacion = sin_rotacion

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not self.dinamica:
            densidad = 0

        fixture = box2d.b2FixtureDef(shape=box2d.b2CircleShape(radius=self._radio),
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)

        # Agregamos un identificador para controlarlo posteriormente en las
        # colisiones.
        self.userData = { 'id' : self.id }
        fixture.userData = self.userData

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(x, y), fixtures=fixture)
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(position=(x, y), fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
Beispiel #18
0
    def concavePoly(self,
                    vertices,
                    dynamic=True,
                    density=1.0,
                    restitution=0.16,
                    friction=0.5,
                    screenCoord=True):
        # 1. Step: Reduce
        # Detect if the polygon is closed or open
        if vertices[0] != vertices[-1]:
            is_closed = False
        else:
            is_closed = True

        # Continue reducing the vertecs
        x, y = c = tools_poly.calc_center(vertices)
        vertices = tools_poly.poly_center_vertices(vertices)

        # Bring coordinates into the world coordinate system (flip, camera
        # offset, ...)
        if screenCoord:
            x, y = self.parent.to_world(c)
        else:
            x, y = c

        # If required, translate pixel -> meters
        if self.parent.input == INPUT_PIXELS:
            # translate pixel -> meters
            x /= self.parent.ppm
            y /= self.parent.ppm

        # Let's add the body
        bodyDef = box2d.b2BodyDef()
        bodyDef.position = (x, y)

        userData = {'color': self.parent.get_color()}
        bodyDef.userData = userData

        # Create the Body
        if not dynamic:
            density = 0
        else:
            bodyDef.type = box2d.b2_dynamicBody

        body = self.parent.world.CreateBody(bodyDef)

        self.parent.element_count += 1

        # Create the reusable Box2D polygon and circle definitions
        polyDef = box2d.b2PolygonShape()
        polyDef.vertexCount = 4  # rectangle
        polyDef.density = density
        polyDef.restitution = restitution
        polyDef.friction = friction

        circleShape = box2d.b2CircleShape()
        circleShape.radius = radius
        circleDef = box2d.b2FixtureDef()
        circleDef.shape = circleShape
        circleDef.density = density
        circleDef.restitution = restitution
        circleDef.friction = friction

        # Set the scale factor
        factor = 8.0

        v2 = box2d.b2Vec2(*vertices[0])
        for v in vertices[1:]:
            v1 = v2.copy()
            v2 = box2d.b2Vec2(*v)

            vdir = v2 - v1  # (v2x-v1x, v2y-v1y)
            vdir.Normalize()

            # we need a little size for the end part
            vn = box2d.b2Vec2(-vdir.y * factor, vdir.x * factor)

            v = [v1 + vn, v1 - vn, v2 - vn, v2 + vn]

            # Create a line (rect) for each part of the polygon,
            # and attach it to the body
            polyDef.setVertices([vi / self.parent.ppm for vi in v])

            try:
                polyDef.checkValues()
            except ValueError:
                print "concavePoly: Created an invalid polygon!"
                return None

            body.CreateFixture(polyDef)

            # Now add a circle to the points between the rects
            # to avoid sharp edges and gaps
            if not is_closed and v2.tuple() == vertices[-1]:
                # Don't add a circle at the end
                break

            circleDef.localPosition = v2 / self.parent.ppm
            body.CreateFixture(circleDef)

        # Return hard and soft reduced vertices
        return body
Beispiel #19
0
pisoDef.position = (0, 0)
pisoDef.angle = -10 * math.pi / 180
pisoDef.type = b2.b2_staticBody

# Criar o corpo com a definição
piso = cenario.CreateBody(pisoDef)

# Criar o corpo com a definição
corpo = cenario.CreateBody(corpoDef)

# Definição do Fixture
fixDef = b2.b2FixtureDef()
fixDef.restitution = 0.9
fixDef.friction = 0.6
fixDef.density = 3
fixDef.shape = b2.b2CircleShape(radius=1)

# Definição do Fixture Piso
pisoFixDef = b2.b2FixtureDef()
pisoFixDef.restitution = 0.5
pisoFixDef.friction = 0.6
pisoFixDef.density = 1
pisoFixDef.shape = b2.b2PolygonShape(box=(50, 2))

# Associa o Fixture ao corpo
corpo.CreateFixture(fixDef)
piso.CreateFixture(pisoFixDef)

while True:
    # Calcula regras
    cenario.Step(1.0 / 30.0, 8, 3)
def add_fixture(
        b2_world_body,
        jsw,
        jsw_fixture,
        ):
     # create and fill fixture definition
    fixtureDef = b2.b2FixtureDef()

    # Done with issues:
    ### missing pybox2d "filter" b2BodyDef property

    # special case for rube documentation of
    #"filter-categoryBits": 1, //if not present, interpret as 1
    if "filter-categoryBits" in jsw_fixture.keys():
        setAttr(jsw_fixture, "filter-categoryBits", fixtureDef, "categoryBits")
    else:
        fixtureDef.categoryBits = 1

    # special case for Rube Json property
    #"filter-maskBits": 1, //if not present, interpret as 65535
    if "filter-maskBits" in jsw_fixture.keys():
        setAttr(jsw_fixture, "filter-maskBits", fixtureDef, "maskBits")
    else:
        fixtureDef.maskBits = 65535

    setAttr(jsw_fixture, "density", fixtureDef)
    setAttr(jsw_fixture, "filter-groupIndex", fixtureDef, "groupIndex")
    setAttr(jsw_fixture, "friction", fixtureDef)
    setAttr(jsw_fixture, "sensor", fixtureDef, "isSensor")
    setAttr(jsw_fixture, "restitution", fixtureDef)

    # fixture has one shape that is
    # polygon, circle or chain in json
    # chain may be open or loop, or edge in pyBox2D
    if "circle" in jsw_fixture.keys():  # works ok
        if jsw_fixture["circle"]["center"] == 0:
            center_b2Vec2 = b2.b2Vec2(0, 0)
        else:
            center_b2Vec2 = rubeVecToB2Vec2(
                jsw_fixture["circle"]["center"]
                )
        fixtureDef.shape = b2.b2CircleShape(
            pos=center_b2Vec2,
            radius=jsw_fixture["circle"]["radius"],
            )

    if "polygon" in jsw_fixture.keys():  # works ok
        polygon_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["polygon"]["vertices"]
            )
        fixtureDef.shape = b2.b2PolygonShape(vertices=polygon_vertices)

    if "chain" in jsw_fixture.keys():  # works ok
        chain_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["chain"]["vertices"]
            )

        if len(chain_vertices) >= 3:
            # closed-loop b2LoopShape
            # Done
            if "hasNextVertex" in jsw_fixture["chain"].keys():

                # del last vertice to prevent crash from first and last
                # vertices being to close
                del chain_vertices[-1]

                fixtureDef.shape = b2.b2LoopShape(
                    vertices_loop=chain_vertices,
                    count=len(chain_vertices),
                    )

                setAttr(
                    jsw_fixture["chain"],
                    "hasNextVertex",
                    fixtureDef.shape,
                    "m_hasNextVertex",
                    )
                setB2Vec2Attr(
                    jsw_fixture["chain"],
                    "nextVertex",
                    fixtureDef,
                    "m_nextVertex",
                    )

                setAttr(
                    jsw_fixture["chain"],
                    "hasPrevVertex",
                    fixtureDef.shape,
                    "m_hasPrevVertex",
                    )
                setB2Vec2Attr(
                    jsw_fixture["chain"],
                    "prevVertex",
                    fixtureDef.shape,
                    "m_prevVertex"
                    )

            else:  # open-ended ChainShape
                # Done
                fixtureDef.shape = b2.b2ChainShape(
                    vertices_chain=chain_vertices,
                    count=len(chain_vertices),
                    )

        # json chain is b2EdgeShape
        # Done
        if len(chain_vertices) < 3:
            fixtureDef.shape = b2.b2EdgeShape(
                vertices=chain_vertices,
                )

    # create fixture
    b2_world_body.CreateFixture(fixtureDef)
Beispiel #21
0
def add_fixture(b2_world_body, jsw, jsw_fixture):
    """add a fixture to a body

    :param b2_world_body: a body
    :type b2_world_body: b2Body

    :param jsw: dictionary defining all the gropups of data
                in the json file
    :type jsw: dict(sting: variant)

    :param jsw_fixture: a fixture
    :type jsw_fixture: b2Fixture

    """

    # create and fill fixture definition
    fixtureDef = b2.b2FixtureDef()

    # Done with issues:
    ### missing pybox2d "filter" b2BodyDef property

    # special case for rube documentation of
    # "filter-categoryBits": 1, //if not present, interpret as 1
    if "filter-categoryBits" in list(jsw_fixture.keys()):
        setAttr(jsw_fixture, "filter-categoryBits", fixtureDef, "categoryBits")
    else:
        fixtureDef.categoryBits = 1

    # special case for Rube Json property
    # "filter-maskBits": 1, //if not present, interpret as 65535
    if "filter-maskBits" in list(jsw_fixture.keys()):
        setAttr(jsw_fixture, "filter-maskBits", fixtureDef, "maskBits")
    else:
        fixtureDef.maskBits = 65535

    setAttr(jsw_fixture, "density", fixtureDef)
    setAttr(jsw_fixture, "group_index", fixtureDef, "groupIndex")
    setAttr(jsw_fixture, "friction", fixtureDef)
    setAttr(jsw_fixture, "sensor", fixtureDef, "isSensor")
    setAttr(jsw_fixture, "restitution", fixtureDef)

    # fixture has one shape that is
    # polygon, circle or chain in json
    # chain may be open or loop, or edge in pyBox2D
    if "circle" in list(jsw_fixture.keys()):  # works ok
        if jsw_fixture["circle"]["center"] == 0:
            center_b2Vec2 = b2.b2Vec2(0, 0)
        else:
            center_b2Vec2 = rubeVecToB2Vec2(jsw_fixture["circle"]["center"])
        fixtureDef.shape = b2.b2CircleShape(
            pos=center_b2Vec2,
            radius=jsw_fixture["circle"]["radius"],
        )

    if "polygon" in list(jsw_fixture.keys()):  # works ok
        polygon_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["polygon"]["vertices"])
        fixtureDef.shape = b2.b2PolygonShape(vertices=polygon_vertices)

    if "chain" in list(jsw_fixture.keys()):  # works ok
        chain_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["chain"]["vertices"])

        if len(chain_vertices) >= 3:
            # closed-loop b2LoopShape
            # Done
            if "hasNextVertex" in list(jsw_fixture["chain"].keys()):

                # del last vertice to prevent crash from first and last
                # vertices being to close
                del chain_vertices[-1]

                fixtureDef.shape = b2.b2LoopShape(
                    vertices_loop=chain_vertices,
                    count=len(chain_vertices),
                )

                setAttr(
                    jsw_fixture["chain"],
                    "hasNextVertex",
                    fixtureDef.shape,
                    "m_hasNextVertex",
                )
                setB2Vec2Attr(
                    jsw_fixture["chain"],
                    "nextVertex",
                    fixtureDef,
                    "m_nextVertex",
                )

                setAttr(
                    jsw_fixture["chain"],
                    "hasPrevVertex",
                    fixtureDef.shape,
                    "m_hasPrevVertex",
                )
                setB2Vec2Attr(jsw_fixture["chain"], "prevVertex",
                              fixtureDef.shape, "m_prevVertex")

            else:  # open-ended ChainShape
                # Done
                fixtureDef.shape = b2.b2ChainShape(
                    vertices_chain=chain_vertices,
                    count=len(chain_vertices),
                )

        # json chain is b2EdgeShape
        # Done
        if len(chain_vertices) < 3:
            fixtureDef.shape = b2.b2EdgeShape(vertices=chain_vertices, )

    # create fixture
    b2_world_body.CreateFixture(fixtureDef)
Beispiel #22
0
    def create(self,
               world,
               TERRAIN_HEIGHT,
               module=None,
               node=None,
               connection_site=None,
               p_c=None,
               module_list=None,
               position=None):
        # get module height and width
        if p_c is not None and connection_site is None:
            raise (
                "When you want to attach a new component to a parent component, you have to supply",
                "a connection_site object with it. This connection_site object defines where to anchor",
                "the joint in between to components")
        n_radius = self.radius
        angle = 0

        pos = [7, 10, 0]
        if position is not None:
            pos = position
        if (p_c is not None):
            local_pos_x = math.cos(connection_site.orientation.x +
                                   math.pi / 2) * n_radius
            local_pos_y = math.sin(connection_site.orientation.x +
                                   math.pi / 2) * n_radius
            pos[0] = (local_pos_x) + connection_site.position.x
            pos[1] = (local_pos_y) + connection_site.position.y

        # This module will create one component that will be temporarily stored in ncomponent
        new_component = None
        # This module will create one joint (if a parent component is present) that will be temporarily stored in njoint
        njoint = None

        components = []
        joints = []

        if connection_site:
            angle += connection_site.orientation.x

        if (pos[1] - n_radius < TERRAIN_HEIGHT
            ):  #TODO CHANGE TO TERRAIN_HEIGT OR DO CHECK ELSEWHERE
            if node is not None:
                node.component = None
            return components, joints
        else:
            fixture = fixtureDef(shape=B2D.b2CircleShape(radius=n_radius),
                                 density=1,
                                 friction=0.1,
                                 restitution=0.0,
                                 categoryBits=0x0020,
                                 maskBits=0x001)
            new_component = world.CreateDynamicBody(position=(pos[0], pos[1]),
                                                    angle=angle,
                                                    fixtures=fixture)

            color = [255, 255, 255]
            if node is not None and module_list is not None:
                color = world.cmap(node.type / len(module_list))
            elif node is not None and module_list is None:
                print(
                    "Note: cannot assign a color to the module since the 'module_list' is not passed as an argument"
                )
            # move to component creator
            new_component.color1 = (color[0], color[1], color[2])
            new_component.color2 = (color[0], color[1], color[2])
            components.append(new_component)
            if node is not None:
                node.component = [new_component]

        if connection_site is not None:
            joint = mu.create_joint(world, p_c, new_component, connection_site,
                                    angle, self.torque)
            joints.append(joint)

        return components, joints
Beispiel #23
0
    def json_load(self, path, serialized=False):
        import json

        self.world.groundBody.userData = {"saveid": 0}

        f = open(path, 'r')
        worldmodel = json.loads(f.read())
        f.close()
        # clean world
        for joint in self.world.joints:
            self.world.DestroyJoint(joint)
        for body in self.world.bodies:
            if body != self.world.groundBody:
                self.world.DestroyBody(body)

        # load bodies
        for body in worldmodel['bodylist']:
            bodyDef = box2d.b2BodyDef()
            if body['dynamic']:
                bodyDef.type = box2d.b2_dynamicBody
            bodyDef.position = body['position']
            bodyDef.userData = body['userData']
            bodyDef.angle = body['angle']
            newBody = self.world.CreateBody(bodyDef)
            # _logger.debug(newBody)
            newBody.angularVelocity = body['angularVelocity']
            newBody.linearVelocity = body['linearVelocity']
            if 'shapes' in body:
                for shape in body['shapes']:
                    if shape['type'] == 'polygon':
                        polyDef = box2d.b2FixtureDef()
                        polyShape = box2d.b2PolygonShape()
                        polyShape.vertices = shape['vertices']
                        polyDef.shape = polyShape
                        polyDef.density = shape['density']
                        polyDef.restitution = shape['restitution']
                        polyDef.friction = shape['friction']
                        newBody.CreateFixture(polyDef)
                    if shape['type'] == 'circle':
                        circleDef = box2d.b2FixtureDef()
                        circleShape = box2d.b2CircleShape()
                        circleShape.radius = shape['radius']
                        circleShape.pos = shape['localPosition']
                        circleDef.shape = circleShape
                        circleDef.density = shape['density']
                        circleDef.restitution = shape['restitution']
                        circleDef.friction = shape['friction']
                        newBody.CreateFixture(circleDef)

        for joint in worldmodel['jointlist']:
            if joint['type'] == 'distance':
                jointDef = box2d.b2DistanceJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                anch1 = joint['anchor1']
                body2 = self.getBodyWithSaveId(joint['body2'])
                anch2 = joint['anchor2']
                jointDef.collideConnected = joint['collideConnected']
                jointDef.Initialize(body1, body2, anch1, anch2)
                jointDef.userData = joint['userData']
                self.world.CreateJoint(jointDef)
            if joint['type'] == 'revolute':
                jointDef = box2d.b2RevoluteJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                body2 = self.getBodyWithSaveId(joint['body2'])
                anchor = joint['anchor']
                jointDef.Initialize(body1, body2, anchor)
                jointDef.userData = joint['userData']
                jointDef.motorEnabled = joint['enableMotor']
                jointDef.motorSpeed = joint['motorSpeed']
                jointDef.maxMotorTorque = joint['maxMotorTorque']
                self.world.CreateJoint(jointDef)

        self.additional_vars = {}
        addvars = {}
        for (k, v) in list(worldmodel['additional_vars'].items()):
            addvars[k] = v

        if serialized and 'trackinfo' in addvars:
            trackinfo = addvars['trackinfo']
            for key, info in trackinfo.items():
                if not info[3]:
                    addvars['trackinfo'][key][0] = \
                        self.getBodyWithSaveId(info[0])
                    addvars['trackinfo'][key][1] = \
                        self.getBodyWithSaveId(info[1])
                else:
                    addvars['trackinfo'][key][0] = None
                    addvars['trackinfo'][key][1] = None

        self.additional_vars = addvars

        for body in self.world.bodies:
            del body.userData['saveid']  # remove temporary data
Beispiel #24
0
    def __init__(self, player, level, level_width, level_height):

        worldAABB = b2.b2AABB()

        worldAABB.upperBound = (.5, .5)
        worldAABB.lowerBound = (level_width, level_height)

        gravity = (0, 0)
        doSleep = True

        self.world = b2.b2World(gravity, doSleep)

        wall_shape = b2.b2PolygonShape()
        wall_shape.SetAsBox(.5, .5)
        wall_fixture = b2.b2FixtureDef()
        wall_fixture.shape = wall_shape
        wall_fixture.density = 5.0
        wall_fixture.friction = 0.5
        wall_fixture.reistitution = 0

        wall_body = b2.b2BodyDef()
        wall_body.type = b2.b2_staticBody
        wall_body.angle = 0
        wall_body.allowSleep = True
        wall_body.awake = False
        wall_body.fixedRotation = True
        wall_body.fixtures = [wall_fixture]

        for x in range(level_width):
            for y in range(level_height):
                if level[(x, y)].blocked:
                    wall_body.position = (x+0.5, y+.5)
                    level[(x, y)].body = self.world.CreateBody(wall_body)

        player_shape = b2.b2CircleShape()
        player_shape.radius = 0.3

        player_fixture = b2.b2FixtureDef()
        player_fixture.shape = player_shape
        player_fixture.density = 1
        player_fixture.friction = 0.5
        player_fixture.reistitution = 5

        player_body = b2.b2BodyDef()
        player_body.type = b2.b2_dynamicBody
        player_body.angle = radians(player.heading)
        player_body.position = (player.ux, player.uy)
        player_body.allowSleep = True
        player_body.awake = True
        player_body.fixtures = [player_fixture]
        player_body.linearDamping = 3.5

        player.body = self.world.CreateBody(player_body)

        mob_shape = b2.b2CircleShape()
        mob_shape.radius = 0.5

        mob_fixture = b2.b2FixtureDef()
        mob_fixture.shape = mob_shape
        mob_fixture.density = 1
        mob_fixture.friction = 0.5
        mob_fixture.reistitution = 5

        self.mob_body = b2.b2BodyDef()
        self.mob_body.type = b2.b2_dynamicBody
        # self.mob_body.type = b2.b2_staticBody
        self.mob_body.linearDamping = 3.5/2
        self.mob_body.allowSleep = True
        self.mob_body.awake = True
        self.mob_body.fixtures = [mob_fixture]
        self.mob_body.angle = radians(0)
Beispiel #25
0
    def json_load(self, path, serialized=False):
        import json

        self.world.groundBody.userData = {"saveid": 0}

        f = open(path, 'r')
        worldmodel = json.loads(f.read())
        f.close()
        # clean world
        for joint in self.world.joints:
            self.world.DestroyJoint(joint)
        for body in self.world.bodies:
            if body != self.world.groundBody:
                self.world.DestroyBody(body)

        # load bodies
        for body in worldmodel['bodylist']:
            bodyDef = box2d.b2BodyDef()
            if body['dynamic']:
                bodyDef.type = box2d.b2_dynamicBody
            bodyDef.position = body['position']
            bodyDef.userData = body['userData']
            bodyDef.angle = body['angle']
            newBody = self.world.CreateBody(bodyDef)
            # _logger.debug(newBody)
            newBody.angularVelocity = body['angularVelocity']
            newBody.linearVelocity = body['linearVelocity']
            if 'shapes' in body:
                for shape in body['shapes']:
                    if shape['type'] == 'polygon':
                        polyDef = box2d.b2FixtureDef()
                        polyShape = box2d.b2PolygonShape()
                        polyShape.vertices = shape['vertices']
                        polyDef.shape = polyShape
                        polyDef.density = shape['density']
                        polyDef.restitution = shape['restitution']
                        polyDef.friction = shape['friction']
                        newBody.CreateFixture(polyDef)
                    if shape['type'] == 'circle':
                        circleDef = box2d.b2FixtureDef()
                        circleShape = box2d.b2CircleShape()
                        circleShape.radius = shape['radius']
                        circleShape.pos = shape['localPosition']
                        circleDef.shape = circleShape
                        circleDef.density = shape['density']
                        circleDef.restitution = shape['restitution']
                        circleDef.friction = shape['friction']
                        newBody.CreateFixture(circleDef)

        for joint in worldmodel['jointlist']:
            if joint['type'] == 'distance':
                jointDef = box2d.b2DistanceJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                anch1 = joint['anchor1']
                body2 = self.getBodyWithSaveId(joint['body2'])
                anch2 = joint['anchor2']
                jointDef.collideConnected = joint['collideConnected']
                jointDef.Initialize(body1, body2, anch1, anch2)
                jointDef.userData = joint['userData']
                self.world.CreateJoint(jointDef)
            if joint['type'] == 'revolute':
                jointDef = box2d.b2RevoluteJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                body2 = self.getBodyWithSaveId(joint['body2'])
                anchor = joint['anchor']
                jointDef.Initialize(body1, body2, anchor)
                jointDef.userData = joint['userData']
                jointDef.motorEnabled = joint['enableMotor']
                jointDef.motorSpeed = joint['motorSpeed']
                jointDef.maxMotorTorque = joint['maxMotorTorque']
                self.world.CreateJoint(jointDef)

        self.additional_vars = {}
        addvars = {}
        for (k, v) in worldmodel['additional_vars'].items():
            addvars[k] = v

        if serialized and 'trackinfo' in addvars:
            trackinfo = addvars['trackinfo']
            for key, info in trackinfo.iteritems():
                if not info[3]:
                    addvars['trackinfo'][key][0] = \
                        self.getBodyWithSaveId(info[0])
                    addvars['trackinfo'][key][1] = \
                        self.getBodyWithSaveId(info[1])
                else:
                    addvars['trackinfo'][key][0] = None
                    addvars['trackinfo'][key][1] = None

        self.additional_vars = addvars

        for body in self.world.bodies:
            del body.userData['saveid']  # remove temporary data
Beispiel #26
0
IUP = 10
P1HP = IUP
P1Scr = 0
sSpd1 = 0
Xmov = 300 * 1000
Sdamp = 11
Ship1Def = b2.b2BodyDef()
Ship1Def.linearDamping = Sdamp
Ship1Def.position = (53, 58.1)
Ship1Def.type = b2.b2_dynamicBody
ship1 = world.CreateBody(Ship1Def)
shipFixture = b2.b2FixtureDef()
shipFixture.friction = 0
shipFixture.restitution = 4
shipFixture.density = 1000
shipFixture.shape = b2.b2CircleShape(radius=5)
ship1.CreateFixture(shipFixture)


# Define Player 1
def draw_ship(ship1):
    global ship1X, ship1Y, ship1Pos
    shape = ship1.fixtures[0].shape
    if shape.type == b2.b2Shape.e_circle:
        ship1Pos = ship1.position
        ship1X = int(ship1Pos[0] * PPM)
        ship1Y = int(ship1Pos[1] * PPM)
        screen.blit(S1, (ship1X - 50, ship1Y - 50))


# Player 2