Beispiel #1
0
    def __init__(self, x0, target, render):
        # TODO: try to pass the initial point as shift so that it will not affect the original code
        self.render = render
        if self.render:
            super(VehicleWorld, self).__init__()
        else: 
            self.world = b2.b2World(gravity=(0, -10), doSleep=True)
        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = x0[2]
        self.initial_linear_velocity = (x0[3], x0[4])
        self.initial_angular_velocity = x0[5]
        # ?? how to assign the parameter setting to dynamic body itself?  
        self.wheelbase = BUS_LENGTH
        self.lr = BUS_LENGTH/2

        ground = self.world.CreateBody(position=(0,0)) # set the initial position of the body
        ground.CreateEdgeChain(
            [(-GROUND_EDGE, -GROUND_EDGE),
             (-GROUND_EDGE, GROUND_EDGE),
             (GROUND_EDGE, GROUND_EDGE),
             (GROUND_EDGE, -GROUND_EDGE),
             (-GROUND_EDGE, -GROUND_EDGE)]
             )
        # ground.CreateEdgeChain(
        #     [(0, 0), (0, GROUND_EDGE), (GROUND_EDGE, GROUND_EDGE), (GROUND_EDGE, 0),(0, 0)])

        # self.introduce_roads()

        # Initialize the rectangular bus
        rectangle_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(BUS_LENGTH/2, BUS_WIDTH/2)),
            density=1.5,
            friction=1.,
        )
        square_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(0.5, 0.5)),
            density=10,
            friction=5.,
        )

        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            fixtures=rectangle_fixture,
        )

        self.target = self.world.CreateStaticBody(
            position=target[:2],
            # angle=target[2],
            # linearVelocity=target[3:5],
            # angularVelocity=target[5],
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            fixtures = rectangle_fixture,
        )
        self.target.active = False
Beispiel #2
0
    def __init__(self, xpos, ypos, dimensionX, dimensionY, isDynamic):
        # Creating the body definition
        self.bodyDef = Box2D.b2BodyDef()
        if isDynamic:
            self.bodyDef.type = Box2D.b2_dynamicBody
        else:
            self.bodyDef.type = Box2D.b2_staticBody
            # put object to "Sleep" to spare CPU
            self.bodyDef.awake = False
        self.bodyDef.position = (xpos, ypos)
        # platform body in world
        self.body = world.CreateBody(self.bodyDef)
        self.body.mass = 0.001
        # platform box shape
        self.objectBox = Box2D.b2PolygonShape(box=(dimensionX / 2,
                                                   dimensionY / 2))
        # fixture definition
        if isDynamic:
            self.objectBoxFixture = Box2D.b2FixtureDef(shape=self.objectBox)
        else:
            self.objectBoxFixture = Box2D.b2FixtureDef(shape=self.objectBox,
                                                       density=1,
                                                       friction=0.3)
        self.body.CreateFixture(self.objectBoxFixture)

        # the boundaries
        # The boundaries
        ground = world.CreateBody(position=(400, 0))
        ground.CreateEdgeChain([(-1200, -1200), (-1200, 1200), (2000, 2000),
                                (2000, -1200), (-1200, -1200)])

        world.CreateFrictionJoint(bodyA=ground, bodyB=self.body)
