def server_created_object(self, tag, height, radius): # This shape is used for collision detection, preventing the player falling through the ground for # example. shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) # A character controller is a physical body which responds instantly to keyboard controls. (Bodies # which respond to forces are difficult to control in a satisfactory way using typical video game # controls. Players expect them to move instantly when a button is pressed, but physics dictates that # they should take a short time to accelerate.) node = BulletCharacterControllerNode(shape, 0.4, tag) node_path = self.render.attachNewNode(node) Thing.add(tag, node, node_path) self.world.attachCharacter(node) # Does this object represent the player who is using this client? if tag == self.__player_tag: # If yes, attach the camera to the object, so the player's view follows the object. self.camera.reparentTo(node_path) else: # If no, create a new Actor to represent the player or NPC. humanoid = Actor("player.bam") humanoid.setH(180) humanoid.reparentTo(node_path) # Scale the Actor so it is the same height as the bounding volume requested by the server. point1 = Point3() point2 = Point3() humanoid.calcTightBounds(point1, point2) humanoid.setScale(height / (point2.z - point1.z)) # If the 3D model has the origin point at floor level, we need to move it down by half the height # of the bounding volume. Otherwise it will hang in mid air, with its feet in the middle of the # bounding volume. humanoid.setZ(-height / 2)
def __init__(self, name, scene, visualMesh, physicsMesh=None, physicsType="character", shapeMargin=0.02, stepHeight=0.5, x=0, y=0, z=0, mass=0, convex=True, directRender=True, parent=None): global physicsTypes self.name = name self.scene = scene NodePath.__init__(self, self.scene.loadEgg(visualMesh)) if physicsMesh != None: if physicsType == "rigid": self.body = BulletRigidBodyNode(self.name + "_RigidBody") self.attachNewNode(self.body) m = self.scene.Base.loader.loadModel(physicsMesh) if convex: sTuple = modelToConvex(m) else: sTuple = modelToShape(m) sTuple[0].setMargin(shapeMargin) self.body.addShape(sTuple[0], sTuple[1]) self.body.setMass(mass) self.body.setPythonTag("name", self.name + "_RigidBody") self.scene.world.attachRigidBody(self.body) elif physicsType=="character": m = self.scene.Base.loader.loadModel(physicsMesh) sTuple = modelToConvex(m) sTuple[0].setMargin(shapeMargin) self.body = BulletCharacterControllerNode(sTuple[0], stepHeight, self.name + "_Character") self.attachNewNode(self.body) self.body.setPythonTag("name", self.name + "_Character") self.scene.world.attachCharacter(self.body) self.setPos(x, y, z) if directRender: self.reparentTo(self.scene.Base.render) elif parent != None: self.reparentTo(parent)
def __init__(self, world, render, name, animator, position, pose): # Create a box shape shape = BulletBoxShape(Vec3(0.3, 0.2, 0.7)) # Create a Controller Node with the shape self.controllerNode = BulletCharacterControllerNode(shape, 0.4, name) self.controllerNode.setIntoCollideMask(BitMask32.allOn()) # Attach the Controller Node to the world world.attachCharacter(self.controllerNode) # Attach Controller Node to the render and get a NodePath self.nodePath = render.attachNewNode(self.controllerNode) # Setup the nodePath self.nodePath.setCollideMask(BitMask32.allOn()) self.nodePath.setH(DEFAULT_NODEPATH_HEIGHT) self.nodePath.setPos(position) # Set the actor of the Character self.animator = animator # Add animator to NodePath so it can be rendered self.animator.reparentTo(self.nodePath) # Configure the animator self.animator.setScale(DEFAULT_ANIMATOR_SCALE) self.animator.setH(DEFAULT_ANIMATOR_HEIGHT) self.animator.setPos(DEFAULT_ANIMATOR_OFFSET) # Set Current Character Pose self.pose = pose # Save home position self.home = position
def createPlayer(self, render, world): h = 3.38 w = 0.4 shape = BulletCapsuleShape(w + 0.3, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Robot') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(2, 0, 18) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character) self.actorNP = Actor( '../models/robot/lack.egg', { 'walk': '../models/robot/lack-run.egg', 'idle': '../models/robot/lack-idle.egg', 'jump': '../models/robot/lack-jump.egg', 'land': '../models/robot/lack-land.egg', 'damage': '../models/robot/lack-damage.egg' }) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.15) self.actorNP.setH(180) self.actorNP.setPos(0, 0, -0.06)
def createCharacter(self): charColl = BulletCapsuleShape(0.4, 1.75 - 2 * 0.4, ZUp) self.diamondChar = BulletCharacterControllerNode( charColl, 0.4, 'Player') self.diamondCharNP = self.worldNP.attachNewNode(self.diamondChar) self.diamondCharNP.setPos(0, 0, 0) self.diamondCharNP.setH(-90) self.diamondCharNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.diamondChar) # Summon the lord Diamondback self.diamondbackChar = Actor( "Resources/models/CHAR/CHRIS", { "walk": "Resources/models/CHAR/CHRIS-Walk2", "idle": "Resources/models/CHAR/CHRIS-Idle2", "jump": "Resources/models/CHAR/CHRIS-Jump" }) self.diamondbackChar.reparentTo(self.diamondCharNP) self.diamondbackChar.setPos(0, 0, -.83) self.diamondbackChar.setScale(1) self.diamondbackChar.setBlend(animBlend=True, frameBlend=True) # Set the camera position tracker self.camPos = NodePath(PandaNode("camTracker")) self.camPos.reparentTo(self.diamondbackChar) # Set the camera to track the lord base.camera.reparentTo(self.camPos) base.camera.setPosHpr(0, 6, 2.5, 180, -5, 0) base.camLens.setFov(90)
def __init__(self, render, world, x, y, z, type): self.type = type h = 1.5 w = 0.4 shape = BulletCapsuleShape(w + 0.3, h - 2 * w, ZUp) self.badCharacter = BulletCharacterControllerNode(shape, 0.4, 'Lego') self.badCharacterNP = render.attachNewNode(self.badCharacter) self.badCharacterNP.setPos(x, y, z) self.startPositionX = self.badCharacterNP.getX() self.startPositionY = self.badCharacterNP.getY() self.startPositionZ = self.badCharacterNP.getZ() # self.badCharacterNP.setH(45) self.badCharacterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.badCharacter) # self.world.attachRigidBody(self.badCharacter.node()) self.badActorNP = Actor( '../models/lego/' + self.type + '/' + self.type + '.egg', { 'walk': '../models/lego/' + self.type + '/' + self.type + '-walk.egg', 'attack': '../models/lego/' + self.type + '/' + self.type + '-attack.egg', }) self.badActorNP.reparentTo(self.badCharacterNP) self.badActorNP.setScale(0.3) self.badActorNP.setH(180) self.badActorNP.setPos(0, 0, 0.5) # Associates badActorNP with badCharacterNP self.badCharacterNP.setPythonTag("badActorNP", self.badActorNP)
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) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, -1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(10.0) np.node().addShape(shape) np.setPos(3, 0, 4) np.setH(20.0) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Character self.crouching = False h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') # self.character.setMass(1.0) self.characterNP = self.worldNP.attachNewNode(self.character) self.characterNP.setPos(-2, 0, 14) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.actorNP = Actor('models/ralph/ralph.egg', { 'run' : 'models/ralph/ralph-run.egg', 'walk' : 'models/ralph/ralph-walk.egg', 'jump' : 'models/ralph/ralph-jump.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3048) # 1ft = 0.3048m self.actorNP.setH(180) self.actorNP.setPos(0, 0, -1)
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) #img = PNMImage(Filename('models/elevation.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground')) np.node().add_shape(shape) np.set_pos(0, 0, -1) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Box shape = BulletBoxShape(LVector3(1.0, 3.0, 0.3)) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box')) np.node().set_mass(10.0) np.node().add_shape(shape) np.set_pos(3, 0, 4) np.setH(20.0) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Character self.crouching = False h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = self.worldNP.attach_new_node(self.character) self.characterNP.set_pos(-2, 0, 14) self.characterNP.set_h(45) self.characterNP.set_collide_mask(BitMask32.all_on()) self.world.attach(self.character) self.actorNP = Actor( 'samples/roaming-ralph/models/ralph.egg.pz', { 'run': 'samples/roaming-ralph/models/ralph-run.egg.pz', 'walk': 'samples/roaming-ralph/models/ralph-walk.egg.pz' }) self.actorNP.reparent_to(self.characterNP) self.actorNP.set_scale(0.3048) # 1ft = 0.3048m self.actorNP.setH(180) self.actorNP.set_pos(0, 0, -1)
def __init__(self, game_state, height, radius, name): Thing.__init__(self, game_state) self.height = height self.radius = radius shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.node = BulletCharacterControllerNode(shape, 0.4, self.get_unique_name(name)) self.node_path = self.game_state.render.attachNewNode(self.node) self.game_state.world.attachCharacter(self.node)
def buildCharacterController(self, _height, _radius, _pos, _head): """Build a basic BulletCharacter Controller""" shape = BulletCapsuleShape(_radius, _height - 2 * _radius, ZUp) charNode = BulletCharacterControllerNode(shape, _radius, "Player") np = self.engine.BulletObjects["player"].attachNewNode(charNode) np.setPos(_pos) np.setH(_head) np.setCollideMask(BitMask32.allOn()) self.engine.bulletWorld.attachCharacter(np.node()) return np
def setUp(self): self.itemNumber = 0 self.incBar() # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(0, 0, 130) self.characterNP.setH(180) self.characterNP.setCollideMask(BitMask32.allOn()) self.models.world.attachCharacter(self.character) self.actorNP = Actor( 'models/Bricker/Bricker3.egg', { 'run': 'models/Bricker/Bricker-run.egg', 'walk': 'models/Bricker/Bricker-walk.egg', 'jump': 'models/Bricker/Bricker-jump.egg', 'fallbackGetup': 'models/Bricker/FallbackGetup.egg', 'fallforwardGetup': 'models/Bricker/Bricker-FallforwardGetup.egg', 'fireball': 'models/Bricker/Bricker-fireball.egg', 'punching': 'models/Bricker/Bricker-punching.egg', 'superpunch': 'models/Bricker/Bricker-superpunch.egg' }) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3) self.actorNP.setH(180) self.actorNP.setPos(0, 0, 0.2) #enemies #self.setUpEnemies() #debug self.debugNode = BulletDebugNode('Debug') self.debugNode.showWireframe(True) self.debugNode.showConstraints(True) self.debugNode.showBoundingBoxes(False) self.debugNode.showNormals(False) self.debugNP = render.attachNewNode(self.debugNode) self.debugNP.hide() self.models.world.setDebugNode(self.debugNP.node())
def set_physics(self, phys_mgr): """Set the locomotive physics. Args: phys_mgr (panda3d.bullet.BulletWorld): Physical world. """ self._phys_shape = BulletCharacterControllerNode( BulletBoxShape(Vec3(0.095, 0.55, 0.1)), 10, "train_shape") self._phys_node = self.model.attachNewNode(self._phys_shape) self._phys_node.setZ(0.1) phys_mgr.attachCharacter(self._phys_shape) taskMgr.doMethodLater( # noqa: F821 0.1, self._check_contacts, "check_train_contacts", extraArgs=[phys_mgr, self._phys_node.node()], appendTask=True, )
def __init__(self, x, y, z, id): self.health = 100 radius = .15 height = 1 shape = BulletCylinderShape(radius, height, ZUp) self.playerNode = BulletCharacterControllerNode(shape, 0.4, str(id)) self.playerNode.setMaxJumpHeight(2.0) self.playerNode.setJumpSpeed(4.0) self.playerNP = base.render.attachNewNode(self.playerNode) self.playerNP.setPos(x, y, z) self.playerModel = Actor('models/soldier.egg', {"idle": "models/soldier_ani_idle.egg", "walk": "models/soldier_ani_walk.egg", "pistol": "models/soldier_ani_pistol.egg", "death": "models/soldier_ani_death.egg",}) self.playerModel.makeSubpart("legs", ["mixamorig:LeftUpLeg", "mixamorig:RightUpLeg"]) self.playerModel.makeSubpart("hips", ["mixamorig:Hips"], ["mixamorig:LeftUpLeg", "mixamorig:RightUpLeg", "mixamorig:Spine"]) self.playerModel.makeSubpart("upperBody", ["mixamorig:Spine"]) self.playerModel.pose("idle", 0, partName="hips") self.playerModel.setH(90) self.playerModel.setScale(.06) self.playerModel.setZ(-.45) self.playerModel.flattenLight() # self.playerModel.setLightOff()self.playerSpine self.playerModel.reparentTo(self.playerNP) self.playerSpine = self.playerModel.controlJoint(None, 'modelRoot', 'mixamorig:Spine') self.hand = self.playerModel.exposeJoint(None, 'modelRoot', 'mixamorig:RightHand') self.spineExpose = self.playerModel.exposeJoint(None, 'modelRoot', 'mixamorig:Spine') self.playerSpine.setH(-7) # player weapon self.weapon = Ak47(self.hand) # player animation self.xSpeed = 0 self.ySpeed = 0 self.animation = Animation(self) self.model = NodePath("MySpineNode")
def __init__(self): super().__init__() self.master = window.Window.get_instance() self.keyMap = { self.master.bind[Bind.FWD.value]: False, self.master.bind[Bind.BWD.value]: False, self.master.bind[Bind.RIGHT.value]: False, self.master.bind[Bind.LEFT.value]: False, self.master.bind[Bind.UP.value]: False, self.master.bind[Bind.DOWN.value]: False, self.master.bind[Bind.SPACE.value]: False } self.equipment = Equipment(self) self.rotation = [-70, 140] height = 2.5 radius = 0.4 character_shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.player_node = BulletCharacterControllerNode( character_shape, 0.4, 'Player') self.player_node_path = self.master.world_node.attachNewNode( self.player_node) self.player_node_path.setPos(90, 31, 395) self.player_node_path.setCollideMask(BitMask32.allOn()) self.master.camera.reparentTo(self.player_node_path) self.master.camera.setY(self.master.camera, -5) self.camera_model = self.master.loader.loadModel( "mesh/models/person/person") self.camera_model.reparentTo(self.player_node_path) self.bind() self.master.taskMgr.add(self.camera_control, "Camera Control") self.master.world.attachCharacter(self.player_node_path.node())
def setupPhysics(self, **kwargs): self.worldNp = kwargs['worldnp'] self.world = kwargs['world'] h = .2 w = .1 shape = BulletCapsuleShape(w, h, ZUp) self.character = BulletCharacterControllerNode( shape, .5, 'Player_{}'.format(self.name)) self.characterNP = self.worldNp.attachNewNode(self.character) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.floater = NodePath(PandaNode('floater')) self.floater.reparentTo(self.characterNP) self.floater.setZ(self.characterNP, .52) self.floater.setY(self.characterNP.getY() + .25)
def characterController(self, name, height, mass, radius, step_height): shape = BulletCapsuleShape(radius, height - 2*radius, ZUp) body = BulletRigidBodyNode(name) body.setMass(mass) body.addShape(shape) return BulletCharacterControllerNode(shape, step_height, name)
def __init__(self): load_prc_file_data( "", """ win-size 1920 1080 window-title Panda3D Arena Sample FPS Bullet Auto Colliders PBR HW Skinning show-frame-rate-meter #t framebuffer-srgb #t framebuffer-multisample 1 multisamples 4 view-frustum-cull 0 textures-power-2 none hardware-animated-vertices #t gl-depth-zero-to-one true clock-frame-rate 60 interpolate-frames 1 cursor-hidden #t fullscreen #f """) # Initialize the showbase super().__init__() gltf.patch_loader(self.loader) props = WindowProperties() props.set_mouse_mode(WindowProperties.M_relative) base.win.request_properties(props) base.set_background_color(0.5, 0.5, 0.8) self.camLens.set_fov(80) self.camLens.set_near_far(0.01, 90000) self.camLens.set_focal_length(7) # self.camera.set_pos(0, 0, 2) # ConfigVariableManager.getGlobalPtr().listVariables() # point light generator for x in range(0, 3): plight_1 = PointLight('plight') # add plight props here plight_1_node = self.render.attach_new_node(plight_1) # group the lights close to each other to create a sun effect plight_1_node.set_pos(random.uniform(-21, -20), random.uniform(-21, -20), random.uniform(20, 21)) self.render.set_light(plight_1_node) # point light for volumetric lighting filter plight_1 = PointLight('plight') # add plight props here plight_1_node = self.render.attach_new_node(plight_1) # group the lights close to each other to create a sun effect plight_1_node.set_pos(random.uniform(-21, -20), random.uniform(-21, -20), random.uniform(20, 21)) self.render.set_light(plight_1_node) scene_filters = CommonFilters(base.win, base.cam) scene_filters.set_bloom() scene_filters.set_high_dynamic_range() scene_filters.set_exposure_adjust(0.6) scene_filters.set_gamma_adjust(1.1) # scene_filters.set_volumetric_lighting(plight_1_node, 32, 0.5, 0.7, 0.1) # scene_filters.set_blur_sharpen(0.9) # scene_filters.set_ambient_occlusion(32, 0.05, 2.0, 0.01, 0.000002) self.accept("f3", self.toggle_wireframe) self.accept("escape", sys.exit, [0]) exponential_fog = Fog('world_fog') exponential_fog.set_color(0.6, 0.7, 0.7) # this is a very low fog value, set it higher for a greater effect exponential_fog.set_exp_density(0.00009) self.render.set_fog(exponential_fog) self.game_start = 0 from panda3d.bullet import BulletWorld from panda3d.bullet import BulletCharacterControllerNode from panda3d.bullet import ZUp from panda3d.bullet import BulletCapsuleShape from panda3d.bullet import BulletTriangleMesh from panda3d.bullet import BulletTriangleMeshShape from panda3d.bullet import BulletBoxShape from panda3d.bullet import BulletGhostNode from panda3d.bullet import BulletRigidBodyNode from panda3d.bullet import BulletPlaneShape self.world = BulletWorld() self.world.set_gravity(Vec3(0, 0, -9.81)) arena_1 = self.loader.load_model('models/arena_1.gltf') arena_1.reparent_to(self.render) arena_1.set_pos(0, 0, 0) def make_collision_from_model(input_model, node_number, mass, world, target_pos, h_adj): # tristrip generation from static models # generic tri-strip collision generator begins geom_nodes = input_model.find_all_matches('**/+GeomNode') geom_nodes = geom_nodes.get_path(node_number).node() # print(geom_nodes) geom_target = geom_nodes.get_geom(0) # print(geom_target) output_bullet_mesh = BulletTriangleMesh() output_bullet_mesh.add_geom(geom_target) tri_shape = BulletTriangleMeshShape(output_bullet_mesh, dynamic=False) print(output_bullet_mesh) body = BulletRigidBodyNode('input_model_tri_mesh') np = self.render.attach_new_node(body) np.node().add_shape(tri_shape) np.node().set_mass(mass) np.node().set_friction(0.01) np.set_pos(target_pos) np.set_scale(1) np.set_h(h_adj) # np.set_p(180) # np.set_r(180) np.set_collide_mask(BitMask32.allOn()) world.attach_rigid_body(np.node()) make_collision_from_model(arena_1, 0, 0, self.world, (arena_1.get_pos()), 0) # load the scene shader scene_shader = Shader.load(Shader.SL_GLSL, "shaders/simplepbr_vert_mod_1.vert", "shaders/simplepbr_frag_mod_1.frag") self.render.set_shader(scene_shader) self.render.set_antialias(AntialiasAttrib.MMultisample) scene_shader_attrib = ShaderAttrib.make(scene_shader) scene_shader_attrib = scene_shader_attrib.setFlag( ShaderAttrib.F_hardware_skinning, True) # initialize player character physics the Bullet way shape_1 = BulletCapsuleShape(0.75, 0.5, ZUp) player_node = BulletCharacterControllerNode( shape_1, 0.1, 'Player') # (shape, mass, player name) # player_node.set_max_slope(0.1) # player_node.set_linear_movement(1, True) player_np = self.render.attach_new_node(player_node) player_np.set_pos(-20, -10, 10) player_np.set_collide_mask(BitMask32.allOn()) self.world.attach_character(player_np.node()) # cast player_np to self.player self.player = player_np # reparent player character to render node fp_character = actor_data.player_character fp_character.reparent_to(self.render) fp_character.set_scale(1) # set the actor skinning hardware shader fp_character.set_attrib(scene_shader_attrib) self.camera.reparent_to(self.player) # reparent character to FPS cam fp_character.reparent_to(self.player) fp_character.set_pos(0, 0, -0.95) # self.camera.set_x(self.player, 1) self.camera.set_y(self.player, 0.03) self.camera.set_z(self.player, 0.5) # player gun begins self.player_gun = actor_data.arm_handgun self.player_gun.reparent_to(self.render) self.player_gun.reparent_to(self.camera) self.player_gun.set_x(self.camera, 0.1) self.player_gun.set_y(self.camera, 0.4) self.player_gun.set_z(self.camera, -0.1) # directly make a text node to display text text_1 = TextNode('text_1_node') text_1.set_text("") text_1_node = self.aspect2d.attach_new_node(text_1) text_1_node.set_scale(0.05) text_1_node.set_pos(-1.4, 0, 0.92) # import font and set pixels per unit font quality nunito_font = loader.load_font('fonts/Nunito/Nunito-Light.ttf') nunito_font.set_pixels_per_unit(100) nunito_font.set_page_size(512, 512) # apply font text_1.set_font(nunito_font) # small caps # text_1.set_small_caps(True) # on-screen target dot for aiming target_dot = TextNode('target_dot_node') target_dot.set_text(".") target_dot_node = self.aspect2d.attach_new_node(target_dot) target_dot_node.set_scale(0.075) target_dot_node.set_pos(0, 0, 0) # target_dot_node.hide() # apply font target_dot.set_font(nunito_font) target_dot.set_align(TextNode.ACenter) # see the Task section for relevant dot update logic # directly make a text node to display text text_2 = TextNode('text_2_node') text_2.set_text("Neutralize the NPC by shooting the head." + '\n' + "Press 'f' to toggle the flashlight.") text_2_node = self.aspect2d.attach_new_node(text_2) text_2_node.set_scale(0.04) text_2_node.set_pos(-1.4, 0, 0.8) # import font and set pixels per unit font quality nunito_font = self.loader.load_font('fonts/Nunito/Nunito-Light.ttf') nunito_font.set_pixels_per_unit(100) nunito_font.set_page_size(512, 512) # apply font text_2.set_font(nunito_font) text_2.set_text_color(0, 0.3, 1, 1) # print player position on mouse click def print_player_pos(): print(self.player.get_pos()) self.player.node().do_jump() self.accept('mouse3', print_player_pos) self.flashlight_state = 0 def toggle_flashlight(): current_flashlight = self.render.find_all_matches("**/flashlight") if self.flashlight_state == 0: if len(current_flashlight) == 0: self.slight = 0 self.slight = Spotlight('flashlight') self.slight.set_shadow_caster(True, 1024, 1024) self.slight.set_color(VBase4(0.5, 0.6, 0.6, 1)) # slightly bluish lens = PerspectiveLens() lens.set_near_far(0.5, 5000) self.slight.set_lens(lens) self.slight.set_attenuation((0.5, 0, 0.0000005)) self.slight = self.render.attach_new_node(self.slight) self.slight.set_pos(-0.1, 0.3, -0.4) self.slight.reparent_to(self.camera) self.flashlight_state = 1 self.render.set_light(self.slight) elif len(current_flashlight) > 0: self.render.set_light(self.slight) self.flashlight_state = 1 elif self.flashlight_state > 0: self.render.set_light_off(self.slight) self.flashlight_state = 0 self.accept('f', toggle_flashlight) # add a few random physics boxes for x in range(0, 40): # dynamic collision random_vec = Vec3(1, 1, 1) special_shape = BulletBoxShape(random_vec) # rigidbody body = BulletRigidBodyNode('random_prisms') d_coll = self.render.attach_new_node(body) d_coll.node().add_shape(special_shape) d_coll.node().set_mass(0.9) d_coll.node().set_friction(0.5) d_coll.set_collide_mask(BitMask32.allOn()) # turn on Continuous Collision Detection d_coll.node().set_ccd_motion_threshold(0.000000007) d_coll.node().set_ccd_swept_sphere_radius(0.30) d_coll.node().set_deactivation_enabled(False) d_coll.set_pos(random.uniform(-60, -20), random.uniform(-60, -20), random.uniform(5, 10)) box_model = self.loader.load_model('models/1m_cube.gltf') box_model.reparent_to(self.render) box_model.reparent_to(d_coll) box_model.set_color(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1), 1) self.world.attach_rigid_body(d_coll.node()) # portal #1 begins # make a new texture buffer, render node, and attach a camera mirror_buffer = self.win.make_texture_buffer("mirror_buff", 4096, 4096) mirror_render = NodePath("mirror_render") mirror_render.set_shader(scene_shader) self.mirror_cam = self.make_camera(mirror_buffer) self.mirror_cam.reparent_to(mirror_render) self.mirror_cam.set_pos(0, -60, 5) self.mirror_cam.set_hpr(0, 25, 0) self.mirror_cam.node().get_lens().set_focal_length(10) self.mirror_cam.node().get_lens().set_fov(90) mirror_filters = CommonFilters(mirror_buffer, self.mirror_cam) # mirror_filters.set_high_dynamic_range() mirror_filters.set_exposure_adjust(1.1) # mirror_filters.set_gamma_adjust(1.3) # load in a mirror/display object model in normal render space self.mirror_model = self.loader.loadModel( 'models/wide_screen_video_display.egg') self.mirror_model.reparent_to(self.render) self.mirror_model.set_pos(-20, 0, 1) self.mirror_model.set_sz(3) # self.mirror_model.flatten_strong() # mirror scene model load-in # reparent to mirror render node house_uv = self.loader.load_model('models/hangar_1.gltf') house_uv.reparent_to(mirror_render) windows = house_uv.find('**/clear_arches') windows.hide() house_uv.set_pos(0, 0, 0) house_uv.set_scale(1) # the portal ramp house_uv = self.loader.load_model('models/ramp_1.gltf') house_uv.reparent_to(mirror_render) house_uv.set_h(180) house_uv.set_scale(1.5) house_uv.set_pos(0, -50, 0) # mirror scene lighting # point light generator for x in range(0, 1): plight_1 = PointLight('plight') # add plight props here plight_1_node = mirror_render.attach_new_node(plight_1) # group the lights close to each other to create a sun effect plight_1_node.set_pos(random.uniform(-21, -20), random.uniform(-21, -20), random.uniform(20, 21)) mirror_render.set_light(plight_1_node) # set the live buffer texture to the mirror/display model in normal render space self.mirror_model.set_texture(mirror_buffer.get_texture()) # secret hangar far off somewhere on the graph house_uv = self.loader.load_model('models/hangar_1.gltf') house_uv.reparent_to(self.render) windows = house_uv.find('**/clear_arches') windows.hide() house_uv.set_pos(400, 400, -1) # the portal ring house_uv = self.loader.load_model('models/ring_1.gltf') house_uv.reparent_to(self.render) house_uv.set_h(90) house_uv.set_pos(-20, 0, -2) # the portal ramp house_uv = self.loader.load_model('models/ramp_1.gltf') house_uv.reparent_to(self.render) house_uv.set_h(0) house_uv.set_pos(-20, -5.5, 0) r_pos = house_uv.get_pos() make_collision_from_model(house_uv, 0, 0, self.world, (r_pos[0], r_pos[1], r_pos[2] + 1), 0) self.count_frames_1 = 0 self.screen_cap_num = 1 def make_screenshot(): # Ensure the frame is rendered. base.graphicsEngine.render_frame() # Grab the screenshot into a big image full = PNMImage() base.win.get_screenshot(full) # Now reduce it reduced = PNMImage(500, 300) reduced.gaussianFilterFrom(1, full) # And write it out. reduced.write( Filename('screen_cap_' + str(self.screen_cap_num) + '.jpg')) self.screen_cap_num += 1 def update_portal_cam(Task): if self.count_frames_1 < 30: self.count_frames_1 += 1 if self.count_frames_1 == 15: pass # make_screenshot() if self.count_frames_1 == 29: self.count_frames_1 = 0 p_dist = (self.player.get_pos() - self.mirror_model.get_pos(base.render)).length() target_fov = 115 if p_dist < 2.25: target_fov = 145 self.player.set_pos(400, 400, 3) # adjust the ground plane self.ground_plane.set_pos(0, 0, 0) # move the normal point lights lights = self.render.find_all_matches('**/plight*') for l in lights: l.set_pos(400, 400, 21) player_h = self.player.get_h() self.mirror_cam.set_h(player_h) self.mirror_cam.node().get_lens().set_fov(target_fov) return Task.cont self.task_mgr.add(update_portal_cam) # portal #2 begins # the portal ring house_uv = self.loader.load_model('models/ring_1.gltf') house_uv.reparent_to(self.render) house_uv.set_h(90) house_uv.set_pos(400, 400, -2) # the portal ramp house_uv = self.loader.load_model('models/ramp_1.gltf') house_uv.reparent_to(self.render) house_uv.set_h(180) house_uv.set_pos(400, 405.5, 0) r_pos = house_uv.get_pos() make_collision_from_model(house_uv, 0, 0, self.world, (r_pos[0], r_pos[1], r_pos[2] + 1), 180) # NPC_1 load-in comp_shape_1 = BulletCapsuleShape(0.05, 0.01, ZUp) npc_1_node = BulletCharacterControllerNode( comp_shape_1, 0.2, 'NPC_A_node') # (shape, mass, character name) np = self.render.attach_new_node(npc_1_node) np.set_pos(-40, -40, 5) np.set_collide_mask(BitMask32.allOn()) self.world.attach_character(np.node()) np.set_h(random.randint(0, 180)) npc_model_1 = actor_data.NPC_1 npc_model_1.reparent_to(np) # set the actor skinning hardware shader npc_model_1.set_attrib(scene_shader_attrib) # get the separate head model npc_1_head = self.loader.load_model('models/npc_1_head.gltf') npc_1_head.reparent_to(actor_data.NPC_1.get_parent()) # npc base animation loop npc_1_control = actor_data.NPC_1.get_anim_control('walking') if not npc_1_control.is_playing(): actor_data.NPC_1.stop() actor_data.NPC_1.loop("walking", fromFrame=60, toFrame=180) actor_data.NPC_1.set_play_rate(6.0, 'walking') # create special hit areas # use Task section for npc collision movement logic # special head node size special_shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1)) # ghost npc node body = BulletGhostNode('special_node_A') special_node = self.render.attach_new_node(body) special_node.node().add_shape( special_shape, TransformState.makePos(Point3(0, 0, 0.4))) # special_node.node().set_mass(0) # special_node.node().set_friction(0.5) special_node.set_collide_mask(BitMask32(0x0f)) # turn on Continuous Collision Detection special_node.node().set_deactivation_enabled(False) special_node.node().set_ccd_motion_threshold(0.000000007) special_node.node().set_ccd_swept_sphere_radius(0.30) self.world.attach_ghost(special_node.node()) # dynamic collision special_shape = BulletBoxShape(Vec3(0.3, 0.15, 0.6)) # rigidbody npc node body = BulletRigidBodyNode('d_coll_A') d_coll = self.render.attach_new_node(body) d_coll.node().add_shape(special_shape, TransformState.makePos(Point3(0, 0, 0.7))) # d_coll.node().set_mass(0) d_coll.node().set_friction(0.5) d_coll.set_collide_mask(BitMask32.allOn()) # turn on Continuous Collision Detection d_coll.node().set_deactivation_enabled(False) d_coll.node().set_ccd_motion_threshold(0.000000007) d_coll.node().set_ccd_swept_sphere_radius(0.30) self.world.attach_rigid_body(d_coll.node()) # npc state variables self.npc_1_is_dead = False self.npc_1_move_increment = Vec3(0, 0, 0) self.gun_anim_is_playing = False # npc movement timer def npc_1_move_gen(): while not self.npc_1_is_dead: m_incs = [] for x in range(0, 2): m_incs.append(random.uniform(2, 5)) print('NPC_1 movement increments this cycle: ' + str(m_incs)) self.npc_1_move_increment[0] = m_incs[0] self.npc_1_move_increment[1] = m_incs[1] time.sleep(3) self.npc_1_move_increment[0] = m_incs[0] self.npc_1_move_increment[1] = m_incs[1] time.sleep(3) self.npc_1_move_increment[0] = (-1 * m_incs[0]) * 2 self.npc_1_move_increment[1] = (-1 * m_incs[1]) * 2 time.sleep(3) self.npc_1_move_increment[0] = 0 self.npc_1_move_increment[1] = 0 # activate the movement timer in a dedicated thread to prevent lockup with .sleep() threading2._start_new_thread(npc_1_move_gen, ()) def is_npc_1_shot(): # animate the gun gun_ctrl = actor_data.arm_handgun.get_anim_control('shoot') if not gun_ctrl.is_playing(): actor_data.arm_handgun.stop() actor_data.arm_handgun.play("shoot") actor_data.arm_handgun.set_play_rate(15.0, 'shoot') # target dot ray test # get mouse data mouse_watch = base.mouseWatcherNode if mouse_watch.has_mouse(): posMouse = base.mouseWatcherNode.get_mouse() posFrom = Point3() posTo = Point3() base.camLens.extrude(posMouse, posFrom, posTo) posFrom = self.render.get_relative_point(base.cam, posFrom) posTo = self.render.get_relative_point(base.cam, posTo) rayTest = self.world.ray_test_closest(posFrom, posTo) target = rayTest.get_node() target_dot = self.aspect2d.find_all_matches( "**/target_dot_node") if 'special_node_A' in str(target): def npc_cleanup(): # the head is hit, the npc is dead self.npc_1_is_dead = True text_2.set_text('Congrats, you have won!') npc_1_control = actor_data.NPC_1.get_anim_control( 'walking') if npc_1_control.is_playing(): actor_data.NPC_1.stop() npc_1_control = actor_data.NPC_1.get_anim_control( 'death') if not npc_1_control.is_playing(): actor_data.NPC_1.play('death') # Bullet node removals self.world.remove(target) rigid_target = self.render.find('**/d_coll_A') self.world.remove(rigid_target.node()) threading2._start_new_thread(npc_cleanup, ()) self.accept('mouse1', is_npc_1_shot) def smooth_load_physics(): # this is a patch to speed up the cold start hitch on success condition # Bullet node removals self.world.remove(special_node.node()) rigid_target = self.render.find('**/d_coll_A') self.world.remove(rigid_target.node()) print('NPC physics init removed.') smooth_load_physics() # repeat the NPC physics initialization after smooth_load_physics # create special hit areas # use Task section for npc collision movement logic # special head node size special_shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1)) # ghost npc node body = BulletGhostNode('special_node_A') special_node = self.render.attach_new_node(body) special_node.node().add_shape( special_shape, TransformState.makePos(Point3(0, 0, 0.4))) # special_node.node().set_mass(0) # special_node.node().set_friction(0.5) special_node.set_collide_mask(BitMask32(0x0f)) # turn on Continuous Collision Detection special_node.node().set_deactivation_enabled(False) special_node.node().set_ccd_motion_threshold(0.000000007) special_node.node().set_ccd_swept_sphere_radius(0.30) self.world.attach_ghost(special_node.node()) # dynamic collision special_shape = BulletBoxShape(Vec3(0.3, 0.15, 0.6)) # rigidbody npc node body = BulletRigidBodyNode('d_coll_A') d_coll = self.render.attach_new_node(body) d_coll.node().add_shape(special_shape, TransformState.makePos(Point3(0, 0, 0.7))) # d_coll.node().set_mass(0) d_coll.node().set_friction(0.5) d_coll.set_collide_mask(BitMask32.allOn()) # turn on Continuous Collision Detection d_coll.node().set_deactivation_enabled(False) d_coll.node().set_ccd_motion_threshold(0.000000007) d_coll.node().set_ccd_swept_sphere_radius(0.30) self.world.attach_rigid_body(d_coll.node()) # 3D player movement system begins self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "run": 0, "jump": 0 } def setKey(key, value): self.keyMap[key] = value # define button map self.accept("a", setKey, ["left", 1]) self.accept("a-up", setKey, ["left", 0]) self.accept("d", setKey, ["right", 1]) self.accept("d-up", setKey, ["right", 0]) self.accept("w", setKey, ["forward", 1]) self.accept("w-up", setKey, ["forward", 0]) self.accept("s", setKey, ["backward", 1]) self.accept("s-up", setKey, ["backward", 0]) self.accept("shift", setKey, ["run", 1]) self.accept("shift-up", setKey, ["run", 0]) self.accept("space", setKey, ["jump", 1]) self.accept("space-up", setKey, ["jump", 0]) # disable mouse self.disable_mouse() # the player movement speed self.movementSpeedForward = 5 self.movementSpeedBackward = 5 self.dropSpeed = -0.2 self.striveSpeed = 6 self.ease = -10.0 self.static_pos_bool = False self.static_pos = Vec3() def move(Task): if self.game_start > 0: if not self.npc_1_is_dead: npc_pos_1 = actor_data.NPC_1.get_parent().get_pos() # place head hit box special_node.set_pos(npc_pos_1[0], npc_pos_1[1], npc_pos_1[2] + 1) special_node.set_h(actor_data.NPC_1.get_h()) # dynamic collision node d_coll.set_pos(npc_pos_1[0], npc_pos_1[1], npc_pos_1[2]) d_coll.set_h(actor_data.NPC_1.get_h()) # make the npc look at the player continuously actor_data.NPC_1.look_at(self.player) npc_1_head.look_at(self.player) if actor_data.NPC_1.get_p() > 3: actor_data.NPC_1.set_p(3) if npc_1_head.get_p() > 3: npc_1_head.set_p(3) m_inst = self.npc_1_move_increment t_inst = globalClock.get_dt() actor_data.NPC_1.get_parent().set_pos( npc_pos_1[0] + (m_inst[0] * t_inst), npc_pos_1[1] + (m_inst[1] * t_inst), npc_pos_1[2]) if self.npc_1_is_dead: npc_1_head.hide() inst_h = actor_data.NPC_1.get_h() inst_p = actor_data.NPC_1.get_p() actor_data.NPC_1.set_hpr(inst_h, inst_p, 0) # target dot ray test # turns the target dot red # get mouse data mouse_watch = base.mouseWatcherNode if mouse_watch.has_mouse(): posMouse = base.mouseWatcherNode.get_mouse() posFrom = Point3() posTo = Point3() base.camLens.extrude(posMouse, posFrom, posTo) posFrom = self.render.get_relative_point(base.cam, posFrom) posTo = self.render.get_relative_point(base.cam, posTo) rayTest = self.world.ray_test_closest(posFrom, posTo) target = rayTest.get_node() target_dot = self.aspect2d.find_all_matches( "**/target_dot_node") if 'special_node_A' in str(target): # the npc is recognized, make the dot red for dot in target_dot: dot.node().set_text_color(0.9, 0.1, 0.1, 1) if 'd_coll_A' in str(target): # the npc is recognized, make the dot red for dot in target_dot: dot.node().set_text_color(0.9, 0.1, 0.1, 1) if 'special_node_A' not in str(target): # no npc recognized, make the dot white if 'd_coll_A' not in str(target): for dot in target_dot: dot.node().set_text_color(1, 1, 1, 1) # get mouse data mouse_watch = base.mouseWatcherNode if mouse_watch.has_mouse(): pointer = base.win.get_pointer(0) mouseX = pointer.get_x() mouseY = pointer.get_y() # screen sizes window_Xcoord_halved = base.win.get_x_size() // 2 window_Ycoord_halved = base.win.get_y_size() // 2 # mouse speed mouseSpeedX = 0.2 mouseSpeedY = 0.2 # maximum and minimum pitch maxPitch = 90 minPitch = -50 # cam view target initialization camViewTarget = LVecBase3f() if base.win.movePointer(0, window_Xcoord_halved, window_Ycoord_halved): p = 0 if mouse_watch.has_mouse(): # calculate the pitch of camera p = self.camera.get_p() - ( mouseY - window_Ycoord_halved) * mouseSpeedY # sanity checking if p < minPitch: p = minPitch elif p > maxPitch: p = maxPitch if mouse_watch.has_mouse(): # directly set the camera pitch self.camera.set_p(p) camViewTarget.set_y(p) # rotate the self.player's heading according to the mouse x-axis movement if mouse_watch.has_mouse(): h = self.player.get_h() - ( mouseX - window_Xcoord_halved) * mouseSpeedX if mouse_watch.has_mouse(): # sanity checking if h < -360: h += 360 elif h > 360: h -= 360 self.player.set_h(h) camViewTarget.set_x(h) # hide the gun if looking straight down if p < -30: self.player_gun.hide() if p > -30: self.player_gun.show() if self.keyMap["left"]: if self.static_pos_bool: self.static_pos_bool = False self.player.set_x(self.player, -self.striveSpeed * globalClock.get_dt()) myAnimControl = actor_data.player_character.get_anim_control( 'walking') if not myAnimControl.isPlaying(): actor_data.player_character.play("walking") actor_data.player_character.set_play_rate( 4.0, 'walking') if not self.keyMap["left"]: if not self.static_pos_bool: self.static_pos_bool = True self.static_pos = self.player.get_pos() self.player.set_x(self.static_pos[0]) self.player.set_y(self.static_pos[1]) self.player.set_z(self.player, self.dropSpeed * globalClock.get_dt()) if self.keyMap["right"]: if self.static_pos_bool: self.static_pos_bool = False self.player.set_x(self.player, self.striveSpeed * globalClock.get_dt()) myAnimControl = actor_data.player_character.get_anim_control( 'walking') if not myAnimControl.isPlaying(): actor_data.player_character.play("walking") actor_data.player_character.set_play_rate( 4.0, 'walking') if not self.keyMap["right"]: if not self.static_pos_bool: self.static_pos_bool = True self.static_pos = self.player.get_pos() self.player.set_x(self.static_pos[0]) self.player.set_y(self.static_pos[1]) self.player.set_z(self.player, self.dropSpeed * globalClock.get_dt()) if self.keyMap["forward"]: if self.static_pos_bool: self.static_pos_bool = False self.player.set_y( self.player, self.movementSpeedForward * globalClock.get_dt()) myAnimControl = actor_data.player_character.get_anim_control( 'walking') if not myAnimControl.isPlaying(): actor_data.player_character.play("walking") actor_data.player_character.set_play_rate( 4.0, 'walking') if self.keyMap["forward"] != 1: if not self.static_pos_bool: self.static_pos_bool = True self.static_pos = self.player.get_pos() self.player.set_x(self.static_pos[0]) self.player.set_y(self.static_pos[1]) self.player.set_z(self.player, self.dropSpeed * globalClock.get_dt()) if self.keyMap["backward"]: if self.static_pos_bool: self.static_pos_bool = False self.player.set_y( self.player, -self.movementSpeedBackward * globalClock.get_dt()) myBackControl = actor_data.player_character.get_anim_control( 'walking') if not myBackControl.isPlaying(): myBackControl.stop() actor_data.player_character.play('walking') actor_data.player_character.set_play_rate( -4.0, 'walking') return Task.cont # infinite ground plane # the effective world-Z limit ground_plane = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('ground') node.add_shape(ground_plane) node.set_friction(0.1) self.ground_plane = self.render.attach_new_node(node) self.ground_plane.set_pos(0, 0, -1) self.world.attach_rigid_body(node) # Bullet debugger from panda3d.bullet import BulletDebugNode debugNode = BulletDebugNode('Debug') debugNode.show_wireframe(True) debugNode.show_constraints(True) debugNode.show_bounding_boxes(False) debugNode.show_normals(False) debugNP = self.render.attach_new_node(debugNode) self.world.set_debug_node(debugNP.node()) # debug toggle function def toggle_debug(): if debugNP.is_hidden(): debugNP.show() else: debugNP.hide() self.accept('f1', toggle_debug) def update(Task): if self.game_start < 1: self.game_start = 1 return Task.cont def physics_update(Task): dt = globalClock.get_dt() self.world.do_physics(dt) return Task.cont self.task_mgr.add(move) self.task_mgr.add(update) self.task_mgr.add(physics_update)
def setup(self): # World self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug')) self.debugNP.hide() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Floor shape = BulletPlaneShape(Vec3(0, 0, 1), 0) floorNP = self.render.attachNewNode(BulletRigidBodyNode('Floor')) floorNP.node().addShape(shape) floorNP.setPos(0, 0, 0) floorNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(floorNP.node()) self.environ = loader.loadModel('models/environment') self.environ.reparentTo(floorNP) # Stair origin = Point3(2, 0, 0) size = Vec3(4, 4.75, 0.5) shape = BulletBoxShape(size * 0.55) for i in range(15): pos = origin*i + size * i pos.setY(0) pos.setZ(4) stairNP = self.render.attachNewNode(BulletRigidBodyNode('Stair%i' % i)) stairNP.node().addShape(shape) stairNP.setPos(pos) stairNP.setCollideMask(BitMask32.allOn()) if i > 0 and i != 14: if i%2 != 0: # Rotating stairs StairHprInterval1 = stairNP.hprInterval(2, Point3(0, 0, 0),startHpr=Point3(0, 0, 0)) StairHprInterval2 = stairNP.hprInterval(2, Point3(0, 0, 0),startHpr=Point3(360, 0, 0)) self.StairPace1 = Sequence(StairHprInterval1,StairHprInterval2) self.StairPace1.loop() if i%2 == 0 and i%3 != 0: # Up-down motion stairs StairsPosInterval1 = stairNP.posInterval(3, Point3(pos.getX(),pos.getY(),pos.getZ()-2),startPos=Point3(pos.getX(),pos.getY(),pos.getZ()+2)) StairsPosInterval2 = stairNP.posInterval(3, Point3(pos.getX(),pos.getY(),pos.getZ()+2),startPos=Point3(pos.getX(),pos.getY(),pos.getZ()-2)) self.StairPace2 = Sequence(StairsPosInterval1,StairsPosInterval2) self.StairPace2.loop() if i%2 == 0 and i%3 == 0: # Side to side motion stairs StairsPosInterval1 = stairNP.posInterval(3, Point3(pos.getX(),pos.getY()-4,pos.getZ()),startPos=Point3(pos.getX(),pos.getY()+4,pos.getZ())) StairsPosInterval2 = stairNP.posInterval(3, Point3(pos.getX(),pos.getY()+4,pos.getZ()),startPos=Point3(pos.getX(),pos.getY()-4,pos.getZ())) self.StairPace2 = Sequence(StairsPosInterval1,StairsPosInterval2) self.StairPace2.loop() modelNP = loader.loadModel('models/stone-cube/stone.egg') modelNP.reparentTo(stairNP) modelNP.setPos(0, 0, 0) modelNP.setScale(size) self.world.attachRigidBody(stairNP.node()) # panda character if i == 14: self.panda = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.panda.reparentTo(render) self.panda.setScale(0.002, 0.002, 0.002) self.panda.setPos(pos.getX(),pos.getY(),pos.getZ()+0.5) if i%2 != 0: TokenModel = self.loader.loadModel('models/smiley') TokenModel.reparentTo(self.render) TokenModel.setPos(pos.getX(),pos.getY(),pos.getZ()+1) TokenModel.setScale(0.6) TokenModel.setTag("token",str(i)) # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') #self.character.setMass(1.0) self.characterNP = self.render.attachNewNode(self.character) self.characterNP.setPos(0, 0, 14) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) # Special thanks to the creator of LEGO Characters "Lewis Chen" self.actorNP = Actor('models/Voltage/Voltage.egg', { 'die' : 'models/Voltage/Voltage-FallbackGetup.egg', 'walk' : 'models/Voltage/Voltage-walk.egg', 'jump' : 'models/Voltage/Voltage-jump.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3048) self.actorNP.setH(180) self.actorNP.setPos(0, 0, 0.35)
"""Bullet character controllers are a special Body. It behaves as one expect an FPS character to behave: does not bounce, is always upright, and is controlled via velocity, not forces. It still uses a Shape, but has other ways of assigning physical properties. It seems to a bit incomplete: I moved the ground, and it didn't fall with it. It also reacts strangely to the prop box. But I think that might be my fault... Most people seem to be making their own CCs. But I think we don't need to yet.""" # shape shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) # bullect character object node = BulletCharacterControllerNode (shape, 1) # attach to the nodetree via a parent, for easier access which isn't really done np = render.attachNewNode(node) np.setPos(0, 0, 2) #np.setR(10) # attach to the Bullet world, as a character, note world.attach_character(node) # This isn't necessary anymore due to debug ## make it visible #BUG: this model too did not match the actual shape, be careful next time #model = loader.loadModel('models/box.egg') #model.flattenLight() #model.reparentTo(np)
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() ####### MV self.environ = loader.loadModel("world/world") self.environ.reparentTo(render) 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) #actor = Actor('world/world') mesh = BulletTriangleMesh() ###### create terrein colligion shape geomNodeCollection = self.environ.findAllMatches('**/+GeomNode') for nodePath in geomNodeCollection: #.asList(): geomNode = nodePath.node() print("here1") for i in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(i) print("here2") print(geom) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) shape.set_margin(0.0) #print(geomNodeCollection) # for geom in actor.getGeomNode().get_geoms(): # mesh.addGeom(geom) # shape = BulletTriangleMeshShape(mesh, dynamic=False) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, 0) #-1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(50.0) np.node().addShape(shape) np.setPos(3, 0, 7) np.setH(0) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.player = BulletCharacterControllerNode( shape, 0.4, 'Player') #MV was: BulletCharacterNode(shape, 0.4, 'Player') #self.player.setMass(20.0) self.player.setMaxSlope(70.0) self.player.setGravity(9.81) #self.player.setFrictionSlip(100.0) self.playerNP = self.worldNP.attachNewNode(self.player) #self.playerNP.setMass(20.0) self.playerNP.setPos(-2, 0, 10) self.playerNP.setH(-90) self.playerNP.setCollideMask(BitMask32.allOn()) #self.playerNP.flattenLight() self.world.attachCharacter(self.player) self.ralph = Actor("ralph/ralph", { "run": "ralph/ralph-run", "walk": "ralph/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3048) self.ralph.setPos(0, 0, -1) self.ralph.setH(180) self.ralph.reparentTo(self.playerNP) ## Camera self.camera = base.cam base.disableMouse() self.camera.setPos(self.playerNP.getX(), self.playerNP.getY() + 10, 2) self.camera.lookAt(self.playerNP)
def install_upgrade(self, upgrade): """Install the given upgrade on to the locomotive. Args: upgrade (dict): The upgrade description. """ self._upgrades.append(upgrade["name"]) if upgrade["name"] in ("Armor Plate", "Пластина Брони"): self._armor_plate = ArmorPlate(self.model) return if upgrade["name"] in ("Grenade Launcher", "Гранатомёт"): self._grenade_launcher = GrenadeLauncher(self.model) self._gui.activate_weapon( "Grenade Launcher", base.train.load_grenade_launcher # noqa: F821 ) return if upgrade["name"] in ("Cluster Howitzer", "Ракетомёт"): self._cluster_howitzer = ClusterHowitzer(self.model) self._gui.activate_weapon( "Cluster Howitzer", base.train.load_cluster_howitzer # noqa: F821 ) return if upgrade["name"] in ("Machine Gun", "Пулемёт"): self._machine_gun = MachineGun(self.model) self._gui.activate_weapon( "Machine Gun", base.train.load_machine_gun # noqa: F821 ) return up_model = loader.loadModel(address(upgrade["model"])) # noqa: F821 up_model.reparentTo(self.model) if upgrade["name"] in ("Ram", "Таран"): taskMgr.remove("update_physics") # noqa: F821 taskMgr.remove("check_train_contacts") # noqa: F821 base.world.phys_mgr.removeCharacter(self._phys_shape) # noqa: F821 self._phys_node.removeNode() self._phys_shape = self._phys_shape = BulletCharacterControllerNode( BulletBoxShape(Vec3(0.095, 0.58, 0.1)), 10, "train_shape") self._phys_node = self.model.attachNewNode(self._phys_shape) self._phys_node.setPos(0, 0.03, 0.1) base.world.phys_mgr.attachCharacter(self._phys_shape) # noqa: F821 taskMgr.add( # noqa: F821 base.world.update_physics, # noqa: F821 "update_physics", extraArgs=[0.03], appendTask=True, ) taskMgr.doMethodLater( # noqa: F821 0.1, self._check_contacts, "check_train_contacts", extraArgs=[base.world.phys_mgr, self._phys_node.node()], # noqa: F821 appendTask=True, ) return if upgrade["name"] in ("Floodlights", "Прожекторы"): self._floodlights_mat = up_model.findMaterial("lamp_glass") self._lights[0].node().setColor((1, 1, 1, 1)) for light in self._lights[1:]: light.node().setAttenuation(1.7) return if upgrade["name"] in ("Fire Extinguishers", "Огнетушители"): taskMgr.doMethodLater(30, self._repair, "train_repair") # noqa: F821 return if upgrade["name"] in ("Sleeper", "Место"): self.cells += 1 self.parts["part_rest"].cells += 1 base.res_gui.update_chars() # noqa: F821 return if upgrade["name"] in ("Protectors", "Протекторы"): self._max_durability = 1500 self.durability += 500 SHOT_COORS[0][0] += 0.02 self._gui.increase_max_duration()
def __init__(self): ShowBase.__init__(self) #self.word = BulletWorld() self.cx = 0.0 self.cy = 0.0 self.current_omega = 0 s = self.loader.loadSfx('Doom Soundtrack - Level 1 (Extended).mp3') s.play() self.current_pos = (10, 5, 1) self.current_hpr = (0, 0, 0) #self.fxboy = self.loader.loadModel("cubearm.egg") self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -12.0)) #self.physicsMgr.attachPhysicalNode(self.camera) keyboard.on_press_key('w', self.moveForward) keyboard.on_press_key('s', self.moveBackward) keyboard.on_press_key('j', self.lookLeft) keyboard.on_press_key('y', self.lookUp) keyboard.on_press_key('h', self.lookDown) keyboard.on_press_key('g', self.lookRight) keyboard.on_press_key('d', self.moveLeft) #self.fxboy.reparentTo(self.render) #self.camera.reparentTo(self.render) #self.camera.reparentTo(self.fxboy) keyboard.on_press_key('a', self.moveRight) keyboard.on_press_key('space', self.fire) keyboard.on_press_key('2', self.jump) #keyboard.on_press_key('y',self.lookUp) keyboard.on_press_key('1', self.moveUp) self.cam = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.player = BulletCharacterControllerNode(self.cam, 0.4, 'Player') self.playernp = self.render.attachNewNode(self.player) self.world.attachCharacter(self.playernp.node()) self.camera.reparentTo(self.playernp) self.playernp.setPos(self.current_pos) self.playernp.setHpr(self.current_hpr) self.playernp.setH(45) #self.player.setMass(10.0) # self.playernp.setCollideMask(BitMask32.allOn()) self.disableMouse() self.scenes = BulletBoxShape(Vec3(0.25, 0.25, 0.25)) self.scenenode = BulletRigidBodyNode('Scene') self.scenenode.setMass(12.0) self.scenenode.addShape(self.scenes) self.scenenp = render.attachNewNode(self.scenenode) self.scenenp.setPos(-8, 40, 0) self.world.attachRigidBody(self.scenenode) self.scene = self.loader.loadModel("models/environment.egg.pz") self.scene.reparentTo(self.render) self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 40, 0) self.scene.reparentTo(self.scenenp) self.scenenode.setGravity(Vec3(0, 0, 0)) #self.taskMgr.add(self.spinCameraTask,"SpinCameraTask") self.taskMgr.add(self.moveChar, "MoveChar") self.taskMgr.add(self.moveCBod, "MoveCBod") self.pandaActor = Actor("cubearm.egg", {"walk": "cubearm4-ArmatureAction.egg"}) self.pandaActor.setScale(0.12, 0.12, 0.12) self.pandaActor.setPos((10, 10, 0.5)) self.pandaPos = (10, 10, 0.5) self.pandaActor.reparentTo(self.render) self.pandaActor.loop('walk') '''
def __init__(self, name, scene, visualMeshEgg, parent, physicsType, physicsShapeEgg=None, shapeMargin=0.04, animable=False, animationsDict=None, stepHeight=0.5, x=0, y=0, z=0, mass=0, perpixelShading=False): """ :type name: str :type scene: HLevel :type visualMeshEgg: str :type parent: panda3d.core.NodePath :type physicsType: int :type physicsShapeEgg: str :type shapeMargin: float :type animable: bool :type animationsDict: dict :type stepHeight: float :type x: float :type y: float :type z: float :type mass: float :type perpixelShading: bool """ self.name = name self.scene = scene if visualMeshEgg is not None: if animable: if animationsDict is not None: self.vMesh = Actor(visualMeshEgg, animationsDict) self.vMesh.setBlend(frameBlend=True) else: self.vMesh = Actor(visualMeshEgg) self.vMesh.setBlend(frameBlend=True) else: self.vMesh = scene.Base.loader.loadModel(visualMeshEgg) else: self.vMesh = None if physicsType == physicsTypes["character"]: print name + " is a character" self.shapeModel = self.scene.loadEgg(physicsShapeEgg) self.shape = modelToConvex(self.shapeModel)[0] self.shape.setMargin(shapeMargin) self.body = BulletCharacterControllerNode(self.shape, stepHeight, name) self.bodyNP = parent.attachNewNode(self.body) if visualMeshEgg is not None: self.vMesh.reparentTo(self.bodyNP) self.scene.world.attachCharacter(self.body) self.bodyNP.setPos(x, y, z) self.body.setPythonTag("name", name) elif physicsType == physicsTypes["dynamic"]: self.shapeModel = self.scene.loadEgg(physicsShapeEgg) self.shape = modelToConvex(self.shapeModel)[0] self.shape.setMargin(shapeMargin) self.body = BulletRigidBodyNode(name) self.body.setMass(mass) self.body.addShape(self.shape) self.bodyNP = parent.attachNewNode(self.body) if visualMeshEgg is not None: self.vMesh.reparentTo(self.bodyNP) self.scene.world.attachRigidBody(self.body) self.bodyNP.setPos(x, y, z) self.body.setPythonTag("name", name) elif physicsType == physicsTypes["ghost"]: self.shapeModel = self.scene.loadEgg(physicsShapeEgg) self.shape = modelToConvex(self.shapeModel)[0] self.shape.setMargin(shapeMargin) self.body = BulletGhostNode(name) # self.body.setMass(mass) self.body.addShape(self.shape) self.bodyNP = parent.attachNewNode(self.body) if visualMeshEgg is not None: self.vMesh.reparentTo(self.bodyNP) self.scene.world.attachGhost(self.body) self.bodyNP.setPos(x, y, z) self.body.setPythonTag("name", name) else: pass # ###3Events # self.scene.Base.taskMgr.add(self.onFrame,"onFrame") self.shaders = perpixelShading if self.vMesh is not None and not self.shaders: self.scene.Base.taskMgr.add(self.clearShaderTask, name + "_clearShader") # self.scene.Base.taskMgr.add(self._calcVel,self.name+"_calcVelTask") self._lastPos = Point3() self.velocity = Vec3()
def __init__(self): # Notice that you must not call ShowBase.__init__ (or super), the # render pipeline does that for you. If this is unconvenient for you, # have a look at the other initialization possibilities. # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes. In case you placed the render # pipeline in a subfolder of your project, you have to adjust this. sys.path.insert(0, "../../") sys.path.insert(0, "../../RenderPipeline") # Import the main render pipeline class from rpcore import RenderPipeline, SpotLight world = BulletWorld() # Construct and create the pipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) from rpcore.util.movement_controller import MovementController self.render_pipeline.daytime_mgr.time = 0.769 self.controller = MovementController(self) self.controller.set_initial_position(Vec3(6.6, -18.8, 4.5), Vec3(4.7, -16.7, 3.4)) self.controller.setup() # Done! You can start setting up your application stuff as regular now. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0 } self.speed = 1.0 base.win.setClearColor(Vec4(0, 0, 0, 1)) # # vertex_format = GeomVertexFormat.get_v3n3() # vertex_data = GeomVertexData("triangle_data", vertex_format, Geom.UH_static) # # pos_writer = GeomVertexWriter(vertex_data,"vertex") # normal_writer = GeomVertexWriter(vertex_data,"normal") # normal = Vec3(0., -1., 0.) # # pos_writer.add_data3(-1., 0., -1.) # pos_writer.add_data3(1., 0., -1.) # pos_writer.add_data3(0., 0., 1.) # # for _ in range(3): # normal_writer.add_data3(normal) # # prim = GeomTriangles(Geom.UH_static) # prim.add_vertices(0, 1, 2) # # geom = Geom(vertex_data) # geom.add_primitive(prim) # node = GeomNode("my_triangle") # node.add_geom(geom) # triangle = NodePath(node) # triangle.reparent_to(some_other_nodepath) # square1 = create_colored_rect(0, 0, 200, 200) # square2 = create_colored_rect(350, 100, 200, 200, (0, 0, 1, 1)) # square3 = create_colored_rect(-640, -360, 200, 200, (0, 1, 0, 1)) self.tr1 = create_triangle(0, 0, 0, 0, 200, 0, 0, 0, 200, (0, 1, 0, 1)) self.tr2 = create_triangle(-500, 0, 0, -300, 200, 0, -300, 0, 200, (0, 1, 0, 1)) radius = 60 height = 40 shape1 = BulletCylinderShape(radius, height, ZUp) shape2 = BulletCylinderShape(Vec3(radius, 0, 0.5 * height), ZUp) self.gnode = GeomNode('square') # gnode.addGeom(square1) # gnode.addGeom(square2) # gnode.addGeom(square3) height = 1.75 radius = 0.4 shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.gnode.addGeom(self.tr1) self.gnode.addGeom(self.tr2) playerNode = BulletCharacterControllerNode(shape, 0.4, 'Player') playerNP = self.render.attachNewNode(playerNode) playerNP.setPos(0, 0, 14) playerNP.setH(45) playerNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(playerNP.node()) # self.tr1.setPos(400,400, 0) # self.render.attachNewNode(self.gnode) gnode2 = GeomNode('square2') textured_rect = create_textured_rect(-320, 0, 200, 280) gnode2.addGeom(textured_rect) texture = self.loader.loadTexture("assets/playte.png") ship = self.render.attachNewNode(gnode2) ship.setTransparency(TransparencyAttrib.MAlpha) ship.setTexture(texture) # self.ralph = Actor(tr1) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("escape", sys.exit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("p", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("=", self.adjustSpeed, [0.25]) self.accept("+", self.adjustSpeed, [0.25]) self.accept("-", self.adjustSpeed, [-0.25]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(5, 5, 0) base.camLens.setFov(80)