def __init__(self, state, numb, player): # Model taken from https://www.blendswap.com/blends/view/76294 self.enemyModel = base.loader.loadModel('models/knight') self.state = state self.player = player self.enemyModel.setScale(3.5, 3.5, 3.5) x = random.randint(-120, 120) y = random.randint(-100, 100) self.enemyModel.setPos(x, y, 3) self.enemyModel.setHpr(0, 0, 0) self.isAlive = True self.numb = numb self.speed = 0.1 self.enemyModel.reparentTo(render) # fire self.fireballFired = Fireball(self) taskMgr.doMethodLater(5, self.fire, 'fireFireballs') # set up collision self.enemyCollide = CollisionSphere(0, 0, 0, 0.5) self.enemyCollisionNode = CollisionNode('enemy' + str(self.numb)) self.enemyCollisionNode.addSolid(self.enemyCollide) self.enemyCollisionNode.setFromCollideMask(CollideMask.bit(0)) self.enemyCollisionNode.setIntoCollideMask(CollideMask.allOff()) self.collider = self.enemyModel.attachNewNode(self.enemyCollisionNode) # image taken from https://br.depositphotos.com/186812564/stock-photo-gray-steel-background-old-iron.html enemyTexture = loader.loadTexture("models/enemyTexture.jpg") self.enemyModel.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.enemyModel.setTexture(enemyTexture)
def initHero(self): self.hero = loader.loadModel("charaRoot") self.hero.reparentTo(self.stage) model = base.gameData.heroModel self.heroArmature = Actor( "{}".format(model), { "idle": "{}-idle".format(model), "walk": "{}-run".format(model) }) self.heroArmature.reparentTo(self.hero) self.hero.setPos(self.startPos) cNode = CollisionNode('hero') cNode.addSolid(CollisionSphere(0, 0, 1.5, 1)) heroCollision = self.hero.attachNewNode(cNode) ######################################################### # heroCollision.show() self.pusher.addCollider( heroCollision, self.hero, base.drive.node()) base.cTrav.addCollider(heroCollision, self.pusher) heroGroundRay = CollisionRay() heroGroundRay.setOrigin(0, 0, 9) heroGroundRay.setDirection(0, 0, -1) heroGroundCol = CollisionNode('heroRay') heroGroundCol.addSolid(heroGroundRay) heroGroundCol.setFromCollideMask(CollideMask.bit(0)) heroGroundCol.setIntoCollideMask(CollideMask.allOff()) heroGroundColNp = self.hero.attachNewNode(heroGroundCol) ######################################################### # heroGroundColNp.show() base.cTrav.addCollider(heroGroundColNp, self.heroGroundHandler) self.controlCamera()
def setUpCarCollider(self): self.carCollideTrav = CollisionTraverser() base.cTrav = self.carCollideTrav self.handler = CollisionHandlerQueue() self.carRay = CollisionRay(self.carPositionX, self.carPositionY, self.carPositionZ, 0, 0, -1) self.carForwardHandler = CollisionHandlerQueue() # so that it doesn't collide with things forward and backward. degToRad = math.pi / 180 (xDir, yDir, zDir) = self.findCarFrontDir() self.carRayForward = CollisionRay(self.carPositionX, self.carPositionY, self.carPositionZ, xDir, yDir, zDir) self.carForwardCollision = CollisionNode("forwardCollision") self.carForwardCollision.addSolid(self.carRayForward) self.carForwardCollision.setIntoCollideMask(CollideMask.allOff()) self.carForwardCollisionNode = self.car.attachNewNode( self.carForwardCollision) (centerX, centerY) = self.findActualCenter(0, 0, self.adjustedXForCenter, self.adjustedYForCenter, self.carYaw) self.carRayForward.setOrigin(5, 10, 5) self.carCollision = CollisionNode("groundCollision") self.carCollision.addSolid(self.carRay) self.carCollision.setIntoCollideMask(CollideMask.allOff()) self.carCollisionNode = self.car.attachNewNode(self.carCollision) self.carCollideTrav.addCollider(self.carCollisionNode, self.handler) self.carCollideTrav.addCollider(self.carForwardCollisionNode, self.carForwardHandler) self.carForwardCollisionNode.show()
def __init__(self): self.flyBot = base.loader.loadModel('models/flyBot') self.flyBot.setScale(1, 1, 1) self.flyBot.setPos(0, 0, 4) self.flyBot.setHpr(0, 0, 0) self.flyBot.reparentTo(render) self.moved = False self.playerCollide = CollisionBox(0, 3, 1.5, 1.5) self.playerNode = CollisionNode('player') self.playerNode.addSolid(self.playerCollide) self.playerNode.setFromCollideMask(CollideMask.bit(0)) self.playerNode.setIntoCollideMask(CollideMask.allOff()) self.playerCollider = self.flyBot.attachNewNode(self.playerNode)
def __init__(self, base, player): self.base=base self.player=player # actor self.actor=Actor("models/zorrito") self.actor.reparentTo(self.base.render) self.actor.setScale(0.15) # collision # ray collRay=CollisionRay(0, 0, 1.5, 0, 0, -1) collRayN=CollisionNode("playerCollRay") collRayN.addSolid(collRay) collRayN.setFromCollideMask(1) collRayN.setIntoCollideMask(CollideMask.allOff()) #collRayNP=self.actor.attachNewNode(collRayN) self.collQRay=CollisionHandlerQueue() #self.base.cTrav.addCollider(collRayNP, self.collQRay) # ai self.aiWorld=AIWorld(self.base.render) self.aiChar=AICharacter("aiZorrito", self.actor, 150, 0.05, 6) self.aiWorld.addAiChar(self.aiChar) self.aiBehaviors=self.aiChar.getAiBehaviors() self.aiBehaviors.initPathFind("models/navmesh.csv") # state self.distanceToPlayer=1000 self.zOffset=0 self.terrainSurfZ=0 self.state=Zorrito.STATE_IDLE self.currentStateTimeout=4+6*random.random() # uptade task self.base.taskMgr.add(self.update, "zorritoUpdateTask")
def __init__(self, sender, pos, dir, damage, speed, range, accuracy=1): #bullets have a speed, a model, and a damage. Both should be parameters #range as well self.start = pos self.sender = sender self.accuracy = accuracy self.direction = dir.normalized() self.damage = damage self.tasks = [] self.speed = speed self.range = range self.model = base.loader.loadModel('models/bullet') self.model.reparentTo(base.render) self.model.setPos(pos) #self.target=target #create collision sphere #TODO account for larger bullet sizes cs = CollisionSphere(0, 0, 0, 1) self.mainCol = CollisionNode('cNode') #set up circular reference so collision volume knows parent self.mainCol.setPythonTag('owner', self) self.mainCol.setIntoCollideMask( CollideMask.bit(1) ) # send objects with intoCollideMask bit 1. Relates to most entities self.cNode = self.model.attachNewNode(self.mainCol) self.cNode.node().addSolid(cs) #create collider handler, if one doesn't already exist try: # attempt to add to global collision traverser base.cTrav.addCollider(self.cNode, base.bulletCollider) except AttributeError: base.bulletCollider = CollisionHandlerEvent() # create event called 'bulletCollision' on hit base.bulletCollider.addInPattern('bulletCollision') finally: # retry base.cTrav.addCollider(self.cNode, base.bulletCollider) #rotate model such that it follows the passed direction argument vector self.model.setHpr(helper.vectorToHPR(dir)) #assign direction based on rotation #THIS TOOK WAY TOO MUCH EFFORT TO FIGURE OUT #normVec here is the model nodepath taking the passed argument vector (dir) #belonging to another node (base.render) #and adjusting it to its local coordinate space - what would this vector look like from #self.model's perspective. Then it is normalized and assigned. normVec = self.model.getRelativeVector(base.render, dir) normVec.normalize() self.direction = normVec #normVec=base.render.getRelativeVector(self.model,Vec3(0,1,0)) #print(self.model.getHpr()) #print(normVec) #start task to move forward at speed self.tasks.append(taskMgr.add(self.accelerate, "bulletAccelerateTask"))
def setupCollisionRay(self, node, origin=(0, 0, 0), direction=(0, 0, 0), name=None): ray = CollisionRay() ray.setOrigin(origin) ray.setDirection(direction) col = CollisionNode(name) col.addSolid(ray) col.setFromCollideMask(CollideMask.bit(0)) col.setIntoCollideMask(CollideMask.allOff()) colNode = node.attachNewNode(col) queue = CollisionHandlerQueue() self.cTrav.addCollider(colNode, queue) return queue
def setup_ray(node, traverser, bitmask, point_a=(0, 0, 1), point_b=(0, 0, 0)): ray = CollisionSegment(point_a, point_b) col = CollisionNode(node.getName() + "-ray") col.add_solid(ray) col.set_from_collide_mask(bitmask) col.set_into_collide_mask(CollideMask.all_off()) col_node = node.attach_new_node(col) handler = CollisionHandlerQueue() traverser.add_collider(col_node, handler) return {"collider": col, "ray": ray, "handler": handler, "node": col_node}
def colSpheres(parent, spheres=[((0,0,0),1)]): col = CollisionNode(parent.getName()+"-colSpheres") for sphere in spheres: col.addSolid(CollisionSphere(*sphere)) col.setIntoCollideMask(CollideMask.allOff()) colNode = parent.attachNewNode(col) handler = CollisionHandlerQueue() base.cTrav.addCollider(colNode, handler) #colNode.show() return handler
def initModel(self, pos, scale, player, buffState, parent=None): ''' 初始化道具模型和设置碰撞检测 #pos 道具模型的放置位置 (世界坐标系) #scale 模型缩放比例 #player 英雄实例 ''' # 加载并设置模型 try: modelName = ModelPath + "model_" + self.itemName self.item = Actor(modelName, {'revolve': modelName}) self.item.loop('revolve') except Exception: self.item = Actor() self.item.setScale(0.3) self.item.setPos(pos) self.item.setScale(scale) if parent == None: self.item.reparentTo(base.render) else: self.item.reparentTo(parent) # 设置碰撞检测 collisionSphere = CollisionSphere(0, 0, 0, 1) self.collisionNodeName = "{}CollisionNode{}".format( self.itemName, self.number) itemColNode = CollisionNode(self.collisionNodeName) itemColNode.addSolid(collisionSphere) itemColNode.setIntoCollideMask(CollideMask.bit(DefaultHeroMaskVal)) itemColNode.setFromCollideMask(CollideMask.allOff()) self.itemCollision = self.item.attachNewNode(itemColNode) self.itemCollision.setPythonTag("Item", self) ##显示包围体 用于粗略模拟道具盒 # self.itemCollision.show() base.cTrav.addCollider(self.itemCollision, base.cHandler) inEvent = "{}-into-{}".format(player.colliderName, self.collisionNodeName) self.accept(inEvent, self.action) buffState.accept(inEvent, buffState.addBuff)
def colRay(parent, origin=(0,0,0.1), direction=(0,0,-1)): ray = CollisionRay() ray.setOrigin(origin) ray.setDirection(direction) col = CollisionNode(parent.getName()+"-ray") col.addSolid(ray) col.setIntoCollideMask(CollideMask.allOff()) colNode = parent.attachNewNode(col) handler = CollisionHandlerQueue() base.cTrav.addCollider(colNode, handler) #colNode.show() return handler
def __init__(self, x, y, angle): self.wall = base.loader.loadModel('models/wall') self.wall.setPos(x, y, 0) self.wall.setScale(10, 10, 10) self.wall.setH(angle) self.wall.reparentTo(render) # image taken from https://www.pinterest.com/pin/685602743251144929/?lp=true wallTexture = loader.loadTexture('models/walltest.jpg') self.wall.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap) self.wall.setTexProjector(TextureStage.getDefault(), render, self.wall) self.wall.setTexture(wallTexture) self.wallCollide = CollisionRay() self.wallNode = CollisionNode('wall') self.wallNode.addSolid(self.wallCollide) self.wallNode.setFromCollideMask(CollideMask.bit(0)) self.wallNode.setIntoCollideMask(CollideMask.allOff()) self.wallCollider = self.wall.attachNewNode(self.wallNode)
def __init__(self, game): self.game = game self.c_trav = CollisionTraverser() self.mouse_groundHandler = CollisionHandlerQueue() self.mouse_ground_ray = CollisionRay() self.mouse_ground_col = CollisionNode('mouseRay') self.mouse_ground_ray.setOrigin(0, 0, 0) self.mouse_ground_ray.setDirection(0, -1, 0) self.mouse_ground_col.addSolid(self.mouse_ground_ray) self.mouse_ground_col.setFromCollideMask(CollideMask.bit(0)) self.mouse_ground_col.setIntoCollideMask(CollideMask.allOff()) self.mouse_ground_col_np = self.game.camera.attachNewNode(self.mouse_ground_col) self.c_trav.addCollider(self.mouse_ground_col_np, self.mouse_groundHandler) self.game.taskMgr.add(self.update, 'updateMouse')
def hadle_collisions(self): self.cTrav = CollisionTraverser() self.player_ground_ray = CollisionRay() self.player_ground_ray.setOrigin(0, 0, 9) self.player_ground_ray.setDirection(0, 0, -1) self.player_ground_collider = CollisionNode('PlayerRay') self.player_ground_collider.addSolid(self.player_ground_ray) self.player_ground_collider.setFromCollideMask(CollideMask.bit(0)) self.player_ground_collider.setIntoCollideMask(CollideMask.allOff()) self.player_ground_collision_handle = self.player_body.attachNewNode(self.player_ground_collider) self.player_ground_handler = CollisionHandlerQueue() self.cTrav.addCollider(self.player_ground_collision_handle, self.player_ground_handler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('CamRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
def __init__(self, game): self.game = game self.c_trav = CollisionTraverser() self.mouse_groundHandler = CollisionHandlerQueue() self.mouse_ground_ray = CollisionRay() self.mouse_ground_col = CollisionNode('mouseRay') self.mouse_ground_ray.setOrigin(0, 0, 0) self.mouse_ground_ray.setDirection(0, -1, 0) self.mouse_ground_col.addSolid(self.mouse_ground_ray) self.mouse_ground_col.setFromCollideMask(CollideMask.bit(0)) self.mouse_ground_col.setIntoCollideMask(CollideMask.allOff()) self.mouse_ground_col_np = self.game.camera.attachNewNode( self.mouse_ground_col) self.c_trav.addCollider(self.mouse_ground_col_np, self.mouse_groundHandler) self.game.taskMgr.add(self.update, 'updateMouse')
def ray(self, name, bitmask, point_a=(0, 0, 1), point_b=(0, 0, 0)): shape = CollisionSegment(point_a, point_b) col = CollisionNode(self.node.getName() + "-ray-" + name) col.add_solid(shape) col.set_from_collide_mask(bitmask) col.set_into_collide_mask(CollideMask.all_off()) col_node = self.node.attach_new_node(col) handler = CollisionHandlerQueue() self.traverser.add_collider(col_node, handler) return { "collider": col, "shape": shape, "handler": handler, "node": col_node }
def sphere(self, name, bitmask, pos=(0, 0, 1), radius=0.2): col = CollisionNode(self.node.getName() + "-sphere-" + name) shape = CollisionSphere(pos, radius) col.add_solid(shape) col.set_from_collide_mask(bitmask) col.set_into_collide_mask(CollideMask.allOff()) col_node = self.node.attachNewNode(col) handler = CollisionHandlerPusher() handler.add_collider(col_node, self.node) self.traverser.add_collider(col_node, handler) return { "collider": col, "shape": shape, "handler": handler, "node": col_node }
def setUpMouseCollider(self): # clicking on objects stuff came from here: # https://www.panda3d.org/manual/index.php/Collision_Traversers # https://www.panda3d.org/manual/index.php/Collision_Handlers # will not use the traverser set up by car because slow # instead we will render each time clicked self.mouseCollideTrav = CollisionTraverser("mouseTraverse") self.mousehandler = CollisionHandlerQueue() # edit this so that from Object is the camera # self.mouseCollideTrav.addCollider(fromObject, queue) # self.mouseCollideTrav.traverse(render) # this next part came from: # https://www.panda3d.org/manual/index.php/Clicking_on_3D_Objects pickerNode = CollisionNode("mouseRay") pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask()) pickerNode.setIntoCollideMask(CollideMask.allOff()) self.pickerRay = CollisionRay() pickerNode.addSolid(self.pickerRay) pickerNp = camera.attachNewNode(pickerNode) self.mouseCollideTrav.addCollider(pickerNp, self.mousehandler)
def __init__(self, world): self.world = world self.root = self.world.root.attach_new_node("player") self.root_target = self.world.root.attach_new_node("player_target") self.pivot = self.root.attach_new_node("player_pivot") base.camera.reparent_to(self.pivot) base.camera.set_z(1.7) base.cam.node().get_lens().set_fov(90) self.traverser = CollisionTraverser() self.ray = setup_ray( self.pivot, self.traverser, self.world.mask, # ray ends well below feet to register downward slopes (0, 0, 1), (0, 0, -1)) self.xyh_inertia = Vec3(0, 0, 0) h_acc = ConfigVariableDouble('mouse-accelleration', 0.1).get_value() self.xyh_acceleration = Vec3(0.8, 0.8, h_acc) self.friction = 0.15 self.torque = 0.5 self.last_up = Vec3(0, 0, 1) # Collider for portals csphere = CollisionSphere(0, 0, 1.25, 1.5) cnode = CollisionNode('player') cnode.add_solid(csphere) cnode.set_from_collide_mask(0x2) cnode.set_into_collide_mask(CollideMask.all_off()) self.collider = self.root.attach_new_node(cnode) self.event_handler = CollisionHandlerEvent() self.event_handler.add_in_pattern('into-%in') self.traverser.add_collider(self.collider, self.event_handler) self.collider.show() self.teleported = False base.input.set_mouse_relativity(True)
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right") self.dirText = addInstructions(0.42, "pos") self.anglesText = addInstructions(0.48, "angle") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. #self.environ = loader.loadModel("models/world") #self.environ.reparentTo(render) self.createArm() # Create the main character, Ralph #ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) #self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", self.exitButton) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(15, 0, 3)#self.ralph.getX(), self.ralph.getY() + 10, 2) self.camera.setHpr(90, -5, 0) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) base.render.setAttrib(LightRampAttrib.makeHdr0()) # Configure depth pre-pass prepass_pass = lionrender.DepthScenePass() # Configure scene pass scene_fb_props = FrameBufferProperties() scene_fb_props.set_rgb_color(True) scene_fb_props.set_rgba_bits(8, 8, 8, 0) scene_fb_props.set_depth_bits(32) scene_pass = lionrender.ScenePass( frame_buffer_properties=scene_fb_props, clear_color=LColor(0.53, 0.80, 0.92, 1), share_depth_with=prepass_pass) scene_pass.node_path.set_depth_write(False) # Configure post processing filter_pass = lionrender.FilterPass(fragment_path='shaders/fsq.frag') filter_pass.node_path.set_shader_input('inputTexture', scene_pass.output) # Enable FXAA fxaa_pass = lionrender.FxaaFilterPass() fxaa_pass.node_path.set_shader_input('inputTexture', filter_pass.output) # Output result fxaa_pass.output_to(render2d) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward") self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # We do not have a skybox, so we will just use a sky blue background color self.setBackgroundColor(0.53, 0.80, 0.92, 1) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 1.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) self.accept("v", self.toggleCards) taskMgr.add(self.move, "moveTask") # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.cTrav = CollisionTraverser() # Use a CollisionHandlerPusher to handle collisions between Ralph and # the environment. Ralph is added as a "from" object which will be # "pushed" out of the environment if he walks into obstacles. # # Ralph is composed of two spheres, one around the torso and one # around the head. They are slightly oversized since we want Ralph to # keep some distance from obstacles. self.ralphCol = CollisionNode('ralph') self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5)) self.ralphCol.addSolid( CollisionSphere(center=(0, -0.25, 4), radius=1.5)) self.ralphCol.setFromCollideMask(CollideMask.bit(0)) self.ralphCol.setIntoCollideMask(CollideMask.allOff()) self.ralphColNp = self.ralph.attachNewNode(self.ralphCol) self.ralphPusher = CollisionHandlerPusher() self.ralphPusher.horizontal = True # Note that we need to add ralph both to the pusher and to the # traverser; the pusher needs to know which node to push back when a # collision occurs! self.ralphPusher.addCollider(self.ralphColNp, self.ralph) self.cTrav.addCollider(self.ralphColNp, self.ralphPusher) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Clean up texture attributes for texture in self.render.find_all_textures(): texture.set_format(Texture.F_srgb)
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) self.ser = serial.Serial('/dev/tty.usbmodem1421', 9600) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "reverse": 0, "cam-left": 0, "cam-right": 0 } #Initialize Track self.track = self.loader.loadModel("luigi_circuit") self.track.setScale(1.5) self.track.reparentTo(render) #Intitial where Mario needs to be #marioStartPos = self.track.find("**/start_point").getPos() marioStartPos = Vec3(50, -29, 0.35) #Actual start possition #Using ralph because the model is made with correct collision masking and animation self.marioActor = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.marioActor.setScale(0.1, 0.1, 0.1) self.marioActor.setH(self.marioActor, 270) self.marioActor.reparentTo(self.render) self.marioActor.setPos(marioStartPos + (0, 0, 0.5)) #Floater above so Camera has something to look at self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.marioActor) self.floater.setZ(2.0) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.marioActor.getX() + 100, self.marioActor.getY(), 1) #Collision Rays self.cTrav = CollisionTraverser() self.marioGroundRay = CollisionRay() self.marioGroundRay.setOrigin(0, 0, 9) self.marioGroundRay.setDirection(0, 0, -1) self.marioGroundCol = CollisionNode('marioRay') self.marioGroundCol.addSolid(self.marioGroundRay) self.marioGroundCol.setFromCollideMask(CollideMask.bit(0)) self.marioGroundCol.setIntoCollideMask(CollideMask.allOff()) self.marioGroundColNp = self.marioActor.attachNewNode( self.marioGroundCol) self.marioGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.marioGroundColNp, self.marioGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left trackpad]: Rotate Left") self.inst3 = addInstructions(0.18, "[Right trackpad]: Rotate Right") self.inst4 = addInstructions(0.24, "[Up trackpad]: Walk Forward") self.inst4 = addInstructions(0.30, "[Down trackpad]: Walk Backward") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph self.vr = RoamingRalphVR() self.vr.init(msaa=4) self.ralph = render.attachNewNode('ralph') self.ralphStartPos = self.environ.find("**/start_point").getPos() self.vr.tracking_space.setPos(self.ralphStartPos) self.ralph.setPos(self.vr.hmd_anchor.getPos(render)) self.accept("escape", sys.exit) taskMgr.add(self.collision, "collisionTask") # Set up the camera self.disableMouse() # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self, pos=(0, 0, 0), scale=1, parent=None): DirectObject.__init__(self) MovableObject.__init__(self) # 英雄属性 self._maxHP = defaultHeroHP self._HP = defaultHeroHP self._attackPower = defaultHeroAttackPower self._attackSpeed = defaultHeroAttackSpeed self.isMoving = False self._moveSpeed = defaultHeroMoveSpeed self.mousePos = (0, 0, 0) self.leapAttackTime = -1 #英雄被击闪烁 self.invincible = False #是否无敌 self.changeTime = -1 #下次变换形态时间 self.recoveryTime = -1 #恢复正常的时间 self.isHide = False ########## set model size hero self.bullet = SphereBullet( ) #(intoMask = CollideMask.bit(DefaultMonsterMaskVal)) if not self.bullet.model.isEmpty(): self.bullet.model.removeNode() self.attackMode = "Common" self.lastAttackTime = 0 # to enable shoutting at the beginning self.position = pos self.initAttackMethod = self.attack #'model_dierguanBOSS',{ # # 英雄模型和相应动画 self.model = Actor( HeroModelPath + "model_mainChara", { "Walk": HeroModelPath + "anim_mainChara_running_attack", #"Attack": HeroModelPath + "anim_mainChara_standing", "Hit": HeroModelPath + "anim_mainChara_standing", "Die": HeroModelPath + "anim_mainChara_standing" }) if parent == None: self.model.reparentTo(base.render) else: self.model.reparentTo(parent) self.model.setPos(self.position) self.lastPos = self.position self.scale = scale self.model.setScale(scale) self.model.hide() # 设置碰撞检测 self.colliderName = "hero" characterSphere = CollisionSphere(0, 0, 2, 1) characterColNode = CollisionNode(self.colliderName) characterColNode.addSolid(characterSphere) characterColNode.setFromCollideMask( CollideMask.bit(DefaultHeroMaskVal) ^ CollideMask.bit(defaultHeroInMonsterMaskVal)) # print characterColNode.getFromCollideMask() self.colliderNodePath = self.model.attachNewNode(characterColNode) #self.colliderNodePath.show() #将对象添加到nodepath中 用于在碰撞事件处理中获取对象 self.colliderNodePath.setPythonTag("Hero", self) base.cTrav.addCollider(self.colliderNodePath, base.cHandler) #用于处理英雄与墙壁的碰撞 characterSphere2 = CollisionSphere(0, 0, 2, 1) characterColNode2 = CollisionNode(self.colliderName) characterColNode2.addSolid(characterSphere2) self.colliderNodePath2 = self.model.attachNewNode(characterColNode2) self.modelGroundHandler = CollisionHandlerQueue() base.cTrav.addCollider(self.colliderNodePath2, self.modelGroundHandler) # #用于支持英雄与怪物的物理碰撞 characterSphere3 = CollisionSphere(0, 0, 2, 1) characterColNode3 = CollisionNode(self.colliderName) characterColNode3.addSolid(characterSphere3) self.colliderNodePath3 = self.model.attachNewNode(characterColNode3) base.cPusher.addCollider(self.colliderNodePath3, self.model) #用于支持鼠标控制英雄的朝向---------------- self.angle = 0 self.pickerName = 'mouseRay' self.pickerNode = CollisionNode(self.pickerName) self.pickerNP = camera.attachNewNode(self.pickerNode) self.pickerNode.setFromCollideMask(CollideMask.bit(5)) self.pickerNode.setIntoCollideMask(CollideMask.allOff()) self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) #self.pickerNP.show() base.cTrav.addCollider(self.pickerNP, base.cHandler) self.pickedName = 'mousePlane' self.pickedNode = CollisionNode(self.pickedName) self.pickedNP = render.attachNewNode(self.pickedNode) self.pickedNode.setFromCollideMask(CollideMask.allOff()) self.pickedNode.setIntoCollideMask(CollideMask.bit(5)) self.pickedPlane = CollisionPlane( LPlane(LVector3f(0, 0, 1), LPoint3f(0, 0, 2))) self.pickedNode.addSolid(self.pickedPlane) #self.pickedNP.show() #------------------------------------ #加载英雄的各种音效 self.sounds["GetItem"] = loader.loadSfx(HeroSoundPath + "getItem.wav") self.sounds["Die"] = loader.loadSfx(HeroSoundPath + "robot_death.wav") self.sounds["Attack"] = loader.loadSfx(HeroSoundPath + "bullet_shooting.wav") #键位字典 self.keyMap = { "left": 0, "right": 0, "forward": 0, "back": 0, "fire": 0 } self._initAccept()
def __openDoor(self, door): for key, value in self.doorControls.iteritems(): if door == key.getParent().getName(): base.messenger.send("PuzzleSolved") value[0].play() value[1].node().setIntoCollideMask(CollideMask.allOff())
def startGame(self): # Load the map. self.environ = loader.loadModel("models/background_model") # Reparent the model to render. self.environ.reparentTo(render) # Apply scale and position transforms on the model. # image taken from http://motorbikes-passion.info/scary-dark-room.html myTexture = loader.loadTexture("models/backgroundtexture.jpg") self.environ.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap) self.environ.setTexture(myTexture) self.environ.setScale(1, 1, 1) self.environ.setPos(0, 0, 0) self.environ.reparentTo(render) # random generate map self.numbWalls = 4 walls = generateRoom([], self.numbWalls) # if random generation fails, input default map if walls == None: walls = [(120, 30, 0), (-100, 80, 90), (-130, -70, 0), (50, -50, 90)] # load wall models in respective location for wall in walls: x, y, angle = wall newWall = Wall(x, y, angle) self.walls.append(newWall) # generate chests in random areas chests = generateChestLocation(walls) for chest in chests: x, y, chestNumb = chest newChest = Chest(self.player, self.flyBot, x, y, chestNumb) self.chests.append(newChest) # display player stats self.display = self.player.displayStats() # run collision settings base.cTrav = CollisionTraverser() # Set up collision for environment self.backgroundCollide = CollisionRay() self.backgroundNode = CollisionNode('backgroundCollider') self.backgroundNode.addSolid(self.backgroundCollide) self.backgroundNode.setFromCollideMask(CollideMask.bit(0)) self.backgroundNode.setIntoCollideMask(CollideMask.allOff()) self.backgroundCollider = self.environ.attachNewNode( self.backgroundNode) # call all functions that deal with collisions taskMgr.add(self.swordHitEnemy, 'killEnemy') self.wallCollisions() taskMgr.add(self.fireballHitPlayer, 'fireballHits') # load sound effects # sound taken from https://bigsoundbank.com/detail-0129-sword.html self.swordCut = loader.loadSfx('musics/0129.ogg') # sound taken from https://bigsoundbank.com/detail-0437-shot-beretta-m12-9-mm.html self.fireballHit = loader.loadSfx('musics/0437.ogg') # run quitGame self.quitGame() # Set up initial camera position base.camera.setPos(0, 0, 0) base.camera.setHpr(0, 0, 0) base.camera.reparentTo(self.flyBot.flyBot) # import player controls from player file self.playerControl = player.KeyboardControl(self.flyBot, self.chests, self.door, self.walls, self.player) # import leap motion control self.leapControl = player.swordControl(self.leap, self.player) taskMgr.add(self.leapControl.swingsword, 'swingsword') # spawn new enemies sec = 5 - self.player.atLevel taskMgr.doMethodLater(sec, self.spawnEnemies, 'createNewEnemy') # test enemy movements taskMgr.add(self.enemyMovements, 'enemyMovements') # Game AI AI = GameAI(self.enemies, self.flyBot) taskMgr.add(AI.makeDecision, 'enemyStateDetermination')
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward") self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # We do not have a skybox, so we will just use a sky blue background color self.setBackgroundColor(0.53, 0.80, 0.92, 1) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 1.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.cTrav = CollisionTraverser() # Use a CollisionHandlerPusher to handle collisions between Ralph and # the environment. Ralph is added as a "from" object which will be # "pushed" out of the environment if he walks into obstacles. # # Ralph is composed of two spheres, one around the torso and one # around the head. They are slightly oversized since we want Ralph to # keep some distance from obstacles. self.ralphCol = CollisionNode('ralph') self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5)) self.ralphCol.addSolid(CollisionSphere(center=(0, -0.25, 4), radius=1.5)) self.ralphCol.setFromCollideMask(CollideMask.bit(0)) self.ralphCol.setIntoCollideMask(CollideMask.allOff()) self.ralphColNp = self.ralph.attachNewNode(self.ralphCol) self.ralphPusher = CollisionHandlerPusher() self.ralphPusher.horizontal = True # Note that we need to add ralph both to the pusher and to the # traverser; the pusher needs to know which node to push back when a # collision occurs! self.ralphPusher.addCollider(self.ralphColNp, self.ralph) self.cTrav.addCollider(self.ralphColNp, self.ralphPusher) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) self.ground = 1.2 #Create the fairy. # self.pnode2 = Actor("models/ralph", # {"run": "models/ralph-run", # "walk": "models/ralph-walk"}) # self.pnode2.reparentTo(self.ralph) # self.pnode2.setScale(0.5) # self.ground = 1.2 # self.pnode2.setPos(3,0,self.ground) # self.vz = 0 # self.vx = 0 # self.vy = 0 # self.angle = 0 # self.speed = (2*3.1416)/10 # self.radius = 2; # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) self.wizard = [] #list that contains the wizards wizards = self.loader.loadModel("models/eve") #load the random wizards for i in range(0,20): pos = LPoint3((random.random()-1) * 180, (random.random()-1) * 180, self.ground) w = wizards.copy_to(self.render) w.setScale(0.5) w.setPos(pos) w.setH(0) w.reparentTo(self.render) self.wizard.append(w) #Create the fairy. self.pnode2 = self.loader.loadModel("models/eve") self.pnode2.reparentTo(w) self.pnode2.setScale(0.5) self.ground = 1.2 self.pnode2.setPos(3,0,self.ground) self.vz = 0 self.vx = 0 self.vy = 0 self.angle = 0 self.speed = (2*3.1416)/10 self.radius = 2; # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor(BACKGROUND_COLOR) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character playerStartPos = self.environ.find("**/start_point").getPos() self.player = Actor("models/player", {"run": "models/player-run", "walk": "models/player-walk"}) self.player.reparentTo(render) self.player.setScale(0.2) self.player.setPos(playerStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above player. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.player) self.floater.setZ(CAMERA_TARGET_HEIGHT_DELTA) self.first_person = False def key_dn(name): return lambda: self.setKey(name, True) def key_up(name): return lambda: self.setKey(name, False) def quit(): self.destroy() def toggle_first(): self.first_person = not self.first_person # Accept the control keys for movement and rotation key_map = [ # key command action help # --- ------- ------ ---- ("escape", "esc", lambda: quit(), "[ESC]: Quit"), ("arrow_left", "left", key_dn("left"), "[Left Arrow]: Rotate Left"), ("arrow_left-up", "left", key_up("left"), None), ("arrow_right", "right", key_dn("right"), "[Right Arrow]: Rotate Right"), ("arrow_right-up", "right", key_up("right"), None), ("arrow_up", "forward", key_dn("forward"), "[Up Arrow]: Run Forward"), ("arrow_up-up", "forward", key_up("forward"), None), ("arrow_down", "backward", key_dn("backward"), "[Down Arrow]: Run Backward"), ("arrow_down-up", "backward", key_up("backward"), None), ("a", "cam-left", key_dn("cam-left"), "[A]: Rotate Camera Left"), ("a-up", "cam-left", key_up("cam-left"), None), ("s", "cam-right", key_dn("cam-right"), "[S]: Rotate Camera Right"), ("s-up", "cam-right", key_up("cam-right"), None), ("f", "first-pers", lambda: toggle_first(), "[F]: Toggle first-person"), ] self.keyMap = {} inst = Instructions() for key, command, action, description in key_map: if command: self.setKey(command, False) self.accept(key, action) if description: inst.add(description) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.player.getX(), self.player.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above player's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.playerGroundRay = CollisionRay() self.playerGroundRay.setOrigin(0, 0, 9) self.playerGroundRay.setDirection(0, 0, -1) self.playerGroundCol = CollisionNode("playerRay") self.playerGroundCol.addSolid(self.playerGroundRay) self.playerGroundCol.setFromCollideMask(CollideMask.bit(0)) self.playerGroundCol.setIntoCollideMask(CollideMask.allOff()) self.playerGroundColNp = self.player.attachNewNode(self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode("camRay") self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays self.playerGroundColNp.show() self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((0.3, 0.3, 0.3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) #self.setupCD() # Set the background color to black # self.win.setClearColor((0.6, 0.6, 1.0, 1.0)) # self.fog = Fog('myFog') # self.fog.setColor(0, 0, 0) # self.fog.setExpDensity(.05) # render.setFog(self.fog) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0, "c":0, "back":0, "space":0} # Post the instructions #self.title = addTitle( # "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") #self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left") #self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") #self.environ.reparentTo(render) self.room = loader.loadModel("models/room2.egg") self.room.reparentTo(render) #self.room.setScale(.1) self.room.setPos(0,0,-5) self.room.setShaderAuto() #self.room.writeBamFile("myRoom1.bam") #self.room.setColor(1,.3,.3,1) self.room2 = loader.loadModel("models/abstractroom2") self.room2.reparentTo(render) self.room2.setScale(.1) self.room2.setPos(-12,0,0) # Create the main character, Ralph #ralphStartPos = LVecBase3F(0,0,0) #self.room.find("**/start_point").getPos() self.ralph = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(0,0,0) #cs = CollisionSphere(0, 0, 0, 1) #cnodePath = self.ralph.attachNewNode(CollisionNode('cnode')) #cnodePath.node().addSolid(cs) #cnodePath.node().setPos(0,0,0) #cnodePath.show() self.gianteye = loader.loadModel("models/gianteye") self.gianteye.reparentTo(render) self.gianteye.setScale(.1) self.gianteye.setPos(10,10,0) #self.bluefinal = loader.loadModel("models/chrysalis") #self.bluefinal.reparentTo(render) #self.bluefinal.setScale(.1) #self.bluefinal.setPos(7,7,0) #self.blue = loader.loadModel("models/blue1") #self.blue.reparentTo(render) #self.blue.setScale(.1) #self.blue.setPos(10,5,0) self.chik = loader.loadModel("models/chik") self.chik.reparentTo(render) self.chik.setScale(.1) self.chik.setPos(3,13,0) self.pawn = loader.loadModel("pawn") self.pawn.reparentTo(render) self.pawn.setPos(0,0,0) self.shot = loader.loadModel("models/icosphere.egg") self.shot.reparentTo(render) self.shot.setScale(.5) self.shot.setPos(0,0,1) self.shot.setColor(1,.3,.3,1) self.myShot = loader.loadModel("models/icosphere.egg") #self.myShot.reparentTo(render) self.myShot.setScale(.1) self.myShot.setPos(0,0,1) self.myShotVec = LVector3(0,0,0) self.lightpivot3 = render.attachNewNode("lightpivot3") self.lightpivot3.setPos(0, 0, 0) self.lightpivot3.hprInterval(10, LPoint3(0, 0, 0)).loop() plight3 = PointLight('plight2') plight3.setColor((0, .3,0, 1)) plight3.setAttenuation(LVector3(0.7, 0.05, 0)) plnp3 = self.lightpivot3.attachNewNode(plight3) plnp3.setPos(0, 0, 0) self.room2.setLight(plnp3) self.room.setLight(plnp3) sphere3 = loader.loadModel("models/icosphere") sphere3.reparentTo(plnp3) sphere3.setScale(0.1) sphere3.setColor((0,1,0,1)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(8.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["back", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["back", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) self.accept("space", self.setKey, ["space", True]) self.accept("space-up", self.setKey, ["space", False]) self.accept("c",self.setKey,["c",True]) self.accept("c-up",self.setKey,["c",False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False self.jumping = False self.vz = 0 # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 7, 3) self.camLens.setFov(60) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. def setupCollision(self): cs = CollisionSphere(0,0,2,1) cnodePath = self.ralph.attachNewNode(CollisionNode('cnode')) cnodePath.node().addSolid(cs) cnodePath.show() #for o in self.OBS: #ct = CollisionTube(0,0,0, 0,0,1, 0.5) #cn = o.attachNewNode(CollisionNode('ocnode')) #cn.node().addSolid(ct) #cn.show() eyecs = CollisionSphere(0,0,4,5) cnodePath = self.gianteye.attachNewNode(CollisionNode('cnode')) cnodePath.node().addSolid(eyecs) cnodePath.show() eyecs = CollisionSphere(0,0,4,2) cnodePath = self.chik.attachNewNode(CollisionNode('cnode')) cnodePath.node().addSolid(eyecs) cnodePath.show() pusher = CollisionHandlerPusher() pusher.addCollider(cnodePath, self.player) self.cTrav = CollisionTraverser() self.cTrav.add_collider(cnodePath,pusher) self.cTrav.showCollisions(render) self.walls = self.room2.find("**/wall_collide") #self.walls.node().setIntoCollideMask(BitMask32.bit(0)) self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) self.sphere = CollisionSphere(0,0,4,2) self.sphere2 = CollisionSphere(0,0,2,2) self.cnodePath = self.ralph.attachNewNode((CollisionNode('cnode'))) self.cnodePath.node().addSolid(self.sphere) self.cnodePath.node().addSolid(self.sphere2) self.cnodePath.show() self.pusher = CollisionHandlerPusher() self.pusher.addCollider(self.cnodePath, self.ralph) self.cTrav.add_collider(self.cnodePath, self.pusher) self.eyecs = CollisionSphere(0,0,22,25) self.cnodePath1 = self.gianteye.attachNewNode(CollisionNode('cnode')) self.cnodePath1.node().addSolid(self.eyecs) self.cnodePath1.show() self.pusher1 = CollisionHandlerPusher() self.pusher1.addCollider(self.cnodePath1, self.gianteye) self.cTrav.add_collider(self.cnodePath1, self.pusher1) self.cTrav.showCollisions(render) self.eyeGroundRay = CollisionRay() self.eyeGroundRay.setOrigin(0, 0, 9) self.eyeGroundRay.setDirection(0, 0, -1) self.eyeGroundCol = CollisionNode('eyeRay') self.eyeGroundCol.addSolid(self.eyeGroundRay) self.eyeGroundCol.setFromCollideMask(CollideMask.bit(0)) self.eyeGroundCol.setIntoCollideMask(CollideMask.allOff()) self.eyeGroundColNp = self.gianteye.attachNewNode(self.eyeGroundCol) self.eyeGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.eyeGroundColNp, self.eyeGroundHandler) self.chikcs = CollisionSphere(0,0,11,20) self.cnodePath2 = self.chik.attachNewNode(CollisionNode('cnode')) self.cnodePath2.node().addSolid(self.chikcs) self.cnodePath2.show() self.pusher2 = CollisionHandlerPusher() self.pusher2.addCollider(self.cnodePath, self.chik) self.cTrav.add_collider(self.cnodePath, self.pusher2) self.cTrav.showCollisions(render) self.chikGroundRay = CollisionRay() self.chikGroundRay.setOrigin(0, 0, 9) self.chikGroundRay.setDirection(0, 0, -1) self.chikGroundCol = CollisionNode('chikRay') self.chikGroundCol.addSolid(self.chikGroundRay) self.chikGroundCol.setFromCollideMask(CollideMask.bit(0)) self.chikGroundCol.setIntoCollideMask(CollideMask.allOff()) self.chikGroundColNp = self.chik.attachNewNode(self.chikGroundCol) self.chikGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.chikGroundColNp, self.chikGroundHandler) # Uncomment this line to see the collision rays self.ralphGroundColNp.show() self.camGroundColNp.show() #self.ralphroom1ColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, .4)) ambientLight2 = AmbientLight("ambientLight2") ambientLight2.setColor((1, 1, 1, 10)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((0, 0, -2)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) #self.environ.setLight(self.environ.attachNewNode(ambientLight2)) render.setLight(render.attachNewNode(directionalLight)) # Add a light to the scene. self.lightpivot = render.attachNewNode("lightpivot") self.lightpivot.setPos(0, 0, 1.6) self.lightpivot.hprInterval(20, LPoint3(360, 0, 0)).loop() plight = PointLight('plight') plight.setColor((.7, .3, 0, 1)) plight.setAttenuation(LVector3(0.7, 0.05, 0)) plnp = self.lightpivot.attachNewNode(plight) plnp.setPos(5, 0, 0) self.room.setLight(plnp) sphere = loader.loadModel("models/icosphere") sphere.reparentTo(plnp) sphere.setScale(0.1) sphere.setColor((1,1,0,1)) self.lightpivot2 = render.attachNewNode("lightpivot") self.lightpivot2.setPos(-16, 0, 1.6) self.lightpivot2.hprInterval(20, LPoint3(360, 0, 0)).loop() plight2 = PointLight('plight2') plight2.setColor((0, .4,.8, 1)) plight2.setAttenuation(LVector3(0.7, 0.05, 0)) plnp2 = self.lightpivot2.attachNewNode(plight2) plnp2.setPos(5, 0, 0) self.room2.setLight(plnp2) sphere2 = loader.loadModel("models/icosphere") sphere2.reparentTo(plnp2) sphere2.setScale(0.2) sphere2.setColor((0,0,1,1)) self.vec = LVector3(0,1,0)
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } ########################################################################### self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # We do not have a skybox, so we will just use a sky blue background color #self.setBackgroundColor(0.53, 0.80, 0.92, 1) self.setBackgroundColor(.1, .1, .1, 1) # Create the main character, person #personStartPos = self.environ.find("**/start_point").getPos() #self.person = Actor("models/panda", # {"run": "models/panda-walk", # "walk": "models/panda-walk"}) person2StartPos = self.environ.find("**/start_point").getPos() self.person2 = Actor("models/passenger_penguin", {"run": "models/passenger_penguin", "walk": "models/passenger_penguin"}) self.person2.reparentTo(render) self.person2.setScale(.1) self.person2.setPos(person2StartPos + (px, py, 1)) person3StartPos = self.environ.find("**/start_point").getPos() self.person3 = Actor("models/MagicBunny", {"run": "models/MagicBunny", "walk": "models/MagicBunny"}) #px = random.randint(-1,1) #py = random.randint(-1,1) self.person3.reparentTo(render) self.person3.setScale(.04) #self.person.setPos(personStartPos + (0, 0, 2)) self.person3.setPos(person3StartPos + (px/1.5+3, py/2, 0)) personStartPos = self.environ.find("**/start_point").getPos() self.person = Actor("models/panda", {"run": "models/panda-walk", "walk": "models/panda-walk"}) self.person.reparentTo(render) self.person.setScale(.1) self.person.setPos(personStartPos + (0, 0, 1.5)) self.person.loop("run") arenaStartPos = self.environ.find("**/start_point").getPos() self.arena = Actor("models/FarmHouse") self.arena.reparentTo(render) self.arena.setScale(.1) self.arena.setPos(arenaStartPos + (-1, 0, 0)) arena2StartPos = self.environ.find("**/start_point").getPos() self.arena2 = Actor("models/fence") self.arena2.reparentTo(render) self.arena2.setScale(5.9) self.arena.setPos(arenaStartPos + (px, py-12, 1)) self.arena2.setPos(arenaStartPos + (8, 5, -1)) arena2StartPos = self.environ.find("**/start_point").getPos() self.arena3 = Actor("models/gate") self.arena3.reparentTo(render) self.arena3.setScale(.01) self.arena3.setPos(arenaStartPos + (px/2+random.randint(12,15), py/2, -1)) self.arena4 = Actor("models/FarmHouse") self.arena4.reparentTo(render) self.arena4.setScale(.1) self.arena4.setPos(arenaStartPos + (px/3-random.randint(18,22), py/3, -1)) self.arena5 = Actor("models/gate") self.arena5.reparentTo(render) self.arena5.setScale(.008) self.arena5.setPos(arenaStartPos + (px/1.2-9, py/1.2, -1)) ##################################################################################################################################### base.enableParticles() self.t = loader.loadModel("teapot") # for the particle enhancer self.t.setScale(10) self.t.setPos(-10, -20, -1) self.t.reparentTo(render) #self.setupLights() self.p = ParticleEffect() self.p.setScale(1000) self.loadParticleConfig('smoke.ptf') # looks like a storm at night self.p.setScale(20) #################################################3 # Create a floater object, which floats 2 units above person. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.person) self.floater.setZ(2.0) # Accept the control keys for movement and rotation taskMgr.add(self.move, "moveTask") # Set up the camera self.disableMouse() self.camera.setPos(self.person.getX(), self.person.getY() + 10, 2) self.cTrav = CollisionTraverser() self.personCol = CollisionNode('person') self.personCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5)) self.personCol.addSolid(CollisionSphere(center=(0, -0.25, 4), radius=1.5)) self.personCol.setFromCollideMask(CollideMask.bit(0)) self.personCol.setIntoCollideMask(CollideMask.allOff()) self.personColNp = self.person.attachNewNode(self.personCol) self.personPusher = CollisionHandlerPusher() self.personPusher.horizontal = True self.personPusher.addCollider(self.personColNp, self.person) self.cTrav.addCollider(self.personColNp, self.personPusher) self.personGroundRay = CollisionRay() self.personGroundRay.setOrigin(0, 0, 9) self.personGroundRay.setDirection(0, 0, -1) self.personGroundCol = CollisionNode('personRay') self.personGroundCol.addSolid(self.personGroundRay) self.personGroundCol.setFromCollideMask(CollideMask.bit(0)) self.personGroundCol.setIntoCollideMask(CollideMask.allOff()) self.personGroundColNp = self.person.attachNewNode(self.personGroundCol) self.personGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.personGroundColNp, self.personGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, .2)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((.2, .2, .2, 1)) directionalLight.setSpecularColor((.1, .1, .1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): ShowBase.__init__(self) # Load Lights self.light = LoadLight.Light self.light.setupLight(self) # Load Environment self.model = LoadModel.Model() self.model.initialize(self) Map.init() map_center = (0, 0) subprova = Submap.Submap(map_center) global stored_submaps_list global current_submap stored_submaps_list[map_center] = subprova current_submap = subprova print("stored in init:", stored_submaps_list) self.drawMap(subprova) """ self.model.loadAnimal(5,6,0, "bear") self.model.loadAnimal(12,-6,0, "cow") self.model.loadAnimal(7,-9,0, "panther") self.model.loadAnimal(-17,5,0, "rabbit") self.model.loadAnimal(-7,5,0, "wolf") self.model.loadPlant(8,-2,0, "fir") self.model.loadPlant(-3,-2,0, "grass") self.model.loadPlant(-4,2,0, "oak") self.model.loadPlant(-1,17,0, "berry_bush") """ # Text on screen self.text_char_pos = None self.text_submap = None self.text_lock = None # Create the main character self.char = self.model.loadCharacter(0, 0, 0) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above char's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.charGroundRay = CollisionRay() self.charGroundRay.setOrigin(0, 0, 9) self.charGroundRay.setDirection(0, 0, -1) self.charGroundCol = CollisionNode('charRay') self.charGroundCol.addSolid(self.charGroundRay) self.charGroundCol.setFromCollideMask(CollideMask.bit(0)) self.charGroundCol.setIntoCollideMask(CollideMask.allOff()) self.charGroundColNp = self.char.attachNewNode(self.charGroundCol) self.charGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.charGroundColNp, self.charGroundHandler) # Uncomment this line to see the collision rays #self.charGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # This is used to store which keys are currently pressed. self.keyMap = { "restart": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-q": 0, "cam-w": 0, "cam-e": 0, "cam-d": 0, "cam-s": 0, "cam-a": 0 } # Post the instructions self.title = addTitle("Isometric HexaMap test") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Arrow Keys]: Move char") self.inst3 = addInstructions( 0.18, "[Q,W,E,D,S,A]: Change camera's angle of view") #self.inst8 = addInstructions(0.48, "[R]: Restart") # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("n", self.print_all_nodes) self.accept("k", self.clear_all_nodes) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("q", self.setKey, ["cam-q", True]) self.accept("w", self.setKey, ["cam-w", True]) self.accept("e", self.setKey, ["cam-e", True]) self.accept("d", self.setKey, ["cam-d", True]) self.accept("s", self.setKey, ["cam-s", True]) self.accept("a", self.setKey, ["cam-a", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("q-up", self.setKey, ["cam-q", False]) self.accept("w-up", self.setKey, ["cam-w", False]) self.accept("e-up", self.setKey, ["cam-e", False]) self.accept("d-up", self.setKey, ["cam-d", False]) self.accept("s-up", self.setKey, ["cam-s", False]) self.accept("a-up", self.setKey, ["cam-a", False]) # self.accept("restart", self.char.setPos(0,0,0)) self.taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera with isometric perspective self.disableMouse() lens = OrthographicLens() lens.setFilmSize(20, 11.25) lens.setNear(-20) self.cam.node().setLens(lens) self.camera.setPos(self.char.getPos() + (math.sin(cam_angle[cam_view]) * cam_dist, -math.cos(cam_angle[cam_view]) * cam_dist, cam_dz)) self.camera.lookAt(self.char)
def __init__(self): CosmoniumBase.__init__(self) config = RalphConfigParser() (self.noise, self.biome_noise, self.terrain_control, self.terrain_appearance, self.water, self.fog) = config.load_and_parse('ralph-data/ralph.yaml') self.tile_density = 64 self.default_size = 128 self.max_vertex_size = 64 self.max_lod = 10 self.size = 128 * 8 self.max_distance = 1.001 * self.size * sqrt(2) self.noise_size = 512 self.biome_size = 128 self.noise_scale = 0.5 * self.size / self.default_size self.objects_density = int(25 * (1.0 * self.size / self.default_size) * (1.0 * self.size / self.default_size)) self.objects_density = 250 self.height_scale = 100 * 5.0 self.has_water = True self.fullscreen = False self.shadow_caster = None self.light_angle = None self.light_dir = LVector3.up() self.vector_to_star = self.light_dir self.light_quat = LQuaternion() self.light_color = (1.0, 1.0, 1.0, 1.0) self.directionalLight = None self.shadow_size = self.default_size / 8 self.shadow_box_length = self.height_scale self.observer = RalphCamera(self.cam, self.camLens) self.observer.init() self.distance_to_obs = float('inf') self.height_under = 0.0 self.scene_position = LVector3() self.scene_scale_factor = 1 self.scene_orientation = LQuaternion() #Size of an edge seen from 4 units above self.edge_apparent_size = (1.0 * self.size / self.tile_density) / (4.0 * self.observer.pixel_size) print("Apparent size:", self.edge_apparent_size) self.win.setClearColor((135.0/255, 206.0/255, 235.0/255, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0, "sun-left": 0, "sun-right": 0, "turbo": 0} # Set up the environment # # Create some lighting self.vector_to_obs = base.cam.get_pos() self.vector_to_obs.normalize() if True: self.shadow_caster = ShadowCaster(1024) self.shadow_caster.create() self.shadow_caster.set_lens(self.shadow_size, -self.shadow_box_length / 2.0, self.shadow_box_length / 2.0, -self.light_dir) self.shadow_caster.set_pos(self.light_dir * self.shadow_box_length / 2.0) self.shadow_caster.bias = 0.1 else: self.shadow_caster = None self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((settings.global_ambient, settings.global_ambient, settings.global_ambient, 1)) self.directionalLight = DirectionalLight("directionalLight") self.directionalLight.setDirection(-self.light_dir) self.directionalLight.setColor(self.light_color) self.directionalLight.setSpecularColor(self.light_color) render.setLight(render.attachNewNode(self.ambientLight)) render.setLight(render.attachNewNode(self.directionalLight)) render.setShaderAuto() base.setFrameRateMeter(True) self.create_terrain() self.create_populator() self.terrain_shape.set_populator(self.object_collection) self.create_tile(0, 0) self.skybox_init() self.set_light_angle(45) # Create the main character, Ralph ralphStartPos = LPoint3() self.ralph = Actor("ralph-data/models/ralph", {"run": "ralph-data/models/ralph-run", "walk": "ralph-data/models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) self.ralph_shape = InstanceShape(self.ralph) self.ralph_shape.parent = self self.ralph_shape.set_owner(self) self.ralph_shape.create_instance() self.ralph_appearance = ModelAppearance(self.ralph) self.ralph_appearance.set_shadow(self.shadow_caster) self.ralph_shader = BasicShader() self.ralph_appearance.bake() self.ralph_appearance.apply(self.ralph_shape, self.ralph_shader) self.ralph_shader.apply(self.ralph_shape, self.ralph_appearance) self.ralph_shader.update(self.ralph_shape, self.ralph_appearance) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("control-q", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("shift", self.setKey, ["turbo", True]) self.accept("a", self.setKey, ["cam-left", True], direct=True) self.accept("s", self.setKey, ["cam-right", True], direct=True) self.accept("u", self.setKey, ["cam-up", True], direct=True) self.accept("u-up", self.setKey, ["cam-up", False]) self.accept("d", self.setKey, ["cam-down", True], direct=True) self.accept("d-up", self.setKey, ["cam-down", False]) self.accept("o", self.setKey, ["sun-left", True], direct=True) self.accept("o-up", self.setKey, ["sun-left", False]) self.accept("p", self.setKey, ["sun-right", True], direct=True) self.accept("p-up", self.setKey, ["sun-right", False]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("shift-up", self.setKey, ["turbo", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) self.accept("w", self.toggle_water) self.accept("h", self.print_debug) self.accept("f2", self.connect_pstats) self.accept("f3", self.toggle_filled_wireframe) self.accept("shift-f3", self.toggle_wireframe) self.accept("f5", self.bufferViewer.toggleEnable) self.accept("f8", self.terrain_shape.dump_tree) self.accept('alt-enter', self.toggle_fullscreen) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.camera_height = 2.0 render.set_shader_input("camera", self.camera.get_pos()) self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) #self.terrain_shape.test_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance) #self.terrain_shape.update_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance) #self.terrain.shape_updated() self.terrain.update_instance(LPoint3d(*self.ralph.getPos()), None)
def __init__(self): global speed global maxspeed self.keyMap = {"left":0, "right":0, "forward":0, "accelerate":0, "decelerate":0, "cam-left":0, "cam-right":0} base.win.setClearColor(Vec4(0,0,0,1)) # Post the instructions self.title = addTitle("HW2: Roaming Ralph Modified (Walking on the Moon) with friends") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[W]: Move Ralph Forward") self.inst5 = addInstructions(0.75, "[P]: Increase Ralph Velocity (Run)") self.inst6 = addInstructions(0.70, "[O]: Decrease Ralph Velocity (Walk)") self.inst7 = addInstructions(0.60, "[Left Arrow]: Rotate Camera Left") self.inst8 = addInstructions(0.55, "[Right Arrow]: Rotate Camera Right") # Set up the environment self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.environ.setScale(100,100,1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) # Create the main character, Ralph if(v ==[0]): print(model) self.ralph = Actor("models/ralph", {"run":"models/ralph-run", "walk":"models/ralph-walk"}) self.ralph.setScale(.2) elif(v == [1]): print(model) self.ralph = Actor("models/panda-model", {"walk": "models/panda-walk4"}) speed = 100 maxspeed =10000 self.ralph.setScale(0.0001, 0.00015, 0.0005) self.ralph.setScale(.002) self.ralph.setPlayRate(100.0, "models/panda-walk4") speed = 100 maxspeed =10000 self.ralph.setScale(.0035) else: print(model) self.ralph = Actor("models/GroundRoamer.egg") self.ralph.setScale(.15) self.ralph.setHpr(180,0,0) self.Groundroamer_texture = loader.loadTexture("models/Groundroamer.tif") self.ralph.setTexture(self.Groundroamer_texture) self.ralph.reparentTo(render) self.ralph.setPos(0,0,0) #creates Earth self.earth = Actor("models/planet_sphere.egg.pz") self.earth.reparentTo(render) self.earth.setScale(6.0) self.earth.setPos(40,25,6) self.earth_texture = loader.loadTexture("models/earth_1k_tex.jpg") self.earth.setTexture(self.earth_texture) #creates Mercury self.mercury = Actor("models/planet_sphere.egg.pz") self.mercury.reparentTo(render) self.mercury.setScale(2.0) self.mercury.setPos(-40,-25,2) self.mercury_texture = loader.loadTexture("models/mercury_1k_tex.jpg") self.mercury.setTexture(self.mercury_texture) #creates Venus self.venus = Actor("models/planet_sphere.egg.pz") self.venus.reparentTo(render) self.venus.setScale(4.0) self.venus.setPos(40,-30,4) self.venus_texture = loader.loadTexture("models/venus_1k_tex.jpg") self.venus.setTexture(self.venus_texture) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation 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("s", 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("arrow_left-up", self.setKey, ["cam-left",0]) self.accept("arrow_right-up", self.setKey, ["cam-right",0]) self.accept("p", self.setKey, ["accelerate",1]) self.accept("o", self.setKey, ["decelerate",1]) self.accept("p-up", self.setKey, ["accelerate",0]) self.accept("o-up", self.setKey, ["decelerate",0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2) self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) #self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() #self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self, base): self.base = base self.keyState = { "WalkFw": False, "WalkBw": False, "Run": False, "RotateL": False, "RotateR": False, "Jump": False, "Duck": False } self.isKeyDown = self.base.mouseWatcherNode.isButtonDown self.state = Player.STATE_IDLE self.sub_state = None self.walkDir = 0 self.rotationDir = 0 self.zVelocity = 0 self.zOffset = None self.jumpHeight = None self.terrainZone = Player.TERRAIN_NONE self.terrainSurfZ = None self.waterDepth = 0 self.collidedObjects = list() # actor anims = { "idle": "models/player-idle", "walk": "models/player-walk", "run": "models/player-run", "jump": "models/player-jump", "duck": "models/player-duck", "float": "models/player-float", "swim": "models/player-swim", "grab": "models/player-grab" } self.actor = Actor("models/player", anims) self.actor.reparentTo(self.base.render) self.actor.setH(200) log.debug("actor tight bounds is %s" % str(self.actor.getTightBounds())) # animation info Player.DUCK_FRAME_COUNT = self.actor.getNumFrames("duck") Player.DUCK_FRAME_MID = int(Player.DUCK_FRAME_COUNT / 2) # camara point self.camNode = NodePath("camNode") self.camNode.reparentTo(self.actor) self.camNode.setPos(0, 0, 1) # collision # ray collRay = CollisionRay(0, 0, 1.5, 0, 0, -1) collRayN = CollisionNode("playerCollRay") collRayN.addSolid(collRay) collRayN.setFromCollideMask(1) collRayN.setIntoCollideMask(CollideMask.allOff()) collRayNP = self.actor.attachNewNode(collRayN) self.collQRay = CollisionHandlerQueue() self.base.cTrav.addCollider(collRayNP, self.collQRay) # sphere mask 2 collSphere2 = CollisionSphere(0, 0, 0.5, 0.25) collSphere2N = CollisionNode("playerCollSphere2") collSphere2N.addSolid(collSphere2) collSphere2N.setFromCollideMask(2) collSphere2N.setIntoCollideMask(CollideMask.allOff()) self.collSphere2NP = self.actor.attachNewNode(collSphere2N) self.collPSphere = CollisionHandlerPusher() self.collPSphere.addCollider(self.collSphere2NP, self.actor) self.base.cTrav.addCollider(self.collSphere2NP, self.collPSphere) # key events self.base.accept("i", self.dump_info) # task self.base.taskMgr.add(self.update, "playerUpdateTask")
def initCollision(self): self.enemyGroundRay = [] self.enemyGroundCol = [] self.enemyGroundColNp = [] self.enemyGroundHandler = [] self.npcGroundRay = [] self.npcGroundCol = [] self.npcGroundColNp = [] self.npcGroundHandler = [] self.cTrav = CollisionTraverser() self.playerGroundRay = CollisionRay() self.playerGroundRay.setOrigin(0, 0, 9) self.playerGroundRay.setDirection(0, 0, -1) self.playerGroundCol = CollisionNode('playerRay') self.playerGroundCol.addSolid(self.playerGroundRay) self.playerGroundCol.setFromCollideMask(CollideMask.bit(0)) self.playerGroundCol.setIntoCollideMask(CollideMask.allOff()) self.playerGroundColNp = self.player.moveFloater.attachNewNode(self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) self.mouseGroundRay = CollisionRay() self.mouseGroundRay.setOrigin(0, 0, 9) self.mouseGroundRay.setDirection(0, 0, -1) self.mouseGroundCol = CollisionNode('mouseRay') self.mouseGroundCol.addSolid(self.mouseGroundRay) self.mouseGroundCol.setFromCollideMask(CollideMask.bit(0)) self.mouseGroundCol.setIntoCollideMask(CollideMask.allOff()) self.mouseGroundColNp = self.camera.attachNewNode(self.mouseGroundCol) self.mouseGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.mouseGroundColNp, self.mouseGroundHandler) # Uncomment this line to see the collision rays #self.playerGroundColNp.show() #self.mouseGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) i = 0 for enemy in self.enemies: self.enemyGroundRay.append(CollisionRay()) self.enemyGroundRay[i].setOrigin(0, 0, 9) self.enemyGroundRay[i].setDirection(0, 0, -1) self.enemyGroundCol.append(CollisionNode('%sRay' % enemy.name)) self.enemyGroundCol[i].addSolid(self.enemyGroundRay[i]) self.enemyGroundCol[i].setFromCollideMask(CollideMask.bit(0)) self.enemyGroundCol[i].setIntoCollideMask(CollideMask.allOff()) self.enemyGroundColNp.append(enemy.enemyActor.attachNewNode(self.enemyGroundCol[i])) self.enemyGroundHandler.append(CollisionHandlerQueue()) self.cTrav.addCollider(self.enemyGroundColNp[i], self.enemyGroundHandler[i]) #self.enemyGroundColNp.show() i += 1 i = 0 for npc in self.npcs: self.npcGroundRay.append(CollisionRay()) self.npcGroundRay[i].setOrigin(0, 0, 9) self.npcGroundRay[i].setDirection(0, 0, -1) self.npcGroundCol.append(CollisionNode('%sRay' % npc.name)) self.npcGroundCol[i].addSolid(self.npcGroundRay[i]) self.npcGroundCol[i].setFromCollideMask(CollideMask.bit(0)) self.npcGroundCol[i].setIntoCollideMask(CollideMask.allOff()) self.npcGroundColNp.append(npc.npcActor.attachNewNode(self.npcGroundCol[i])) self.npcGroundHandler.append(CollisionHandlerQueue()) self.cTrav.addCollider(self.npcGroundColNp[i], self.npcGroundHandler[i]) #self.npcGroundColNp.show() i += 1
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.key_map = {"left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} # Post the Instruction self.title = add_title("Panda 3D Demo") # Instructions self.inst1 = add_instructions(0.06, "[ESC]: Quit") self.inst2 = add_instructions(0.12, "[Left Arrow]: Rotate Left") self.inst3 = add_instructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = add_instructions(0.24, "[Up Arrow]: Run Ralph Forward") # self.inst6 = add_instructions(0.30, "[A]: Rotate Camera Left") # self.inst7 = add_instructions(0.36, "[S]: Rotate Camera Right") # Load the Environment Model self.environ = self.loader.loadModel(ENVIRONMENT) # Reparent the model to the render controller self.environ.reparentTo(render) # Apply scale and position transform on the model # self.environ.setScale(0.25, 0.25, 0.25) # self.environ.setPos(-8, 42, 0) # Create the Main Character # Load and transform the panda actor ralph_start_pos = self.environ.find("**/start_point").getPos() self.ralph = Actor(RALPH_ACTOR, RALPH_ACTIONS) # self.ralph.setScale(0.005, 0.005, 0.005) self.ralph.reparentTo(render) # Loop it's animation self.ralph.setScale(0.2) self.ralph.setPos(ralph_start_pos + (0, 0, 0.5)) # self.ralph.loop("walk") # Create a floater object, which floats 2 units above rlaph. We use this as a target for the camera to look at self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) # 2 Units above Ralph self.floater.setZ(2.0) # Configure the Camera # Add the spin camera taks procedure to the taks manager # self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Accept certain control keys self.accept("escape", sys.exit) self.accept("arrow_left", self.set_key, ["left", True]) self.accept("arrow_right", self.set_key, ["right", True]) self.accept("arrow_up", self.set_key, ["forward", True]) self.accept("a", self.set_key, ["cam-left", True]) self.accept("s", self.set_key, ["cam-right", True]) self.accept("arrow_left-up", self.set_key, ["left", False]) self.accept("arrow_right-up", self.set_key, ["right", False]) self.accept("arrow_up-up", self.set_key, ["forward", False]) self.accept("a-up", self.set_key, ["cam-left", False]) self.accept("s-up", self.set_key, ["cam-right", False]) # Game States taskMgr.add(self.move, "moveTask") self.is_moving = False self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.camera.lookAt(self.floater) """ Detect the height of hte terrain by creating a collision ray and casting it down towards the terrain. One ray will start above ralph's head and the other will start above the camera. A ray may hit the terrain, or it may hit a rock or a tree. If it hits the terrain we ca ndetect the height. If it hits anything else, we rule that the move is illegal. """ self.cTrav = CollisionTraverser() # Create a vector, it's location is at the top of ralph's head self.ralph_ground_ray = CollisionRay() self.ralph_ground_ray.setOrigin(0, 0, 9) # Top of ralph's head self.ralph_ground_ray.setDirection(0, 0, -1) # Points -Z axis # Create a Collision node self.ralph_ground_col = CollisionNode("ralph_ray") # Give the node a name self.ralph_ground_col.addSolid(self.ralph_ground_ray) # the vector from ralph's head to the ground is solid self.ralph_ground_col.setFromCollideMask(CollideMask.bit(0)) # ?? self.ralph_ground_col.setIntoCollideMask( CollideMask.allOff() ) # ?? This seems like it defines the behavior of ray self.ralph_ground_col_np = self.ralph.attachNewNode(self.ralph_ground_col) # Attach the ray to ralph self.ralph_ground_handler = ( CollisionHandlerQueue() ) # I think that when a collision occurs it sends through this self.cTrav.addCollider(self.ralph_ground_col_np, self.ralph_ground_handler) # Attach the collision """ Attach the a camera ray to the camera """ self.cam_ground_ray = CollisionRay() self.cam_ground_ray.setOrigin(0, 0, 9) self.cam_ground_ray.setDirection(0, 0, -1) self.cam_ground_col = CollisionNode("camera_ray") self.cam_ground_col.addSolid(self.cam_ground_ray) self.cam_ground_col.setFromCollideMask(CollideMask.bit(0)) self.cam_ground_col.setIntoCollideMask(CollideMask.allOff()) self.cam_ground_col_np = self.camera.attachNewNode(self.cam_ground_col) self.cam_ground_handler = CollisionHandlerQueue() self.cTrav.addCollider(self.cam_ground_col_np, self.cam_ground_handler) # Uncomment the following lines to view the rays self.ralph_ground_col_np.show() self.cam_ground_col_np.show() # Uncomment this line to show a visual representation of the Collision occuring self.cTrav.showCollisions(render) # Create some lighting ambient_light = AmbientLight("ambient_light") ambient_light.setColor((0.3, 0.3, 0.3, 1)) directional_light = DirectionalLight("directional_light") directional_light.setDirection((-5, -5, -5)) directional_light.setColor((1, 1, 1, 1)) directional_light.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambient_light)) render.setLight(render.attachNewNode(directional_light)) # Add Cube X_OFFSET = 0 Y_OFFSET = -3 Z_OFFSET = 1 CUBE_SIZE = 2 x, y, z = ralph_start_pos x += X_OFFSET y += Y_OFFSET z += Z_OFFSET