Beispiel #3
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 #4
0
    def __init__(self, fisica, pilas, x, y, ancho, alto, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False, sensor=False,
                 plataforma=False):

        Figura.__init__(self, fisica, pilas)

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

        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        self._escala = 1

        self.fisica = fisica

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

        if not dinamica:
            densidad = 0

        shape = box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2))
        shape.SetAsBox(self._ancho/2.0, self._alto/2.0)

        try:
            fixture = box2d.b2FixtureDef(
                                     shape=shape,
                                     density=densidad,
                                     friction=friccion,
                                     restitution=restitucion)
        except TypeError:
            fixture = box2d.b2FixtureDef(
                                     shape=shape,
                                     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

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

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor

        if not dinamica:
            self._cuerpo.mass = 1000000
Beispiel #5
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 #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, verbose=1):
        self.contactListener_keep_ref = FrictionDetector(self)
        self.world = Box2D.b2World(
            (0, 0), contactListener=self.contactListener_keep_ref)
        self.viewer = None
        self.invisible_state_window = None
        self.invisible_video_window = None
        self.road = None
        self.car = None
        self.reward = 0.0
        self.prev_reward = 0.0
        self.verbose = verbose

        self.fd_tile = Box2D.b2FixtureDef(shape=Box2D.b2PolygonShape(
            vertices=[(0, 0), (1, 0), (1, -1), (0, -1)]))

        self.state_temp = None  # Yonv1943
        self.tile_visited_count = 0
        self.road_poly = []
        self.transform = None
        self.t = None
        self.num_step = 0

        self.env_name = 'CarRacingFix'
        self.state_dim = (STATE_W, STATE_H, 3 * 2)
        self.action_dim = 6
        self.if_discrete = False
        self.max_step = 512
        self.target_return = 950
        self.action_max = 1
Beispiel #8
0
def create_body(world, shape_type, position = (0, 0), angle = 0,
friction = None, restitution = None, density = None, linear_damping = None,
is_sensor = False, fixed_rotation = False,
body_type = Box2D.b2_dynamicBody, user_data = None, **kwargs):
	"""Creates a body.
	All parameters should be self-explanatory with a quick skim of the Box2D manual.
	
	**kwargs will be set on the shape type after its construction."""
	shape = shape_type()
	for i, j in kwargs.iteritems():
		setattr(shape, i, j)
	fixture_def = Box2D.b2FixtureDef()
	if friction is not None:
		fixture_def.friction = friction
	if restitution is not None:
		fixture_def.restitution = restitution
	if density is not None:
		fixture_def.density = density
	fixture_def.shape = shape
	fixture_def.isSensor = is_sensor
	body_def = Box2D.b2BodyDef()
	body_def.type = body_type
	body_def.position = position
	body_def.angle = angle
	body = world.CreateBody(body_def)
	body.CreateFixture(fixture_def)
	body.userData = user_data
	if linear_damping:
		body.linearDamping = linear_damping
	body.fixedRotation = fixed_rotation
	return body
Beispiel #9
0
    def __init__(self, x, y, puntos, dinamica=True, densidad=1.0,
            restitucion=0.56, friccion=10.5, amortiguacion=0.1,
            fisica=None, sin_rotacion=False):

        Figura.__init__(self)

        self._escala = 1

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

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

        self.vertices = [(convertir_a_metros(x1) * self._escala, convertir_a_metros(y1) * self._escala) for (x1, y1) in self.puntos]

        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(vertices=self.vertices),
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)

        self.userData = { 'id' : self.id }
        fixture.userData = self.userData

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

        self._cuerpo.fixedRotation = self.sin_rotacion
 def transfer(self):
     to_transfer = {'fixedRotation': 'fixedRotation',
                    'userData': 'userData',
                    'sleepingAllowed': 'allowSleep'}
     transfer_dict = {}
     for old_name, new_name in to_transfer.items():
         transfer_dict[new_name] = eval('self.b2body.'+old_name)
     new_b2body = self.world.CreateDynamicBody(**transfer_dict)
     for fixture in self.b2body.fixtures:
         to_transfer = {'filterData': 'filter',
                        'friction': 'friction',
                        'sensor': 'isSensor',
                        'userData': 'userData',
                        'shape': 'shape'}
         transfer_dict = {}
         for old_name, new_name in to_transfer.items():
             transfer_dict[new_name] = eval('fixture.'+old_name)
         def_fix = b2.b2FixtureDef(**transfer_dict)
         new_fixture = new_b2body.CreateFixture(def_fix)
         handlers = self.b2body.cool_world.true_listener.getHandlers(fixture)
         if handlers:
             self.b2body.cool_world.true_listener.removeEventHandler(fixture)
             self.world.addEventHandler(new_fixture, *handlers)
     self.b2body.cool_world.destroy_body(self.b2body)
     self.b2body = new_b2body
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 #12
0
    def __init__(self, env, size, pos, world):
        # static rectangle shaped prop
        # pars:
        # size - array [width, height]
        # position - array [x, y], in world meters, of center

        self.env = env
        self.size = size
        self.pos = pos

        # initialize body
        bdef = Box2D.b2BodyDef()
        bdef.position = Box2D.b2Vec2(self.pos[0], self.pos[1])
        bdef.angle = 0
        bdef.fixedRotation = True
        self.body = world.CreateBody(bdef)

        # strange rect due to Box2D's way of representing objects
        self.rect = pygame.rect.Rect(self.pos[0] - self.size[0]/2,
                                     self.pos[1] - self.size[1]/2,
                                     self.size[0], self.size[1])

        # initialize shape
        fixdef = Box2D.b2FixtureDef()
        fixdef.shape = Box2D.b2PolygonShape()
        fixdef.shape.SetAsBox(self.size[0]/2, self.size[1]/2)
        fixdef.restitution = 0.4
        self.body.CreateFixture(fixdef)
Beispiel #13
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)
Beispiel #14
0
def createBoxFixture(pos=(0, 0),
                     width=1.0,
                     height=1.0,
                     bDynamic=True,
                     density=1,
                     collisionGroup=None,
                     restitution=None):
    global world
    boxShape = Box2D.b2PolygonShape()
    boxShape.SetAsBox(width, height, pos,
                      0)  # width, height, position (x,y), angle
    fixtureDef = Box2D.b2FixtureDef()
    fixtureDef.shape = boxShape

    fixtureDef.friction = 0.3
    if (abs(world.gravity[1]) > 1):
        fixtureDef.restitution = 0.6

    if (restitution != None): fixtureDef.restitution = restitution

    if (collisionGroup != None): fixtureDef.filter.groupIndex = collisionGroup

    if bDynamic: fixtureDef.density = density
    else: fixtureDef.density = 0
    return fixtureDef
Beispiel #15
0
    def _rect(self, pos, width, height, angle=0, dynamic=True, density=1.0,
              restitution=0.16, friction=0.5):
        # Add a rect without correcting any settings
        # meaning, pos and vertices are in meters
        # angle is now in radians ((degrees * pi) / 180))
        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
        boxDef = box2d.b2FixtureDef()

        polygonShape = box2d.b2PolygonShape()
        polygonShape.SetAsBox(width, height, (0, 0), angle)
        boxDef.shape = polygonShape
        boxDef.density = density
        boxDef.restitution = restitution
        boxDef.friction = friction
        body.CreateFixture(boxDef)

        return body
Beispiel #16
0
    def _poly(self, pos, vertices, dynamic=True, density=1.0,
              restitution=0.16, friction=0.5):
        # add a centered poly at pos without correcting any settings
        # meaning, pos and vertices are in meters
        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
        polyDef = box2d.b2FixtureDef()

        polygonShape = box2d.b2PolygonShape()
        polygonShape.vertices = vertices
        polyDef.shape = polygonShape
        polyDef.density = density
        polyDef.restitution = restitution
        polyDef.friction = friction
        body.CreateFixture(polyDef)

        return body
