def makePerspective(parent): v = Viewport('persp', parent) v.camPos = Point3(-19, -19, 19) v.camLookAt = Point3(0, 0, 0) v.grid = DirectGrid(parent=render) collPlane = CollisionNode('PerspGridCol') collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) #oldBitmask = collPlane.getIntoCollideMask() #collPlane.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.reparentTo(v.grid) collPlane2 = CollisionNode('PerspGridCol2') collPlane2.addSolid(CollisionPlane(Plane(0, 0, -1, 0))) #oldBitmask = collPlane2.getIntoCollideMask() #collPlane2.setIntoCollideMask(BitMask32.bit(21)|oldBitmask) collPlane2.setIntoCollideMask(BitMask32.bit(21)) v.collPlane2 = NodePath(collPlane2) v.collPlane2.reparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_perspViewGridBack") LE_showInOneCam(v.grid, 'persp') return v
def makeOrthographic(parent, name, campos): v = Viewport(name, parent) v.lens = OrthographicLens() v.lens.setFilmSize(30) v.camPos = campos v.camLookAt = Point3(0, 0, 0) v.grid = DirectGrid(parent=render) if name == 'left': v.grid.setHpr(0, 0, 90) collPlane = CollisionNode('LeftGridCol') collPlane.addSolid(CollisionPlane(Plane(1, 0, 0, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.wrtReparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_leftViewGridBack") LE_showInOneCam(v.grid, name) elif name == 'front': v.grid.setHpr(90, 0, 90) collPlane = CollisionNode('FrontGridCol') collPlane.addSolid(CollisionPlane(Plane(0, -1, 0, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.wrtReparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_frontViewGridBack") LE_showInOneCam(v.grid, name) else: collPlane = CollisionNode('TopGridCol') collPlane.addSolid(CollisionPlane(Plane(0, 0, 1, 0))) collPlane.setIntoCollideMask(BitMask32.bit(21)) v.collPlane = NodePath(collPlane) v.collPlane.reparentTo(v.grid) #v.grid.gridBack.findAllMatches("**/+GeomNode")[0].setName("_topViewGridBack") LE_showInOneCam(v.grid, name) return v
def _initCollisions(self): self.collPlane = CollisionPlane(Plane(Vec3(0, 0, 1.0), Point3(0, 0, 10))) self.collPlane.setTangible(0) self.collNode = CollisionNode('fogPlane') self.collNode.setIntoCollideMask(OTPGlobals.FloorBitmask) self.collNode.addSolid(self.collPlane) self.collNodePath = self.root.attachNewNode(self.collNode) self.collNodePath.hide()
def __init__(self, cr): DistributedObject.__init__(self, cr) #self.model = loader.loadModel('environment') #self.model.setZ(0) #self.builder = Builder(self, "map.txt", "development") plane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) cnode = CollisionNode('cnode') cnode.setIntoCollideMask(BitMask32.bit(1)) cnode.setFromCollideMask(BitMask32.bit(1)) cnode.addSolid(plane) self.planeNP = self.model.attachNewNode(cnode) self.planeNP.show() # Setup a traverser for the picking collisions self.picker = CollisionTraverser() # Setup mouse ray self.pq = CollisionHandlerQueue() # Create a collision Node pickerNode = CollisionNode('MouseRay') # set the nodes collision bitmask pickerNode.setFromCollideMask(BitMask32.bit(1)) # create a collision ray self.pickerRay = CollisionRay() # add the ray as a solid to the picker node pickerNode.addSolid(self.pickerRay) # create a nodepath with the camera to the picker node self.pickerNP = base.camera.attachNewNode(pickerNode) # add the nodepath to the base traverser self.picker.addCollider(self.pickerNP, self.pq) print "model loaded" #TODO: check how to load multiple levels and set players in specific levels! self.accept("mouse1", self.mouseClick)
def addPlanes(self): for plane in self.planes: colPlane = CollisionPlane(LPlane(*plane)) planeNode = CollisionNode('planeNode') planeNode.addSolid(colPlane) planeNP = render.attachNewNode(planeNode) planeNP.show()
def update_trackplane(self): self.trackplane_cn.setSolid( 0, CollisionPlane( Plane( Point3(-self.base.cam.getMat().getRow3(1)), Point3(self.lookatpos_pdv3[0], self.lookatpos_pdv3[1], 0.0))))
def create_wall_collider(self, render, x_angle, y_angle, angle): wallSolid = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(x_angle * self.size / 2) wall.setY(y_angle * self.size / 2) wall.setHpr(angle, -90, 0)
def __init__(self): print("TerrainTest object created") self.make_traverser_handler() self.tm = TerrainManager(16, 16) self.down = 0 self.PCs = {} #self.make_actor() self.char = Character("pandabuddy") self.pc = self.char.panda_actor self.make_actor_collisions(self.pc) #self.make_test_capsule() self.tm.get_terrain(0, 0).terrain.getRoot().setTag('myObjectTag', '1') #self.tm.get_terrain(0, 0).terrain.getRoot().setIntoCollideMask(BitMask32.bit(0)) #col_t = CollisionNode("col_t") #col_t.addSolid(CollisionPolygon(self.tm.get_terrain(0, 0).terrain.getRoot())) #CollisionPolygon(self.tm.get_terrain(0, 0).terrain.getRoot()) #base.cTrav.addCollider(self.tm.get_terrain(0, 0).terrain.getRoot(), base.mchandler) #pusher = CollisionHandlerPusher() #pusher.addCollider(self.collision_node, self.char.boxc) #base.cTrav.addCollider(self.collision_node, pusher) #base.cTrav.addCollider(self.collision_node, base.mchandler) cp = CollisionPlane(LPlane((0, 0, 1), (0, 0, 0))) #self.planeANP = render.attachNewNode(ActorNode('p actor')) planeNP = base.render.attachNewNode(CollisionNode('planecnode')) #planeNP = self.planeANP.attachNewNode(CollisionNode('planecnode')) self.accept('into-planecnode', self.hanev) self.accept('pcol-again-planecnode', self.hanev) planeNP.node().addSolid(cp) planeNP.show() planeNP.setScale(100, 100, 100) planeNP.node().setIntoCollideMask(BitMask32.bit(0)) planeNP.node().setFromCollideMask(BitMask32.allOff()) planeNP.setPos(0, 0, -100) #base.mchandler.addCollider(planeNP, self.planeANP) #base.cTrav.addCollider(planeNP, base.mchandler) #base.physicsMgr.attachPhysicalNode(self.planeANP.node()) base.cTrav.addCollider(self.char.boxc, base.mchandler) base.cTrav.setRespectPrevTransform(True) #base.mchandler.addCollider(self.collision_node, self.char.panda_actor) #base.mchandler.addCollider(self.collision_node, self.char.boxc) #base.mchandler.addCollider(self.char.boxc, self.collision_node) Globals.g_task_manager.add(self.move, "moveTask", priority=-100) self.task1 = Task(self.gravity) Globals.g_task_manager.add(self.task1, "gravityTask", extraArgs=[self.task1, self.pc])
def setup_interactiongeometries(self): """ set up collision rays, spheres, and planes for mouse manipulation :return: None author: weiwei date: 20161110 """ # create a trackball ray and set its bitmask to 8 # the trackball ray must be a subnode of cam since we will # transform the clicked point (in the view of the cam) to the world coordinate system # using the ray self.tracker_cn = CollisionNode("tracker") self.tracker_ray = CollisionRay() self.tracker_cn.addSolid(self.tracker_ray) self.tracker_cn.setFromCollideMask(BitMask32.bit(8)) self.tracker_cn.setIntoCollideMask(BitMask32.allOff()) self.tracker_np = self.base.cam.attachNewNode(self.tracker_cn) # create an inverted collision sphere and puts it into a collision node # its bitmask is set to 8, and it will be the only collidable object at bit 8 self.trackball_cn = CollisionNode("trackball") self.trackball_cn.addSolid( CollisionSphere(self.lookatpos_pdv3[0], self.lookatpos_pdv3[1], self.lookatpos_pdv3[2], self.camdist)) self.trackball_cn.setFromCollideMask(BitMask32.allOff()) self.trackball_cn.setIntoCollideMask(BitMask32.bit(8)) self.trackball_np = self.base.render.attachNewNode(self.trackball_cn) # self.trackball_np.show() # This creates a collision plane for mouse track self.trackplane_cn = CollisionNode("trackplane") self.trackplane_cn.addSolid( CollisionPlane( Plane( Point3(-self.base.cam.getMat().getRow3(1)), Point3(self.lookatpos_pdv3[0], self.lookatpos_pdv3[1], 0.0)))) self.trackplane_cn.setFromCollideMask(BitMask32.allOff()) self.trackplane_cn.setIntoCollideMask(BitMask32.bit(8)) self.trackplane_np = self.base.render.attachNewNode(self.trackplane_cn) # self.trackplane_np.show() # creates a traverser to do collision testing self.ctrav = CollisionTraverser() # creates a queue type handler to receive the collision event info self.chandler = CollisionHandlerQueue() # register the ray as a collider with the traverser, # and register the handler queue as the handler to be used for the collisions. self.ctrav.addCollider(self.tracker_np, self.chandler) # create a pickerray self.picker_cn = CollisionNode('picker') self.picker_ray = CollisionRay() self.picker_cn.addSolid(self.picker_ray) self.picker_cn.setFromCollideMask(BitMask32.bit(7)) self.picker_cn.setIntoCollideMask(BitMask32.allOff()) self.picker_np = self.base.cam.attachNewNode(self.picker_cn) self.ctrav.addCollider(self.picker_np, self.chandler)
def add_border_walls(self): '''Attaching invisible walls to map's borders, to avoid falling off map''' log.debug("Adding invisible walls to collide with on map's borders") wall_coordinates = [ ((self.map_size[0], 0, 0), (self.map_size[1], 0, 0)), ((-self.map_size[0], 0, 0), (-self.map_size[1], 0, 0)), ((0, self.map_size[2], 0), (0, self.map_size[3], 0)), ((0, -self.map_size[2], 0), (0, -self.map_size[3], 0)) ] for sizes in wall_coordinates: wall_node = CollisionNode("wall") #it looks like without adding node to pusher (we dont need that there), #masks wont work. Thus for now I wont use them, as defaults seem to work #wall_node.set_collide_mask(BitMask32(shared.WALLS_COLLISION_MASK)) wall_node.add_solid(CollisionPlane(Plane(*sizes))) wall = render.attach_new_node(wall_node)
def add_borders(self): """Attach invisible walls to map's borders, to avoid falling off map""" log.debug("Adding invisible walls to collide with on map's borders") wall_coordinates = [ ((self.map_size[0], 0, 0), (self.map_size[1], 0, 0)), ((-self.map_size[0], 0, 0), (-self.map_size[1], 0, 0)), ((0, self.map_size[2], 0), (0, self.map_size[3], 0)), ((0, -self.map_size[2], 0), (0, -self.map_size[3], 0)), ] for sizes in wall_coordinates: wall_node = CollisionNode(shared.game_data.border_category) # it looks like without adding node to pusher (we dont need that there), # masks wont work. Thus for now I wont use them, as defaults seem to work # wall_node.set_collide_mask(BitMask32(shared.WALLS_COLLISION_MASK)) wall_node.add_solid(CollisionPlane(Plane(*sizes))) wall = self.scene.attach_new_node(wall_node) # adding tag with wall's coordinations, so it will be possible to # push entities back if these collide with wall # because calling .get_pos() will return LPoint3f(0,0,0) wall_node.set_python_tag("position", sizes)
def __init__(self,base,Golog, folder_path = None, parent = None): # Set up basic attributes self.base = base self.golog = Golog self.bools = {'textboxes':True} self.buttons = dict() self.window_tasks = dict() self.bt = None self.mw = None self.listener = DirectObject() self.folder_path = folder_path #absolute path of golog folder '/path/to/golog/folder' if self.folder_path: self.file_path = os.path.abspath(self.folder_path + '/' + self.golog.label+ '.golog') autosave = True self.has_window = False self.parent = parent #for autosaving up to original golog self.reset = self.basic_reset self.garbage = [] #list of deleted math_data/graphics_data etc. #create a 2d rende self.render2d = NodePath('2d render') self.camera2D = self.render2d.attachNewNode(Camera('2d Camera')) self.camera2D.setDepthTest(False) self.camera2D.setDepthWrite(False) lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setNearFar(-1000, 1000) self.camera2D.node().setLens(lens) # make a dictionary of mode_heads in the underlying golog if hasattr(self.golog,'mode_heads'): m = 0 while m in self.golog.mode_heads.keys(): m+=1 #get smallest unused mode_head index self.index = m self.label = self.golog.label+"_mode_head_"+str(self.index) self.golog.mode_heads[self.index] = self else: self.golog.mode_heads = dict() self.index = 0 self.label = self.golog.label+"_mode_head_"+ str(self.index) self.golog.mode_heads[self.index] = self ########## ### set up collision handling ### self.queue = CollisionHandlerQueue() ### set up selection tools self.create_list = [[],[]] #select nodes and add to create_list in order to create higher simplecies self.bools = {'selecter':False,'textboxes':True,'shift_clicked':False} #some bools that will be usefull self.dict = {'shift_pt':[None,None]} # set up mouse picker self.pickerNode = CollisionNode('mouseRay') self.pickerNP = self.golog.camera.attachNewNode(self.pickerNode) #attach collision node to camera self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) self.pickerNode.set_into_collide_mask(0) #so that collision rays don't collide into each other if there are two mode_heads self.golog.cTrav.addCollider(self.pickerNP,self.queue) #send collisions to self.queue # set up plane for picking self.planeNode = self.golog.render.attachNewNode("plane") self.planeNode.setTag("mode_head",self.label) # tag to say it belongs to this mode_head self.planeNode.setTag("mode_node", 'plane') self.planeFromObject = self.planeNode.attachNewNode(CollisionNode("planeColNode")) self.planeFromObject.node().addSolid(CollisionPlane(Plane(Vec3(0,-1,0),Point3(0,0,0)))) self.plane = self.planeFromObject.node().getSolid(0) ### # set up preview text self.textNP = self.render2d.attachNewNode(TextNode('text node')) self.textNP.setScale(.2) self.textNP.setPos(-1,0,0) self.textNP.show() #set up dragging info self.grabbed_dict = dict() self.drag_dict = dict() #a mapping from selected nodes to their original positions for dragging self.mouse_down_loc = (0,0,0) self.lowest_level = 3
def __init__(self): # Create a traverser that Panda3D will automatically use every frame. base.cTrav = CollisionTraverser() # Create a handler for the events. self.collHandler = CollisionHandlerQueue() # Define a few bitmasks for use. # Teaching the concepts of bitmasks is out of the scope of this sample. # This just shows a practical application of bitmasks. goodMask = BitMask32(0x1) badMask = BitMask32(0x2) floorMask = BitMask32(0x4) # Make a list of different combinations of the masks for later use. # We will switch between these masks later on. self.maskList = [["floor", floorMask], ["smiley", goodMask], ["frowney", badMask], ["characters", goodMask | badMask], ["smiley and floor", goodMask | floorMask], ["frowney and floor", badMask | floorMask], ["all", floorMask | goodMask | badMask]] # This keeps track of where we are in the dictionary. self.maskPos = 0 # First we create a floor collision plane. floorNode = base.render.attachNewNode("Floor NodePath") # Create a collision plane solid. collPlane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) # Call our function that creates a nodepath with a collision node. floorCollisionNP = self.makeCollisionNodePath(floorNode, collPlane) # Get the collision node the Nodepath is referring to. floorCollisionNode = floorCollisionNP.node() # The floor is only an into object, so just need to set its into mask. floorCollisionNode.setIntoCollideMask(floorMask) # Create a collision sphere. Since the models we'll be colliding # are basically the same we can get away with just creating one # collision solid and adding the same solid to both collision nodes. collSphere = CollisionSphere(0, 0, 0, 1.5) # Make a smiley. smiley = base.loader.loadModel('smiley') smiley.reparentTo(base.render) smiley.setPos(-3, 3, 3) smiley.setName("Smiley") smileyCollisionNP = self.makeCollisionNodePath(smiley, collSphere) # Like with the floor plane we need to set the into mask. # Here we shortcut getting the actual collision node. smileyCollisionNP.node().setIntoCollideMask(goodMask) # Make a frowney. frowney = base.loader.loadModel('frowney') frowney.reparentTo(base.render) frowney.setPos(-3, 3, 7) frowney.setName("Frowney") frowneyCollisionNP = self.makeCollisionNodePath(frowney, collSphere) # Use the the Nodepath.setCollideMask() function to set the into mask. # setCollideMask() sets the into mask of all child nodes to the given # mask. frowneyCollisionNP.setCollideMask(badMask) # Note that we don't call setCollideMask() from frowney because this # will turn the frowney mesh into a collision mesh which is unwanted. # Note that we didn't set a from collide mask for previous objects # since we're not adding them to the traverser as from objects. # Make a collision ray that passes through all of the objects. self.pointerNode = base.render.attachNewNode("Main Collider") self.pointerNode.setPos(-3, 3, 10) # Create a ray collision solid that points downwards. raySolid = CollisionRay(0, 0, 0, 0, 0, -1) mainColNP = self.makeCollisionNodePath(self.pointerNode, raySolid) self.mainColNode = mainColNP.node() # Set a from collide mask for this ray so that we can selectively # collide against the other objects. self.mainColNode.setFromCollideMask(self.maskList[self.maskPos][1]) base.cTrav.addCollider(mainColNP, self.collHandler) # Set up the camera. base.disableMouse() base.camera.setPos(20, -20, 5) base.camera.lookAt(0, 0, 5) # Debug mode for collision traversers; shows collisions visually. base.cTrav.showCollisions(base.render) # Setup the title text. collideText = self.maskList[self.maskPos][0] self.title = OnscreenText(text="Colliding with %s" % (collideText), mayChange=True, pos=(0.3, 0), align=TextNode.ALeft, fg=(1, 1, 1, 1)) OnscreenText(text="Press space to change collision mask", pos=(0, 0.8), fg=(1, 1, 1, 1)) # Set space to change the from collision mask of the collision ray. base.accept("space", self.switchCollisionMask)
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 run(self, root_node, restart_scene_cb): self.restart_scene_cb = restart_scene_cb self.root_node = root_node self.base.accept("escape", sys.exit) # Escape quits self.base.camera.set_pos(0, 0, 90) self.base.camera.set_hpr(0, -90, 0) self.score = Scores(self.game_end, self.game_quit_cb, self.restart_game) self.game_ended = False lens = OrthographicLens() lens.set_film_size(40 * win_aspect, 40) self.base.cam.node().setLens(lens) self.gc = GameControls(self.base, self.move_player, mouse_magnitude=7) self.base.disable_mouse() # debug camera movement # self.fm = FlyMove(self) # self.camera.set_pos(-20, 0, 10) # self.camera.set_hpr(-90, -50, 0) self.base.cTrav = CollisionTraverser() self.coll_hand_event = CollisionHandlerEvent() self.coll_hand_event.addInPattern('into-%in') paddle_path = 'models/paddle' self.player_paddle = pp = self.load_and_render(paddle_path) pp.set_pos(-20, 0, 0) pp.set_hpr((90, 0, 0)) self.ai_paddle = aip = self.load_and_render(paddle_path, copy=True) aip.set_pos(20, 0, 0) aip.set_hpr((90, 0, 0)) self.ball = self.load_and_render('models/ball') collision_ball = CollisionSphere(0, 0, 0, 1) cnodePath = self.ball.attachNewNode(CollisionNode('ball')) cnodePath.node().addSolid(collision_ball) self.base.cTrav.add_collider(cnodePath, self.coll_hand_event) # ball movement self.reset_ball() self.ball_speed_scale = 0.30 self.base.task_mgr.add(self.ball_move_task, 'ball-move') # set up boundaries on the top and bottom self.border_distance = border_distance = 20 self.top_boundary = self.load_and_render(paddle_path, copy=True) self.top_boundary.set_sx(5) self.top_boundary.set_y(border_distance) self.bottom_boundary = self.load_and_render(paddle_path, copy=True) self.bottom_boundary.set_sx(5) self.bottom_boundary.set_y(-1 * border_distance) horizontal_distance = 30 self.player_side_plane = CollisionPlane( Plane(LVector3f(1, 0, 0), LPoint3f(-1 * horizontal_distance, 0, 0))) self.player_side_cnode = self.root_node.attachNewNode( CollisionNode('pplane')) self.player_side_cnode.node().add_solid(self.player_side_plane) self.ai_side_plane = CollisionPlane( Plane(LVector3f(-1, 0, 0), LPoint3f(horizontal_distance, 0, 0))) self.ai_side_cnode = self.root_node.attachNewNode( CollisionNode('aiplane')) self.ai_side_cnode.node().add_solid(self.ai_side_plane) # add collision to paddles and walls, everything the ball can reflect off of for np in [pp, aip, self.bottom_boundary, self.top_boundary]: cs = CollisionBox((0, 0, 0), 5, 0.25, 8) cnodePath = np.attachNewNode(CollisionNode('wall')) cnodePath.node().addSolid(cs) self.base.cTrav.add_collider(cnodePath, self.coll_hand_event) self.base.accept('into-wall', self.ball_collision) self.base.accept('into-pplane', self.player_side_goal) self.base.accept('into-aiplane', self.ai_side_goal) self.ai = PongAI(self.base, self.ai_paddle, self.ball, border_distance)
def __init__(self): ShowBase.__init__(self) self.grid = np.loadtxt("input/maze.txt") f = open("input/start_point.txt", "r") self.start_pos = eval(f.read()) if FULLSCREEN: wp = WindowProperties() wp.setFullscreen(True) base.win.requestProperties(wp) self.disableMouse() self.accept("escape", sys.exit) self.camera.setPosHpr(self.start_pos[0], self.start_pos[1], CAMERA_SCALE, 0, -90, 0) # maze wall offset = 0.05 # expand collision boundaries for the walls for i in range(-1, len(self.grid) + 1): for j in range(-1, len(self.grid[0]) + 1): if i == -1 or j == -1 or i == len(self.grid) or j == len( self.grid[0]) or self.grid[i][j]: #box-1_-1 is not a valid name so we change it to boxa_b texti = i textj = j if i == -1: texti = 'a' if j == -1: textj = 'b' suffix = str(texti) + "_" + str(textj) # model exec("self.box" + suffix + " = self.loader.loadModel('models/cube')") exec("self.box" + suffix + ".reparentTo(self.render)") exec("self.box" + suffix + ".setPos(" + str(i) + ", " + str(j) + ", 1)") # collision node exec("self.boxCollider" + suffix + " = self.box" + suffix + ".attachNewNode(CollisionNode('wall_collide'))") exec( "self.boxCollider" + suffix + ".node().addSolid(CollisionBox(Point3(0-offset,0-offset,0-offset),Point3(1+offset,1+offset,1+offset)))" ) exec("self.boxCollider" + suffix + ".node().setIntoCollideMask(BitMask32.bit(0))") #exec("self.boxCollider" + suffix + ".show()") # maze ground model self.maze = loader.loadModel("models/cube") self.maze.setScale(len(self.grid), len(self.grid[0]), 1) self.maze.reparentTo(self.render) # maze ground collision node self.walls = self.maze.attachNewNode(CollisionNode('wall_collide')) self.walls.node().addSolid( CollisionBox(Point3(0, 0, 0), Point3(1, 1, 1))) self.walls.node().setIntoCollideMask(BitMask32.bit(1)) # maze ground plane collision node self.mazeGround = self.maze.attachNewNode( CollisionNode('ground_collide')) self.mazeGround.node().addSolid( CollisionPlane(Plane(Vec3(0, 0, 1), Point3(2, 2, 1)))) self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) # ball model self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # ball material m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1) # ball collision node self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) # collision ray self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0, 0, 10) self.ballGroundRay.setDirection(0, 0, -1) # ray collision node self.ballGroundCol = CollisionNode('groundRay') self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # ray self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # collision traverser and handler queue self.cHandler = CollisionHandlerQueue() self.cTrav = CollisionTraverser() self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # visual effects ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) self.start()
def __init__(self): ShowBase.__init__(self) # generate a new game game = Game() game.create_player('Player One') game.create_player('Player Two') game.create_player('Player Three') game.initialize_board() # place some random cities for player in game.players.values(): # give the player some random resources for resource in player.resources: player.resources[resource] = random.randint(0,8) while True: n = random.choice(game.board.network.nodes()) if game.board.node_available(n): game.board.update_building(n, player, 'city') # place a random road m = random.choice(game.board.network.neighbors(n)) game.board.network.edge[n][m]['road'] = True game.board.network.edge[n][m]['player'] = player break self.board_renderer = BoardRenderer(self, game.board) self.hand_renderer = HandRenderer(self, game.players.values()[0]) # setup some 3-point lighting for the whole board lKey = DirectionalLight('lKey') lKey.setColor(VBase4(0.9,0.9,0.9,1)) lKeyNode = render.attachNewNode(lKey) lKeyNode.setH(-63) lKeyNode.setP(-60) lKeyNode.setR(-30) render.setLight(lKeyNode) lFill = DirectionalLight('lFill') lFill.setColor(VBase4(0.4,0.4,0.4,1)) lFillNode = render.attachNewNode(lFill) lFillNode.setH(27) lFillNode.setP(-15) lFillNode.setR(-30) render.setLight(lFillNode) lBack = DirectionalLight('lBack') lBack.setColor(VBase4(0.3,0.3,0.3,1)) lBackNode = render.attachNewNode(lBack) lBackNode.setH(177) lBackNode.setP(-20) lBackNode.setR(0) render.setLight(lBackNode) lBelow = DirectionalLight('lBelow') lBelow.setColor(VBase4(0.4,0.4,0.4,1)) lBelowNode = render.attachNewNode(lBelow) lBelowNode.setH(0) lBelowNode.setP(90) lBelowNode.setR(0) render.setLight(lBelowNode) self.accept('a', self.on_toggle_anti_alias) self.mouse_controlled = True self.on_toggle_mouse_control() self.accept('m', self.on_toggle_mouse_control) self.accept('q', self.on_quit) # onto-board selection collision test select_mask = BitMask32(0x100) self.select_ray = CollisionRay() select_node = CollisionNode('mouseToSurfaceRay') select_node.setFromCollideMask(select_mask) select_node.addSolid(self.select_ray) select_np = self.camera.attachNewNode(select_node) self.select_queue = CollisionHandlerQueue() self.select_traverser = CollisionTraverser() self.select_traverser.addCollider(select_np, self.select_queue) # create a plane that only collides with the mouse ray select_plane = CollisionPlane(Plane(Vec3(0,0,1), Point3(0,0,0))) # add plane to render self.select_node = CollisionNode('boardCollisionPlane') self.select_node.setCollideMask(select_mask) self.select_node.addSolid(select_plane) self.select_plane_np = self.render.attachNewNode(self.select_node) self.debug_select = draw_debugging_arrow(self, Vec3(0,0,0), Vec3(0,1,0)) self.taskMgr.add(self.update_mouse_target, "mouseTarget") self.taskMgr.add(self.update_debug_arrow, "updateDebugArrow")
class CogdoFlyingLevel(DirectObject): notify = directNotify.newCategory('CogdoFlyingLevel') def __init__(self, parent, frameModel, startPlatformModel, endPlatformModel, quadLengthUnits, quadVisibilityAhead, quadVisibiltyBehind): self.parent = parent self.quadLengthUnits = quadLengthUnits self._halfQuadLengthUnits = quadLengthUnits / 2.0 self.quadVisibiltyAhead = quadVisibilityAhead self.quadVisibiltyBehind = quadVisibiltyBehind self._frameModel = frameModel self.root = NodePath('CogdoFlyingLevel') self.quadrantRoot = NodePath('QuadrantsRoot') self.quadrantRoot.reparentTo(self.root) self._startPlatformModel = startPlatformModel self._startPlatformModel.reparentTo(self.root) self._startPlatformModel.setZ(Globals.Level.StartPlatformHeight) self._endPlatformModel = endPlatformModel self._endPlatformModel.reparentTo(self.root) self._endPlatformModel.setZ(Globals.Level.EndPlatformHeight) self.wallR = self._frameModel.find('**/wallR') self.wallL = self._frameModel.find('**/wallL') self._exit = CogdoGameExit() self._exit.reparentTo(self._endPlatformModel) loc = self._endPlatformModel.find('**/exit_loc') offset = loc.getPos(render) self._exit.setPos(render, offset) self.quadrants = [] self.visibleQuadIndices = [] self._numQuads = 0 self._currentQuadNum = -1 self._camera = None self._initCollisions() self.upLimit = self._frameModel.find('**/limit_up').getZ(render) self.downLimit = self._frameModel.find('**/limit_down').getZ(render) self.leftLimit = self._frameModel.find('**/limit_left').getX( render) - 30.0 self.rightLimit = self._frameModel.find('**/limit_right').getX( render) + 30.0 self.backLimit = -self.quadLengthUnits self.forwardLimit = self.quadLengthUnits * 20 self._frameModel.flattenStrong() self.gatherableFactory = CogdoFlyingGatherableFactory() self.obstacleFactory = CogdoFlyingObstacleFactory() return def getExit(self): return self._exit def getBounds(self): return ((self.leftLimit, self.rightLimit), (self.backLimit, self.forwardLimit), (self.downLimit, self.upLimit)) def getGatherable(self, serialNum): for quadrant in self.quadrants: for gatherable in quadrant.gatherables: if gatherable.serialNum == serialNum: return gatherable return def ready(self): self.gatherableFactory.destroy() del self.gatherableFactory self.obstacleFactory.destroy() del self.obstacleFactory self._initStartEndPlatforms() self._frameModel.reparentTo(self.root) self.root.reparentTo(self.parent) self.root.stash() def _initStartEndPlatforms(self): self.startPlatform = CogdoFlyingPlatform( self._startPlatformModel, Globals.Level.PlatformTypes.StartPlatform) self.endPlatform = CogdoFlyingPlatform( self._endPlatformModel, Globals.Level.PlatformTypes.EndPlatform) self._endPlatformModel.setY(self.convertQuadNumToY(self._numQuads)) self.backLimit = self._startPlatformModel.getY( render) - Globals.Level.StartPlatformLength * 0.7 self.forwardLimit = self._endPlatformModel.getY( render) + Globals.Level.EndPlatformLength * 0.7 def _initCollisions(self): self.collPlane = CollisionPlane( Plane(Vec3(0, 0, 1.0), Point3(0, 0, 10))) self.collPlane.setTangible(0) self.collNode = CollisionNode('fogPlane') self.collNode.setIntoCollideMask(OTPGlobals.FloorBitmask) self.collNode.addSolid(self.collPlane) self.collNodePath = self.root.attachNewNode(self.collNode) self.collNodePath.hide() def destroy(self): del self.collPlane self.collNodePath.removeNode() del self.collNodePath del self.collNode for quadrant in self.quadrants: quadrant.destroy() self._exit.destroy() del self._exit self.root.removeNode() del self.root def onstage(self): self.root.unstash() self.update(0.0) def offstage(self): self.root.stash() def start(self, startTime=0.0): self._startTime = startTime def stop(self): pass def getLength(self): return self.quadLengthUnits * self.getNumQuadrants() def appendQuadrant(self, model): quadrant = CogdoFlyingLevelQuadrant(self._numQuads, model, self, self.root) if self._numQuads == 0: quadrant.generateGatherables(self._startPlatformModel) quadrant.offstage() self.quadrants.append(quadrant) self._numQuads = len(self.quadrants) def getNumQuadrants(self): return self._numQuads def setCamera(self, camera): self._camera = camera def getCameraActualQuadrant(self): camY = self._camera.getY(render) y = self.root.getY(render) return self.convertYToQuadNum(camY - y) def update(self, dt=0.0): if self._camera is None: return else: quadNum = clamp(self.getCameraActualQuadrant(), 0, self._numQuads - 1) if quadNum < self._numQuads: self.quadrants[quadNum].update(dt) if quadNum + 1 < self._numQuads: self.quadrants[(quadNum + 1)].update(dt) if quadNum != self._currentQuadNum: self._switchToQuadrant(quadNum) return def _switchToQuadrant(self, quadNum): self.visibleQuadIndices = [] if quadNum >= 0: if quadNum > 0: self.quadrants[max(quadNum - self.quadVisibiltyBehind, 0)].onstage() for i in xrange( quadNum, min(quadNum + self.quadVisibiltyAhead + 1, self._numQuads)): self.quadrants[i].onstage() self.visibleQuadIndices.append(i) if i == 0: self.startPlatform.onstage() elif i == self._numQuads - 1: self.endPlatform.onstage() self._currentQuadNum = quadNum for i in range( 0, max( self._currentQuadNum - self.quadVisibiltyBehind, 0)) + range( min(self._currentQuadNum + self.quadVisibiltyAhead + 1, self._numQuads), self._numQuads): self.quadrants[i].offstage() if i == 0: self.startPlatform.offstage() elif i == self._numQuads - 1: self.endPlatform.offstage() def convertQuadNumToY(self, quadNum): return quadNum * self.quadLengthUnits def convertYToQuadNum(self, y): return int(y / self.quadLengthUnits) def convertCenterYToQuadNum(self, y): return self.convertYToQuadNum(y + self._halfQuadLengthUnits)
class CogdoFlyingLevel(DirectObject): notify = directNotify.newCategory('CogdoFlyingLevel') def __init__(self, parent, frameModel, startPlatformModel, endPlatformModel, quadLengthUnits, quadVisibilityAhead, quadVisibiltyBehind): self.parent_ = parent self.quadLengthUnits = quadLengthUnits self._halfQuadLengthUnits = quadLengthUnits / 2.0 self.quadVisibiltyAhead = quadVisibilityAhead self.quadVisibiltyBehind = quadVisibiltyBehind self._frameModel = frameModel self.root = NodePath('CogdoFlyingLevel') self.quadrantRoot = NodePath('QuadrantsRoot') self.quadrantRoot.reparentTo(self.root) self._startPlatformModel = startPlatformModel self._startPlatformModel.reparentTo(self.root) self._startPlatformModel.setZ(Globals.Level.StartPlatformHeight) self._endPlatformModel = endPlatformModel self._endPlatformModel.reparentTo(self.root) self._endPlatformModel.setZ(Globals.Level.EndPlatformHeight) self.wallR = self._frameModel.find('**/wallR') self.wallL = self._frameModel.find('**/wallL') self._exit = CogdoGameExit() self._exit.reparentTo(self._endPlatformModel) loc = self._endPlatformModel.find('**/exit_loc') offset = loc.getPos(render) self._exit.setPos(render, offset) self.quadrants = [] self.visibleQuadIndices = [] self._numQuads = 0 self._currentQuadNum = -1 self._camera = None self._initCollisions() self.upLimit = self._frameModel.find('**/limit_up').getZ(render) self.downLimit = self._frameModel.find('**/limit_down').getZ(render) self.leftLimit = self._frameModel.find('**/limit_left').getX(render) - 30.0 self.rightLimit = self._frameModel.find('**/limit_right').getX(render) + 30.0 self.backLimit = -self.quadLengthUnits self.forwardLimit = self.quadLengthUnits * 20 self._frameModel.flattenStrong() self.gatherableFactory = CogdoFlyingGatherableFactory() self.obstacleFactory = CogdoFlyingObtacleFactory() return def getExit(self): return self._exit def getBounds(self): return ((self.leftLimit, self.rightLimit), (self.backLimit, self.forwardLimit), (self.downLimit, self.upLimit)) def getGatherable(self, serialNum): for quadrant in self.quadrants: for gatherable in quadrant.gatherables: if gatherable.serialNum == serialNum: return gatherable return None def ready(self): self.gatherableFactory.destroy() del self.gatherableFactory self.obstacleFactory.destroy() del self.obstacleFactory self._initStartEndPlatforms() self._frameModel.reparentTo(self.root) self.root.reparentTo(self.parent_) self.root.stash() def _initStartEndPlatforms(self): self.startPlatform = CogdoFlyingPlatform(self._startPlatformModel, Globals.Level.PlatformTypes.StartPlatform) self.endPlatform = CogdoFlyingPlatform(self._endPlatformModel, Globals.Level.PlatformTypes.EndPlatform) self._endPlatformModel.setY(self.convertQuadNumToY(self._numQuads)) self.backLimit = self._startPlatformModel.getY(render) - Globals.Level.StartPlatformLength * 0.7 self.forwardLimit = self._endPlatformModel.getY(render) + Globals.Level.EndPlatformLength * 0.7 def _initCollisions(self): self.collPlane = CollisionPlane(Plane(Vec3(0, 0, 1.0), Point3(0, 0, 10))) self.collPlane.setTangible(0) self.collNode = CollisionNode('fogPlane') self.collNode.setIntoCollideMask(OTPGlobals.FloorBitmask) self.collNode.addSolid(self.collPlane) self.collNodePath = self.root.attachNewNode(self.collNode) self.collNodePath.hide() def destroy(self): del self.collPlane self.collNodePath.removeNode() del self.collNodePath del self.collNode for quadrant in self.quadrants: quadrant.destroy() self._exit.destroy() del self._exit self.root.removeNode() del self.root def onstage(self): self.root.unstash() self.update(0.0) def offstage(self): self.root.stash() def start(self, startTime = 0.0): self._startTime = startTime def stop(self): pass def getLength(self): return self.quadLengthUnits * self.getNumQuadrants() def appendQuadrant(self, model): quadrant = CogdoFlyingLevelQuadrant(self._numQuads, model, self, self.root) if self._numQuads == 0: quadrant.generateGatherables(self._startPlatformModel) quadrant.offstage() self.quadrants.append(quadrant) self._numQuads = len(self.quadrants) def getNumQuadrants(self): return self._numQuads def setCamera(self, camera): self._camera = camera def getCameraActualQuadrant(self): camY = self._camera.getY(render) y = self.root.getY(render) return self.convertYToQuadNum(camY - y) def update(self, dt = 0.0): if self._camera is None: return quadNum = clamp(self.getCameraActualQuadrant(), 0, self._numQuads - 1) if quadNum < self._numQuads: self.quadrants[quadNum].update(dt) if quadNum + 1 < self._numQuads: self.quadrants[quadNum + 1].update(dt) if quadNum != self._currentQuadNum: self._switchToQuadrant(quadNum) return def _switchToQuadrant(self, quadNum): self.visibleQuadIndices = [] if quadNum >= 0: if quadNum > 0: self.quadrants[max(quadNum - self.quadVisibiltyBehind, 0)].onstage() for i in xrange(quadNum, min(quadNum + self.quadVisibiltyAhead + 1, self._numQuads)): self.quadrants[i].onstage() self.visibleQuadIndices.append(i) if i == 0: self.startPlatform.onstage() elif i == self._numQuads - 1: self.endPlatform.onstage() self._currentQuadNum = quadNum for i in xrange(0, max(self._currentQuadNum - self.quadVisibiltyBehind, 0)) + range(min(self._currentQuadNum + self.quadVisibiltyAhead + 1, self._numQuads), self._numQuads): self.quadrants[i].offstage() if i == 0: self.startPlatform.offstage() elif i == self._numQuads - 1: self.endPlatform.offstage() def convertQuadNumToY(self, quadNum): return quadNum * self.quadLengthUnits def convertYToQuadNum(self, y): return int(y / self.quadLengthUnits) def convertCenterYToQuadNum(self, y): return self.convertYToQuadNum(y + self._halfQuadLengthUnits)
def __init__(self): # Level model self.level = loader.loadModel("Level") self.key = loader.loadModel("Key") self.artifact = loader.loadModel("Artifact") """Logic connections INFO Switch.000 opens door Wooden_Door_Basic Switch.001-4 in correct order open Boulder_Door Key opens Boulder_Door.001 Switch.005 opens Boulder_Door.002 Defeating Golem opens Wooden_Door_Basic.001 """ random.seed() self.switchLogic = { "Switch.000":"Wooden_Door_Basic", "Switch.001":"ORDER1", "Switch.002":"ORDER1", "Switch.003":"ORDER1", "Switch.004":"ORDER1", "ORDER1":"Boulder_Door", "Switch.005":"Boulder_Door.002"} self.switchOrderLogic = {} # possible switch activation orders self.switchOrders = [ [_("First the highest, the second highest comes third and the lowest before the last."),[4,1,3,2]], [_("The second lowest is the first then lower, highest and finally the remaining."),[2,1,4,3]], [_("Before the last comes the second lowest, the first is the second highest followed by the lowest."),[3,1,2,4]] ] self.enemyLogic = {"Golem":"Wooden_Door_Basic.001"} self.KeyDoorLogic = ["Boulder_Door.001"] self.chestLogic = { "Box_long_looseLid.000":"GET_Key", "Box_long_looseLid.001":"GET_Artifact"} self.activeSwitch = None self.activePostsign = None self.activeBox = None self.activeDoor = None self.numKeys = 0 # Set up all the little details if base.particleMgrEnabled: self.initTorchParticles() self.initSwitches() self.initSwitchSigns() self.initPostsigns() self.initDoors() self.initKeyDoors() self.initChests() self.initHearts() plane = self.level.find("**/Deathplane") deathplane = CollisionPlane(Plane((0, 0, 1), (0,0,-1))) deathplane.setTangible(False) self.deathplaneColNP = render.attachNewNode(CollisionNode('deathplane')) self.deathplaneColNP.node().addSolid(deathplane) self.accept("playerCollision-in-deathplane", lambda args: base.messenger.send("player-die"))
def __init__(self): super().__init__() # disables the default mouse camera controls # self.disableMouse() self.cam.setPos(0, -150, 35) self.cTrav = CollisionTraverser() # pusher used to keep player in frame self.pusher = CollisionHandlerPusher() # self.pusher.setHorizontal(True) # used to detect collisions and deal with them self.collisionEventHandler = CollisionHandlerEvent() # example of how to load multiple models into a list # self.teapots = [] # for i in range(10): # self.teapots.append(self.loader.loadModel("models/teapot")) # self.teapots[i].setColor(0.6, 0.6, 1.0, 1.0) # self.teapots[i].setPos(5 * i, 0, 0) # self.teapots[i].reparentTo(self.render) self.player = self.loader.loadModel("my-models/X-WING") self.player.setColor(0.6, 0.6, 1.0, 1.0) self.player.setHpr(90, 180, 90) self.player.reparentTo(self.render) self.playerColliderNode = CollisionNode("player") self.playerColliderNode.addSolid(CollisionSphere(2, -0.6, 0, 3)) self.playerCollider = self.player.attachNewNode( self.playerColliderNode) base.pusher.addCollider(self.playerCollider, self.player) base.cTrav.addCollider(self.playerCollider, self.pusher) # self.playerCollider.show() leftPlane = CollisionPlane(Plane((1, 0, 0), (0, 0, 0))) self.wallNode = CollisionNode("wall") self.wallNode.addSolid(leftPlane) wall = self.render.attachNewNode(self.wallNode) wall.setX(-72) wall.show() rightPlane = CollisionPlane(Plane((1, 0, 0), (0, 0, 0))) rightPlane.flip() self.wallNode = CollisionNode("wall") self.wallNode.addSolid(rightPlane) wall = self.render.attachNewNode(self.wallNode) wall.setX(72) wall.show() lowerPlane = CollisionPlane(Plane((0, 0, 1), (0, 0, 0))) self.wallNode = CollisionNode("wall") self.wallNode.addSolid(lowerPlane) wall = self.render.attachNewNode(self.wallNode) wall.setZ(-6) wall.show() upperPlane = CollisionPlane(Plane((0, 0, 1), (0, 0, 0))) upperPlane.flip() self.wallNode = CollisionNode("wall") self.wallNode.addSolid(upperPlane) wall = self.render.attachNewNode(self.wallNode) wall.setZ(80) wall.show() self.accept("w", updateKeyMap, ["up", True]) self.accept("w-up", updateKeyMap, ["up", False]) self.accept("s", updateKeyMap, ["down", True]) self.accept("s-up", updateKeyMap, ["down", False]) self.accept("a", updateKeyMap, ["left", True]) self.accept("a-up", updateKeyMap, ["left", False]) self.accept("d", updateKeyMap, ["right", True]) self.accept("d-up", updateKeyMap, ["right", False]) self.accept("space", updateKeyMap, ["weapon", True]) self.accept("space-up", updateKeyMap, ["weapon", False]) self.speed = 30 self.angle = 90 self.taskMgr.add(self.keyBindupdate, "keyBindupdate")
def __init__(self, img_size=512, screen_off=True, target_area_radius=5, initial_area_radius=10, keyboard_input=False, random_reset_around_target=False, test=False): logging.info('random_reset_around_target :%s', random_reset_around_target) self.random_reset_around_target = random_reset_around_target self.keyboard_input = keyboard_input # Configure the parallax mapping settings (these are just the defaults) self.img_size = img_size self.initial_area_radius = initial_area_radius self.target_area_radius = target_area_radius loadPrcFileData("", "side-by-side-stereo 1") if test: loadPrcFileData("", "load-display p3tinydisplay") loadPrcFileData("", "transform-cache false") loadPrcFileData("", "audio-library-name null") # Prevent ALSA errors loadPrcFileData("", "win-size %d %d" % (2 * img_size, img_size)) loadPrcFileData("", "parallax-mapping-samples 3\n" "parallax-mapping-scale 0.1") if screen_off: # Spawn an offscreen buffer loadPrcFileData("", "window-type offscreen") # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} # Load the 'abstract room' model. This is a model of an # empty room containing a pillar, a pyramid, and a bunch # of exaggeratedly bumpy textures. self.room = loader.loadModel("models/abstractroom") self.room.reparentTo(render) # Create the main character, Ralph ghost = BulletGhostNode('Ghost') ghostNP = render.attachNewNode(ghost) # self.agent = Actor("models/agent", # {"run": "models/agent-run", # "walk": "models/agent-walk"}) self.agent = ghostNP self.agent.reparentTo(render) # self.agent.setScale(.2) target = BulletGhostNode('target') self.navigation_target = render.attachNewNode(target) self.navigation_target.reparentTo(render) # knghit=Knight((0,0,0),(0.3,.3,.3,1)) self.pieces = [Piece(self.room) for _ in range(200)] ################################################## cnodePath = self.room.attachNewNode(CollisionNode('room')) plane = CollisionPlane(Plane(Vec3(1, 0, 0), Point3(-60, 0, 0))) # left cnodePath.node().addSolid(plane) plane = CollisionPlane( Plane(Vec3(-1, 0, 0), Point3(60, 0, 0))) # right cnodePath.node().addSolid(plane) plane = CollisionPlane(Plane(Vec3(0, 1, 0), Point3(0, -60, 0))) # back cnodePath.node().addSolid(plane) plane = CollisionPlane( Plane(Vec3(0, -1, 0), Point3(0, 60, 0))) # front cnodePath.node().addSolid(plane) sphere = CollisionSphere(-25, -25, 0, 12.5) # tube = CollisionTube(-25, -25,0 , -25, -25, 1, 12.5) cnodePath.node().addSolid(sphere) box = CollisionBox(Point3(5, 5, 0), Point3(45, 45, 10)) cnodePath.node().addSolid(box) # cnodePath.show() # Make the mouse invisible, turn off normal mouse controls self.disableMouse() # props = WindowProperties() # props.setCursorHidden(True) # self.win.requestProperties(props) # self.camLens.setFov(60) self.camLens.setFov(80) # Set the current viewing target self.focus = LVector3(55, -55, 20) self.heading = 180 self.pitch = 0 self.mousex = 0 self.mousey = 0 self.last = 0 self.mousebtn = [0, 0, 0] # Start the camera control task: # taskMgr.add(self.controlCamera, "camera-task") # self.accept("escape", sys.exit, [0]) # self.accept("enter", self.toggleShader) # self.accept("j", self.rotateLight, [-1]) # self.accept("k", self.rotateLight, [1]) # self.accept("arrow_left", self.rotateCam, [-1]) # self.accept("arrow_right", self.rotateCam, [1]) # 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]) # Add a light to the scene. self.lightpivot = render.attachNewNode("lightpivot") self.lightpivot.setPos(0, 0, 25) self.lightpivot.hprInterval(10, LPoint3(360, 0, 0)).loop() plight = PointLight('plight') plight.setColor((5, 5, 5, 1)) plight.setAttenuation(LVector3(0.7, 0.05, 0)) plnp = self.lightpivot.attachNewNode(plight) plnp.setPos(45, 0, 0) self.room.setLight(plnp) # Add an ambient light alight = AmbientLight('alight') alight.setColor((0.2, 0.2, 0.2, 1)) alnp = render.attachNewNode(alight) self.room.setLight(alnp) # Create a sphere to denote the light sphere = loader.loadModel("models/icosphere") sphere.reparentTo(plnp) # self.cameraModel = self.agent # self.win2 = self.openWindow() # self.win2.removeAllDisplayRegions() # self.dr2 = self.win2.makeDisplayRegion() # camNode = Camera('cam') # camNP = NodePath(camNode) # camNP.reparentTo(self.cameraModel) # camNP.setZ(150) # camNP.lookAt(self.cameraModel) # self.dr2.setCamera(camNP) # self.cam2 = camNP # Camera('cam')p # 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 agent'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() cs = CollisionSphere(0, 0, 0, 0.2) cnodePath = self.agent.attachNewNode(CollisionNode('agent')) cnodePath.node().addSolid(cs) # cnodePath.show() self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(cnodePath, self.ralphGroundHandler) cnodePath = self.navigation_target.attachNewNode( CollisionNode('target')) cnodePath.node().addSolid(CollisionSphere(0, 0, 0, 2)) self.cTrav.addCollider(cnodePath, self.ralphGroundHandler) # Tell Panda that it should generate shaders performing per-pixel # lighting for the room. self.room.setShaderAuto() self.shaderenable = 1 # tex = self.win.getScreenshot() # tex.setFormat(Texture.FDepthComponent) tex = Texture() self.depthmap = tex tex.setFormat(Texture.FDepthComponent) altBuffer = self.win.makeTextureBuffer( "hello", img_size, img_size, tex, True) self.altBuffer = altBuffer altCam = self.makeCamera(altBuffer) altCam.reparentTo(self.agent) # altRender) altCam.setZ(0.4) l = altCam.node().getLens() l.setFov(80) l.setNear(.1) camera.reparentTo(self.agent) camera.setZ(0.4) l = self.camLens # l.setFov(80) l.setNear(.1)
def __init__(self): self.base = ShowBase() self.thrust = 0.5 self.wind = 0.2 self.UP = Vec3(0, 0, 1) # might as well just make this a variable # set up camera self.base.disableMouse() self.base.camera.setPos(20, -20, 5) self.base.camera.lookAt(0, 0, 5) # Set up the collision traverser. If we bind it to base.cTrav, then Panda will handle # management of this traverser (for example, by calling traverse() automatically for us once per frame) self.base.cTrav = CollisionTraverser() # Now let's set up some collision bits for our masks self.ground_bit = 1 self.ball_bit = 2 self.base.setBackgroundColor(0.64, 0, 0) # First, we build a card to represent the ground cm = CardMaker('ground-card') cm.setFrame(-60, 60, -60, 60) card = self.base.render.attachNewNode(cm.generate()) card.lookAt(0, 0, -1) # align upright #tex = loader.loadTexture('maps/envir-ground.jpg') tex = loader.loadTexture('models/textures/rock12.bmp') card.setTexture(tex) # Then we build a collisionNode which has a plane solid which will be the ground's collision # representation groundColNode = card.attachNewNode(CollisionNode('ground-cnode')) groundColPlane = CollisionPlane(Plane(Vec3(0, -1, 0), Point3(0, 0, 0))) groundColNode.node().addSolid(groundColPlane) # Now, set the ground to the ground mask groundColNode.setCollideMask(BitMask32().bit(self.ground_bit)) # Why aren't we adding a collider? There is no need to tell the collision traverser about this # collisionNode, as it will automatically be an Into object during traversal. # enable forces self.base.enableParticles() node = NodePath("PhysicsNode") node.reparentTo(self.base.render) # may want to have force dependent on mass eventually, # but at the moment assume all balls same weight self.force_mag = 200 # gravity gravity_fn = ForceNode('world-forces') gravity_fnp = self.base.render.attachNewNode(gravity_fn) gravity_force = LinearVectorForce(0.0, 0.0, -9.81) gravity_fn.addForce(gravity_force) self.base.physicsMgr.addLinearForce(gravity_force) # wind wind_fn = ForceNode('world-forces') wind_fnp = self.base.render.attachNewNode(wind_fn) wind_force = LinearVectorForce(1.0, 0.5, 0.0) wind_fn.addForce(wind_force) self.base.physicsMgr.addLinearForce(wind_force) # spurt out of fountain, bounce self.spurt = ForceNode("spurt") spurt_np = self.base.render.attachNewNode(self.spurt) # create a list for our ball actors, not sure if I need this, but seems likely self.ball_actors = [] # make a teapot teapot = loader.loadModel('teapot.egg') tex = loader.loadTexture('maps/color-grid.rgb') #teapot.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) teapot.setTexture(tex) teapot.reparentTo(self.base.render) teapot.setPos(-5, 10, 10) # create the first ball: #ball = self.create_a_ball() #self.enliven_ball(ball) smiley = loader.loadModel('smiley.egg') lerper = NodePath('lerper') smiley.setTexProjector(TextureStage.getDefault(), NodePath(), lerper) smiley.reparentTo(self.base.render) smiley.setPos(5, 10, 10) i = lerper.posInterval(5, VBase3(0, 1, 0)) i.loop() # Tell the messenger system we're listening for smiley-into-ground messages and invoke our callback self.base.accept('ball_cnode-into-ground-cnode', self.ground_callback) ball_fountain = taskMgr.doMethodLater(.5, self.spurt_balls, 'tickTask')