def add_gravity_region(self, size, pos, gravity): """Makes a bullet ghost, when a object enters its gravity is changed to match the arguments passed """ shape = BulletBoxShape(Vec3(size)) grav_ghost = BulletGhostNode('Ghost') grav_ghost.addShape(shape) grav_ghost_NP = render.attachNewNode(grav_ghost) grav_ghost_NP.setPos(pos) grav_ghost_NP.setCollideMask(BitMask32(0x0f)) self.world.attachGhost(grav_ghost) def check_gravity_region(task): """Check what bullet nodes are inside and apply gravity to them. """ ghost = grav_ghost_NP.node() print ghost.getNumOverlappingNodes() for node in ghost.getOverlappingNodes(): print node #TODO: Make this only apply when in the region #EX: Gravity is set to X inside, set back to normal when out node.setGravity(Vec3(gravity)) return task.cont #Add the region checker task taskMgr.add(check_gravity_region, "check_gravity_region")
class SMCollect(): def __init__(self, world, worldNP, sPos): self.world = world self.worldNP = worldNP self.collected = False self.collectShape = BulletBoxShape(Vec3(3, 5, 5)) self.collectGN = BulletGhostNode('Box') self.collectGN.addShape(self.collectShape) self.collectNP = self.create(sPos, self.collectGN) print("Collectable Initialized") def exists(self): return not(self.collected) def getNode(self): return self.collectGN def create(self, pos, ghostNode): collectNode = render.attachNewNode(ghostNode) collectNode.setPos(pos) collectNode.setCollideMask(BitMask32(0x0f)) self.world.attachGhost(ghostNode) visualCN = loader.loadModel("../res/models/snowflake.egg") visualCN.reparentTo(collectNode) visualCN.setScale(2) return collectNode def destroy(self): self.collected = True self.world.removeGhost(self.collectGN) self.collectNP.removeNode()
def __init__(self, world, parent, params): self.params = params self.__world = world self.__g = world.getGravity().z # negative value self.__events = Events() self.__shape_stand = BulletCapsuleShape(params['radius'], params['height'] - 2 * params['radius'], ZUp) self.__shape_crouch = BulletCapsuleShape(params['radius'], params['crouch_height'] - 2 * params['radius'], ZUp) self.__ghost = BulletGhostNode('Capsule for ' + params['name']) self.__ghost.addShape(self.__shape_stand, TransformState.makePos((0, 0, params['height'] / 2))) self.node = parent.attachNewNode(self.__ghost) self.node.setCollideMask(BitMask32.allOn()) world.attachGhost(self.__ghost) self.__foot_contact = self.__head_contact = None self.velocity = Vec3() self.__outer_motion = Vec3() self.__motion_time_ival = 0 self.__ignore_player_motion = False self.__outer_rotation = self.__rotation_time_ival = 0 self.__ignore_player_rotation = False self.__falling = False self.__crouches = False # controls self.__want_crouch = False self.__want_fly = False
class SMCollect(): def __init__(self, world, worldNP, sPos): self.world = world self.worldNP = worldNP self.collected = False self.collectShape = BulletBoxShape(Vec3(3, 5, 5)) self.collectGN = BulletGhostNode('Box') self.collectGN.addShape(self.collectShape) self.collectNP = self.create(sPos, self.collectGN) print("Collectable Initialized") def exists(self): return not (self.collected) def getNode(self): return self.collectGN def create(self, pos, ghostNode): collectNode = render.attachNewNode(ghostNode) collectNode.setPos(pos) collectNode.setCollideMask(BitMask32(0x0f)) self.world.attachGhost(ghostNode) visualCN = loader.loadModel("../res/models/snowflake.egg") visualCN.reparentTo(collectNode) visualCN.setScale(2) return collectNode def destroy(self): self.collected = True self.world.removeGhost(self.collectGN) self.collectNP.removeNode()
def setupCoins2(self): # display coins = 0 textN = TextNode('coin-score') textN.setText(str("Coins: " + str(self.coinsCollected2))) textN.setSlant(0.1) textNodePath = self.aspect2d.attachNewNode(textN) textNodePath.setPos(0, 0.95, 0.9) textNodePath.setScale(0.08) randNum = random.sample(range(0, 1500, 200), 6) # coins for i in range(6): randX = random.uniform(-3.0, 3.2) randY = float(randNum[i]) shape = BulletSphereShape(0.3) coinNode = BulletGhostNode('Coin-' + str(i)) coinNode.addShape(shape) np = self.render.attachNewNode(coinNode) np.setCollideMask(BitMask32.allOff()) np.setPos(randX, randY, 2) # Adding sphere model sphereNp = loader.loadModel('models/smiley.egg') sphereNp_tex = loader.loadTexture("models/sky/coin_2_tex.jpg") sphereNp.setTexture(sphereNp_tex, 1) sphereNp.reparentTo(np) sphereNp.setScale(0.45) sphereNp.hprInterval(2.5, Vec3(360, 0, 0)).loop() self.world2.attachGhost(coinNode) self.coins2.append(coinNode) print "node name:" + str(coinNode.getName())
def build_node_path(self, parent_node_path, bullet_world): land_geom = self.__build_land_mesh() ocean_geom = self.__build_ocean_mesh() land_mesh = BulletTriangleMesh() land_mesh.addGeom(land_geom) land_shape = BulletTriangleMeshShape(land_mesh, dynamic=False) ocean_shape = BulletSphereShape(self.__radius) land_bullet_node = BulletRigidBodyNode('land collider') land_bullet_node.addShape(land_shape) bullet_world.attachRigidBody(land_bullet_node) land_bullet_node_path = parent_node_path.attachNewNode( land_bullet_node) ocean_bullet_node = BulletGhostNode('ocean collider') ocean_bullet_node.addShape(ocean_shape) bullet_world.attachGhost(ocean_bullet_node) ocean_bullet_node_path = land_bullet_node_path.attachNewNode( ocean_bullet_node) land_node = GeomNode('land') land_node.addGeom(land_geom) land_node_path = land_bullet_node_path.attachNewNode(land_node) ocean_node = GeomNode('ocean') ocean_node.addGeom(ocean_geom) ocean_node_path = ocean_bullet_node_path.attachNewNode(ocean_node) ocean_node_path.setTransparency(TransparencyAttrib.MAlpha) self.__node_path = land_bullet_node_path land_bullet_node.setPythonTag('planet', self) return land_bullet_node_path
def __init__(self, world, worldNP, sPos): self.world = world self.worldNP = worldNP self.collected = False self.collectShape = BulletBoxShape(Vec3(3, 5, 5)) self.collectGN = BulletGhostNode('Box') self.collectGN.addShape(self.collectShape) self.collectNP = self.create(sPos, self.collectGN) print("Collectable Initialized")
class floatTrap(): traps = list() model = 0 index = 0 def __init__(self, ppos, world, worldNP): self.world = world if floatTrap.model==0: floatTrap.model = Model("../assets/3d/Actors/beartrap2.egg") h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) npos = map(lambda i: ppos[i]+dir[i]*25, range(3)) self.instance = floatTrap.model.createInstance(pos=npos,hpr=(0,0,0)) self.index = floatTrap.index pmin = LPoint3() pmax = LPoint3() self.instance.calcTightBounds(pmin,pmax) norm = pmin-pmax self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5) r = max(norm) shape = BulletSphereShape(.7*r) self.sphere = BulletGhostNode('TrapSphere') self.sphere.addShape(shape) self.sphere.setDeactivationEnabled(False) self.np = worldNP.attachNewNode(self.sphere) self.np.setPos(LVecBase3(npos[0],npos[1],npos[2])) self.np.setCollideMask(BitMask32.allOn()) world.attachGhost(self.sphere) #taskMgr.add(self.check,"floatTrap"+str(self.index)+"Check") floatTrap.traps.append(self) floatTrap.index = floatTrap.index + 1 #pos = self.instance.getPos() #self.np.setPos(pos[0]-self.off[0],pos[1]-self.off[1],pos[2]-self.off[2]) def kill(self): floatTrap.traps.remove(self) self.world.removeGhost(self.sphere) self.instance.detachNode() def check(self,contacts,human,players): if len(contacts)>0: contactObject = contacts[0].getNode0() if contacts[0].getNode0().getName()=="TrapSphere": contactObject = contacts[0].getNode1() name = contactObject.getName() print contactObject if name==human.character.getName(): human.trap1() self.kill() return for i in range(len(players)): if name==players[i].character.getName(): players[i].trap1() self.kill() return
def _createBtGhostNode_(self,np): """ @brief Creates a Bullet Ghost node from the shapes in the model node. Ignores any local geometry transforms but applies local scaling encoded in the model node. """ bt_shape = self._createBulletShape_(np,True,False) if bt_shape is None: return None bt_ghost = BulletGhostNode(np.getName()) bt_ghost.addShape(bt_shape) return bt_ghost
def buildItemColSphereNP(cls, _engine, _radius, _pos, _head): """Build a basic BulletCharacter Controller""" sphere = BulletSphereShape(_radius) node = BulletGhostNode('ItemSphere') node.addShape(sphere) np = _engine.BulletObjects["object"].attachNewNode(node) np.setPos(_pos) np.setH(_head) np.setCollideMask(BitMask32(0xf)) _engine.bulletWorld.attachGhost(node) return np
def __init__(self, mediator, pos): self.pos = pos self.ghost = None PhysColleague.__init__(self, mediator) self.ghost = BulletGhostNode('Bonus') self.ghost.add_shape(BulletBoxShape((1, 1, 2.5))) ghost_np = self.eng.attach_node(self.ghost) pos = self.pos pos = Vec(pos.x, pos.y, pos.z) ghost_np.set_pos(pos) ghost_np.set_collide_mask(BitMask32.bit(BitMasks.ghost)) self.eng.phys_mgr.attach_ghost(self.ghost)
def setupSensor(self, _obj, _eggFile): shape = BulletBoxShape(Vec3(_obj.getScale())) ghost = BulletGhostNode("Counter_Ghost_Node") ghost.addShape(shape) np = self.rootNode.attachNewNode(ghost) np.setPos(_obj.getPos()) np.setCollideMask(BitMask32(0x0f)) self.parent.physics_world.attachGhost(ghost) self.parent.game_counter_node = np
def _initPhysics(self, world, x, y, w, h, adir, parent_node): shape = BulletBoxShape(Vec3(w / 4.0, w / 4.0, h / 4.0)) self._g_node = BulletGhostNode('Box') #self._rb_node.setMass(0) self._g_node.addShape(shape) #self._rb_node.setAngularFactor(Vec3(0,0,0)) #self._rb_node.setDeactivationEnabled(False, True) world.attachGhost(self._g_node) self._modulo_node = parent_node.attachNewNode(self._g_node) self._modulo_node.setPos(x, y, h / 2.0) self._modulo_node.setHpr(adir, 0, 0) self._modulo_node.setPos(self._modulo_node, 0, w / 2.0, 0)
def _add_box_body(self, lane_start, lane_end, middle, parent_np: NodePath, line_type, line_color): length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1]) if LineType.prohibit(line_type): node_name = BodyName.White_continuous_line if line_color == LineColor.GREY else BodyName.Yellow_continuous_line else: node_name = BodyName.Broken_line body_node = BulletGhostNode(node_name) body_node.set_active(False) body_node.setKinematic(False) body_node.setStatic(True) body_np = parent_np.attachNewNode(body_node) shape = BulletBoxShape( Vec3(length / 2, Block.LANE_LINE_WIDTH / 2, Block.LANE_LINE_GHOST_HEIGHT)) body_np.node().addShape(shape) mask = Block.CONTINUOUS_COLLISION_MASK if line_type != LineType.BROKEN else Block.BROKEN_COLLISION_MASK body_np.node().setIntoCollideMask(BitMask32.bit(mask)) self.static_nodes.append(body_np.node()) body_np.setPos(panda_position(middle, Block.LANE_LINE_GHOST_HEIGHT / 2)) direction_v = lane_end - lane_start theta = -numpy.arctan2(direction_v[1], direction_v[0]) body_np.setQuat( LQuaternionf(numpy.cos(theta / 2), 0, 0, numpy.sin(theta / 2)))
def setupFloaters2(self): size = Vec3(3.5, 5.5, 0.3) randNum = random.sample(range(10, 1500, 500), 3) for i in range(3): randX = random.randrange(-2, 3, 10) randY = float(randNum[i]) # randY = random.randint(1000, 1500) shape = BulletBoxShape(size * 0.55) node = BulletRigidBodyNode('Floater') node.setMass(0) node.addShape(shape) np = self.render.attachNewNode(node) # np.setPos(9, 30, 3) np.setPos(randX, randY, 6) np.setR(0) self.world2.attachRigidBody(node) dummyNp = self.render.attachNewNode('milkyway') dummyNp.setPos(randX, randY, 6) modelNP = loader.loadModel('models/box.egg') modelNP_tex = loader.loadTexture("models/sky/moon_tex.jpg") modelNP.setTexture(modelNP_tex, 1) modelNP.reparentTo(dummyNp) modelNP.setPos(-1, 0, -1) modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0) modelNP.setScale(size) dummyNp.hprInterval(2.5, Vec3(360, 0, 0)).loop() # Put A Coin On the Floater shape = BulletSphereShape(0.75) coinNode = BulletGhostNode('FloaterCoin-' + str(i)) coinNode.addShape(shape) np = self.render.attachNewNode(coinNode) np.setCollideMask(BitMask32.allOff()) # np.setPos(randX, randY, 2) np.setPos(randX, randY, 7.0) # Adding sphere model sphereNp = loader.loadModel('models/smiley.egg') sphereNp_tex = loader.loadTexture("models/sky/coin_2_tex.jpg") sphereNp.setTexture(sphereNp_tex, 1) sphereNp.reparentTo(np) sphereNp.setScale(0.85) sphereNp.hprInterval(1.5, Vec3(360, 0, 0)).loop() self.world2.attachGhost(coinNode) self.coins2.append(coinNode) print "node name:" + str(coinNode.getName())
def addSpings(self): for pos in SPRING_LIST: print "add spring #{} at: {}".format(len(self.springs), pos) shape = BulletBoxShape(Vec3(0.3, 0.3, 0.8)) node = BulletGhostNode('Spring' + str(len(self.springs))) node.addShape(shape) springNP = self.render.attachNewNode(node) springNP.setCollideMask(BitMask32.allOff()) springNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 3.4) modelNP = loader.loadModel('models/spring/spring.egg') modelNP.reparentTo(springNP) modelNP.setScale(1, 1, 1) modelNP.setPos(0, 0, -1) self.world.attachGhost(node) self.springs.append(springNP)
def __createBulletGhostNodeFromBoxes__(self,boxes,scale, name ): ghost_node = BulletGhostNode(name) transform = TransformState.makeIdentity() for box in boxes: box.scale = scale size = box.size center = box.center box_shape = BulletBoxShape(Vec3(0.5*size[0],0.5*AnimationActor.DEFAULT_WIDTH,0.5 * size[1])) #box_shape.setMargin(AnimationActor.COLLISION_MARGIN) transform = transform.setPos(Vec3(center[0],0,center[1])) ghost_node.addShape(box_shape,transform) return ghost_node
def setupElevator(self, makeIvals=True): collisionRadius = ElevatorData[self.type]['collRadius'] self.elevatorSphere = BulletSphereShape(collisionRadius) self.elevatorSphereNode = BulletGhostNode( self.uniqueName('elevatorSphere')) self.elevatorSphereNode.setKinematic(True) self.elevatorSphereNode.setIntoCollideMask(CIGlobals.EventGroup) self.elevatorSphereNode.addShape( self.elevatorSphere, TransformState.makePos(Point3(0, 5, 0))) self.elevatorSphereNodePath = self.getElevatorModel().attachNewNode( self.elevatorSphereNode) self.elevatorSphereNodePath.reparentTo(self.getElevatorModel()) base.physicsWorld.attachGhost(self.elevatorSphereNode) if makeIvals: self.makeIvals()
def buildCharacterGhost(cls, _engine, _height, _radius, _bulletBody, _playerModel, _head): """Build a basic BulletGhost body for the player to be used for tracking eventObjects""" shape = BulletSphereShape(_radius*4) ghost = BulletGhostNode("player_ghost") ghost.addShape(shape) ghostNP = _engine.BulletObjects["player"].attachNewNode(ghost) newz = _playerModel.getPos() newz.z = newz.z + 2.5 ghostNP.setPos(newz) ghostNP.setCollideMask(BitMask32.allOff()) _engine.bulletWorld.attachGhost(ghost) ghostNP.reparentTo(_playerModel) return ghostNP
class BonusPhys(Phys): def __init__(self, mdt, pos): self.pos = pos Phys.__init__(self, mdt) def sync_bld(self): self.ghost = BulletGhostNode('Bonus') self.ghost.addShape(BulletBoxShape((1, 1, 2.5))) ghostNP = eng.attach_node(self.ghost) ghostNP.setPos(self.pos) eng.attach_ghost(self.ghost) def destroy(self): self.ghost = eng.remove_ghost(self.ghost) Phys.destroy(self)
def __init__(self, ppos, world, worldNP): self.world = world if floatTrap.model==0: floatTrap.model = Model("../assets/3d/Actors/beartrap2.egg") h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) npos = map(lambda i: ppos[i]+dir[i]*25, range(3)) self.instance = floatTrap.model.createInstance(pos=npos,hpr=(0,0,0)) self.index = floatTrap.index pmin = LPoint3() pmax = LPoint3() self.instance.calcTightBounds(pmin,pmax) norm = pmin-pmax self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5) r = max(norm) shape = BulletSphereShape(.7*r) self.sphere = BulletGhostNode('TrapSphere') self.sphere.addShape(shape) self.sphere.setDeactivationEnabled(False) self.np = worldNP.attachNewNode(self.sphere) self.np.setPos(LVecBase3(npos[0],npos[1],npos[2])) self.np.setCollideMask(BitMask32.allOn()) world.attachGhost(self.sphere) #taskMgr.add(self.check,"floatTrap"+str(self.index)+"Check") floatTrap.traps.append(self) floatTrap.index = floatTrap.index + 1
def addMeshConvexRB(self,vertices, faces,ghost=False,**kw): #step 1) create GeomVertexData and add vertex information format=GeomVertexFormat.getV3() vdata=GeomVertexData("vertices", format, Geom.UHStatic) vertexWriter=GeomVertexWriter(vdata, "vertex") [vertexWriter.addData3f(v[0],v[1],v[2]) for v in vertices] #step 2) make primitives and assign vertices to them tris=GeomTriangles(Geom.UHStatic) [self.setGeomFaces(tris,face) for face in faces] #step 3) make a Geom object to hold the primitives geom=Geom(vdata) geom.addPrimitive(tris) #step 4) create the bullet mesh and node mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletConvexHullShape(mesh, dynamic=not ghost)# if ghost : inodenp = self.worldNP.attachNewNode(BulletGhostNode('Mesh')) else : inodenp = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) inodenp.node().addShape(shape) # inodenp.setPos(0, 0, 0.1) self.setRB(inodenp,**kw) inodenp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(inodenp.node()) return inodenp
def __checkFutureSpace(self, globalVel): globalVel = globalVel * self.futureSpacePredictionDistance pFrom = Point3(self.capsuleNP.getPos(render) + globalVel) pUp = Point3(pFrom + Point3(0, 0, self.__capsuleH * 2.0)) pDown = Point3(pFrom - Point3(0, 0, self.__capsuleH * 2.0 + self.__levitation)) upTest = self.__world.rayTestClosest(pFrom, pUp, CIGlobals.WallGroup) downTest = self.__world.rayTestClosest( pFrom, pDown, CIGlobals.FloorGroup | CIGlobals.StreetVisGroup) if not (upTest.hasHit() and downTest.hasHit()): return True upNode = upTest.getNode() if upNode.getMass() or upNode.isOfType(BulletGhostNode.getClassType()): return True space = abs(upTest.getHitPos().z - downTest.getHitPos().z) if space < self.__levitation + self.__capsuleH + self.capsule.getRadius( ): return False return True
def add_ghostnode(node): """ Adds a child ghostnode to a node as a workaround for the ghost-static node collision detection problem.""" name = "%s-ghost" % node.getName() ghost = NodePath(BulletGhostNode(name)) ghost.reparentTo(node) return ghost
def setupEndPoint(self): blocks_tex8 = loader.loadTexture("models/blocks_tex8.jpg") self.endpoint= loader.loadModel("models/Sphere_HighPoly/Sphere_HighPoly") self.endpoint.reparentTo(render) self.endpoint.setScale(.8) self.endpoint.setPos(0,-200,2) self.endpoint.setTexture(blocks_tex8, 1) radius = 2.65 self.shapeEnd = BulletSphereShape(radius) self.nodeEnd = BulletGhostNode('EndPoint') self.nodeEnd.addShape(self.shapeEnd) self.npEnd = render.attachNewNode(self.nodeEnd) self.npEnd.setPos(0, -200, 2) self.npEnd.setCollideMask(BitMask32.allOn()) self.world.attachGhost(self.nodeEnd)
def _add_lane_line2bullet(self, lane_start, lane_end, middle, parent_np: NodePath, color: Vec4, line_type: LineType, straight_stripe=False): length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1]) if length <= 0: return if LineType.prohibit(line_type): node_name = BodyName.White_continuous_line if color == LineColor.GREY else BodyName.Yellow_continuous_line else: node_name = BodyName.Broken_line # add bullet body for it if straight_stripe: body_np = parent_np.attachNewNode(node_name) else: body_node = BulletGhostNode(node_name) body_node.set_active(False) body_node.setKinematic(False) body_node.setStatic(True) body_np = parent_np.attachNewNode(body_node) # its scale will change by setScale body_height = DrivableAreaProperty.LANE_LINE_GHOST_HEIGHT shape = BulletBoxShape( Vec3(length / 2 if line_type != LineType.BROKEN else length, DrivableAreaProperty.LANE_LINE_WIDTH / 2, body_height)) body_np.node().addShape(shape) mask = DrivableAreaProperty.CONTINUOUS_COLLISION_MASK if line_type != LineType.BROKEN else DrivableAreaProperty.BROKEN_COLLISION_MASK body_np.node().setIntoCollideMask(mask) self.static_nodes.append(body_np.node()) # position and heading body_np.setPos( panda_position(middle, DrivableAreaProperty.LANE_LINE_GHOST_HEIGHT / 2)) direction_v = lane_end - lane_start # theta = -numpy.arctan2(direction_v[1], direction_v[0]) theta = -math.atan2(direction_v[1], direction_v[0]) body_np.setQuat( LQuaternionf(math.cos(theta / 2), 0, 0, math.sin(theta / 2))) if self.render: # For visualization lane_line = self.loader.loadModel( AssetLoader.file_path("models", "box.bam")) lane_line.setScale(length, DrivableAreaProperty.LANE_LINE_WIDTH, DrivableAreaProperty.LANE_LINE_THICKNESS) lane_line.setPos( Vec3(0, 0 - DrivableAreaProperty.LANE_LINE_GHOST_HEIGHT / 2)) lane_line.reparentTo(body_np) body_np.set_color(color)
def addMultiSphereGhost(self,rads,centT,**kw): inodenp = self.worldNP.attachNewNode(BulletGhostNode("Sphere")) for radc, posc in zip(rads, centT): shape = BulletSphereShape(radc) inodenp.node().addShape(shape, TransformState.makePos(Point3(posc[0],posc[1],posc[2])))# self.setRB(inodenp,**kw) inodenp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(inodenp.node()) return inodenp
def get_available_respawn_places(self, map, randomize=False): """ In each episode, we allow the vehicles to respawn at the start of road, randomize will give vehicles a random position in the respawn region """ engine = get_engine() ret = {} for bid, bp in self.safe_spawn_places.items(): if bid in self.spawn_places_used: continue # save time calculate once if not bp.get("spawn_point_position", False): lane = map.road_network.get_lane( bp["config"]["spawn_lane_index"]) assert isinstance( lane, StraightLane ), "Now we don't support respawn on circular lane" long = self.RESPAWN_REGION_LONGITUDE / 2 spawn_point_position = lane.position(longitudinal=long, lateral=0) bp.force_update({ "spawn_point_heading": np.rad2deg(lane.heading_at(long)), "spawn_point_position": (spawn_point_position[0], spawn_point_position[1]) }) spawn_point_position = bp["spawn_point_position"] lane_heading = bp["spawn_point_heading"] result = rect_region_detection(engine, spawn_point_position, lane_heading, self.RESPAWN_REGION_LONGITUDE, self.RESPAWN_REGION_LATERAL, CollisionGroup.Vehicle) if (engine.global_config["debug"] or engine.global_config["debug_physics_world"]) \ and bp.get("need_debug", True): shape = BulletBoxShape( Vec3(self.RESPAWN_REGION_LONGITUDE / 2, self.RESPAWN_REGION_LATERAL / 2, 1)) vis_body = engine.render.attach_new_node( BulletGhostNode("debug")) vis_body.node().addShape(shape) vis_body.setH(panda_heading(lane_heading)) vis_body.setPos(panda_position(spawn_point_position, z=2)) engine.physics_world.dynamic_world.attach(vis_body.node()) vis_body.node().setIntoCollideMask(CollisionGroup.AllOff) bp.force_set("need_debug", False) if not result.hasHit(): new_bp = copy.deepcopy(bp).get_dict() if randomize: new_bp["config"] = self._randomize_position_in_slot( new_bp["config"]) ret[bid] = new_bp self.spawn_places_used.append(bid) return ret
def do_explosion(self, node, radius, force): center = node.get_pos(self.scene) expl_body = BulletGhostNode("expl") expl_shape = BulletSphereShape(radius) expl_body.add_shape(expl_shape) expl_bodyNP = self.scene.attach_new_node(expl_body) expl_bodyNP.set_pos(center) self.physics.attach_ghost(expl_body) result = self.physics.contact_test(expl_body) for contact in result.getContacts(): n0_name = contact.getNode0().get_name() n1_name = contact.getNode1().get_name() obj = None try: obj = self.objects[n1_name] except: break if n0_name == "expl" and n1_name not in EXPLOSIONS_DONT_PUSH and not n1_name.startswith( 'Walker'): # repeat contact test with just this pair of objects # otherwise all manifold point values will be the same # for all objects in original result real_c = self.physics.contact_test_pair(expl_body, obj.solid) mpoint = real_c.getContacts()[0].getManifoldPoint() distance = mpoint.getDistance() if distance < 0: if hasattr(obj, 'decompose'): obj.decompose() else: expl_vec = Vec3(mpoint.getPositionWorldOnA() - mpoint.getPositionWorldOnB()) expl_vec.normalize() magnitude = force * 1.0 / math.sqrt( abs(radius - abs(distance))) obj.solid.set_active(True) obj.solid.apply_impulse(expl_vec * magnitude, mpoint.getLocalPointB()) if hasattr(obj, 'damage'): obj.damage(magnitude / 5) self.physics.remove_ghost(expl_body) expl_bodyNP.detach_node() del (expl_body, expl_bodyNP)
def think(self): elapsed = self.getEntityStateElapsed() state = self.getEntityState() if state == self.StateUp: if self.timeInAir >= 0 and elapsed >= (self.timeInAir + self.startDelay): self.b_setEntityState(self.StateStomp) elif state == self.StateDown: if self.timeOnGround >= 0 and elapsed >= self.timeOnGround: self.b_setEntityState(self.StateRaise) if not self.stomped: self.stomped = True result = self.dispatch.getPhysicsWorld().contactTest( self.floorColl.node()) for contact in result.getContacts(): node = contact.getNode1() if node == self.floorColl.node(): node = contact.getNode0() if node.isOfType(BulletGhostNode.getClassType()): continue avNP = NodePath(node).getParent() for obj in self.air.avatars[self.dispatch.zoneId]: if (CIGlobals.isAvatar(obj) and obj.getKey() == avNP.getKey() and obj not in self.damaged): if self.damage != -1: obj.takeDamage( TakeDamageInfo(self, damageAmount=self.damage, damageType=DMG_FORCE)) else: obj.takeDamage( TakeDamageInfo( self, damageAmount=obj.getHealth(), damageType=DMG_FORCE)) self.damaged.append(obj) break elif state == self.StateStomp: self.startDelay = 0.0 if elapsed >= self.height / self.stompSpeed: self.b_setEntityState(self.StateDown) elif state == self.StateRaise: if elapsed >= self.height / self.raiseSpeed: self.b_setEntityState(self.StateUp)
def create_solid(self): walker_capsule = BulletGhostNode(self.name + "_walker_cap") self.walker_capsule_shape = BulletCylinderShape(.7, .2, YUp) walker_bullet_np = self.actor.attach_new_node(walker_capsule) walker_bullet_np.node().add_shape(self.walker_capsule_shape) walker_bullet_np.node().set_kinematic(True) walker_bullet_np.set_pos(0,1.5,0) walker_bullet_np.wrt_reparent_to(self.actor) self.world.physics.attach_ghost(walker_capsule) walker_bullet_np.node().setIntoCollideMask(GHOST_COLLIDE_BIT) return None
def __ghostNodeWatcherTask(triggerNp, callback, extraArgs, task): if triggerNp.isEmpty() or not triggerNp.node().isOfType( BulletGhostNode.getClassType()): return task.done for node in triggerNp.node().getOverlappingNodes(): if node.hasPythonTag( "localAvatar" ) and base.localAvatar.walkControls.getCollisionsActive(): callback(*extraArgs) return task.done return task.cont
def setupCollector(self, _obj, _eggFile): tb = _obj.getTightBounds() boxSize = VBase3(tb[1] - tb[0]) # TODO: istn't there a better way to multiply those two vectors? s = _obj.getTransform().getScale() boxSize[0] *= s[0] boxSize[1] *= s[1] boxSize[2] *= s[2] shape = BulletBoxShape(boxSize * 0.5) ghost = BulletGhostNode("Collector_Ghost_Node") ghost.addShape(shape) np = self.rootNode.attachNewNode(ghost) np.setPos(_obj.getPos()) np.setHpr(_obj.getHpr()) np.setCollideMask(BitMask32(0x0f)) self.parent.physics_world.attachGhost(ghost) self.parent.game_collector_nodes.append(np)
def makeBulletCollFromPandaColl(rootNode, exclusions=[]): """ Replaces all of the CollisionNodes underneath `rootNode` with static BulletRigidBodyNodes/GhostNodes which contain the shapes from the CollisionNodes. Applies the same transform as the node it is replacing, goes underneath same parent, has same name, has same collide mask. If the Panda CollisionNode is intangible, a BulletGhostNode is created. Else, a BulletRigidBodyNode is created. """ # First combine any redundant CollisionNodes. optimizePhys(rootNode) for pCollNp in rootNode.findAllMatches("**"): if pCollNp.getName() in exclusions: continue if pCollNp.node().getType() != CollisionNode.getClassType(): continue if pCollNp.node().getNumSolids() == 0: continue mask = pCollNp.node().getIntoCollideMask() group = CIGlobals.WallGroup if mask == CIGlobals.FloorBitmask: group = CIGlobals.FloorGroup elif mask == CIGlobals.EventBitmask: group = CIGlobals.LocalAvGroup elif mask == CIGlobals.CameraBitmask: group = CIGlobals.CameraGroup isGhost = not pCollNp.node().getSolid(0).isTangible() if isGhost: rbnode = BulletGhostNode(pCollNp.getName()) group = CIGlobals.LocalAvGroup else: rbnode = BulletRigidBodyNode(pCollNp.getName()) rbnode.addShapesFromCollisionSolids(pCollNp.node()) for shape in rbnode.getShapes(): if shape.isOfType(BulletTriangleMeshShape.getClassType()): shape.setMargin(0.1) rbnode.setKinematic(True) rbnodeNp = NodePath(rbnode) rbnodeNp.reparentTo(pCollNp.getParent()) rbnodeNp.setTransform(pCollNp.getTransform()) rbnodeNp.setCollideMask(group) # Now that we're using bullet collisions, we don't need the panda collisions anymore. pCollNp.removeNode()
def __init__(self,name,right_side_ledge, size = __DEFAULT_SIZE__): ''' Ledge(string name,Bool right_side_ledge, Platform parent_platform, Vec3 size = default) Creates a ledge object used to detect the extent of a platform at a given location The size should be [diameter, height, 0] and the cylinder shape axis is oriented in the Y+ direction. ''' # storing members radius = size.getX()*0.5 height = size.getY(); self.size_ = size self.parent_platform_ = None #parent_platform self.is_right_side_ledge_ = right_side_ledge ledge_gn = BulletGhostNode(name) ledge_gn.addShape(BulletCylinderShape(radius,height, Y_up) ) ledge_gn.setIntoCollideMask(CollisionMasks.LEDGE) GameObject.__init__(self,ledge_gn)
def __init__(self, name, radius, collideEvent=None, mask=CIGlobals.WorldGroup, offset=Point3(0), needSelfInArgs=False, startNow=True, myMask=CIGlobals.EventGroup, exclusions=[], resultInArgs=False, useSweep=False, world=None, initNp=True, useGhost=True): if self.WantNPInit: NodePath.__init__(self) if useGhost: node = BulletGhostNode(name) else: node = BulletRigidBodyNode(name) self.assign(NodePath(node)) self.needSelfInArgs = needSelfInArgs self.resultInArgs = resultInArgs self.event = collideEvent self.mask = mask self.__exclusions = [] self.useSweep = useSweep if not world and hasattr(base, 'physicsWorld') and not self.IsAI: world = base.physicsWorld self.world = world self.initialPos = Point3(0) self.lastPos = Point3(0) self.lastPosTime = 0.0 self.hitCallbacks = [] sphere = BulletSphereShape(radius) self.node().addShape(sphere, TransformState.makePos(offset)) self.node().setKinematic(True) if useSweep: self.node().setCcdMotionThreshold(1e-7) self.node().setCcdSweptSphereRadius(radius * 1.05) self.setCollideMask(myMask) if startNow: self.start()
def do_explosion(self, node, radius, force): center = node.get_pos(self.scene); expl_body = BulletGhostNode("expl") expl_shape = BulletSphereShape(radius) expl_body.add_shape(expl_shape) expl_bodyNP = self.scene.attach_new_node(expl_body) expl_bodyNP.set_pos(center) self.physics.attach_ghost(expl_body) result = self.physics.contact_test(expl_body) for contact in result.getContacts(): n0_name = contact.getNode0().get_name() n1_name = contact.getNode1().get_name() obj = None try: obj = self.objects[n1_name] except: break if n0_name == "expl" and n1_name not in EXPLOSIONS_DONT_PUSH and not n1_name.startswith('Walker'): # repeat contact test with just this pair of objects # otherwise all manifold point values will be the same # for all objects in original result real_c = self.physics.contact_test_pair(expl_body, obj.solid) mpoint = real_c.getContacts()[0].getManifoldPoint() distance = mpoint.getDistance() if distance < 0: if hasattr(obj, 'decompose'): obj.decompose() else: expl_vec = Vec3(mpoint.getPositionWorldOnA() - mpoint.getPositionWorldOnB()) expl_vec.normalize() magnitude = force * 1.0/math.sqrt(abs(radius - abs(distance))) obj.solid.set_active(True) obj.solid.apply_impulse(expl_vec*magnitude, mpoint.getLocalPointB()) if hasattr(obj, 'damage'): obj.damage(magnitude/5) self.physics.remove_ghost(expl_body) expl_bodyNP.detach_node() del(expl_body, expl_bodyNP)
def __init__(self, num_lasers: int = 240, distance: float = 50, enable_show=False): super(Lidar, self).__init__(num_lasers, distance, enable_show) self.origin.hide(CamMask.RgbCam | CamMask.Shadow | CamMask.Shadow | CamMask.DepthCam) self.mask = CollisionGroup.Vehicle | CollisionGroup.InvisibleWall | CollisionGroup.TrafficObject # lidar can calculate the detector mask by itself self.angle_delta = 360 / num_lasers if num_lasers > 0 else None self.broad_detector = NodePath(BulletGhostNode("detector_mask")) self.broad_detector.node().addShape(BulletCylinderShape(self.BROAD_PHASE_EXTRA_DIST + distance, 5)) self.broad_detector.node().setIntoCollideMask(CollisionGroup.LidarBroadDetector) self.broad_detector.node().setStatic(True) engine = get_engine() engine.physics_world.static_world.attach(self.broad_detector.node()) self.enable_mask = True if not engine.global_config["_disable_detector_mask"] else False
def __init__(self, cords, radius, name, parentnode): self.cords = cords self.planetNode = parentnode.attachNewNode(name) self.planetNode.setPos(cords) self.psize = radius # chunks self.radius = (self.psize / 2) #planet self.colisionnp = parentnode.attachNewNode(BulletGhostNode(name)) self.colisionnp.node().addShape(BulletSphereShape(radius * 16)) self.colisionnp.setPos(0, 0, 0) self.colisionnp.node().setDeactivationEnabled(False) manager.physics.getWorld().attachGhost(self.colisionnp.node()) """
def __initCollisions(self, name): self.notify.debug("Initializing collision sphere...") numSlots = len(self.circles) ss = BulletSphereShape(self.numPlayers2SphereRadius[numSlots]) snode = BulletGhostNode(name) snode.addShape(ss) snode.setKinematic(True) snode.setIntoCollideMask(CIGlobals.LocalAvGroup) self.snp = self.attach_new_node(snode) self.snp.setZ(3) self.snp.setY(self.numPlayers2SphereY[numSlots]) self.snp.setSx(self.numPlayers2SphereSx[numSlots]) self.snp.setSy(self.numPlayers2SphereSy[numSlots]) base.physicsWorld.attachGhost(snode) self.acceptOnce("enter" + self.snp.node().getName(), self.__handleEnterCollisionSphere)
def setupPhysics(self): shape = BulletSphereShape(1.0) bnode = BulletGhostNode(self.uniqueName('codeNumberPhys')) bnode.addShape(shape) bnode.setIntoCollideMask(CIGlobals.EventGroup) DistributedEntity.setupPhysics(self, bnode, True) self.stopWaterCheck() self.acceptOnce('enter' + self.uniqueName('codeNumberPhys'), self.__handlePickup)
def __setupCollisions(self): sphere = BulletSphereShape(4.0) gnode = BulletGhostNode(self.uniqueName('NPCToonSphere')) gnode.addShape(sphere) gnode.setKinematic(True) self.collisionNodePath = self.attachNewNode(gnode) self.collisionNodePath.setY(1.5) self.collisionNodePath.setCollideMask(CIGlobals.EventGroup) base.physicsWorld.attachGhost(self.collisionNodePath.node())
def searchMode(self,location,heading): self.state['normal'] = True self.state['rolling'] = False (self.init_x,self.init_y,self.init_z) = location self.__capsule_shape = BulletCapsuleShape(Eve.WIDTH, Eve.HEIGHT - 2 * Eve.WIDTH, ZUp) # Create bullet character controller self.character1= BulletCharacterControllerNode(self.__capsule_shape,0.4,self.name) #self.character1.setMaxJumpHeight(Eve.MAX_JUMP_HEIGHT) self.character1.setJumpSpeed(Eve.JUMP_SPEED) self.character1.setGravity(70) self.characterNP1 = self.__render.attachNewNode(self.character1) self.characterNP1.setPos(self.init_x,self.init_y,self.init_z) self.characterNP1.setH(heading) self.characterNP1.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character1) self.actorNP1.reparentTo(self.characterNP1) self.actorNP1.setScale(4.0) self.actorNP1.setH(180) self.actorNP1.setPos(0,0,-9) self.currentNode = self.actorNP1 self.currentNP = self.characterNP1 self.currentControllerNode = self.character1 # Create a cylindrical collision shape collisionShape = BulletCylinderShape(6.5,3,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode('Weapon') self.ghostNode.addShape(collisionShape) self.weaponNP = self.__game.render.attachNewNode(self.ghostNode) self.weaponNP.setCollideMask(BitMask32.allOff()) self.weaponNP.setPos(self.init_x, self.init_y, self.init_z) self.__game.world.attachGhost(self.ghostNode) self.weapon = self.__game.loader.loadModel('models/environ/tire/tire.egg') self.weapon.setScale(4,4,4) self.weapon.setPos(-.5,0,0) self.weapon.reparentTo(self.weaponNP) self.weapon.hide() self.__game.taskMgr.add(self.update_weapon_pos,"weapon")
class Checkpoint(object): ''' checkpoint object to track race posistions ''' count = 0 def __init__(self, main, pos, h): ''' Constructor ''' self.setupCheckpoint(main, pos, h) self.cid = Checkpoint.count Checkpoint.count += 1 def setupCheckpoint(self, main, pos, h): # Chassis shape = BulletBoxShape(Vec3(1, 5, 1)) ts = TransformState.makePos(Point3(0, 0, 0)) self.cpnode = BulletGhostNode('CheckPoint') self.cpnode = render.attachNewNode(self.cpnode) self.cpnode.node().addShape(shape, ts) self.cpnode.setCollideMask(BitMask32(0x0f)) # self.cpnode.node().notifyCollisions(True) self.cpnode.setPos(pos.x, pos.y, pos.z) self.cpnode.setH(h) main.bulletWorld.attachGhost(self.cpnode.node())
def create_big_token(self): # Create a cylindrical collision shape collisionShape = BulletCylinderShape(Token.L_HEIGHT,Token.L_RADIUS,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode(self.name) self.ghostNode.addShape(collisionShape) self.np = self.__game.render.attachNewNode(self.ghostNode) self.np.setCollideMask(BitMask32.allOff()) self.np.setPos(self.x, self.y, self.z) self.__game.world.attachGhost(self.ghostNode) token = self.__game.loader.loadModel(Token.MODEL_PATH) token.setScale(Token.L_TOKEN_SCALE[0],Token.L_TOKEN_SCALE[1],Token.L_TOKEN_SCALE[2]) token.setPos(-.5,0,0) token.reparentTo(self.np) self.__game.e.tokens.append(self)
def __init__(self, ppos, h, p, parent, parentVel, world, worldNP): self.world=world if Projectile.model==0: Projectile.model = Model("../assets/3d/Actors/ball_proj2.egg") h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) ppos = map(lambda i: ppos[i]+dir[i]*20, range(3)) self.instance = Projectile.model.createInstance(pos=ppos,hpr=(h,p,0),scale=3) self.dhpr = [random.random(),random.random(),random.random()] pmin = LPoint3() pmax = LPoint3() self.instance.calcTightBounds(pmin,pmax) norm = pmin-pmax self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5) r = max(norm) pos = ppos shape = BulletSphereShape(.5*r) self.sphere = BulletGhostNode('ProjectileSphere') self.sphere.addShape(shape) self.sphere.setDeactivationEnabled(False) self.np = worldNP.attachNewNode(self.sphere) self.np.setPos(LVecBase3f(ppos[0],ppos[1],ppos[2])) self.np.setCollideMask(BitMask32.allOn()) world.attachGhost(self.sphere) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) self.vel = parentVel self.vel = map(lambda i: dir[i]*100, range(3)) self.index = Projectile.index self.parent = parent Projectile.index = Projectile.index + 1 taskMgr.add(self.move,"Proj"+str(Projectile.index)+"MoveTask") self.prevTime = 0 self.lifeTime = 0 Projectile.projectiles.append(self) self.TIMEDLIFE = 120 self.dead = 0
def setupCheckpoint(self, main, pos, h): # Chassis shape = BulletBoxShape(Vec3(1, 5, 1)) ts = TransformState.makePos(Point3(0, 0, 0)) self.cpnode = BulletGhostNode('CheckPoint') self.cpnode = render.attachNewNode(self.cpnode) self.cpnode.node().addShape(shape, ts) self.cpnode.setCollideMask(BitMask32(0x0f)) # self.cpnode.node().notifyCollisions(True) self.cpnode.setPos(pos.x, pos.y, pos.z) self.cpnode.setH(h) main.bulletWorld.attachGhost(self.cpnode.node())
def __init__(self, world, worldNP): self.failed = 1 self.world = world if clawTrap.model==0: clawTrap.model = Model("../assets/3d/Actors/claw3.egg") h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) cpos = camera.getPos() vec = map(lambda i: cpos[i]+dir[i]*200, range(3)) rayHit = world.rayTestClosest(cpos,LPoint3(vec[0],vec[1],vec[2])) if not rayHit.hasHit(): return npos = rayHit.getHitPos() n = rayHit.getHitNormal() print n npos = map(lambda i: npos[i]+n[i]*5, range(3)) self.instance = clawTrap.model.createInstance(pos=npos,hpr=(-90*n.x,180*(n.z==1)+90*(abs(n.x)+n.y),0)) self.index = clawTrap.index pmin = LPoint3() pmax = LPoint3() self.instance.calcTightBounds(pmin,pmax) norm = pmin-pmax self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5) r = max(norm) shape = BulletSphereShape(.7*r) self.sphere = BulletGhostNode('TrapSphere') self.sphere.addShape(shape) self.sphere.setDeactivationEnabled(False) self.np = worldNP.attachNewNode(self.sphere) self.np.setPos(LVecBase3(npos[0],npos[1],npos[2])) self.np.setCollideMask(BitMask32.allOn()) world.attachGhost(self.sphere) #taskMgr.add(self.check,"floatTrap"+str(self.index)+"Check") clawTrap.traps.append(self) clawTrap.index = clawTrap.index + 1 self.failed = 0
def create_solid(self): node = BulletGhostNode(self.name) node_shape = BulletSphereShape(.5) node.add_shape(node_shape) node.set_kinematic(True) return node
class Token(): # Class variables for regular sized token R_VALUE = 10 R_RADIUS = 3 R_HEIGHT = 6.5 R_TOKEN_SCALE = (4,4,4) # Class variables for large token L_VALUE = 100 L_RADIUS = 6 L_HEIGHT = 15 L_TOKEN_SCALE = (10,10,10) # Model used for token MODEL_PATH = 'models/environ/tire/tire.egg' ''' Constructor creates instance variables for the name and position or the token as well as a reference to the game. @param name - name of the token can either be 'Token' or 'BigToken' @param location - position where the token will be placed @param game - reference to the current game ''' def __init__(self,name,location,game): self.name = name (self.x,self.y,self.z) = location self.__game = game self.collect = base.loader.loadSfx("sfx/coin_collect.wav") self.collect.setVolume(.04) ''' Creates regular token ''' def create_token(self): # Create a cylindrical collision shape collisionShape = BulletCylinderShape(Token.R_HEIGHT,Token.R_RADIUS,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode(self.name) self.ghostNode.addShape(collisionShape) self.np = self.__game.render.attachNewNode(self.ghostNode) self.np.setCollideMask(BitMask32.allOff()) self.np.setPos(self.x, self.y, self.z) self.__game.world.attachGhost(self.ghostNode) token = self.__game.loader.loadModel(Token.MODEL_PATH) token.setScale((Token.R_TOKEN_SCALE[0],Token.R_TOKEN_SCALE[1],Token.R_TOKEN_SCALE[2])) token.setPos(-.5,0,0) token.reparentTo(self.np) self.__game.e.tokens.append(self) ''' Create big token for end of stage ''' def create_big_token(self): # Create a cylindrical collision shape collisionShape = BulletCylinderShape(Token.L_HEIGHT,Token.L_RADIUS,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode(self.name) self.ghostNode.addShape(collisionShape) self.np = self.__game.render.attachNewNode(self.ghostNode) self.np.setCollideMask(BitMask32.allOff()) self.np.setPos(self.x, self.y, self.z) self.__game.world.attachGhost(self.ghostNode) token = self.__game.loader.loadModel(Token.MODEL_PATH) token.setScale(Token.L_TOKEN_SCALE[0],Token.L_TOKEN_SCALE[1],Token.L_TOKEN_SCALE[2]) token.setPos(-.5,0,0) token.reparentTo(self.np) self.__game.e.tokens.append(self) def collected(self): contactResult = self.__game.world.contactTestPair(self.__game.eve.currentControllerNode, self.ghostNode) if len(contactResult.getContacts()) > 0: if(self.ghostNode.getName() == 'BigToken'): self.__game.levelFinish = True self.__game.user.score += Token.L_VALUE else: self.__game.user.score += Token.L_VALUE self.ghostNode.removeChild(0) self.__game.world.removeGhost(self.ghostNode) self.__game.e.tokens.remove(self) self.__game.eve.tiresCollected += 1 self.collect.play() def spinToken(self): self.np.setH(self.np.getH() + 2)
class Projectile(): projectiles = list() model = 0 index = 0 def __init__(self, ppos, h, p, parent, parentVel, world, worldNP): self.world=world if Projectile.model==0: Projectile.model = Model("../assets/3d/Actors/ball_proj2.egg") h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) ppos = map(lambda i: ppos[i]+dir[i]*20, range(3)) self.instance = Projectile.model.createInstance(pos=ppos,hpr=(h,p,0),scale=3) self.dhpr = [random.random(),random.random(),random.random()] pmin = LPoint3() pmax = LPoint3() self.instance.calcTightBounds(pmin,pmax) norm = pmin-pmax self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5) r = max(norm) pos = ppos shape = BulletSphereShape(.5*r) self.sphere = BulletGhostNode('ProjectileSphere') self.sphere.addShape(shape) self.sphere.setDeactivationEnabled(False) self.np = worldNP.attachNewNode(self.sphere) self.np.setPos(LVecBase3f(ppos[0],ppos[1],ppos[2])) self.np.setCollideMask(BitMask32.allOn()) world.attachGhost(self.sphere) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) self.vel = parentVel self.vel = map(lambda i: dir[i]*100, range(3)) self.index = Projectile.index self.parent = parent Projectile.index = Projectile.index + 1 taskMgr.add(self.move,"Proj"+str(Projectile.index)+"MoveTask") self.prevTime = 0 self.lifeTime = 0 Projectile.projectiles.append(self) self.TIMEDLIFE = 120 self.dead = 0 def kill(self): self.instance.removeNode() self.parent.projectiles.remove(self) self.world.removeGhost(self.sphere) Projectile.projectiles.remove(self) self.dead = 1 def check(self,contacts,human,players): if len(contacts)==0: return contactObject = contacts[0].getNode0() if contacts[0].getNode0().getName()=="ProjectileSphere": contactObject = contacts[0].getNode1() name = contactObject.getName() #print name if name==human.character.getName(): human.impact(self.vel) self.kill() return for i in range(len(players)): if name==players[i].character.getName(): players[i].impact(self.vel) self.kill() return return def move(self,task): if self.dead==1: return dt = task.time-self.prevTime #If the projectile exceeds its maximum lifetime or burns out on the arena bounds - self.lifeTime += dt if(self.lifeTime >= self.TIMEDLIFE): #kill projectile self.instance.removeNode() self.parent.projectiles.remove(self) self.world.removeGhost(self.sphere) Projectile.projectiles.remove(self) return #print "Projectile removed" if(self.lifeTime < self.TIMEDLIFE): #get the position pos = self.instance.getPos() #get the displacement dis = (self.vel[0]*dt,self.vel[1]*dt,self.vel[2]*dt) #set the new position self.np.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2]) self.instance.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2]) hpr = self.instance.getHpr() hpr = map(lambda i: hpr[i]+dt*100*self.dhpr[i], range(3)) self.instance.setHpr(hpr[0],hpr[1],hpr[2]) return task.cont
class clawTrap(): traps = list() model = 0 index = 0 def __init__(self, world, worldNP): self.failed = 1 self.world = world if clawTrap.model==0: clawTrap.model = Model("../assets/3d/Actors/claw3.egg") h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) cpos = camera.getPos() vec = map(lambda i: cpos[i]+dir[i]*200, range(3)) rayHit = world.rayTestClosest(cpos,LPoint3(vec[0],vec[1],vec[2])) if not rayHit.hasHit(): return npos = rayHit.getHitPos() n = rayHit.getHitNormal() print n npos = map(lambda i: npos[i]+n[i]*5, range(3)) self.instance = clawTrap.model.createInstance(pos=npos,hpr=(-90*n.x,180*(n.z==1)+90*(abs(n.x)+n.y),0)) self.index = clawTrap.index pmin = LPoint3() pmax = LPoint3() self.instance.calcTightBounds(pmin,pmax) norm = pmin-pmax self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5) r = max(norm) shape = BulletSphereShape(.7*r) self.sphere = BulletGhostNode('TrapSphere') self.sphere.addShape(shape) self.sphere.setDeactivationEnabled(False) self.np = worldNP.attachNewNode(self.sphere) self.np.setPos(LVecBase3(npos[0],npos[1],npos[2])) self.np.setCollideMask(BitMask32.allOn()) world.attachGhost(self.sphere) #taskMgr.add(self.check,"floatTrap"+str(self.index)+"Check") clawTrap.traps.append(self) clawTrap.index = clawTrap.index + 1 self.failed = 0 #pos = self.instance.getPos() #self.np.setPos(pos[0]-self.off[0],pos[1]-self.off[1],pos[2]-self.off[2]) def kill(self): clawTrap.traps.remove(self) self.world.removeGhost(self.sphere) self.instance.detachNode() def check(self,contacts,human,players): if len(contacts)>0: contactObject = contacts[0].getNode0() if contacts[0].getNode0().getName()=="TrapSphere": contactObject = contacts[0].getNode1() name = contactObject.getName() print contactObject if name==human.character.getName(): human.trap2() self.kill() return for i in range(len(players)): if name==players[i].character.getName(): players[i].trap2() self.kill() return
class Eve(Character): #----- CLASS VARIABLES -----# HEIGHT = 21.00 WIDTH = 5.0 INITIAL_HEADING = 90 MAX_JUMP_HEIGHT = 200.0 JUMP_SPEED = 70 RUNNING_SPEED = 40.0 INITIAL_ROLL_SPEED = 200.0 ROLL_ANIM_RATE = 15 OMEGA = 60.0 #----- CONSTRUCTOR -----# def __init__(self,game,render,world,accept,health=100,damage=0): super(Eve,self).__init__('Eve',health,damage) #----- INSTANCE VARIABLES -----# self.state = {'normal': True, 'jumping' : False, 'rolling' : False} self.speed = Vec3(0, 0, 0) self.omega = 0.0 self.tiresCollected = 0 self.accept = accept self.ready = True #----- PRIVATE INSTANCE VARIABLES -----# self.__render = render self.__world = world self.__game = game #----- ACTOR SETUP -----# self.actorNP1 = Actor('models/eve/eve.egg', { 'run' : 'models/eve/eve-run.egg', 'walk' : 'models/eve/eve-walk.egg', 'jump' : 'models/eve/eve-jump.egg'}) self.actorNP2 = Actor('models/eve/eve-tireroll.egg', {'roll' : 'models/eve/eve-tireroll.egg'}) self.actorNP1.setPlayRate(2,'walk') #----- PREPARE SFX -----# self.jump = base.loader.loadSfx("sfx/jump.wav") self.jump.setVolume(.1) self.running = base.loader.loadSfx("sfx/walking.wav") self.running.setLoop(True) self.running.setPlayRate(1.55) self.running.setVolume(.08) self.land = base.loader.loadSfx("sfx/land.flac") self.land.setLoop(False) self.land.setVolume(.05) self.roll = base.loader.loadSfx("sfx/rolling.wav") self.roll.setLoop(True) self.roll.setVolume(.09) self.ouch = base.loader.loadSfx("sfx/ouch.wav") self.ouch.setLoop(False) self.ouch.setVolume(.75) self.ouch.setPlayRate(1.25) self.throw = base.loader.loadSfx("sfx/throw.wav") self.throw.setLoop(False) self.throw.setVolume(.75) self.blocked = base.loader.loadSfx("sfx/blocked.wav") self.blocked.setVolume(.05) #----- SETUP CONTROL FOR EVE -----# inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('turnLeft', 'a') inputState.watchWithModifiers('turnRight', 'd') inputState.watchWithModifiers('backwards', 's') def render_eve(self,pos): self.searchMode(pos,Eve.INITIAL_HEADING) # Changing jump animation play rate self.currentNode.setPlayRate(1,'jump') self.__game.taskMgr.add(self.process_contacts,'attacks') def disable_character_controls(self): self.accept('m', self.do_nothing) self.accept('space', self.do_nothing) self.accept('enter',self.do_nothing) def enable_character_controls(self): self.accept('m', self.toggle_modes) self.accept('space', self.doJump) self.accept('enter',self.attack) def do_nothing(self): pass #------ METHODS USED TO MODIFY JUMP ANIMATION ------# def firstPart(self): self.currentNode.play('jump', fromFrame=0) def stopInJump(self): self.currentNode.stop() def finishJump(self): self.currentNode.play('jump', fromFrame=11) self.land.play() #self.currentNode.play('jump', fromFrame=self.currentNode.getCurrentFrame('jump')) def doJump(self): if self.currentControllerNode.isOnGround() is True: if self.currentState() is 'normal': if self.speed.getY() > 0: self.running.stop() self.state['jumping'] = True self.jump.play() self.currentControllerNode.doJump() #sequence = Sequence(Func(self.firstPart),Wait(.3),Func(self.stopInJump),Wait(2.95),Func(self.finishJump)) sequence = Sequence(Func(self.firstPart),Wait(.3),Func(self.stopInJump),Wait(2.95)) sequence.start() def searchMode(self,location,heading): self.state['normal'] = True self.state['rolling'] = False (self.init_x,self.init_y,self.init_z) = location self.__capsule_shape = BulletCapsuleShape(Eve.WIDTH, Eve.HEIGHT - 2 * Eve.WIDTH, ZUp) # Create bullet character controller self.character1= BulletCharacterControllerNode(self.__capsule_shape,0.4,self.name) #self.character1.setMaxJumpHeight(Eve.MAX_JUMP_HEIGHT) self.character1.setJumpSpeed(Eve.JUMP_SPEED) self.character1.setGravity(70) self.characterNP1 = self.__render.attachNewNode(self.character1) self.characterNP1.setPos(self.init_x,self.init_y,self.init_z) self.characterNP1.setH(heading) self.characterNP1.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character1) self.actorNP1.reparentTo(self.characterNP1) self.actorNP1.setScale(4.0) self.actorNP1.setH(180) self.actorNP1.setPos(0,0,-9) self.currentNode = self.actorNP1 self.currentNP = self.characterNP1 self.currentControllerNode = self.character1 # Create a cylindrical collision shape collisionShape = BulletCylinderShape(6.5,3,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode('Weapon') self.ghostNode.addShape(collisionShape) self.weaponNP = self.__game.render.attachNewNode(self.ghostNode) self.weaponNP.setCollideMask(BitMask32.allOff()) self.weaponNP.setPos(self.init_x, self.init_y, self.init_z) self.__game.world.attachGhost(self.ghostNode) self.weapon = self.__game.loader.loadModel('models/environ/tire/tire.egg') self.weapon.setScale(4,4,4) self.weapon.setPos(-.5,0,0) self.weapon.reparentTo(self.weaponNP) self.weapon.hide() self.__game.taskMgr.add(self.update_weapon_pos,"weapon") def reset(self): self.characterNP1.setPos(self.init_x,self.init_y,self.init_z) def update_weapon_pos(self,task): self.weaponNP.setPos(self.characterNP1.getX(),self.characterNP1.getY(), self.characterNP1.getZ() + 5) self.weaponNP.setH(self.characterNP1.getH()) return task.cont def attack(self): if self.tiresCollected > 0 and self.ready is True: self.throw.play() self.weapon.show() xpos = 100 * cos((90 - self.characterNP1.getH()) * (pi / 180.0)) ypos = -100 * sin((90 - self.characterNP1.getH()) * (pi / 180.0)) trajectory = ProjectileInterval(self.weaponNP, startPos = self.weaponNP.getPos(), endPos = Point3(self.weaponNP.getX() - xpos,self.weaponNP.getY() - ypos, self.weaponNP.getZ()-10), duration = .5, gravityMult = 15) Sequence(Func(self.set_weapon_busy),trajectory,Func(self.weapon.hide),Func(self.set_weapon_ready)).start() self.tiresCollected -= 1 else: self.blocked.play() def set_weapon_ready(self): self.ready = True def set_weapon_busy(self): self.ready = False def process_contacts(self,task): for enemy in self.__game.e.enemies: self.check_impact(enemy) return task.cont def check_impact(self,enemy): result = self.__game.world.contactTestPair(self.ghostNode,enemy.np.node()) if len(result.getContacts()) > 0: if self.weapon.isHidden() is False: self.weapon.hide() if self.ready is False: enemy.take_damage(self.damage) def attackMode(self,location,heading): self.state['normal'] = False self.state['rolling'] = True (self.init_x,self.init_y,self.init_z) = location self.__cylinder_shape = BulletCylinderShape(Eve.WIDTH + 2, Eve.HEIGHT - 4, XUp) # Create bullet character controller self.character2= BulletCharacterControllerNode(self.__cylinder_shape,0.4,self.name) self.characterNP2 = self.__render.attachNewNode(self.character2) self.characterNP2.setPos(self.init_x,self.init_y,self.init_z-2) self.characterNP2.setH(heading) self.characterNP2.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character2) self.character2.setGravity(70) self.actorNP2.reparentTo(self.characterNP2) self.actorNP2.setScale(4.0) self.actorNP2.setH(180) self.actorNP2.setPos(0,0,0) self.currentNode = self.actorNP2 self.currentNP = self.characterNP2 self.currentControllerNode = self.character2 # Set play rate of the rolling animation self.currentNode.setPlayRate(15,'roll') def is_attack_mode(self): return self.state['rolling'] def toggle_modes(self): if self.is_attack_mode() is False: loc = (self.characterNP1.getX(),self.characterNP1.getY(),self.characterNP1.getZ()) heading = self.characterNP1.getH() self.__world.removeCharacter(self.character1) self.character1.removeChild(0) self.attackMode(loc,heading) else: loc = (self.characterNP2.getX(),self.characterNP2.getY(),self.characterNP2.getZ()) heading = self.characterNP2.getH() self.__world.removeCharacter(self.character2) self.character2.removeChild(0) self.searchMode(loc,heading) def processEveInput(self): if self.currentControllerNode.isOnGround() is True: self.speed = Vec3(0, 0, 0) self.omega = 0.0 if inputState.isSet('forward'): if self.state['rolling'] == True: self.speed.setY( Eve.INITIAL_ROLL_SPEED) else: self.speed.setY( Eve.RUNNING_SPEED) self.currentNode.setP(15) if inputState.isSet('backwards'): if self.state['rolling'] == True: self.speed.setY( Eve.INITIAL_ROLL_SPEED - 300) else: self.speed.setY(-1 * Eve.RUNNING_SPEED - 10) if inputState.isSet('turnLeft'): self.omega = Eve.OMEGA if self.speed.getY() == 0: self.currentNode.setR(0) else: self.currentNode.setR(15) if inputState.isSet('turnRight'): self.omega = Eve.OMEGA * -1 if self.speed.getY() == 0: self.currentNode.setR(0) else: self.currentNode.setR(-15) self.currentControllerNode.setAngularMovement(self.omega) if self.currentControllerNode.isOnGround() is False: self.currentControllerNode.setAngularMovement(0.0) self.currentControllerNode.setLinearMovement(self.speed, True) self.currentNode.setR(0) if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() == 'jump': self.currentNode.setR(0) self.currentControllerNode.setAngularMovement(0.0) self.currentControllerNode.setLinearMovement(0.0, True) if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump': self.currentControllerNode.setAngularMovement(self.omega) self.currentControllerNode.setLinearMovement(self.speed, True) def currentState(self): if self.state['rolling'] is True: return 'rolling' else: return 'normal' def updateEveAnim(self): self.processEveInput() if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump': if self.speed.getY() > 0: if self.omega == 0.0: self.currentNode.setR(0) if self.currentState() is 'rolling': if self.running.status() == self.running.PLAYING: self.running.stop() if self.roll.status() != self.roll.PLAYING: self.roll.play() if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll') elif self.currentState() is 'normal': if self.roll.status() == self.roll.PLAYING: self.roll.stop() if self.running.status() != self.running.PLAYING: self.running.play() if self.currentNode.getCurrentAnim() != 'run': self.currentNode.loop('run') elif self.speed.getY() < 0: if self.currentState() is 'rolling': if self.running.status() == self.running.PLAYING: self.running.stop() if self.roll.status() != self.roll.PLAYING: self.roll.play() if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll') elif self.currentState() is 'normal': if self.roll.status() == self.roll.PLAYING: self.roll.stop() if self.running.status() != self.running.PLAYING: self.running.play() if self.currentNode.getCurrentAnim() != 'walk': self.currentNode.loop('walk') else: if self.omega != 0: if self.currentState() is 'rolling': if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll') elif self.currentState() is 'normal': if self.currentNode.getCurrentAnim() != 'walk': self.actorNP1.setPlayRate(1,'walk') self.currentNode.loop('walk') else: self.currentNode.stop(self.currentNode.getCurrentAnim()) self.actorNP1.setPlayRate(2,'walk') self.currentNode.setP(0) self.currentNode.setR(0) if self.running.status() == self.running.PLAYING: self.running.stop() if self.roll.status() == self.roll.PLAYING: self.roll.stop() if self.state['rolling'] is True: frame = self.currentNode.getCurrentFrame('roll') if frame is None: frame = 0 else: frame = self.currentNode.getCurrentFrame('roll') self.currentNode.pose('roll',frame) elif self.state['normal'] is True: self.currentNode.pose('walk',5) elif self.currentControllerNode.isOnGround() is False and self.state['jumping'] is False: self.currentNode.pose('jump',7) def take_damage(self,damage): self.ouch.play() color_scale_interval1 = LerpColorScaleInterval(self.currentNode, .5, (1,0,0,.1), (1,0,0,0)) Sequence(color_scale_interval1,Wait(.005),Func(self.currentNode.clearColorScale)).start() self.health -= damage