Beispiel #17
0
 def perform(self, time):
     """
     Morph line into real collideable figure.
     """
     #Define geometry and time data
     actor = self.master.owner
     v1 = actor.b2body.GetLocalPoint(pixels_to_tiles((self.start.x, self.start.y)))
     v2 = actor.b2body.GetLocalPoint(pixels_to_tiles((self.end.x, self.end.y)))
     if v2.x <= v1.x:
         v1, v2 = v2, v1
     vlen = math.sqrt((v2.x-v1.x)*(v2.x-v1.x)+(v2.y-v1.y)*(v2.y-v1.y))
     vcent = ((v1.x+v2.x)/2.0, (v1.y+v2.y)/2.0)
     vangle = math.asin((v2.y-v1.y)/vlen)
     v = self.end - self.start
     start = gm.Point2(self.start.x, self.start.y)
     self.trace = gm.LineSegment2(start, v)
     self.cshape = shape_to_cshape(self.trace)
     self.set_time_to_complete(time)
     self.b2fixture = actor.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(vlen, 0,
                                                                                              vcent, vangle)),
                                                                 isSensor=True, userData=self))
     self.b2fixture.filterData.categoryBits = B2SWING
     self.b2fixture.filterData.maskBits = B2HITZONE | B2SWING | B2BODYPART
     actor.world.addEventHandler(self.b2fixture, self.on_begin_contact, self.on_end_contact)
     self.schedule(self.update)
Beispiel #18
0
    def randomize(self, N, x0, x1, rng):
        # randomize how hilly the terrain is. lower number = softer hills
        terrain_freq = 10 + 14 * rng.rand()
        # construct random terrain using frequency domain low-freq noise
        modulus = np.exp(-np.arange(N) / terrain_freq) * rng.randn(N)
        argument = rng.randn(N)
        freqspace = modulus * np.cos(argument) + 1j * modulus * np.sin(
            argument)
        z = np.fft.fft(freqspace).real
        zmin = np.min(z)
        zmax = np.max(z)
        self.z = (TERRAIN_Z_RANGE / (zmax - zmin)) * (z - zmin)
        self.x = np.linspace(x0, x1, N)

        # construct box2d world for lidar.
        self.world = Box2D.b2World()
        verts = zip(self.x, self.z)
        nverts = len(verts)
        for i in range(nverts - 1):
            p0, p1 = verts[i], verts[i + 1]
            edge = Box2D.b2EdgeShape(vertices=[p0, p1])
            body = Box2D.b2BodyDef(
                type=Box2D.b2_staticBody,
                fixtures=Box2D.b2FixtureDef(shape=edge, friction=0),
            )
            self.world.CreateBody(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 #20
0
 def setup_b2body(self):
     super(Actor, self).setup_b2body()
     pix_to_tile = pixels_to_tiles
     rx, ry = pix_to_tile((self.cshape.rx, self.cshape.ry))
     self.b2body.CreateFixture(
         b2.b2FixtureDef(
             shape=b2.b2PolygonShape(
                 vertices=[(-rx, ry), (-rx, -ry + 0.1), (-rx + 0.1, -ry), (rx - 0.1, -ry), (rx, -ry + 0.1), (rx, ry)]
             )
         )
     )
     self.b2body.fixtures[-1].filterData.categoryBits = B2SMTH | B2ACTOR
     self.b2body.CreateFixture(
         b2.b2FixtureDef(shape=b2.b2EdgeShape(vertex1=(-rx, -ry), vertex2=(rx, -ry)), isSensor=True)
     )
     self.b2body.fixtures[-1].filterData.categoryBits = B2GNDSENS
     self.b2body.fixtures[-1].filterData.maskBits = B2LEVEL | B2ACTOR
     self.world.addEventHandler(self.b2body.fixtures[-1], self.on_ground_begin, self.on_ground_end)
Beispiel #21
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 #22
0
 def setup_b2body(self):
     super(Hit_Zone, self).setup_b2body()
     cshape = self.cshape
     hit_shape = self.hit_shape
     img = self.image
     if hit_shape is RECTANGLE:
         rx, ry = pixels_to_tiles((cshape.rx, cshape.ry))
         self.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(rx, ry)), isSensor=True,
                                                   userData=self))
     elif hit_shape is LINE:
         r = pixels_to_tiles(img.width/2.0)
         self.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(r, 0)),
                                                   isSensor=True, userData=self))
     self.b2body.gravityScale = 0
     self.b2body.fixtures[-1].filterData.categoryBits = B2HITZONE
     self.b2body.fixtures[-1].filterData.maskBits = B2HITZONE | \
                                                    B2SWING | B2LEVEL | B2BODYPART
     self.world.addEventHandler(self.b2body.fixtures[-1], self.on_begin_contact, self.on_end_contact)
Beispiel #23
0
 def b2drop(self):
     self.cshape.center = eu.Vector2(self.position[0], self.position[1])
     rx, ry = pixels_to_tiles((self.cshape.rx, self.cshape.ry))
     self.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(rx, ry)), userData=self))
     self.b2body.fixtures[-1].filterData.categoryBits = B2ITEM
     self.b2body.fixtures[-1].filterData.maskBits = B2LEVEL
     self.b2body.fixtures[-1].friction = 10
     x, y = pixels_to_tiles((self.cshape.center.x, self.cshape.center.y))
     self.b2body.position = (x, y)
     self.b2body.linearVelocity.x = self.master.b2body.linearVelocity.x + pixels_to_tiles(randint(-500, 500))
     self.b2body.linearVelocity.y = self.master.b2body.linearVelocity.y + pixels_to_tiles(randint(-100, 100))
