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 _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 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 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 __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
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 __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 __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 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 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 generate(self): DistributedEntity.generate(self) sph = BulletSphereShape(1.0) gn = BulletGhostNode(self.uniqueName("pickupGhost")) print gn.getName() gn.addShape(sph) self.collNode = self.attachNewNode(gn) self.pickupSound = base.loadSfx(self.PickupSoundPath)
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 __initializeEventSphere(self): sphere = BulletSphereShape(2) node = BulletGhostNode(self.uniqueName("DEagleSuit-eventSphere")) node.addShape(sphere) node.setIntoCollideMask(CIGlobals.WallBitmask) np = self.attachNewNode(node) np.setSz(2.5) np.setZ(5.5) base.physicsWorld.attach(node) #np.show() self.eventSphereNodePath = np
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 __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 __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 __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 __init__(self): try: self.__initialized return except: self.__initialized = 1 NodePath.__init__(self, hidden.attachNewNode('PositionExaminer')) bsph = BulletSphereShape(1.5) bgh = BulletGhostNode('positionExaminer_sphereGhost') bgh.addShape(bsph) bgh.setKinematic(True) self.cSphereNodePath = self.attachNewNode(bgh)
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 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 _add_chassis(self, pg_physics_world: PGPhysicsWorld): para = self.get_config() self.LENGTH = self.vehicle_config["vehicle_length"] self.WIDTH = self.vehicle_config["vehicle_width"] chassis = BaseVehicleNode(BodyName.Base_vehicle, self) chassis.setIntoCollideMask(BitMask32.bit(CollisionGroup.EgoVehicle)) chassis_shape = BulletBoxShape( Vec3(self.WIDTH / 2, self.LENGTH / 2, para[Parameter.vehicle_height] / 2)) ts = TransformState.makePos( Vec3(0, 0, para[Parameter.chassis_height] * 2)) chassis.addShape(chassis_shape, ts) heading = np.deg2rad(-para[Parameter.heading] - 90) chassis.setMass(para[Parameter.mass]) self.chassis_np = self.node_path.attachNewNode(chassis) # not random spawn now self.chassis_np.setPos(Vec3(*self.spawn_place, 1)) self.chassis_np.setQuat( LQuaternionf(math.cos(heading / 2), 0, 0, math.sin(heading / 2))) chassis.setDeactivationEnabled(False) chassis.notifyCollisions( True ) # advance collision check, do callback in pg_collision_callback self.dynamic_nodes.append(chassis) chassis_beneath = BulletGhostNode(BodyName.Base_vehicle_beneath) chassis_beneath.setIntoCollideMask( BitMask32.bit(CollisionGroup.EgoVehicleBeneath)) chassis_beneath.addShape(chassis_shape) self.chassis_beneath_np = self.chassis_np.attachNewNode( chassis_beneath) self.dynamic_nodes.append(chassis_beneath) self.system = BulletVehicle(pg_physics_world.dynamic_world, chassis) self.system.setCoordinateSystem(ZUp) self.dynamic_nodes.append( self.system ) # detach chassis will also detach system, so a waring will generate if self.render: if self.MODEL is None: model_path = 'models/ferra/scene.gltf' self.MODEL = self.loader.loadModel( AssetLoader.file_path(model_path)) self.MODEL.setZ(para[Parameter.vehicle_vis_z]) self.MODEL.setY(para[Parameter.vehicle_vis_y]) self.MODEL.setH(para[Parameter.vehicle_vis_h]) self.MODEL.set_scale(para[Parameter.vehicle_vis_scale]) self.MODEL.instanceTo(self.chassis_np)
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 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 setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') np = self.worldNP.attachNewNode(node) np.node().addShape(shape) np.setPos(0, 0, 0) np.setCollideMask(BitMask32(0x0f)) self.world.attachRigidBody(np.node()) # Box shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(0, 0, 4) np.setCollideMask(BitMask32(0x0f)) self.world.attachRigidBody(np.node()) self.boxNP = np visualNP = loader.loadModel('models/box.egg') visualNP.reparentTo(self.boxNP) # Trigger shape = BulletBoxShape(Vec3(1, 1, 2)) np = self.worldNP.attachNewNode(BulletGhostNode('Ghost')) np.node().addShape(shape) np.setPos(3, 0, 0) np.setCollideMask(BitMask32(0x0f)) self.world.attachGhost(np.node()) self.ghostNP = np
def setup(self): self.worldNP = render.attach_new_node('World') # World self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Ground shape = BulletPlaneShape(LVector3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') np = self.worldNP.attach_new_node(node) np.node().add_shape(shape) np.set_pos(0, 0, 0) np.set_collide_mask(BitMask32(0x0f)) self.world.attach(np.node()) # Box shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5)) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box')) np.node().set_mass(1.0) np.node().add_shape(shape) np.set_pos(0, 0, 4) np.set_collide_mask(BitMask32(0x0f)) self.world.attach(np.node()) self.boxNP = np visualNP = loader.load_model('models/box.egg') visualNP.reparent_to(self.boxNP) # Trigger shape = BulletBoxShape(LVector3(1, 1, 2)) np = self.worldNP.attach_new_node(BulletGhostNode('Ghost')) np.node().add_shape(shape) np.set_pos(3, 0, 0) np.set_collide_mask(BitMask32(0x0f)) self.world.attach(np.node()) self.ghostNP = np
def _add_chassis(self, pg_physics_world: PGPhysicsWorld): para = self.get_config() chassis = BulletRigidBodyNode(BodyName.Ego_vehicle_top) chassis.setIntoCollideMask(BitMask32.bit(self.COLLISION_MASK)) chassis_shape = BulletBoxShape( Vec3(para[Parameter.vehicle_width] / 2, para[Parameter.vehicle_length] / 2, para[Parameter.vehicle_height] / 2)) ts = TransformState.makePos( Vec3(0, 0, para[Parameter.chassis_height] * 2)) chassis.addShape(chassis_shape, ts) heading = np.deg2rad(-para[Parameter.heading] - 90) chassis.setMass(para[Parameter.mass]) self.chassis_np = self.node_path.attachNewNode(chassis) # not random born now self.chassis_np.setPos(Vec3(*self.born_place, 1)) self.chassis_np.setQuat( LQuaternionf(np.cos(heading / 2), 0, 0, np.sin(heading / 2))) chassis.setDeactivationEnabled(False) chassis.notifyCollisions(True) # advance collision check self.pg_world.physics_world.dynamic_world.setContactAddedCallback( PythonCallbackObject(self._collision_check)) self.dynamic_nodes.append(chassis) chassis_beneath = BulletGhostNode(BodyName.Ego_vehicle) chassis_beneath.setIntoCollideMask(BitMask32.bit(self.COLLISION_MASK)) chassis_beneath.addShape(chassis_shape) self.chassis_beneath_np = self.chassis_np.attachNewNode( chassis_beneath) self.dynamic_nodes.append(chassis_beneath) self.system = BulletVehicle(pg_physics_world.dynamic_world, chassis) self.system.setCoordinateSystem(ZUp) self.dynamic_nodes.append( self.system ) # detach chassis will also detach system, so a waring will generate self.LENGTH = para[Parameter.vehicle_length] self.WIDTH = para[Parameter.vehicle_width] if self.render: model_path = 'models/ferra/scene.gltf' self.chassis_vis = self.loader.loadModel( AssetLoader.file_path(model_path)) self.chassis_vis.setZ(para[Parameter.vehicle_vis_z]) self.chassis_vis.setY(para[Parameter.vehicle_vis_y]) self.chassis_vis.setH(para[Parameter.vehicle_vis_h]) self.chassis_vis.set_scale(para[Parameter.vehicle_vis_scale]) self.chassis_vis.reparentTo(self.chassis_np)
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 __addElements(self): # Walk Capsule self.__walkCapsule = BulletCapsuleShape(self.__walkCapsuleR, self.__walkCapsuleH) self.__walkCapsuleNP = self.movementParent.attachNewNode( BulletRigidBodyNode('Capsule')) self.__walkCapsuleNP.node().addShape(self.__walkCapsule) self.__walkCapsuleNP.node().setKinematic(True) self.__walkCapsuleNP.node().setCcdMotionThreshold(1e-7) self.__walkCapsuleNP.node().setCcdSweptSphereRadius( self.__walkCapsuleR) self.__walkCapsuleNP.setCollideMask(BitMask32.allOn()) self.__world.attachRigidBody(self.__walkCapsuleNP.node()) # Crouch Capsule self.__crouchCapsule = BulletCapsuleShape(self.__crouchCapsuleR, self.__crouchCapsuleH) self.__crouchCapsuleNP = self.movementParent.attachNewNode( BulletRigidBodyNode('crouchCapsule')) self.__crouchCapsuleNP.node().addShape(self.__crouchCapsule) self.__crouchCapsuleNP.node().setKinematic(True) self.__crouchCapsuleNP.node().setCcdMotionThreshold(1e-7) self.__crouchCapsuleNP.node().setCcdSweptSphereRadius( self.__crouchCapsuleR) self.__crouchCapsuleNP.setCollideMask(BitMask32.allOn()) # Set default self.capsule = self.__walkCapsule self.capsuleNP = self.__walkCapsuleNP # Make the event sphere a tiny bit bigger than the capsule # so our capsule doesn't block the event sphere from entering triggers. eventSphere = BulletSphereShape(self.__walkCapsuleR * 1.5) self.eventSphereNP = self.movementParent.attachNewNode( BulletGhostNode('eventSphere')) self.eventSphereNP.node().addShape( eventSphere, TransformState.makePos(Point3(0, 0, self.__walkCapsuleR * 1.5))) self.eventSphereNP.node().setKinematic(True) self.eventSphereNP.setCollideMask(CIGlobals.EventGroup) self.__world.attach(self.eventSphereNP.node()) # Init self.__updateCapsule()