def create_walls(): wall1_poly = pymunk.Poly.create_box(None, size=(10, full_height * 1.1)) wall1_poly.collision_type = Coll_Type.ENVIRONMENT wall1_poly_moment = pymunk.moment_for_poly(250, wall1_poly.get_vertices()) wall1_body = pymunk.Body(250, wall1_poly_moment, pymunk.Body.STATIC) wall1_poly.body = wall1_body wall1_body.position = 0, 0 space.add(wall1_poly, wall1_body) wall2_poly = pymunk.Poly.create_box(None, size=(full_width * 2.3, 10)) wall2_poly.collision_type = Coll_Type.ENVIRONMENT wall2_poly_moment = pymunk.moment_for_poly(250, wall2_poly.get_vertices()) wall2_body = pymunk.Body(250, wall2_poly_moment, pymunk.Body.STATIC) wall2_poly.body = wall2_body wall2_body.position = 0, full_height space.add(wall2_poly, wall2_body) wall3_poly = pymunk.Poly.create_box(None, size=(10, full_height * 2.3)) wall3_poly.collision_type = Coll_Type.ENVIRONMENT wall3_poly_moment = pymunk.moment_for_poly(250, wall3_poly.get_vertices()) wall3_body = pymunk.Body(250, wall3_poly_moment, pymunk.Body.STATIC) wall3_poly.body = wall3_body wall3_body.position = full_width, 0 space.add(wall3_poly, wall3_body) wall4_poly = pymunk.Poly.create_box(None, size=(full_width * 1.1, 10)) wall4_poly.collision_type = Coll_Type.ENVIRONMENT wall4_poly_moment = pymunk.moment_for_poly(250, wall4_poly.get_vertices()) wall4_body = pymunk.Body(250, wall4_poly_moment, pymunk.Body.STATIC) wall4_poly.body = wall4_body wall4_body.position = 0, 0 space.add(wall4_poly, wall4_body)
def __init_physiscs__(self): image_width = self.image.get_max_width() * 0.8 offset = self.image.get_max_width() - image_width vs = [(offset, 0), (image_width, 0), (image_width, 64), (offset, 64)] mass = 30 moment = pymunk.moment_for_poly(mass, vs) self.body = pymunk.Body(mass, pymunk.inf) self.shape = pymunk.Poly(self.body, vs) self.shape.friction = 0 self.shape.collision_type = 20 self.shape.elasticity = 0 self.body.position = (segment_width * self.initial_positition[0], self.initial_positition[0] * segment_height) self.body.center_of_gravity = 20, 0 self.body.velocity_func = self.limit_velocity self.body.min_walk_x, self.body.max_walk_x = 0, 0 self.body.current_max_velocity = Enemy.max_relative_velocity self.body.touching_ground = False self.moving_force = (40000, 0) self.space.add(self.body, self.shape) # Collison handlers self.platform_collision_handler = self.space.add_collision_handler( 20, 3) self.player_collision_handler = self.space.add_collision_handler(20, 1) self.player_collision_handler.pre_solve = Enemy.attack self.player_collision_handler.separate = Enemy.cease_attack self.platform_collision_handler.pre_solve = Enemy.standing_on_platform self.platform_collision_handler.separate = Enemy.separated_from_platform self.body.attack = False
def __init__(self, pos=(0, 0), color=Color.RED, idn=0, client_id=0): self.alive = True self.hp = 100 self.ammo1 = 40 self.ammo2 = 5 self.isReloading = False self.color = color self.rotating = False self.moving = False self.idn = idn self.CLIENT_ID = client_id self.ammo_type = SharedProjectile.Ammo_Type.REGULAR self.command = SharedTank.Command.NOTHING self.poly = pymunk.Poly.create_box(None, size=(SharedTank.HEIGHT, SharedTank.WIDTH), radius=0.1) self.poly.collision_type = Coll_Type.TANK self.poly.idn = self.idn self.moment = pymunk.moment_for_poly(50000, self.poly.get_vertices()) self.body = pymunk.Body(50000, self.moment, pymunk.Body.DYNAMIC) self.poly.body = self.body self.body.position = pos barrelImg = pyglet.image.load("res/PNG/tanks/barrel%s_outline.png" % color.value) barrelImg.anchor_x = barrelImg.width // 2 barrelImg.anchor_y = (barrelImg.height // 2) - 15 self.barrelSprite = FakeSprite((pos[0], pos[1])) space.add(self.poly, self.body)
def __init__(self,cellspace,num,pos,angle,radius=4,mass=0.1,**kwargs): ##{{{ ## Cell Attributes super(cellc, self).__init__(cellspace,num,pos,angle,**kwargs) self.radius=radius #Radius of hemisphere at cell end self.length=self.radius*2 #The length of the cell measured from the center of the two hemisphere self.height=self.radius*2 #The height of the box connecting the two hemisphere. = diameter self.mass=mass #Self Explanatory self.color="red" self.growthrate=0.5 #Growth rate can be a function of a state variable eventually self.cycle='grow' for i in kwargs.iterkeys(): vars(self)[i]=kwargs[i] ## Initializing cell in space inertia=pm.moment_for_poly(self.mass,\ [(-self.length/2.0,-self.height/2.0), (-self.length/2.0,self.height/2.0), (self.length/2.0,self.height/2.0), (self.length/2.0,-self.height/2.0)],\ (0,0)) self.body=pm.Body(self.mass,inertia) self.body.position = pos self.body.angle = angle #----------- self.box = pm.Poly(self.body, [(0,0), (0,self.height), (self.length,self.height), (self.length,0)],\ (-self.length/2.,-self.height/2.)) # Connecting box self.left = pm.Circle(self.body,self.radius,(-self.length/2.,0)) # left hemisphere self.right = pm.Circle(self.body,self.radius,(self.length/2.,0)) # right hemisphere #----------- self.left.color=self.right.color=self.box.color = pg.color.THECOLORS[self.color] self.space.add(self.body, self.left, self.right, self.box)
def __init__(self,cellspace,num,pos,angle,radius=5,length=None,vertices=6,mass=0.1,biochem=None,**kwargs): ##{{{ ## Cell Attributes super(cellp, self).__init__(cellspace,num,pos,angle,biochem=biochem,**kwargs) self.radius=radius #Radius of hemisphere at cell end. Radius is in uM self.length=radius*2 if length is None else length #The length of the cell measured from the center of the two hemisphere self.height=self.radius*2 self.vertices=vertices #Number of vertices in the hemisphere self.mass=mass #Self Explanatory self.color=pg.color.THECOLORS["red"] self.growthrate=0.05 #Growth rate can be a function of a state variable eventually. um/s growth in length self.divmean=4.*self.radius #Threshold for division self.divstd=0.1*self.divmean self.divthreshold=self.divmean+self.divstd*np.random.randn(1) #Threshold decided at the start to reduce computational cost self.cycle='grow' self.kwargs=kwargs # This is done so that when the cell divides, any special attribute # will be transfered to the daughter cell. for i in kwargs.iterkeys(): vars(self)[i]=kwargs[i] ## Initializing cell in space self._genpoly() inertia=pm.moment_for_poly(self.mass,self.ver, (0,0)) self.body=pm.Body(self.mass,inertia) self.body.position = pos self.body.angle = angle #----------- self.box = pm.Poly(self.body,self.ver,(-self.length/2.,-self.height/2.)) # Connecting box #----------- self.box.elasticity=0.5 self.box.friction=0 self.box.color = self.color self.space.add(self.body, self.box)
def create_square_thing(world, layer, position, image): points = [(0,0),(32,0),(32,32),(0,32)] shape = ConvexPolygonShape(*points) shape.translate( shape.centroid() * -1) moment = pymunk.moment_for_poly( 1.0, shape.vertices ) rv = Debris( world, layer, position, shape, image, moment = moment, collision_type = physics.CollisionTypes["main"] ) return rv
def __init__(self, position): super(Player, self).__init__() self.v1 = 50 self.v2 = 15 #Pymunk physics variables. self.verts = [(-self.v2, -self.v1), (-self.v2, self.v1), (self.v2, self.v1), (self.v2, -self.v1)] self.mass = 100 self.friction = 9 self.elasticity = 0 self.moment = pymunk.moment_for_poly(self.mass, self.verts) self.body = pymunk.Body(self.mass, self.moment) self.body.position = position self.shape = pymunk.Poly(self.body, self.verts) #self.shape.group = 1 #self.shape.layers = 1 #self.shape.collision_type = 1 self.shape.friction = 0.1 self.shape.elasticity = 0.9 self.shape.collision_type = 2 self.pin_body = pymunk.Body() self.pin_body.position = self.body.position self.spring = pymunk.DampedRotarySpring(self.body, self.pin_body, 0, 20000000, 900000) self.groove_body = pymunk.Body() self.groove_body.position = (self.body.position.x, 0) self.groove = pymunk.GrooveJoint(self.groove_body, self.body, (0, 0), (0, 768), (0,0))
def create_bananas(space): mass = 10 size = 50 points = [(-size, -size), (-size, size), (size,size), (size, -size)] moment = pymunk.moment_for_poly(mass, points, (0,0)) body = pymunk.Body(mass, moment) x = random.randint(0, 500) body.position = Vec2d(x,x) banana = pymunk.Poly(body, points, (0,0)) #banana.friction = 2 banana.elasticity = 0.95 space.add(body, banana) """ Circular Banana radius = 10 inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0)) body = pymunk.Body(mass, inertia) x = random.randint(0, 500) body.position = x, x banana = pymunk.Circle(body, radius, (0, 0)) banana.elasticity = 0.95 space.add(body, banana) """ return banana
def generateBodyAndShape(self, physObj, body=None, rel_pos=(0, 0)): if body is None: moment = pymunk.moment_for_poly(physObj.mass, self.verts) body = pymunk.Body( physObj.mass, moment, body_type=pymunk.Body.STATIC if physObj.static else pymunk.Body.DYNAMIC ) shape = pymunk.Poly( body, self.verts, transform=pymunk.Transform( a=np.cos(physObj.rotation), b=np.sin(physObj.rotation), c=-np.sin(physObj.rotation), d=np.cos(physObj.rotation), tx=rel_pos[0], ty=rel_pos[1], ), ) shape.friction = physObj.friction_coefficient shape.elasticity = physObj.restitution_coefficient shape.collision_type = 1 shape.sensor = physObj.sensor from ev3sim.objects.base import STATIC_CATEGORY, DYNAMIC_CATEGORY shape.filter = pymunk.ShapeFilter(categories=STATIC_CATEGORY if physObj.static else DYNAMIC_CATEGORY) return body, shape
def create_world(self): fp = [(self.tray_width / 2, -self.tray_height / 2), (-self.tray_width / 2, self.tray_height / 2), (self.tray_width / 2, self.tray_height / 2), (-self.tray_width / 2, -self.tray_height / 2), (-self.tray_width / 2, -self.tray_height / 2)] mass = 100 moment = pymunk.moment_for_poly(mass, fp[0:2]) self.trayBody = pymunk.Body(mass, moment) self.trayBody.position = self.tray_x_pos, self.tray_y_pos self.trayBody.angle = self.tray_angle trayShape = pymunk.Poly(self.trayBody, fp) if self.tray_has_ends: side1 = [(self.tray_width / 2, self.tray_height / 2), (self.tray_width / 2, self.tray_height * 4), (self.tray_width / 2 - 1, self.tray_height * 4), (self.tray_width / 2 - 1, self.tray_height / 2)] side2 = [(-self.tray_width / 2, self.tray_height / 2), (-self.tray_width / 2, self.tray_height * 4), (-self.tray_width / 2 + 1, self.tray_height * 4), (-self.tray_width / 2 + 1, -self.tray_height / 2)] self.side1_shape = pymunk.Poly(self.trayBody, side1) self.side2_shape = pymunk.Poly(self.trayBody, side2) self.space.add(self.side1_shape, self.side2_shape) self.space.add(self.trayBody, trayShape) trayJointBody = pymunk.Body(body_type=pymunk.Body.KINEMATIC) trayJointBody.position = self.trayBody.position j = pymunk.PinJoint(self.trayBody, trayJointBody, (0, 0), (0, 0)) self.space.add(j) self.__add_ball()
def add_dynamic_structure(self, pos, walls, segments, name, mass, center_of_gravity, action_on_touch=None, is_slippery_slope=False, correct_angle=False): points = [] for a, b in walls: points.append(a) points.append(b) moment = pymunk.moment_for_poly(mass, points, radius=1) body = pymunk.Body(mass, moment, pymunk.Body.DYNAMIC) body.center_of_gravity = center_of_gravity body.position = pos self.reindex_shapes_for_body(body) self._add_structure(pos, walls, segments, name, action_on_touch, is_slippery_slope, body, (0.7, 1))
def __init__(self): self.type = 'attractor' self.radius = 320000 self.density = 0.5 self.mass = self.density * (math.pi * (self.radius * self.radius)) # size = self.radius self.points = make_circle(self.radius, 314) inertia = pymunk.moment_for_poly(self.mass, self.points, (0, 0)) self.body = pymunk.Body(self.mass, inertia) # self.body.position = position self.body.position = 1, 1 # self.body.apply_impulse_at_local_point(velocity, [0,0]) self.shape = pymunk.Poly(self.body, self.points) #inertia = pymunk.moment_for_circle(self.mass, 0, self.radius, (0,0)) #self.body = pymunk.Body(self.mass, inertia) #self.shape = pymunk.Circle(self.body, self.radius, (0,0)) self.shape.friction = 0.5 self.color = (190, 165, 145) self.atmosphere = Atmosphere(self)
def __init__(self, pos=(0, 0), color=Color.RED, idn=0, src_idn=0, client_id=0, type=Ammo_Type.REGULAR): self.idn = idn self.src_idn = src_idn self.CLIENT_ID = client_id self.color = color self.type = type self.damage = 10 self.velocity = 1000 if self.type == SharedProjectile.Ammo_Type.AP: self.damage = 34 self.velocity = 1500 self.poly = pymunk.Poly.create_box(None, size=(SharedProjectile.HEIGHT, SharedProjectile.WIDTH)) self.poly.collision_type = Coll_Type.PROJECTILE self.poly.idn = self.idn self.moment = pymunk.moment_for_poly(25, self.poly.get_vertices()) self.body = pymunk.Body(25, self.moment, pymunk.Body.DYNAMIC) self.poly.body = self.body self.body.position = pos space.add(self.poly, self.body)
def add_square(self, pos, a=18, density=0.1, friction=0.2, elasticity=0.3): """ Adding a Square | Note that a is actually half a side, due to vector easyness :) Parameter: pos == (int(x), int(y)) Optional: a == (sidelen/2) | #physical_parameters Returns: pymunk.Shape() (=> .Poly()) """ mass = density * (a * a * 4) # Square Vectors (Clockwise) verts = [Vec2d(-a,-a), Vec2d(-a, a), Vec2d(a, a), Vec2d(a,-a)] # Square Physic Settings inertia = pm.moment_for_poly(mass, verts, Vec2d(0,0)) # Create Body body = pm.Body(mass, inertia) body.position = self.Vec2df(pos) # Create Shape shape = pm.Poly(body, verts, Vec2d(0,0)) shape.riction = friction shape.elasticity = elasticity shape.color = self.get_color() shape.color2 = self.get_color() # Append to Space self.space.add(body, shape) self.element_count += 1 return shape
def __init__(self, position, velocity): self.type = 'actor' self.mass = 0 self.points = [] self.modules = [] self.modules.append(Module([6, 0])) self.modules.append(Module([-6, 0])) for module in self.modules: self.mass += module.mass self.points += module.points # print self.mass # print self.points inertia = pymunk.moment_for_poly(self.mass, self.points, (0, 0)) self.body = pymunk.Body(self.mass, inertia) self.body.position = position self.body.apply_impulse_at_local_point(velocity, [0, 0]) self.shape = pymunk.Poly(self.body, self.points) self.shape.friction = 0.5 self.orbit = None #initpos_to_orbit(self.) self.freefalling = True self.interacting = False self.color = (200, 50, 50) self.image = None #preprocessed image used to 'blit' onto the screen. self.availableResources = {}
def _build_physics_elements(self): self.dynamic_object = [] for element in self.collect_object_list: width, height = element.size mass = width * height if element.is_circle: moment = pymunk.moment_for_circle(mass, 0, 100) body = pymunk.Body(mass, moment) shape = pymunk.Circle(body, width/2) body.elasticity = 0.9 else: vs = [(-width/2, height/2), (width/2, height/2), (width/2, -height/2), (-width/2, -height/2)] moment = pymunk.moment_for_poly(mass, vs) body = pymunk.Body(mass, moment) shape = pymunk.Poly(body, vs) shape.friction = 0.6 body.position = element.position[0]+width/2, self.flipy(element.position[1]+height/2) body.angle = math.pi self.space.add(body, shape) self.dynamic_object.append((element, shape)) static_body = pymunk.Body() for element in self.collide_object_list: x, y = element.position[0], self.flipy(element.position[1]) width, height = element.size[0], element.size[1] static_lines = [pymunk.Segment(static_body, (x, y), (x+width, y), 0.0), pymunk.Segment(static_body, (x+width, y), (x+width, y-height), 0.0), pymunk.Segment(static_body, (x+width, y-height), (x, y-height), 0.0), pymunk.Segment(static_body, (x, y-height), (x, y), 0.0), ] for l in static_lines: l.friction = 0.5 self.space.add(static_lines)
def create_body_poly(self, mass, posinit, points): center = pm.util.calc_center(points) points = pm.util.poly_vectors_around_center(points) moment = pm.moment_for_poly(mass,points, Vec2d(0,0)) body = pm.Body(mass, moment) body.position = Vec2d(posinit) return body, points
def __init__(self,x=600,y=-20,angle=0,angular_velocity=0,buoyancy=pymunk.Vec2d(0,-8000)): pygame.sprite.Sprite.__init__(self) self.image_default = pygame.image.load("images/airship-balloon.png").convert() self.image_default.set_colorkey((1,0,0)) self.image = self.image_default self.rect = self.image.get_rect() self.rect.center = (x, y) offset = (0,0) # center of gravity points = [(-210, -7), (-196, -24), (-82, -56), (-26, -60), (27, -60), (83, -56), (197, -24), (212, -7), (212, 6), (197, 25), (83, 57), (27, 61), (-26, 61), (-82, 57), (-196, 25), (-210, 8)] mass = 10 moment = pymunk.moment_for_poly(mass,points) self.body = pymunk.Body(mass,moment) self.body.position = x,y self.body.angular_velocity = angular_velocity self.body.velocity_limit = 300 self.shape = pymunk.Poly(self.body, points) self.shapes = [self.shape] self.shape.elasticity = 1 self.shape.friction = .5 self.shape.collision_type = 1 # 0 - can't jump off of it; 1 - can jump when standing on it self.buoyancy = buoyancy self.body.apply_force(buoyancy)
def __init__(self, name, space, vertices, density=DEFAULT_DENSITY, elasticity=DEFAULT_ELASTICITY, friction=DEFAULT_FRICTION, color=DEFAULT_COLOR): PGObject.__init__(self, name, "Poly", space, color, density, friction, elasticity) #vertices = map(lambda v: map(float, v), vertices) vertices = [[float(vp) for vp in v] for v in vertices] loc = centroidForPoly(vertices) area = areaForPoly(vertices) mass = density * area if mass == 0: self._cpShape = pm.Poly(space.static_body, vertices) self._cpShape.elasticity = elasticity self._cpShape.friction = friction self._cpShape.collision_type = COLTYPE_SOLID self._cpShape.name = name space.add(self._cpShape) else: recenterPoly(vertices) imom = pm.moment_for_poly(mass, vertices) self._cpBody = pm.Body(mass, imom) self._cpShape = pm.Poly(self._cpBody, vertices) self._cpShape.elasticity = elasticity self._cpShape.friction = friction self._cpShape.collision_type = COLTYPE_SOLID self._cpShape.name = name self._cpBody.position = loc space.add(self._cpBody, self._cpShape)
def spawn_ball(dt, position, direction): x, y = position angle = random.random() * math.pi vs = [(-23, 26), (23, 26), (0, -26)] mass = 10 moment = pymunk.moment_for_poly(mass, vs) body = pymunk.Body(mass, moment) body.apply_impulse(Vec2d(direction)) # Keep ball velocity at a static value def constant_velocity(body, gravity, damping, dt): body.velocity = body.velocity.normalized() * 400 body.velocity_func = constant_velocity shape = pymunk.Circle(body, ball_img.width / 2) # shape.friction = 0.5 shape.elasticity = 1.0 body.position = x, y body.angle = angle space.add(body, shape) sprite = pyglet.sprite.Sprite(ball_img, batch=batch) sprite.shape = shape sprite.body = body logos.append(sprite)
def __init__(self, world, model, *, position=(0, 0), angle=0, scale=1): self.__world = weakref.ref(world) self.__model = model self.__scale = math.Matrix.scale(scale) shape = model.shape if pymunk.util.is_clockwise(shape): shape = reversed(shape) shape = list(map(lambda p: p * self.__scale, shape)) mass = model.density * pymunk.util.calc_area(shape) self._body = pymunk.Body(mass, pymunk.moment_for_poly(mass, shape)) self._body.__object = weakref.ref(self) self._body.position = tuple(position) self._body.angle = angle self._shapes = [] for convex_polygon in pymunk.util.convexise( pymunk.util.triangulate(shape)): convex_polygon = pymunk.Poly(self._body, convex_polygon) convex_polygon.elasticity = model.elasticity convex_polygon.friction = model.friction self._shapes.append(convex_polygon) world._objects.add(self) world._space.add(self._body, *self._shapes) self.active = False
def _create_pm_object(self, shape): mass = shape.body.mass inertia = shape.body.inertia pm_body = pm.Body(mass, inertia) pm_body.position = shape.position if isinstance(shape, Circle): radius = shape.radius # WARNING: for now, circle shapes are completely aligned to their # body's center of gravity offset = (0, 0) pm_obj = pm.Circle(pm_body, radius, offset) elif isinstance(shape, Segment): # WARNING: the segment is assumed to be centered around its position # points a and b are equally distant from the segments center #print 'creating segment: pos:', pm_body.position, 'from: ', shape.a, 'to: ', shape.b, 'radius: ', shape.radius pm_obj = pm.Segment(pm_body, shape.a, shape.b, shape.radius) elif isinstance(shape, Polygon): vertices = shape.vertices # WARNING: for now, polygon shapes are completely aligned to their # body's center of gravity offset = (0, 0) moment = pm.moment_for_poly(mass, vertices, offset) pm_body = pm.Body(mass, moment) pm_obj = pm.Poly(pm_body, vertices, offset) return pm_obj
def __init__(self, name, context, initPos, mass, width, length, radius = 0): # if num provided for radius, circle assumed self.name = name self.context = context self.mass = mass self.width = width * SCALE self.length = length * SCALE self.pos = initPos * SCALE self.radius = radius * SCALE self.scale = SCALE vertices = [(-self.width/2, -self.length/2),(-self.width/2,self.length/2),(self.width/2,self.length/2),(self.width/2,-self.length/2)] if self.radius > 0: self.inertia = pymunk.moment_for_circle(self.mass,self.radius,self.radius) self.body = pymunk.Body(self.mass,self.inertia) self.shape = pymunk.Circle(self.body,self.radius) else: self.inertia = pymunk.moment_for_poly(self.mass,vertices) self.body = pymunk.Body(self.mass, self.inertia) self.shape = pymunk.Poly(self.body, vertices) self.body.position = self.pos self.shape.elasticity = 0.95 self.shape.friction = 0.9 self.shape.color = pygame.color.THECOLORS["yellow"] self.shape.collision_type = collision_types[self.name] self.context.objects[self.shape._get_shapeid()] = self self.pickedUp = False self.context.numRets+=1
def _create_body(self) -> pymunk.Body: vertices = self._shape.get_vertices() moment = pymunk.moment_for_poly(self._mass, vertices, offset=(10, 10)) body = pymunk.Body(self._mass, moment) self._shape.body = body body.friction = 1.0 return body
def __init__(self, x, y, width, height, color, mass=5, lidar=None): points = [(x[0] * width, x[1] * height) for x in SHIP_TEMPLATE] moment = pm.moment_for_poly(mass, points) # Body creation body = pm.Body(mass, moment) body.position = Vec2d(x, y) # Shape creation shape = pm.Poly(body, points) shape.friction = 0.7 shape.color = color shape.collision_type = 1 self.filter = pm.ShapeFilter( categories=0b1) # This is used for better segment querying self.width = width self.height = height self.shape = shape self.body = body self.force_vector = Vec2d(0, 100) self.rudder_angle = 0 self.point_of_thrust = self.shape.bb.center() self.max_angle = 10 self.lidar = lidar
def load_poly_concave(tmxobject, map_height, static_body, defaults): """ Creates several pymunk.Poly objects parsed from a TiledObject instance. They share a common pymunk.Body object. :param TiledObject tmxobject: A TiledObject instance that represents a \ concave polygon with multiple vertices. :param int map_height: The height of the TiledMap that the TiledObject \ was loaded from in pixels. """ poly_defaults = defaults["pymunktmx_poly"] shape_attrs = get_shape_attrs(tmxobject, poly_defaults) body_attrs = get_body_attrs(tmxobject, poly_defaults) offset = body_attrs[u"offset"] radius = shape_attrs[u"radius"] # break concave shape into triangles points = list(tmxobject.points) # pymunk.util.triangulate expects the list to be in anti-clockwise order if pymunk.util.is_clockwise(points): points.reverse() # the pymunk.util.convexise doesn't create shapes that match originals # so we will just use the triangles triangles = pymunk.util.triangulate(points) shapes = [] if body_attrs[u"static"]: for vertices in triangles: vertices = [(p[0], map_height - p[1]) for p in vertices] shape = pymunk.Poly(static_body, vertices, offset, radius) shapes.append(shape) else: x = float(tmxobject.x) y = float(float(map_height) - tmxobject.y) mass = body_attrs[u"mass"] verts = [(p[0] - x, -(p[1] - y)) for p in tmxobject.points] moment = pymunk.moment_for_poly(mass, verts, offset) body = pymunk.Body(mass, moment) body.position = (x, y) set_attrs(body_attrs, body, skip_keys=[u"position", u"mass", u"static"]) for vertices in triangles: vertices = [(p[0] - x, -(p[1] - y)) for p in vertices] shape = pymunk.Poly(body, vertices, offset, radius) shapes.append(shape) shapes.append(body) for shape in shapes: set_attrs(shape_attrs, shape, skip_keys=[u"radius"]) return shapes
def __init__(self, space, init_pos=(0, 0), image_shape=None, is_player=True, is_geosynch=False, moon_center=(0, 0), boost_sound=None): super().__init__() self.game_over = False self.rocket_boost_sound = boost_sound self.is_geosynch = is_geosynch self.is_player = is_player self.image = pygame.image.load(resource_path("images/catstronaut.png")) self.moon_center = moon_center if image_shape: self.image = pygame.transform.scale(self.image, image_shape) self.image = pygame.transform.flip(self.image, True, True) self.rect = self.image.get_bounding_rect() width = self.rect.width height = self.rect.height self.space = space self.pos = pygame.Vector2(init_pos) vs = [(-width / 2, -height / 2), (width / 2, -height / 2), (width / 2, height / 2), (-width / 2, height / 2)] mass = 5 moment = pymunk.moment_for_poly(mass, vs) self.body = pymunk.Body(mass, moment) self.body.force = (0, -250) self.body.position = self.pos.x, -self.pos.y + 500 self.shape = pymunk.Poly(self.body, vs) self.shape.friction = 0.5 self.space.add(self.body, self.shape) self.can_jump = True
def _make_star( self, star_npoints: int, star_out_rad: float, star_in_rad: float, ) -> Tuple[List[pm.shapes.Poly], List[List[pm.Vec2d]]]: # Body. star_verts = gtools.compute_star_verts(star_npoints, star_out_rad, star_in_rad) # Create an exact convex decomposition. convex_parts = autogeom.convex_decomposition( star_verts + star_verts[:1], 0) star_hull = autogeom.to_convex_hull(star_verts, 1e-5) star_inertia = pm.moment_for_poly(self.mass, star_hull, (0, 0), 0) self.shape_body = body = pm.Body(self.mass, star_inertia) body.position = self.init_pos body.angle = self.init_angle self.add_to_space(body) # Shape. shapes = [] star_group = self.generate_group_id() for convex_part in convex_parts: shape = pm.Poly(body, convex_part) # Avoid self-intersection with a shape filter. shape.filter = pm.ShapeFilter(group=star_group) shapes.append(shape) del shape return shapes, convex_parts
def create_robot(position): global space x, y = position robot_upscale = 21 # robot diameter = 210 mm (21 cm) with open("robot.json", "r") as f: robot_data = json.load(f) verts = robot_data["rigidBodies"][0]["shapes"][0]["vertices"] vertices = [] for vert in verts: vertices.append((vert["x"] * robot_upscale, vert["y"] * robot_upscale)) mass = 700 # robot weights around 1kg inertia = pymunk.moment_for_poly(mass, vertices) body = pymunk.Body(mass, inertia) body.position = x, y shapes = robot_data["rigidBodies"][0]["polygons"] for shape in shapes: verties = [] for vert in shape: vert_x = vert["x"] * robot_upscale vert_y = vert["y"] * robot_upscale verties.append((vert_x, vert_y)) poly_shape = pymunk.Poly(body, verties) poly_shape.color = pygame.color.THECOLORS["red"] poly_shape.elasticity = 0 poly_shape.friction = 10 poly_shape.collision_type = COLLISION_TYPES["robot"] space.add(poly_shape) space.add(body) return body
def __init__(self, position, collision_type, *, size): if collision_type != 5: # Column vertices = [pm.Vec2d(size[SPRITE_WIDTH]/2, -size[SPRITE_HEIGHT]/4), pm.Vec2d(size[SPRITE_WIDTH]/2, size[SPRITE_HEIGHT]), pm.Vec2d(-size[SPRITE_WIDTH]/2, size[SPRITE_HEIGHT]), pm.Vec2d(-size[SPRITE_WIDTH]/2, -size[SPRITE_HEIGHT]/4)] else: # Beam vertices = [pm.Vec2d(size[SPRITE_WIDTH]/8, -size[SPRITE_HEIGHT]/4), pm.Vec2d(size[SPRITE_WIDTH]/8, size[SPRITE_HEIGHT]/8), pm.Vec2d(-size[SPRITE_WIDTH]/4, size[SPRITE_HEIGHT]/8), pm.Vec2d(-size[SPRITE_WIDTH]/4, -size[SPRITE_HEIGHT]/4)] mass = 1 moment = pm.moment_for_poly(mass=mass, vertices=vertices) Body.__init__(self, position, mass, moment) self.shape = pm.Poly(self.body, vertices=vertices, radius=0.5) self.shape.density = .0001 self.shape.elasticity = 0.4 self.shape.friction = 0.1 self.shape.trigger_rotation = False self.shape.collision_type = collision_type self.angle = 0
def __init__(self, space, x, y, mass, sprite, sprite_size=1): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image(sprite) # This is not exactly an ideal way to figure this out self.width = self.rect[2] self.height = self.rect[3] # This will resize the sprite if we've resized it self.image = pygame.transform.scale(self.image, (int(self.width * sprite_size), int(self.height * sprite_size) )) self.space = space self.mass = mass ## Need to offset the points of the shape so that the center of the image is at (0, 0) offset = Vec2d(self.width/2, self.height/2) bounds = self.rect points = [Vec2d(bounds.topleft) - offset, Vec2d(bounds.topright) - offset, Vec2d(bounds.bottomright) - offset, Vec2d(bounds.bottomleft) - offset] #### End of shape offset code - we can now pass the points to the body/shape creation #### inertia = pymunk.moment_for_poly(mass, points, (0,0)) self.body = pymunk.Body(mass, inertia) self.body.position = x, y self.shape = pymunk.Poly(self.body, points, (0, 0) ) self.shape.friction = DEFAULT_FRICTION_AMT game.space.add(self.body, self.shape)
def create_body_poly(self, mass, posinit, points): center = pm.util.calc_center(points) points = pm.util.poly_vectors_around_center(points) moment = pm.moment_for_poly(mass, points, Vec2d(0, 0)) body = pm.Body(mass, moment) body.position = Vec2d(posinit) return body, points
def get_body_and_shape(self): # compile part data vertices = [] mass = 0 centroids_map = {} for p in self.parts: vertices += p.vertices mass += p.mass centroids_map[centroid(p.vertices)] = p.mass # calculate center of mass weighted_centroids_map = { c: m / mass for c, m in centroids_map.items() } centroids = list(weighted_centroids_map.keys()) weights = [weighted_centroids_map[c] for c in centroids] com = centroid(centroids, weights) # calculate offset vertices = list(set(vertices)) center = centroid(vertices) offset = Vec2d(center) - Vec2d(com) # create body body = pymunk.Body(mass) shape = pymunk.Poly(body, vertices) body.moment = pymunk.moment_for_poly(mass, vertices) body.center_of_gravity = com body.position = 450, 300 return body, shape, body.local_to_world(com)
def __init__(self, position): WrapSprite.__init__(self, position, (0, 0)) """ Physical properties of ship. """ triangle_vertices = [(-5, 5), (-5, -5), (5, 0)] # vertices of triangular shape of ship mass = 1.0 # arbitrary self.gravity = Vec2d(0, 0) # no gravity self.body = pymunk.Body(mass=mass, moment=pymunk.moment_for_poly( mass, triangle_vertices), body_type=pymunk.Body.DYNAMIC) self.body.angle = math.pi / 2. # initialize facing up self.shape = pymunk.Poly(self.body, [(-5, 5), (-5, -5), (5, 0)]) # initialize trianglur shape self.body.position = position self.shape.friction = 0.0 # arbitrary self.shape.collision_type = collision_types["Player"] self.shape.game_over = False # flag triggered by collision handler detecting ship was killed by asteroid # legal buttons for player actions self.legal_actions = [K_UP, K_DOWN, K_LEFT, K_RIGHT, K_SPACE] # tune rocket's forward and turning speed self.forward_thrust = 20 # as an impulse self.turning_speed = 0.1 # as radians per step
def create_world(self): self.space = pymunk.Space() self.space.gravity = Vec2d(0., -900.) static_body = pymunk.Body() static_lines = [ #pymunk.Segment(static_body, Vec2d(50,100), Vec2d(550,100), 1), #pymunk.Segment(static_body, Vec2d(450,100), Vec2d(450,300), 1) ] static_blocks = [ pymunk.Poly(static_body, [(50, 100), (550, 100), (550, 99), (50, 99)]) ] for l in static_blocks: l.friction = 0.3 self.space.add(static_blocks) for x in range(5): for y in range(12): size = 5 points = [(-size, -size), (-size, size), (size, size), (size, -size)] mass = 10.0 moment = pymunk.moment_for_poly(mass, points, (0, 0)) body = pymunk.Body(mass, moment) body.position = Vec2d(200 + x * 50, 105 + y * 11) shape = pymunk.Poly(body, points, (0, 0)) shape.friction = 0.3 self.space.add(body, shape)
def __init__(self, world_pos, vertices, mass, friction=0.8, moment = None, taggable=True, grabable=False, texture_name=None, dynamic=True, collision_group=0, layers=2**32-1): self._world_entity_manager = None self._is_dynamic = True self._verts = vertices pymunk_verts = map(Vec2d, vertices) if not moment: moment = pymunk.moment_for_poly(mass, pymunk_verts, (0,0)) self._body = pymunk.Body(mass, moment) self._body.position = world_pos self._shape = pymunk.Poly(self._body, pymunk_verts, (0,0) ) self._shape.friction = friction self._is_taggable = taggable self._is_grabable = grabable self._texture_name = texture_name self._is_dynamic = dynamic self._time_passed = 0.0 self._shape.layers = layers self._taggable_attached = None self._shape.group = collision_group if not self._is_dynamic: self._bounding_rect_cache = self.get_bounding_rect(force=True) self._tags = {} self._attached = False
def __init__(self, pos): Collidable.__init__(self, self.groups) self.left_images = [] for i in self.right_images: self.left_images.append(pygame.transform.flip(i, 1, 0)) self.image = self.right_images[0] self.rect = self.image.get_rect() self.jump_speed = 0 self.jump_accel = 0.3 self.jumping = False self.frame = 0 self.facing = 1 self.still_timer = 0 self.hit_timer = 0 self.health = 5 self.heat = 100 w = self.rect.width/2 - 20 h = self.rect.height/2 - 10 poly = [(-w,-h),(w,-h),(w,h),(-w,h)] mass = 1000 moment = pymunk.moment_for_poly(mass, poly) self.body = pymunk.Body(mass, pymunk.inf) self.shape = pymunk.Poly(self.body, poly) self.shape.color = THECOLORS["blue"] self.shape.friction = 3 self.rect.topleft = pos self.body.position = (self.rect.center[0],480-self.rect.center[1]) self.jumping = False
def add_triangle(self, vertices, random_color): vbackup = vertices vertices = [int(v) for v in vertices] vertices = zip(vertices[::2], vertices[1::2]) center = cymunk.util.calc_center(vertices) body = cymunk.Body(100, cymunk.moment_for_poly(100, vertices)) body.position.x = center[0] body.position.y = center[1] triangle = cymunk.Poly(body, vertices) triangle.elasticity = 0.6 triangle.friction = FRICTION self.space.add(body, triangle) with self.parent.canvas.before: color = Color(*random_color, mode="rgba") rot = Rotate(angle=0, axis=(0, 0, 1), origin=center) triangle_shape = Triangle(points=vbackup) unrot = Rotate(0, (0, 0, 1), origin=center) body.data = { "color": color, "instruction": [triangle_shape, rot, unrot], "type": TRIANGLE_TYPE, "shapes": [triangle], }
def __init__(self, space, vertices, mass=None, position=None, velocity=None): super(PolyBody, self).__init__(space, mass, position, velocity) self.vertices = vertices inertia = pymunk.moment_for_poly(self.mass, self.vertices) self.game_body = pymunk.Body(self.mass, inertia) self.game_body.position = self.position self.game_shape = pymunk.Poly(self.game_body, self.vertices) self.space.game_space.add(self.game_body, self.game_shape)
def create_body(self): if self.item.static: mass = moment = inf else: mass = self.item.geometry.area moment = moment_for_poly(mass, self.item.geometry.verts) body = Body(mass, moment) return body
def __init__(self, space, screen): vs = [(-20, 20), (20, 20), (20, -20), (-20, -20)] mass = 10 moment = pm.moment_for_poly(mass, vs) body = pm.Body(mass, moment) shape = DefenseShape(space, body, vs) PymunkSprite.__init__(self, space, screen, "../assets/img/joint.png", shape)
def makeBox(mass, space, textures, hit_box, scale, x, y): body = pymunk.Body(mass, pymunk.moment_for_poly(mass, vertices=hit_box) * 10) body.position = pymunk.Vec2d((x, y)) shape = pymunk.Poly.create_box(body, (textures[0].width, textures[0].height)) shape.friction = 0.5 space.add(body, shape) sprite = Ground(shape, textures, scale, x, y) return sprite
def create_poly(collision_type=None, elasticity=None, friction=None, mass=None, moment=None, offset=None, position=None, radius=None, vertices=None, **extras): if _lacks_moment(mass, moment): moment = pymunk.moment_for_poly(mass, vertices, offset) body = _create_body(mass, moment, position) shape = pymunk.Poly(body, vertices, offset, radius) return _configure_shape(shape, elasticity, friction, collision_type)
def addPoly(self, actorID, **kwargs): '''Create a polygon shape and body''' if kwargs['moment'] == -1: kwargs['moment'] = pymunk.moment_for_poly(kwargs['mass'], kwargs['vertices']) body = self.createBody(kwargs['isStatic'], kwargs['mass'], kwargs['moment'], kwargs['pos']) shape = pymunk.Poly(body, kwargs['vertices']) self.addShape(actorID, body, shape, kwargs['elasticity'], kwargs['collisionType'])
def create_body(self): verts = map(Vec2d, self.get_verts()) self.body = Body(self.mass, moment_for_poly(self.mass, verts)) self.body.position = (self.x, self.y) self.shape = Poly(self.body, verts, (0, 0)) self.shape.layers = self.layers # this is so you can get to it from collision handlers. # eg. arbiter.shapes[0].parent self.shape.parent = self
def create_poly(self, points, mass=5.0, pos=(0, 0)): moment = pymunk.moment_for_poly(mass, points, Vec2d(0, 0)) body = pymunk.Body(mass, moment) body.position = Vec2d(pos) shape = pymunk.Poly(body, points, Vec2d(0, 0)) shape.friction = 1 # shape.collision_type = COLLTYPE_DEFAULT self.space.add(body, shape) return shape
def __init__(self, space, screen): vs = [(-25, 25), (25, 25), (25, -25), (-25, -25)] mass = 10 moment = pm.moment_for_poly(mass, vs) body = pm.Body(mass, moment) shape = pm.Poly(body, vs) PymunkSprite.__init__(self, space, screen, "../assets/img/MaceBall.png", shape) self.shape.collision_type = COLLISION_OFFENSE
def __init__(self, position, space): self.mass = 1 self.shape = pymunk.Poly.create_box(None, size=(10, 50)) self.moment = pymunk.moment_for_poly(self.mass, self.shape.get_vertices()) self.body = pymunk.Body(self.mass, self.moment) self.shape.body = self.body self.shape.body.position = position space.add(self.shape, self.body)
def _update_cell(self): ##{{{ """ Updates Inertia, Updates length, height etc for pygame Does not update position. """ self._genpoly() self.body.moment=pm.moment_for_poly(self.mass,self.ver, (0,0)) #Sets new inertia self.box.unsafe_set_vertices(self.ver,(-self.length/2.,-self.height/2.))
def create_poly(points, space, mass = 5.0, pos = (0,0)): moment = pymunk.moment_for_poly(mass,points, Vec2d(0,0)) body = pymunk.Body(mass, moment) body.position = Vec2d(pos) shape = pymunk.Poly(body, points, Vec2d(0,0)) shape.collision_type = collisiontype_default shape.friction = 1.0 shape.elasticity = 0.5 space.add(body, shape) return shape
def add_poly(self, points, position=(100,100), mass=1.0): """ Add a closed polygon collision shape. """ moment = pymunk.moment_for_poly(mass, points, (0,0)) self._body = pymunk.Body(mass, moment) self._body.position = position self._body.angle = 47.0 self._shape = pymunk.Poly(self._body, points, (0,0)) return self
def create_arrow(): vs = [(-30,0), (0,3), (10,0), (0,-3)] mass = 1 moment = pymunk.moment_for_poly(mass, vs) arrow_body = pymunk.Body(mass, moment) arrow_shape = pymunk.Poly(arrow_body, vs) arrow_shape.friction = .5 arrow_shape.collision_type = 1 return arrow_body, arrow_shape
def add_wheel(self, space, pos): fp = [(-5, -3), (5, -3), (5, 3), (-5, 3)] mass = 1000 moment = pymunk.moment_for_poly(mass, fp) wheel_body = pymunk.Body(mass, moment) wheel_shape = pymunk.Poly(wheel_body, fp) wheel_shape.group = self.group wheel_body.position = pos joint = pymunk.PivotJoint(self.robot.body, wheel_body, wheel_body.position) space.add(wheel_body, wheel_shape, joint) return wheel_shape
def _body(self): if self.static == False: mass = 20 # saint random! radius = 20 #inertia = pymunk.moment_for_box(mass, 0, radius) inertia = pymunk.moment_for_poly(mass, self.points) body = pymunk.Body(mass, inertia) else: body = pymunk.Body(pymunk.inf, pymunk.inf) return body
def __init__(self, level, pos, player): self.level = level self.level = level self.player = player self.body = Body(self.mass, moment_for_poly(self.mass, self.verticies)) self.body.position = Vec2d(pos) self.body.velocity = Vec2d(self.initialSpeed, 0).rotated(pi*random()) self.createShape(self.verticies) self.shape.friction = 1 self.startTime = game.engine.levelTime self.opacity = 1.
def create_poly(self, points, mass = 5.0, pos = (0,0)): moment = pymunk.moment_for_poly(mass,points, Vec2d(0,0)) #moment = 1000 body = pymunk.Body(mass, moment) body.position = Vec2d(pos) print body.position shape = pymunk.Poly(body, points, Vec2d(0,0)) shape.friction = 0.5 shape.collision_type = 1 self.space.add(body, shape) return shape