Beispiel #24
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 #25
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 create_polygon(vertices, world):
    body = world.CreateBody(Box2D.b2BodyDef())

    box = Box2D.b2ChainShape(vertices_loop=vertices)

    fixture = Box2D.b2FixtureDef()
    fixture.shape = box
    fixture.density = 2
    fixture.friction = .3
    fixture.restitution = .5
    fixture = body.CreateFixture(fixture)
    return body, [fixture]
Beispiel #27
0
    def __init__(self, x0, target, render):
        self.render = render
        if self.render:
            super(PointMassWorld, self).__init__()
        else:
            self.world = b2.b2World(gravity=(0, -10), doSleep=True)

        x0 = np.asfarray(x0)
        target = np.asfarray(target)

        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = b2.b2_pi
        self.initial_linear_velocity = (x0[2], x0[3])
        self.initial_angular_velocity = 0

        ground = self.world.CreateBody(position=(0, 20))
        ground.CreateEdgeChain([(-20, -20), (-20, 20), (20, 20), (20, -20),
                                (-20, -20)])

        xf1 = b2.b2Transform()
        xf1.angle = 0.3524 * b2.b2_pi
        xf1.position = b2.b2Mul(xf1.R, (1.0, 0.0))

        xf2 = b2.b2Transform()
        xf2.angle = -0.3524 * b2.b2_pi
        xf2.position = b2.b2Mul(xf2.R, (-1.0, 0.0))
        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            angularDamping=5,
            linearDamping=0.1,
            shapes=[
                b2.b2PolygonShape(
                    vertices=[xf1 * (-1, 0), xf1 * (1, 0), xf1 * (0, .5)]),
                b2.b2PolygonShape(
                    vertices=[xf2 * (-1, 0), xf2 * (1, 0), xf2 * (0, .5)])
            ],
            shapeFixture=b2.b2FixtureDef(density=1.0),
        )
        self.target = self.world.CreateStaticBody(
            position=target[:2],
            angle=self.initial_angle,
            shapes=[
                b2.b2PolygonShape(
                    vertices=[xf1 * (-1, 0), xf1 * (1, 0), xf1 * (0, .5)]),
                b2.b2PolygonShape(
                    vertices=[xf2 * (-1, 0), xf2 * (1, 0), xf2 * (0, .5)])
            ],
        )
        self.target.active = False
Beispiel #28
0
    def __init__(self,
                 fisica,
                 pilas,
                 x,
                 y,
                 ancho,
                 alto,
                 dinamica=True,
                 densidad=1.0,
                 restitucion=0.5,
                 friccion=.2,
                 amortiguacion=0.1,
                 sin_rotacion=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)
        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        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.b2PolygonShape(box=(self._ancho / 2, self._alto / 2)),
            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 #29
0
def aball(world, x, y, r):
    sd = box2d.b2PolygonShape()
    sd.SetAsBox(r, r)
    sd.restitution = 0.05

    bd = box2d.b2BodyDef()
    bd.position = (x, y)
    body = world.CreateDynamicBody(position=(x, y))
    # body = world.CreateBody(bd)
    groundBoxFixture = box2d.b2FixtureDef(shape=sd)
    body.CreateFixture(groundBoxFixture)
    # body.ResetMassData()
    return body
Beispiel #30
0
def aball(world, x, y, r):
    sd=box2d.b2PolygonShape()
    sd.SetAsBox(r, r)
    sd.restitution = 0.05

    bd=box2d.b2BodyDef()
    bd.position = (x, y)
    body = world.CreateDynamicBody(position=(x,y))
    # body = world.CreateBody(bd)
    groundBoxFixture=box2d.b2FixtureDef(shape=sd)
    body.CreateFixture(groundBoxFixture)
    # body.ResetMassData()
    return body
Beispiel #31
0
 def recreate(self, radius, n):
     self.radius = radius
     if n < 3:
         n = 3
     self.n = n
     for f in self.body.fixtures:
         self.body.DestroyFixture(f)
     for vertices in self._polyhedron_full(r=radius, n=n):
         fixture = B2.b2FixtureDef(
             shape=B2.b2PolygonShape(vertices=vertices),
             density=50,
             friction=5,
         )
         self.body.CreateFixture(fixture)
Beispiel #32
0
 def addSensor(self, world, cfg):
     sensorFov = b2.b2PolygonShape()
     # Define sensor shape
     w, h = cfg.fov.width, cfg.fov.height
     self.fov = (w,h)
     fov = np.array([(-0.5*w,-0.5*h),(0.5*w,-0.5*h),
                     (0.5*w,0.5*h),(-0.5*w, 0.5*h)])
     # Move sensor relative to the body
     relpos = np.array([cfg.relpos.x, cfg.relpos.y])
     sensorFov.vertices = (fov+relpos).tolist()
     sensorFixtureDef = b2.b2FixtureDef()
     sensorFixtureDef.isSensor = True
     sensorFixtureDef.shape = sensorFov
     self.sensor = self.body.CreateFixture(sensorFixtureDef)
Beispiel #33
0
 def _init_box2d(self):
     assert (self.x is not None)
     assert (self.z is not None)
     # construct box2d world for lidar.
     self.world = Box2D.b2World()
     verts = zip(self.x, self.z)
     nverts = len(verts)
     for i in range(nverts - 1):
         p0, p1 = verts[i], verts[i + 1]
         edge = Box2D.b2EdgeShape(vertices=[p0, p1])
         body = Box2D.b2BodyDef(
             type=Box2D.b2_staticBody,
             fixtures=Box2D.b2FixtureDef(shape=edge, friction=0),
         )
         self.world.CreateBody(body)
Beispiel #34
0
    def __init__(self, fisica, pilas, x, y, ancho, alto, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False, sensor=False,
                 plataforma=False):

        Figura.__init__(self, fisica, pilas)

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

        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        self._escala = 1

        self.fisica = fisica

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

        if not dinamica:
            densidad = 0

        shape = box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2))
        shape.SetAsBox(self._ancho/2.0, self._alto/2.0)
        fixture = box2d.b2FixtureDef(shape=shape,
                                     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

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

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor

        if not dinamica:
            self._cuerpo.mass = 1000000
Beispiel #35
0
def abox(world, x, y, w, h):
    sd = box2d.b2PolygonShape()
    sd.SetAsBox(w, h)
    sd.density = 2.0
    sd.friction = 0.3
    sd.restitution = 0.2

    bd = box2d.b2BodyDef()
    bd.position = (x, y)
    body = world.CreateDynamicBody(position=(x, y))
    # body = world.CreateBody(bd)
    groundBoxFixture = box2d.b2FixtureDef(shape=sd)
    body.CreateFixture(groundBoxFixture)
    body.ResetMassData()
    body.inertia = .02
    body.mass = 1
    return body
Beispiel #36
0
def abox(world, x, y, w, h):
    sd=box2d.b2PolygonShape()
    sd.SetAsBox(w, h)
    sd.density = 2.0
    sd.friction = 0.3
    sd.restitution = 0.2

    bd=box2d.b2BodyDef()
    bd.position = (x, y)
    body = world.CreateDynamicBody(position=(x,y))
    # body = world.CreateBody(bd)
    groundBoxFixture=box2d.b2FixtureDef(shape=sd)
    body.CreateFixture(groundBoxFixture)
    body.ResetMassData()
    body.inertia = .02
    body.mass = 1
    return body
Beispiel #37
0
    def __crear_fixture(self):
        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2)),
                                     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 #38
0
    def __init__(self, x0, target):
        super(PointMassWorld, self).__init__()
        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = b2.b2_pi
        self.initial_linear_velocity = (x0[2], x0[3])
        self.initial_angular_velocity = 0

        ground = self.world.CreateBody(position=(0, 20))
        ground.CreateEdgeChain(
            [(-20, -20),
             (-20, 20),
             (20, 20),
             (20, -20),
             (-20, -20)]
            )

        xf1 = b2.b2Transform()
        xf1.angle = 0.3524 * b2.b2_pi
        xf1.position = b2.b2Mul(xf1.R, (1.0, 0.0))

        xf2 = b2.b2Transform()
        xf2.angle = -0.3524 * b2.b2_pi
        xf2.position = b2.b2Mul(xf2.R, (-1.0, 0.0))
        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            angularDamping=5,
            linearDamping=0.1,
            shapes=[b2.b2PolygonShape(vertices=[xf1*(-1, 0),
                                                xf1*(1, 0), xf1*(0, .5)]),
                    b2.b2PolygonShape(vertices=[xf2*(-1, 0),
                                                xf2*(1, 0), xf2*(0, .5)])],
            shapeFixture=b2.b2FixtureDef(density=1.0),
        )
        self.target = self.world.CreateStaticBody(
            position=target,
            angle=self.initial_angle,
            shapes=[b2.b2PolygonShape(vertices=[xf1*(-1, 0), xf1*(1, 0),
                                                xf1*(0, .5)]),
                    b2.b2PolygonShape(vertices=[xf2*(-1, 0), xf2*(1, 0),
                                                xf2*(0, .5)])],
        )
        self.target.active = False
Beispiel #39
0
def geraBody(world, obj):
    bodyDef = b2.b2BodyDef()
    bodyDef.position = obj["pos"]
    bodyDef.type = obj["type"]
    bodyDef.angle = obj["angle"]

    body = world.CreateBody(bodyDef)

    fixDef = b2.b2FixtureDef()
    fixDef.shape = obj["shape"]
    fixDef.restitution = obj["restitution"]
    fixDef.friction = obj["friction"]
    fixDef.density = obj["density"]
    body.CreateFixture(fixDef)

    body.userData = obj

    return body
def createBoxFixture(body, pos = (0,0), width=1.0, height=1.0, dynamic=True, collisionGroup = None, restitution=None):
    global world
    boxShape = Box2D.b2PolygonShape()
    boxShape.SetAsBox(width, height, pos, 0)    # width, height, position (x,y), angle 
    fixtureDef = Box2D.b2FixtureDef()
    fixtureDef.shape = boxShape

    fixtureDef.friction = 0.3
    if(abs(world.gravity[1]) > 1):
        fixtureDef.restitution = 0.6

    if(restitution != None): fixtureDef.restitution = restitution

    if(collisionGroup!=None): fixtureDef.filter.groupIndex = collisionGroup
    
    if dynamic: fixtureDef.density = 1
    else:       fixtureDef.density = 0            
    return fixtureDef
Beispiel #41
0
    def create_obstacle(self, obstacle_spec):

        obstacle_body_def = Box2D.b2BodyDef()
        obstacle_body_def.position = (0, 0)

        obstacle_body = self.world.CreateBody(obstacle_body_def)

        v = []
        for vertex in obstacle_spec["geometry"]['coordinates']:
            v.append((vertex[0], vertex[1]))

        obstacle_box = Box2D.b2PolygonShape(vertices=v)
        obstacle_box_fixture = Box2D.b2FixtureDef(shape=obstacle_box)
        
        if "properties" in obstacle_spec:
            if obstacle_spec["properties"]['collisionGroup']:
                obstacle_box_fixture.filter.groupIndex = obstacle_spec["properties"]['collisionGroup']

        obstacle_body.CreateFixture(obstacle_box_fixture)
Beispiel #42
0
    def definir_escala(self, escala):
        self._escala = escala
        self.vertices = [(convertir_a_metros(x1) * self._escala, convertir_a_metros(y1) * self._escala) for (x1, y1) in self.puntos]
        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(vertices=self.vertices),
                                     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 #43
0
def add_asteroid_play_space(world: Box2D.b2World, left_border: float,
                            right_border: float, bottom_border: float,
                            top_border: float):
    fixture_shape = Box2D.b2PolygonShape()
    width = right_border - left_border + PLAYSPACE_PADDING
    height = top_border - bottom_border + PLAYSPACE_PADDING
    fixture_shape.SetAsBox(
        width, height,
        Box2D.b2Vec2(left_border + width / 2, bottom_border + height / 2), 0)

    fixture_def = Box2D.b2FixtureDef()
    fixture_def.shape = fixture_shape
    fixture_def.isSensor = True

    play_space_body_def = Box2D.b2BodyDef()
    play_space_body_def.fixtures = [fixture_def]
    play_space_body_def.type = Box2D.b2_staticBody
    play_space_body_def.position = (0, 0)

    return world.CreateBody(play_space_body_def)
Beispiel #44
0
def createTri(position, r=0.3, dynamic=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
    bodyDef.linearDamping = 70
    bodyDef.angularDamping = 50
    body = world.CreateBody(bodyDef)
    v = [(-r,-r),(0,r),(r,-r)]
    fixture = body.CreateFixture(shape=Box2D.b2PolygonShape(vertices=v), density=1.0, friction=0.3)
    body.userData = {"name":"tri"}

    return body
Beispiel #45
0
    def test_helloworld(self):
        gravity = Box2D.b2Vec2(0, -10)
         
        doSleep = True
         
        world = Box2D.b2World(gravity, doSleep)

        groundBodyDef = Box2D.b2BodyDef()
        groundBodyDef.position = [0, -10]
         
        groundBody = world.CreateBody(groundBodyDef)
         
        groundBox = Box2D.b2PolygonShape()
         
        groundBox.SetAsBox(50, 10)
         
        groundBody.CreateFixturesFromShapes(groundBox)
         
        bodyDef = Box2D.b2BodyDef()
        bodyDef.type = Box2D.b2_dynamicBody
        bodyDef.position = (0, 4)
        body = world.CreateBody(bodyDef)
         
        dynamicBox = Box2D.b2PolygonShape()
        dynamicBox.SetAsBox(1, 1)

        fixtureDef = Box2D.b2FixtureDef()
        fixtureDef.shape = dynamicBox

        fixtureDef.density = 1
         
        fixtureDef.friction = 0.3
         
        body.CreateFixture(fixtureDef)
         
        timeStep = 1.0 / 60
        vel_iters, pos_iters = 6, 2

        for i in range(60):
            world.Step(timeStep, vel_iters, pos_iters)
            world.ClearForces()
Beispiel #46
0
    def test_helloworld(self):
        gravity = Box2D.b2Vec2(0, -10)

        doSleep = True

        world = Box2D.b2World(gravity, doSleep)

        groundBodyDef = Box2D.b2BodyDef()
        groundBodyDef.position = [0, -10]

        groundBody = world.CreateBody(groundBodyDef)

        groundBox = Box2D.b2PolygonShape()

        groundBox.SetAsBox(50, 10)

        groundBody.CreateFixturesFromShapes(groundBox)

        bodyDef = Box2D.b2BodyDef()
        bodyDef.type = Box2D.b2_dynamicBody
        bodyDef.position = (0, 4)
        body = world.CreateBody(bodyDef)

        dynamicBox = Box2D.b2PolygonShape()
        dynamicBox.SetAsBox(1, 1)

        fixtureDef = Box2D.b2FixtureDef()
        fixtureDef.shape = dynamicBox

        fixtureDef.density = 1

        fixtureDef.friction = 0.3

        body.CreateFixture(fixtureDef)

        timeStep = 1.0 / 60
        vel_iters, pos_iters = 6, 2

        for i in range(60):
            world.Step(timeStep, vel_iters, pos_iters)
            world.ClearForces()
Beispiel #47
0
    def __init__(self, x, y, ancho, alto, dinamica=True, densidad=1.0,
            restitucion=0.5, friccion=.2, amortiguacion=0.1,
            fisica=None, sin_rotacion=False):

        Figura.__init__(self)

        x = convertir_a_metros(x)
        y = convertir_a_metros(y)
        self._ancho = convertir_a_metros(ancho)
        self._alto = convertir_a_metros(alto)
        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.b2PolygonShape(box=(self._ancho/2, self._alto/2)),
                                     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
    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
def createTri(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
    bodyDef.linearDamping = 70
    bodyDef.angularDamping = 50
    body = world.CreateBody(bodyDef)
    v = [(-r,-r),(0,r),(r,-r)]
    fixture = body.CreateFixture(shape=Box2D.b2PolygonShape(vertices=v), density=1.0, friction=0.3)
    
    if(bMatplotlib): 
        createGlobalFigure()
        fixture.userData = drawTri(ax,position,r)
    
    return body
Beispiel #50
0
def _create_fixtures(left_border : float, right_border : float, bottom_border : float, top_border : float):
    # create in clockwise rotation so the edges face inwards
    vertices = (
        (left_border, bottom_border),
        (left_border, top_border),
        (right_border, top_border),
        (right_border, bottom_border)
    )
    fixture_defs = []
    for i, _ in enumerate(vertices):
        next_i = (i + 1) % 4

        side_border_shape = Box2D.b2EdgeShape()
        side_border_shape.vertex1 = vertices[i]
        side_border_shape.vertex2 = vertices[next_i]

        border_fixture_def = Box2D.b2FixtureDef()
        border_fixture_def.shape = side_border_shape
        border_fixture_def.friction = 0
        border_fixture_def.density = 0
        border_fixture_def.filter.categoryBits = CollisionFilterCategory.BORDER
        fixture_defs.append(border_fixture_def)
    
    return fixture_defs
Beispiel #51
0
def runsim(GD, locs, seed, mapgen, vel, frames, slowmo = 1):
    random.seed(seed)
    # Define the size of the world. Simulation will still work
    # if bodies reach the end of the world, but it will be slower.
    worldAABB=box2d.b2AABB()
    worldAABB.lowerBound = (-100, -100)
    worldAABB.upperBound = ( 100,  100)

    # Define the gravity vector.
    gravity = box2d.b2Vec2(0, -10)
     
    # Do we want to let bodies sleep?
    doSleep = False
     
    # Construct a world object, which will hold and simulate the rigid bodies.
    world = box2d.b2World(gravity, doSleep)

    if 1:
        sd=box2d.b2PolygonShape()
        sd.SetAsBox(50.0, 10.0)
        
        bd=box2d.b2BodyDef()
        bd.position = (0.0, -10.05)
        ground = world.CreateBody(bd)
        groundBoxFixture=box2d.b2FixtureDef(shape=sd)
        ground.CreateFixture(groundBoxFixture)
    else:
        # Define the ground body.
        groundBodyDef = box2d.b2BodyDef()
        groundBodyDef.position = [0, -10]
         
        # Call the body factory which allocates memory for the ground body
        # from a pool and creates the ground box shape (also from a pool).
        # The body is also added to the world.
        groundBody = world.CreateBody(groundBodyDef)
         
        # Define the ground box shape.
        groundShapeDef = box2d.b2PolygonShape()
         
        # The extents are the half-widths of the box.
        groundShapeDef.SetAsBox(50, 10)
         
        # Add the ground shape to the ground body.
        help(groundBody)
        groundBody.CreateShape(groundShapeDef)
     
    bodies = [b for b in mapgen(world)]

    # Prepare for simulation. Typically we use a time step of 1/60 of a
    # second (60Hz) and 10 velocity/8 position iterations. This provides a 
    # high quality simulation in most game scenarios.
    timeStep = 1.0 / 60
    vel_iters, pos_iters = 10, 8
    vel_iters, pos_iters = 1000, 1000
     
    # class MyContactListener(box2d.b2ContactListener):
    #     def __init__(self):
    #         self.contact = False
    #         super(MyContactListener, self).__init__()
    #     def Add(self, point):
    #         if box2d.b2CircleShape in (type(point.shape1), type(point.shape2)):
    #             self.contact = True
    # contactListener = MyContactListener()
    # world.SetContactListener(contactListener)

    def bodxy(b):
        x,y = int((220 + 60 * (b.position.x + ox))), int((270 - 60 * (b.position.y + oy)))
        return x - 16,y-16

    bullet = None
    yground = 265
    time = 0.0

    for f in range(800):
        t = min(1, f / 400.)
        xorg = -900 + 900 * smoothstep(t)
        # GD.scrollxy(xorg, 0)
        # COMM+0   SCROLL_X for top section
        # COMM+2   SCROLL_Y for top section
        # COMM+4   Y-coordinate of start of middle section
        # COMM+6   SCROLL_X for middle section
        # COMM+8   SCROLL_Y for middle section
        # COMM+10  Y-coordinate of start of bottom section
        # COMM+12  SCROLL_X for bottom section
        # COMM+14  SCROLL_Y for bottom section
        GD.wrstr(gd.COMM, array.array('H', [
            int(xorg / 4) & 511, 0,
            90,
            int(xorg / 2) & 511,0,
            34 * 8,
            int(xorg) & 511,0]))
        world.Step(timeStep, vel_iters, pos_iters)
        for i,b in enumerate(bodies):
            (ox, oy) = (0,0)
            x,y = bodxy(b)
            a = (f/4) % 120
            a = int(30 * b.angle / (math.pi / 2)) % 120
            fr = a % 30
            rot = (a/30) % 4
            tab = ([0,1,2,3],
                   [1,3,0,2],
                   [3,2,1,0],
                   [2,0,3,1])[rot]
            for j in range(4):
                frame,pal = locs[4*fr+tab[j]]
                GD.sprite(4 * i + j,
                          x + (16 * (j % 2)) - xorg,
                          y + 16 * (j / 2), frame, pal,
                          [0,3,6,5][rot])
        if bullet:
            x,y = bodxy(bullet)
            GD.sprite(255, x + 8, y + 8, 63, 0)
        GD.sync_spr()
        GD.wait()
        time += timeStep
        if f == 400:
            GD.pause()
            bullet = aball(world, -4, 0, .1)
            bullet.mass = 9
            bullet.linearVelocity = box2d.b2Vec2(8,4) * 1
Beispiel #52
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
#for val1,val2 in tail:
#    print val1,val2
tailm = [(val1 / PPM, val2 / PPM) for val1, val2 in tail]
bottomm = [(val1 / PPM, val2 / PPM) for val1, val2 in bottom]
topm = [(val1 / PPM, val2 / PPM) for val1, val2 in top]
nosem = [(val1 / PPM, val2 / PPM) for val1, val2 in nose]
#print tailm
#print bottomm
body = world.CreateDynamicBody(
    position=(10, 10),
    angle=pi,
    angularDamping=5,
    linearDamping=0.1,
    shapes=[Box2D.b2PolygonShape(vertices=tailm)],
    #Box2D.b2PolygonShape(vertices=restm) ],
    shapeFixture=Box2D.b2FixtureDef(density=20.0),
)
#body=world.CreateDynamicBody(position=(13,10), angle=0)
#crusaderTail=body.CreatePolygonFixture(
#                                       Box2D.b2PolygonShape(vertices=[(-1,0), (1,0), (0,.5)])
#                                       , density=1, friction=0.3)

#body=world.CreateDynamicBody(position=(13,14), angle=0)
#crusaderTail=body.CreatePolygonFixture(rest, density=1, friction=0.3)

colors = {
    staticBody: (255, 255, 255, 255),
    dynamicBody: (127, 127, 127, 255),
}
strips = getSpriteStrips()
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 #55
0
    def __init__(self, x0, target):
        super(Arm3World, self).__init__()

        self.world.gravity = (0.0, 0.0)

        fixture_length = 5.0
        self.x0 = x0

        rectangle_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(.5, fixture_length)),
            density=.5,
            friction=1,
        )
        square_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(1, 1)),
            density=100.0,
            friction=1,
        )
        self.base = self.world.CreateBody(
            position=(0, 15),
            fixtures=square_fixture,
        )

        self.body1 = self.world.CreateDynamicBody(
            position=(0, 2),
            fixtures=rectangle_fixture,
            angle=b2.b2_pi,
        )
        self.body2 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 2),
            angle=b2.b2_pi,
        )
        self.body3 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 2),
            angle=b2.b2_pi,
        )


        self.target1 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 0),
            angle=b2.b2_pi,
        )
        self.target2 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 0),
            angle=b2.b2_pi,
        )
        self.target3 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 0),
            angle=b2.b2_pi,
        )

        self.joint1 = self.world.CreateRevoluteJoint(
            bodyA=self.base,
            bodyB=self.body1,
            localAnchorA=(0, 0),
            localAnchorB=(0, fixture_length),
            enableMotor=True,
            maxMotorTorque=400,
            enableLimit=False,
        )

        self.joint2 = self.world.CreateRevoluteJoint(
            bodyA=self.body1,
            bodyB=self.body2,
            localAnchorA=(0, -(fixture_length - 0.5)),
            localAnchorB=(0, fixture_length - 0.5),
            enableMotor=True,
            maxMotorTorque=400,
            enableLimit=False,
        )

        self.joint3 = self.world.CreateRevoluteJoint(
            bodyA=self.body2,
            bodyB=self.body3,
            localAnchorA=(0, -(fixture_length - 0.5)),
            localAnchorB=(0, fixture_length - 0.5),
            enableMotor=True,
            maxMotorTorque=400,
            enableLimit=False,
        )

        self.set_joint_angles(self.body1, self.body2, self.body3, x0[0], x0[1], x0[2] )
        self.set_joint_angles(self.target1, self.target2, self.target3, target[0], target[1], target[2] )
        self.target1.active = False
        self.target2.active = False

        self.joint1.motorSpeed = x0[3]
        self.joint2.motorSpeed = x0[4]
        self.joint3.motorSpeed = x0[5]
Beispiel #56
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 #57
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 #58
0
    def _create_robotarm(self, arm_position=None):
        """
    Creates the robotic arm.
    :param arm_position: Initial angular position
    :return:
    """
        arm_pose = self._calculate_arm_pose(arm_position)
        link0 = self.world.CreateDynamicBody(
            position=arm_pose['link0_center'],
            angle=arm_pose['link0_angle'],
            bullet=True,
            allowSleep=False,
            userData={'name': 'link0'},
            fixtures=b2.b2FixtureDef(
                shape=b2.b2PolygonShape(box=(self.params.LINK_THICKNESS,
                                             self.params.LINK_0_LENGTH / 2)),
                density=5,
                friction=self.params.LINK_FRICTION,
                restitution=self.params.LINK_ELASTICITY))

        # The -.1 in the position is so that the two links can overlap in order to create the joint
        link1 = self.world.CreateDynamicBody(
            position=arm_pose['link1_center'],
            angle=arm_pose['link1_angle'],
            bullet=True,
            allowSleep=False,
            userData={'name': 'link1'},
            fixtures=b2.b2FixtureDef(
                shape=b2.b2PolygonShape(box=(self.params.LINK_THICKNESS,
                                             self.params.LINK_1_LENGTH / 2)),
                density=1,
                friction=self.params.LINK_FRICTION,
                restitution=self.params.LINK_ELASTICITY))

        jointW0 = self.world.CreateRevoluteJoint(
            bodyA=self.walls[3],
            bodyB=link0,
            anchor=self.walls[3].worldCenter,
            lowerAngle=-.4 * b2.b2_pi - arm_pose['link0_angle'],
            upperAngle=.4 * b2.b2_pi - arm_pose['link0_angle'],
            enableLimit=True,
            maxMotorTorque=100.0,
            motorSpeed=0.0,
            enableMotor=True)

        joint01 = self.world.CreateRevoluteJoint(
            bodyA=link0,
            bodyB=link1,
            anchor=arm_pose['joint01_center'],
            lowerAngle=-b2.b2_pi * 0.9 + arm_pose['link0_angle'] -
            arm_pose['link1_angle'],
            upperAngle=b2.b2_pi * 0.9 + arm_pose['link0_angle'] -
            arm_pose['link1_angle'],
            enableLimit=True,
            maxMotorTorque=100.0,
            motorSpeed=0.0,
            enableMotor=True)

        ## Arm definition with links and joints
        self.arm = {
            'link0': link0,
            'link1': link1,
            'joint01': joint01,
            'jointW0': jointW0
        }
Beispiel #59
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