def addRalph(self, pos): ralphStartPos = pos 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) self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0,0,1000) self.ralphGroundRay.setDirection(0,0,-1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.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,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
def loadFood(self, foodIndex): self.foodNum += 1 if foodIndex in self.foodModelDict: foodModel = self.foodModelDict[foodIndex] foodModel.reparentTo(self.foodNodes[foodIndex]) colNp = foodModel.find('**/FoodCol*') colNp.setTag('foodNum', str(self.foodNum)) else: foodModelScale = ToontownGlobals.BossbotFoodModelScale foodModel = loader.loadModel('phase_12/models/bossbotHQ/canoffood') foodModel.setScale(foodModelScale) foodModel.reparentTo(self.foodNodes[foodIndex]) target = CollisionTube(4, 0, 0, -4, 0, 0, 2) target.setTangible(0) colName = 'FoodCol-%d-%d' % (self.index, foodIndex) targetNode = CollisionNode(colName) targetNode.addSolid(target) targetNode.setCollideMask(ToontownGlobals.WallBitmask) targetNodePath = foodModel.attachNewNode(targetNode) targetNodePath.setScale(1.0 / foodModelScale) targetNodePath.setTag('foodIndex', str(foodIndex)) targetNodePath.setTag('beltIndex', str(self.index)) targetNodePath.setTag('foodNum', str(self.foodNum)) targetNodePath.setZ(targetNodePath.getZ() - 1.5) self.accept('enter' + colName, self.touchedFood) self.foodModelDict[foodIndex] = foodModel
def __init__(self,gmap,gaming_zone): DirectObject.__init__(self) #gaming zone (used for mouse movement), as a tools.Rectangle self.gaming_zone=gaming_zone #actual camera node self.p3dcam=base.camera #what the cam is oriented to self._target=base.render.attachNewNode('GaminCam.target') #range=[0,1] between min and max closeness to ground self.level=.7 # #keys_down acts as a pool containing keys (+mouse buttons) currently down self.keys_down=[] update_list.append(self.update) #setup for mouse picking picker_node=CollisionNode('gcam_to_mouse_ray')#general collision node picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask()) self.picker_ray=CollisionRay()#solid ray to attach to coll node picker_node.addSolid(self.picker_ray) self.picker_np=self.p3dcam.attachNewNode(picker_node)#attach this node to gcam self.collision_queue=CollisionHandlerQueue()#stores collisions self.collision_traverser=CollisionTraverser('gcam_traverser')#actual computer self.collision_traverser.addCollider(self.picker_np,self.collision_queue) base.cTrav=self.collision_traverser self.gmap=gmap #stack of states (state=pos+zoom) self.states_stack=[] #enable the cam to move according to keyboard and mouse self.move_enabled=True
def doAttack(self, particlePaths, track_name, particleCollId, animation_name, delayUntilRelease, animationSpeed = 1, handObjPath = None, handObjParent = None, startRightAway = True, ts = 0): for path in particlePaths: particle = ParticleLoader.loadParticleEffect(path) self.particles.append(particle) sphere = CollisionSphere(0, 0, 0, 1) sphere.setTangible(0) node = CollisionNode(particleCollId) node.addSolid(sphere) node.setCollideMask(CIGlobals.WallBitmask) self.targetX = self.attacksClass.target.getX(render) self.targetY = self.attacksClass.target.getY(render) self.targetZ = self.attacksClass.target.getZ(render) if len(self.particles) == 1: self.shootOutCollNP = self.particles[0].attachNewNode(node) else: self.shootOutCollNP = self.suit.attachNewNode(node) if handObjPath and handObjParent: self.handObj = loader.loadModel(handObjPath) self.handObj.reparentTo(handObjParent) self.suit.setPlayRate(animationSpeed, animation_name) self.suit.play(animation_name) if hasattr(self.suit, 'uniqueName'): track_name = self.suit.uniqueName(track_name) particleCollId = self.suit.uniqueName(particleCollId) self.suitTrack = Sequence(name=track_name) self.suitTrack.append(Wait(delayUntilRelease)) self.suitTrack.append(Func(self.releaseAttack)) self.suitTrack.append(Wait(self.particleIvalDur)) self.suitTrack.setDoneEvent(self.suitTrack.getName()) self.acceptOnce(self.suitTrack.getDoneEvent(), self.finishedAttack) if startRightAway: self.suitTrack.start(ts)
class MyPanda: count=0 def __init__(self, tempworld): MyPanda.count += 1 self.id = MyPanda.count self.world = tempworld self.pandaNode=render.attachNewNode('pandaNode') self.actor=Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.actor.reparentTo(self.pandaNode) self.actor.setPos(int(self.id) * 30,0,0) self.actor.setScale(0.002, 0.002, 0.002) self.cNode = CollisionNode('panda') self.cNode.addSolid(CollisionSphere(2, 0, 400, 500)) self.frowneyC = self.actor.attachNewNode(self.cNode) base.cTrav.addCollider(self.frowneyC, self.world.pusher) self.world.pusher.addCollider(self.frowneyC, self.actor, base.drive.node()) def getActor(self): return self.actor def getPandaCount(self): return MyRalph.count def getMyPandaId(self): return self.id
def setupCollisions(self): sphere = CollisionSphere(0, 0, 0, 2) sphere.setTangible(0) node = CollisionNode(self.collisionName) node.addSolid(sphere) node.setCollideMask(CIGlobals.WallBitmask) self.collisionNode = self.attachNewNode(node)
def addWall(render, position, l, w, h=WALL_HEIGHT, opaque=False): cn = CollisionNode('wall') cn.addSolid(CollisionBox((0,0,0),l,w,h)) cube = render.attachNewNode(cn) cube.setTwoSided(True) cube.setPos(position) cube.setScale(1) if opaque: square0 = models.makeSquare(-1*l, -1*w, -1*h, l, -1*w, h) # back plane square1 = models.makeSquare(-1*l, 1*w, -1*h, l, 1*w, h) # square2 = models.makeSquare(-1*l, 1*w, h, l, -1*w, h) square3 = models.makeSquare(-1*l, 1*w, -1*h, l, -1*w, -1*h) square4 = models.makeSquare(-1*l, -1*w, -1*h, -1*l, 1*w, h) square5 = models.makeSquare(1*l, -1*w, -1*h, l, 1*w, h) snode = GeomNode('wall') snode.addGeom(square0) snode.addGeom(square1) snode.addGeom(square2) snode.addGeom(square3) snode.addGeom(square4) snode.addGeom(square5) cubewall = render.attachNewNode(snode) cubewall.setTwoSided(True) cubewall.setPos(position) else: cube.show()
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 __init__(self, _main): self.main = _main self.strenght = self.main.enemyStrength self.id = id(self) self.model = loader.loadModel("Enemy") self.model.setP(-90) self.model.setH(180) self.model.hide() cs = CollisionSphere(0, 0, 0, 0.5) cnode = CollisionNode('colEnemy' + str(self.id)) cnode.addSolid(cs) self.colNP = self.model.attachNewNode(cnode) #self.colNP.show() # Game state self.health = 100 + (100 * self.strenght) self.damageDone = 0.1 + (0.1 * self.strenght) self.lastShot = 0.0 self.attackRate = 10.0 self.statusHealth = DirectWaitBar( text = "", value = self.health, range = self.health, frameSize = (0.12, 0.8, -0.12, 0.0), pos = (-0.5, 0, -0.5), barColor = (1, 0, 0, 1)) self.statusHealth.reparentTo(self.model) self.statusHealth.setDepthWrite(False) self.statusHealth.setBin('fixed', 0) self.statusHealth.setBillboardAxis()
def initCollisions(self): # Initialize the collision traverser. self.cTrav = CollisionTraverser() self.cTrav.showCollisions(self.render) # self.cQueue = CollisionHandlerQueue() # Initialize the Pusher collision handler. # self.pusher = CollisionHandlerPusher() self.pusher = CollisionHandlerFloor() ### player print DirectNotifyGlobal.directNotify.getCategories() # Create a collsion node for this object. playerNode = CollisionNode("player") playerNode.addSolid(CollisionSphere(0, 0, 0, 1)) # playerNode.setFromCollideMask(BitMask32.bit(0)) # playerNode.setIntoCollideMask(BitMask32.allOn()) # Attach the collision node to the object's model. self.playerC = self.fpscamera.player.attachNewNode(playerNode) # Set the object's collision node to render as visible. self.playerC.show()
class MyCar: count=0 def __init__(self, tempworld): self.world = tempworld MyCar.count += 1 self.carNode = render.attachNewNode('dummy_car') self.car = loader.loadModel("models/knucklehead") self.car_tex = loader.loadTexture("models/knucklehead.jpg") self.car.setTexture(self.car_tex, 1) self.car.reparentTo(self.carNode) self.car.setPos(20,20,0) self.car.setScale(.08) self.car.setP(-90) self.car.setColor(0.6, 0.6, 1.0, 1.0) self.car.setColorScale(0.6, 0.6, 1.0, 1.0) self.carCNode = CollisionNode('car') self.carCNode.addSolid(CollisionSphere(0, 0, 3, 3)) self.carC = self.car.attachNewNode(self.carCNode) base.cTrav.addCollider(self.carC, self.world.pusher) self.world.pusher.addCollider(self.carC, self.car, base.drive.node()) #self.actor = self.car def getMyCar(self): return self.car
class MyRalph: count = 0 def __init__(self, tempworld): self.world = tempworld MyRalph.count += 1 self.id = MyRalph.count self.actor = Actor("models/ralph/ralph", {"run":"models/ralph/ralph-run", "walk":"models/ralph/ralph-walk"}) self.actor.reparentTo(render) self.actor.setScale(.2) self.actor.setPos(int(self.id)*20, 0, 0) # Create a collsion node for this object. self.cNode = CollisionNode('ralph') # Attach a collision sphere solid to the collision node. self.cNode.addSolid(CollisionSphere(0, 0, 3, 3)) # Attach the collision node to the object's model. self.smileyC = self.actor.attachNewNode(self.cNode) base.cTrav.addCollider(self.smileyC, self.world.pusher) self.world.pusher.addCollider(self.smileyC, self.actor, base.drive.node()) def getActor(self): return self.actor def getRalphCount(self): return MyRalph.count def getMyRalphId(self): return self.id
class ShipCollision: def __init__(self, ship): self.ship = ship self.setup_collision() self.queue = CollisionHandlerQueue() self.traverser = CollisionTraverser('Collision Traverser') self.traverser.showCollisions(render) self.traverser.add_collider(self.target_nodepath, self.queue) base.taskMgr.add(self.collide, "Collision Task") def setup_collision(self): self.target = CollisionSphere(0, 0, 0, 0.5) self.target_node = CollisionNode('collision_ship') self.target_node.setFromCollideMask(ENEMIES) self.target_node.setIntoCollideMask(ALLIES) self.target_nodepath = self.ship.model.attach_new_node(self.target_node) self.target_nodepath.node().addSolid(self.target) #self.target_nodepath.show() def collide(self, task): self.traverser.traverse(render) for entry in self.queue.get_entries(): #print("Ship:") #print(entry) self.ship.model.cleanup() self.ship.model.removeNode() return task.cont
def loadAttack(self): self.phone = loader.loadModel('phase_3.5/models/props/phone.bam') self.phone.setHpr(0, 0, 180) if self.suit.type == 'B': self.phone.setPos(0.7, 0.15, 0) elif self.suit.type == 'C': self.phone.setPos(0.25, 0, 0) self.receiver = loader.loadModel('phase_3.5/models/props/receiver.bam') self.receiver.reparentTo(self.phone) self.cord = Rope() self.cord.ropeNode.setUseVertexColor(1) self.cord.ropeNode.setUseVertexThickness(1) self.cord.setup(3, ({'node': self.phone, 'point': (0.8, 0, 0.2), 'color': (0, 0, 0, 1), 'thickness': 1000}, {'node': self.phone, 'point': (2, 0, 0), 'color': (0, 0, 0, 1), 'thickness': 1000}, {'node': self.receiver, 'point': (1.1, 0.25, 0.5), 'color': (0, 0, 0, 1), 'thickness': 1000}), []) self.cord.setH(180) self.phoneSfx = base.audio3d.loadSfx('phase_3.5/audio/sfx/SA_hangup.mp3') base.audio3d.attachSoundToObject(self.phoneSfx, self.phone) self.hangupSfx = base.audio3d.loadSfx('phase_3.5/audio/sfx/SA_hangup_place_down.mp3') base.audio3d.attachSoundToObject(self.hangupSfx, self.phone) collSphere = CollisionSphere(0, 0, 0, 2) collSphere.setTangible(0) collNode = CollisionNode('phone_shootout') collNode.addSolid(collSphere) collNode.setCollideMask(CIGlobals.WallBitmask) self.collNP = self.phone.attachNewNode(collNode)
def loadToonup(self, toonupIndex): self.toonupNum += 1 if toonupIndex in self.toonupModelDict: toonupModel = self.toonupModelDict[toonupIndex] toonupModel.reparentTo(self.foodNodes[toonupIndex]) colNp = toonupModel.find('**/ToonupCol*') colNp.setTag('toonupNum', str(self.toonupNum)) else: toonupModelScale = self.ToonupScales[toonupIndex] modelName = self.ToonupModels[toonupIndex] toonupModel = loader.loadModel(modelName) self.foodNodes[toonupIndex].setZ(self.beltHeight - 0.1) toonupModel.setZ(self.ToonupZOffsets[toonupIndex]) toonupModel.setScale(toonupModelScale) toonupModel.reparentTo(self.foodNodes[toonupIndex]) target = CollisionTube(4, 0, 0, -4, 0, 0, 2) target.setTangible(0) colName = 'ToonupCol-%d-%d' % (self.index, toonupIndex) targetNode = CollisionNode(colName) targetNode.addSolid(target) targetNode.setCollideMask(ToontownGlobals.WallBitmask) targetNodePath = toonupModel.attachNewNode(targetNode) targetNodePath.setScale(1.0 / toonupModelScale) targetNodePath.setTag('toonupIndex', str(toonupIndex)) targetNodePath.setTag('beltIndex', str(self.index)) targetNodePath.setTag('toonupNum', str(self.toonupNum)) targetNodePath.setZ(targetNodePath.getZ() - 1.5 / toonupModelScale) self.accept('enter' + colName, self.touchedToonup) self.toonupModelDict[toonupIndex] = toonupModel
def load(self): spawn = random.choice(DGG.SpawnPoints) base.localAvatar.setPos(spawn) base.localAvatar.setHpr(0, 0, 0) self.soundPickUpBarrel = base.loadSfx("phase_6/audio/sfx/SZ_MM_gliss.mp3") self.soundDropOff = base.loadSfx("phase_4/audio/sfx/MG_sfx_travel_game_bell_for_trolley.mp3") self.setMinigameMusic("phase_4/audio/bgm/MG_Delivery.mp3") self.setDescription( "A new supply of Gags were just shipped to Toontown! " + "Run over to a truck with Gag barrels to take a barrel out. Then, carry it over to the Gag Shop. " + "Try to unload and deliver as many barrels as you can to the Gag Shop. " + "Watch out for the Cogs - they might try to snatch a barrel!" ) self.setWinnerPrize(100) self.setLoserPrize(0) self.gagShop = loader.loadModel("phase_4/models/modules/gagShop_TT.bam") self.gagShop.reparentTo(base.render) self.gagShop.setY(-70) sphere = CollisionSphere(0, 0, 0, 3) sphere.setTangible(0) node = CollisionNode("MGDeliveryGagShop") node.addSolid(sphere) self.gagShopCollNP = self.gagShop.attachNewNode(node) self.world = loader.loadModel("phase_4/models/minigames/delivery_area.egg") self.world.setY(-5) self.world.reparentTo(base.render) self.sky = loader.loadModel("phase_3.5/models/props/TT_sky.bam") self.sky.reparentTo(base.camera) ce = CompassEffect.make(NodePath(), CompassEffect.PRot | CompassEffect.PZ) self.sky.node().setEffect(ce) self.sky.setZ(-20) self.skyUtil.startSky(self.sky) base.camera.setPos(20, 50, 30) base.camera.lookAt(20, 0, 7.5) DistributedMinigame.load(self)
class EntityCollision: def __init__(self, entity): self.entity = entity self.setup_collision() self.queue = CollisionHandlerQueue() self.traverser = CollisionTraverser('Collision Traverser') self.traverser.showCollisions(render) self.traverser.add_collider(self.target_nodepath, self.queue) base.taskMgr.add(self.collide, "Collision Task") def setup_collision(self): self.target = CollisionSphere(0, 0, 0, 1) self.target_node = CollisionNode('collision_entity') self.target_node.setFromCollideMask(ALLIES) # unused self.target_node.setIntoCollideMask(ENEMIES) self.target_nodepath = self.entity.model.attach_new_node(self.target_node) self.target_nodepath.node().addSolid(self.target) self.target_nodepath.show() def collide(self, task): self.traverser.traverse(render) for entry in self.queue.get_entries(): # print("Entity:") pos = entry.getSurfacePoint(self.entity.model) pos_x = pos[0] pos_z = pos[2] self.entity.spawn_particles(pos_x, pos_z) self.entity.life -= 1 return task.cont
def announceGenerate(self): DistributedNode.announceGenerate(self) self.kart = loader.loadModel('phase_6/models/karting/Kart3_Final.bam') self.kart.find('**/decals').removeNode() self.kart.reparentTo(self) self.pod = loader.loadModel('phase_4/models/minigames/pods_truck.egg') self.pod.reparentTo(self) self.pod.setScale(0.2) self.pod.setY(8.5) self.pod.setH(180) self.rope = Rope() self.rope.ropeNode.setUseVertexColor(1) self.rope.setup(3, ({'node': self.kart, 'point': (0, 1.5, 0.7), 'color': (0, 0, 0, 1), 'thickness': 1000}, {'node': self.kart, 'point': (0, 1.5, 0.7), 'color': (0, 0, 0, 1), 'thickness': 1000}, {'node': self.pod, 'point': (0, 31, 5), 'color': (0, 0, 0, 1), 'thickness': 1000}), []) self.rope.setH(180) self.rope.reparentTo(self) sphere = CollisionSphere(0, 0, 0, 2) sphere.setTangible(0) node = CollisionNode(self.uniqueName('truck_trigger')) node.addSolid(sphere) node.setCollideMask(CIGlobals.WallBitmask) self.triggerNP = self.attachNewNode(node) self.triggerNP.setPos(0, 8.0, 2.0) self.setScale(2.0) self.accept('enter' + self.triggerNP.node().getName(), self.__handleTruckTrigger)
def addCube(render, position, scale=1, rotate=1): # square0 = models.makeSquare(-1, -1, -1, 1, -1, 1) # square1 = models.makeSquare(-1, 1, -1, 1, 1, 1) # square2 = models.makeSquare(-1, 1, 1, 1, -1, 1) # square3 = models.makeSquare(-1, 1, -1, 1, -1, -1) # square4 = models.makeSquare(-1, -1, -1, -1, 1, 1) # square5 = models.makeSquare(1, -1, -1, 1, 1, 1) # snode = GeomNode('square') # snode.addGeom(square0) # snode.addGeom(square1) # snode.addGeom(square2) # snode.addGeom(square3) # snode.addGeom(square4) # snode.addGeom(square5) #cube = render.attachNewNode(snode) cn = CollisionNode('test') cn.addSolid(CollisionSphere(0, 0, 0, scale)) cube = render.attachNewNode(cn) cube.show() cube.setScale(scale) #if rorate: # cube.hprInterval(1.5, (360, 360, 360)).loop() # OpenGl by default only draws "front faces" (polygons whose vertices are # specified CCW). cube.setTwoSided(True) cube.setPos(position)
def __setupCollisions(self): sphere = CollisionSphere(0, 0, 0, 4) sphere.setTangible(0) collisionNode = CollisionNode(self.uniqueName('NPCToonSphere')) collisionNode.addSolid(sphere) collisionNode.setCollideMask(CIGlobals.WallBitmask) self.collisionNodePath = self.attachNewNode(collisionNode) self.collisionNodePath.setY(1.5)
def setUpCamera(self): """ puts camera behind the player in third person """ # Set up the camera # Adding the camera to actor is a simple way to keep the camera locked # in behind actor regardless of actor's movement. base.camera.reparentTo(self.actor) # We don't actually want to point the camera at actors's feet. # This value will serve as a vertical offset so we can look over the actor self.cameraTargetHeight = 0.5 # How far should the camera be from the actor self.cameraDistance = 10 # Initialize the pitch of the camera self.cameraPitch = 45 # The mouse moves rotates the camera so lets get rid of the cursor props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) #set up FOV pl = base.cam.node().getLens() pl.setFov(70) base.cam.node().setLens(pl) # A CollisionRay beginning above the camera and going down toward the # ground is used to detect camera collisions and the height of the # camera above the ground. A ray may hit the terrain, or it may hit a # rock or a tree. If it hits the terrain, we detect the camera's # height. If it hits anything else, the camera is in an illegal # position. """ TODO:: This will need to be changed to bullet """ self.cTrav = CollisionTraverser() self.groundRay = CollisionRay() self.groundRay.setOrigin(0,0,1000) self.groundRay.setDirection(0,0,-1) self.groundCol = CollisionNode('camRay') self.groundCol.addSolid(self.groundRay) self.groundCol.setFromCollideMask(BitMask32.bit(1)) self.groundCol.setIntoCollideMask(BitMask32.allOff()) self.groundColNp = base.camera.attachNewNode(self.groundCol) self.groundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.groundColNp, self.groundHandler) # We will detect anything obstructing the camera's view of the player self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5)) self.cameraCol = CollisionNode('cameraRay') self.cameraCol.addSolid(self.cameraRay) self.cameraCol.setFromCollideMask(BitMask32.bit(0)) self.cameraCol.setIntoCollideMask(BitMask32.allOff()) self.cameraColNp = self.actor.attachNewNode(self.cameraCol) self.cameraColHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
def getSprayTrack(self, origin, target, scaleUp, hold, scaleDown, horizScale = 1.0, vertScale = 1.0): base.localAvatar.stop(self.toonAnim) self.lastFrame = self.avatar.getCurrentFrame(self.toonAnim) track = Sequence() sprayProp = loader.loadModel(GagGlobals.SPRAY_MDL) sprayProp.setTwoSided(1) sprayScale = hidden.attachNewNode('spray-parent') sprayRot = hidden.attachNewNode('spray-rotate') sprayRot.setColor(GagGlobals.WATER_SPRAY_COLOR) sprayRot.setTransparency(1) collNode = CollisionNode('Collision') spraySphere = CollisionSphere(0, 0, 0, 1) spraySphere.setTangible(0) collNode.addSolid(spraySphere) collNode.setCollideMask(CIGlobals.WallBitmask) sprayNP = sprayRot.attachNewNode(collNode) sprayNP.setY(1) self.sprayNP = sprayNP event = CollisionHandlerEvent() event.set_in_pattern('%fn-into') event.set_out_pattern('%fn-out') base.cTrav.add_collider(sprayNP, event) self.avatar.acceptOnce(sprayNP.node().getName() + '-into', self.onCollision) def showSpray(sprayScale, sprayProp, origin, target): objects = [sprayRot, sprayScale, sprayProp] for item in objects: index = objects.index(item) if index == 0: item.reparentTo(self.sprayJoint) item.setPos(self.sprayJoint.getPos(render)) item.setHpr(self.sprayJoint.getHpr(render)) item.setP(0) else: item.reparentTo(objects[index - 1]) item.clearMat() track.append(Func(showSpray, sprayScale, sprayProp, origin, target)) self.spray = sprayRot def calcTargetScale(): distance = Vec3(target - origin).length() yScale = distance / GagGlobals.SPRAY_LEN targetScale = Point3(yScale * horizScale, yScale, yScale * vertScale) return targetScale track.append(Parallel(LerpScaleInterval(sprayScale, scaleUp, calcTargetScale, startScale=GagGlobals.PNT3NEAR0), sprayNP.posInterval(0.25, self.spray.getPos(render) + Point3(0, 50, 0), startPos=self.spray.getPos(render) + Point3(0, 5, 0)))) track.append(Wait(hold)) track.append(Func(self.handleMiss)) track.append(LerpScaleInterval(sprayScale, 0.75, GagGlobals.PNT3NEAR0)) def hideSpray(): (lambda prop: prop.removeNode(), [sprayProp, sprayRot, sprayScale]) track.append(Func(hideSpray)) track.append(Func(self.completeSquirt)) return track
def __init__(self, _main): self.main = _main self.type = "gun" self.id = id(self) self.model = loader.loadModel("ItemMG") cs = CollisionSphere(0, 0, 0, 0.5) cnode = CollisionNode('itemWeapon' + str(self.id)) cnode.addSolid(cs) self.colNP = self.model.attachNewNode(cnode)
def initCollisionSphere(self,node,name): bounds = node.getBounds() center = bounds.getCenter() radius = bounds.getRadius()*0.6 cNode = CollisionNode(name) cNode.addSolid(CollisionSphere(center,radius)) cNP=node.attachNewNode(cNode) cNP.show() return cNP
def __initializeEventSphere(self): sphere = CollisionSphere(0, 0, 0, 2) sphere.setTangible(0) node = CollisionNode(self.uniqueName('DEagleSuit-eventSphere')) node.addSolid(sphere) node.setCollideMask(CIGlobals.WallBitmask) np = self.attachNewNode(node) np.setSz(2.5) np.setZ(5.5) self.eventSphereNodePath = np
def create_sphere(self, model_name, bitmask): model = loader.loadModel("models/" + model_name) model.reparent_to(base.render) target = CollisionSphere(0, 0, 0, 1) target_node = CollisionNode('collision_target') target_node.setIntoCollideMask(bitmask) target_nodepath = model.attach_new_node(target_node) target_nodepath.node().addSolid(target) target_nodepath.show() return model
def makeCollisionNodePath(self, nodepath, solid): ''' Creates a collision node and attaches the collision solid to the supplied NodePath. Returns the nodepath of the collision node. ''' # Creates a collision node named after the name of the NodePath. collNode = CollisionNode("%s c_node" % nodepath.getName()) collNode.addSolid(solid) collisionNodepath = nodepath.attachNewNode(collNode) return collisionNodepath
def __init__(self, _main, _value=25): self.main = _main self.id = id(self) self.type = "heal" self.healValue = _value self.model = loader.loadModel("ItemHeal") cs = CollisionSphere(0, 0, 0, 0.5) cnode = CollisionNode('itemHeal' + str(self.id)) cnode.addSolid(cs) self.colNP = self.model.attachNewNode(cnode)
def __initCollisions(self, name): self.notify.debug("Initializing collision sphere...") ss = CollisionSphere(0, 0, 0, 5) ss.setTangible(0) snode = CollisionNode(name) snode.add_solid(ss) snode.set_collide_mask(CIGlobals.WallBitmask) self.snp = self.attach_new_node(snode) self.snp.setZ(3) self.acceptOnce("enter" + self.snp.node().getName(), self.__handleEnterCollisionSphere)
def r_constructCollisionTree(self, solidTree, parentNode, colName): for item in solidTree: if type(item[0]) == type([]): newNode = parentNode.attachNewNode('%s-branch' % colName) self.r_constructCollisionTree(item, newNode, colName) else: cn = CollisionNode('%s-leaf' % colName) for solid in item: cn.addSolid(solid) parentNode.attachNewNode(cn)
def CreateGfx( self, loader, idx ): # idx is neccesary to be able to track it down for mouse picking self.idx = idx self.__node = loader.loadModel(os.path.join(os.getcwd(), "models/cube")) self.__node.setPos(0, 0, 0) self.__node.setScale(0.5, 0.5, 0.5) self.__node.setTag("clickable", str(idx)) # to be able to click on it self.__node.setName("cell") # COLLISION collBox = CollisionBox(self.__node.getPos(), 1.0, 1.0, 1.0) cnodePath = self.__node.attachNewNode(CollisionNode("cnode")) cnodePath.node().addSolid(collBox) self.UpdateState(False, False, False)
def createCatchCollisions(self): radius = 0.7 handler = CollisionHandlerEvent() handler.setInPattern('ltCatch%in') self.ltLegsCollNode = CollisionNode('catchLegsCollNode') self.ltLegsCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask) self.ltHeadCollNode = CollisionNode('catchHeadCollNode') self.ltHeadCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask) self.ltLHandCollNode = CollisionNode('catchLHandCollNode') self.ltLHandCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask) self.ltRHandCollNode = CollisionNode('catchRHandCollNode') self.ltRHandCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask) legsCollNodepath = base.localAvatar.attachNewNode(self.ltLegsCollNode) legsCollNodepath.hide() head = base.localAvatar.getHeadParts().getPath(2) headCollNodepath = head.attachNewNode(self.ltHeadCollNode) headCollNodepath.hide() lHand = base.localAvatar.getLeftHands()[0] lHandCollNodepath = lHand.attachNewNode(self.ltLHandCollNode) lHandCollNodepath.hide() rHand = base.localAvatar.getRightHands()[0] rHandCollNodepath = rHand.attachNewNode(self.ltRHandCollNode) rHandCollNodepath.hide() base.localAvatar.cTrav.addCollider(legsCollNodepath, handler) base.localAvatar.cTrav.addCollider(headCollNodepath, handler) base.localAvatar.cTrav.addCollider(lHandCollNodepath, handler) base.localAvatar.cTrav.addCollider(lHandCollNodepath, handler) if self.ShowToonSpheres: legsCollNodepath.show() headCollNodepath.show() lHandCollNodepath.show() rHandCollNodepath.show() self.ltLegsCollNode.addSolid(CollisionSphere(0, 0, radius, radius)) self.ltHeadCollNode.addSolid(CollisionSphere(0, 0, 0, radius)) self.ltLHandCollNode.addSolid( CollisionSphere(0, 0, 0, 2 * radius / 3.0)) self.ltRHandCollNode.addSolid( CollisionSphere(0, 0, 0, 2 * radius / 3.0)) self.toonCollNodes = [ legsCollNodepath, headCollNodepath, lHandCollNodepath, rHandCollNodepath ]
def __init__(self, entity, mesh=None, center=(0,0,0)): super().__init__() center = Vec3(center) if mesh == None and entity.model: print('auto gen mesh colider from entity mesh') mesh = entity.model self.node_path = entity.attachNewNode(CollisionNode('CollisionNode')) node = self.node_path.node() if mesh.triangles: for tri in mesh.triangles: if len(tri) == 3: shape = CollisionPolygon( swap_y_z(Vec3(mesh.vertices[tri[0]])) + center, swap_y_z(Vec3(mesh.vertices[tri[1]])) + center, swap_y_z(Vec3(mesh.vertices[tri[2]])) + center) node.addSolid(shape) elif len(tri) == 4: shape = CollisionPolygon( swap_y_z(Vec3(mesh.vertices[tri[0]])) + center, swap_y_z(Vec3(mesh.vertices[tri[1]])) + center, swap_y_z(Vec3(mesh.vertices[tri[2]])) + center) node.addSolid(shape) shape = CollisionPolygon( swap_y_z(Vec3(mesh.vertices[tri[2]])) + center, swap_y_z(Vec3(mesh.vertices[tri[3]])) + center, swap_y_z(Vec3(mesh.vertices[tri[0]])) + center) node.addSolid(shape) elif mesh.mode == 'triangle': for i in range(0, len(mesh.vertices), 3): shape = CollisionPolygon( swap_y_z(Vec3(mesh.vertices[i])) + center, swap_y_z(Vec3(mesh.vertices[i+1])) + center, swap_y_z(Vec3(mesh.vertices[i+2])) + center ) node.addSolid(shape) else: print('error: mesh collider does not support', mesh.mode, 'mode') self.visible = False
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 _base_combined_cdnp(name, radius): collision_node = CollisionNode(name) collision_primitive_c0 = CollisionBox(Point3(-0.1, 0.0, 0.14 - 0.82), x=.35 + radius, y=.3 + radius, z=.14 + radius) collision_node.addSolid(collision_primitive_c0) collision_primitive_c1 = CollisionBox(Point3(0.0, 0.0, -.3), x=.112 + radius, y=.112 + radius, z=.3 + radius) collision_node.addSolid(collision_primitive_c1) return collision_node
def _base_combined_cdnp(name, radius): collision_node = CollisionNode(name) collision_primitive_c0 = CollisionBox(Point3(.0, 0.0, 0.225), x=.14 + radius, y=.14 + radius, z=.225 + radius) collision_node.addSolid(collision_primitive_c0) collision_primitive_c1 = CollisionBox(Point3(0.031, 0.0, 0.73), x=.0855 + radius, y=.0855 + radius, z=.27 + radius) collision_node.addSolid(collision_primitive_c1) return collision_node
def __endFireWater(self): if self.aimStart == None: return if not self.state == 'Controlled': return if not self.avId == localAvatar.doId: return taskMgr.remove(self.waterPowerTaskName) messenger.send('wakeup') self.aimStart = None origin = self.nozzle.getPos(render) target = self.boss.getPos(render) angle = deg2Rad(self.waterPitcherNode.getH() + 90) x = math.cos(angle) y = math.sin(angle) fireVector = Point3(x, y, 0) if self.power < 0.001: self.power = 0.001 self.lastPowerFired = self.power fireVector *= self.fireLength * self.power target = origin + fireVector segment = CollisionSegment(origin[0], origin[1], origin[2], target[0], target[1], target[2]) fromObject = render.attachNewNode(CollisionNode('pitcherColNode')) fromObject.node().addSolid(segment) fromObject.node().setFromCollideMask(ToontownGlobals.PieBitmask | ToontownGlobals.CameraBitmask | ToontownGlobals.FloorBitmask) fromObject.node().setIntoCollideMask(BitMask32.allOff()) queue = CollisionHandlerQueue() base.cTrav.addCollider(fromObject, queue) base.cTrav.traverse(render) queue.sortEntries() self.hitObject = None if queue.getNumEntries(): entry = queue.getEntry(0) target = entry.getSurfacePoint(render) self.hitObject = entry.getIntoNodePath() base.cTrav.removeCollider(fromObject) fromObject.removeNode() self.d_firingWater(origin, target) self.fireWater(origin, target) self.resetPowerBar() return
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 OnSpawn(self, parent): # Spawn in world (default) # Load a model for now its just one. self.seed = loader.loadModel("./assets/seed/seed") self.seedNP = self.seed.reparentTo(parent) self.seed.setZ(1) # Collision body cs = CollisionSphere(0, 0, 0, 0.4) cs.setTangible(False) self.cnodePath = self.seed.attachNewNode( CollisionNode("seedSphere-" + self.id)) self.cnodePath.node().addSolid(cs) self.cnodePath.node().setIntoCollideMask(BitMask32(0x80)) # 1000 0000 #self.cnodePath.show() self.seedState = 0
def show_target(self): self.target_select() self.intoObject = self.tar.attachNewNode(CollisionNode('colintoNode')) if self.table[self.trial_counter,7] == "sphere": self.intoObject.node().addSolid(CollisionSphere(0,0,0,1)) elif self.table[self.trial_counter,7] == "cylinder": self.intoObject.node().addSolid(CollisionTube(0,0,-1.4,0,0,1.4,1)) else: raise NameError("No such collision type") self.tar.show() self.tar2.show() for i in range(5): if i not in self.highlighted_indices: self.players[i].hide() self.touch_dur = 0
def createSquareCollider(self, px, pz, w, h, modelName, collisionNodeName, nodeName, enableFunction, disableFunction, texture, mask): obj = self.scene.attachNewNode(nodeName) hitbox = CollisionBox(Point3(0, 0, 0), w, 5, h) cNodePath = obj.attachNewNode(CollisionNode(collisionNodeName)) cNodePath.node().addSolid(hitbox) cNodePath.node().setIntoCollideMask(mask) cNodePath.node().setFromCollideMask(mask) #cNodePath.show() base.cTrav.addCollider(cNodePath, self.collisionHandlerEvent) self.scene.find(f'root/{modelName}').reparentTo(obj) obj.setPos(px, 0, pz) obj.setTexture(texture) self.accept(f'into-{collisionNodeName}', enableFunction) self.accept(f'outof-{collisionNodeName}', disableFunction) return obj
def announceGenerate(self): DistributedToonFPSGame.announceGenerate(self) base.camLens.setMinFov(CIGlobals.GunGameFOV / (4. / 3.)) base.camLens.setFar(250) base.localAvatar.setPythonTag('localAvatar', 1) self.avatarBody = base.localAvatar.attachNewNode( CollisionNode('sphereforguardeyes')) self.avatarBody.node().addSolid(CollisionSphere(0, 0, 0, 1.2)) self.avatarBody.node().setFromCollideMask(BitMask32.allOff()) self.avatarBody.node().setIntoCollideMask(CGG.GuardBitmask) self.gameWorld = FactorySneakWorld(self) self.gameWorld.loadWorld() self.gameWorld.loadJellybeanBarrels() self.gameWorld.makeGuards() self.gameWorld.showWorld() self.gameWorld.setupPlayer() self.load()
def __init__(self, n=1, bins=1): #index = md() #def get_index(): #return index #indexMan.register('index',get_index) #self.iman = indexMan(('127.0.0.1',5000),authkey='none') #self.iman.start() index = {} #index_counter = Counter(0,1) collideRoot = render.attachNewNode('collideRoot') bases = [ np.cumsum(np.random.randint(-1, 2, (n, 3)), axis=0) for i in range(bins) ] type_ = GeomPoints runs = [] for base in bases: runs.append(convertToGeom(index_counter, base, type_)) for nodes in runs: for node, idx in nodes(): #FIXME stupid nd = render.attachNewNode(node) index.update(idx) #FIXME this is nasty print(idx) for uid, list_ in index.items(): #TODO to change the color of a selected node we will need something a bit more ... sophisticated #parent = list_[1][0] if list_ == None: continue cNode = collideRoot.attachNewNode( CollisionNode('collider %s' % uid)) #ultimately used to index?? cNode.node().addSolid(CollisionSphere(0, 0, 0, .5)) cNode.node().setIntoCollideMask(BitMask32.bit(BITMASK_COLL_CLICK)) cNode.setPos(*list_[0]) cNode.setPythonTag('uid', uid) cNode.show() list_[ 2] = cNode #FIXME this is inconsistent and the 'uid' means different things in different contexts! print(index_counter.value)
def add_shape(self, entity, movement, solid, shape): model_proxy = self.proxies['character_node'] model = entity[model_proxy.component_type] model_node = model_proxy.field(entity) node = NodePath( CollisionNode( f'{movement.tag_name}-{solid["tag"]}', ), ) solid['node'] = node node.node().add_solid(shape) node.node().set_from_collide_mask(movement.from_collide_mask) node.node().set_into_collide_mask(movement.into_collide_mask) node.reparent_to(model_node) movement.traverser.add_collider(node, movement.queue) node.set_python_tag(movement.tag_name, movement) if 'debug' in solid and solid['debug']: node.show()
def PopulateSpawns(self, cursor, numrows): spawn_coords = list() globals.model_list = list() for x in range(0, numrows): row = cursor.fetchone() point = Point3(long(row["Spawn2Y"]), long(row["Spawn2X"]), long(row["Spawn2Z"])) if point not in spawn_coords: s = loader.loadModel("models/cube.egg") s.reparentTo(render) s.setPos(row["Spawn2Y"], row["Spawn2X"], row["Spawn2Z"]) min,macks= s.getTightBounds() radius = max([macks.getY() - min.getY(), macks.getX() - min.getX()])/2 cs = CollisionSphere(row["Spawn2X"], row["Spawn2Y"], row["Spawn2Z"], radius) csNode = s.attachNewNode(CollisionNode("modelCollide")) csNode.node().addSolid(cs) s.setTag("name", row["name"]) picker.makePickable(s) globals.model_list.append(s) spawn_coords.append(point)
def _initCollisions(self): self._camCollRay = CollisionRay() camCollNode = CollisionNode('CameraToonRay') camCollNode.addSolid(self._camCollRay) camCollNode.setFromCollideMask(OTPGlobals.WallBitmask | OTPGlobals.CameraBitmask | ToontownGlobals.FloorEventBitmask | ToontownGlobals.CeilingBitmask) camCollNode.setIntoCollideMask(0) self._camCollNP = self._camera.attachNewNode(camCollNode) self._camCollNP.show() self._collOffset = Vec3(0, 0, 0.5) self._collHandler = CollisionHandlerQueue() self._collTrav = CollisionTraverser() self._collTrav.addCollider(self._camCollNP, self._collHandler) self._betweenCamAndToon = {} self._transNP = NodePath('trans') self._transNP.reparentTo(render) self._transNP.setTransparency(True) self._transNP.setAlphaScale(Globals.Camera.AlphaBetweenToon) self._transNP.setBin('fixed', 10000)
class MouseCollision: 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 update(self, task): if self.game.mouseWatcherNode.hasMouse(): if self.game.ship.model: mouse_pos = self.game.mouseWatcherNode.getMouse() self.mouse_ground_ray.setFromLens(self.game.camNode, mouse_pos.getX(), mouse_pos.getY()) near_point = render.getRelativePoint( self.game.camera, self.mouse_ground_ray.getOrigin()) near_vec = render.getRelativeVector( self.game.camera, self.mouse_ground_ray.getDirection()) self.game.ship.shipPoint.setPos( self.PointAtY(self.game.ship.model.getY(), near_point, near_vec)) return task.cont def PointAtY(self, y, point, vec): return point + vec * ((y - point.getY()) / vec.getY())
def start(self): self.fullyChargedSound = base.loadSfx( 'phase_4/audio/sfx/MG_pairing_match.ogg') self.rechargeSound = base.loadSfx( 'phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.ogg') self.batteryFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.2, 0, 0.1), scale=(0.8, 0, 1)) self.batteryBg = OnscreenImage( image='phase_4/maps/battery_charge_frame.png', parent=self.batteryFrame) self.batteryBg.setTransparency(1) self.batteryBg.setX(0.03) self.batteryBg.setScale(0.17, 0, 0.05) self.batteryBar = DirectWaitBar(value=0, range=5, barColor=(1, 1, 1, 1), relief=None, scale=(0.12, 0.0, 0.3), parent=self.batteryFrame) self.cameraFocus = loader.loadModel( "phase_4/models/minigames/photo_game_viewfinder.bam") self.cameraFocus.reparentTo(base.aspect2d) self.focusTrav = CollisionTraverser('CSFP.focusTrav') ray = CollisionRay() rayNode = CollisionNode('CSFP.rayNode') rayNode.addSolid(ray) rayNode.setCollideMask(BitMask32(0)) rayNode.setFromCollideMask(CIGlobals.WallBitmask) self.focusRay = ray self.focusRayNode = base.camera.attachNewNode(rayNode) self.focusHandler = CollisionHandlerQueue() self.focusTrav.addCollider(self.focusRayNode, self.focusHandler) base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, 0.0, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed) FirstPerson.start(self)
def __init__(self, cr): DistributedObject.__init__(self, cr) self.name = "Player" self.piece = None self.pickerQueue = CollisionHandlerQueue() self.pickerRay = CollisionRay() pickerNode = CollisionNode('mouseRay') pickerNode.setFromCollideMask(BitMask32(0x80)) pickerNode.addSolid(self.pickerRay) self.pickerNP = base.camera.attachNewNode(pickerNode) base.cTrav.addCollider(self.pickerNP, self.pickerQueue) self.accept("mouse1", self.checkClick)
def __init__(self, charId, charNr, controls): FSM.__init__(self, "FSM-Player{}".format(charNr)) self.charId = charId charPath = "characters/character{}/".format(charNr) self.character = Actor( charPath + "char", { "Idle": charPath + "idle", "Walk": charPath + "walk", "Walk_back": charPath + "walk_back", "Punch_l": charPath + "punch_l", "Punch_r": charPath + "punch_r", "Kick_l": charPath + "kick_l", "Kick_r": charPath + "kick_r", "Hit": charPath + "hit", "Defend": charPath + "defend", "Defeated": charPath + "defeated" }) self.character.reparentTo(render) self.character.hide() self.walkSpeed = 2.0 if controls == "p1": self.character.setH(90) self.leftButton = KeyboardButton.asciiKey("d") self.rightButton = KeyboardButton.asciiKey("f") self.punchLButton = KeyboardButton.asciiKey("q") self.punchRButton = KeyboardButton.asciiKey("w") self.kickLButton = KeyboardButton.asciiKey("a") self.kickRButton = KeyboardButton.asciiKey("s") self.defendButton = KeyboardButton.asciiKey("e") elif controls == "p2": self.character.setH(-90) self.leftButton = KeyboardButton.right() self.rightButton = KeyboardButton.left() self.punchLButton = KeyboardButton.asciiKey("i") self.punchRButton = KeyboardButton.asciiKey("o") self.kickLButton = KeyboardButton.asciiKey("k") self.kickRButton = KeyboardButton.asciiKey("l") self.defendButton = KeyboardButton.asciiKey("p") characterSphere = CollisionSphere(0, 0, 1.0, 0.5) self.collisionNodeName = "character{}Collision".format(charId) characterColNode = CollisionNode(self.collisionNodeName) characterColNode.addSolid(characterSphere) self.characterCollision = self.character.attachNewNode( characterColNode) base.pusher.addCollider(self.characterCollision, self.character) base.cTrav.addCollider(self.characterCollision, base.pusher) characterHitRay = CollisionSegment(0, -0.5, 1.0, 0, -0.8, 1.0) characterColNode.addSolid(characterHitRay) self.getPos = self.character.getPos self.getX = self.character.getX
def __init__(self, pos, modelName, maxHealth, maxSpeed, colliderName, size): Enemy.__init__(self, pos, modelName, maxHealth, maxSpeed, colliderName, size) self.acceleration = 100.0 self.turnRate = 200.0 self.yVector = Vec2(0, 1) self.steeringRayNPs = [] self.steeringQueue = CollisionHandlerQueue() self.state = FighterEnemy.STATE_ATTACK self.breakAwayTimer = 0 self.breakAwayMaxDuration = 5 self.evasionDuration = 2 self.evasionDurationVariability = 0.2 self.evasionTimer = 0 self.evasionDirection = (0, 0) for i in range(4): ray = CollisionSegment(0, 0, 0, 0, 1, 0) rayNode = CollisionNode("steering ray") rayNode.addSolid(ray) rayNode.setFromCollideMask(MASK_WALLS) rayNode.setIntoCollideMask(0) rayNodePath = self.actor.attachNewNode(rayNode) #rayNodePath.show() self.steeringRayNPs.append(rayNodePath) Common.framework.traverser.addCollider(rayNodePath, self.steeringQueue)
def __initCollisions(self, name): self.notify.debug('Initializing collision sphere...') numSlots = len(self.circles) ss = CollisionSphere(0, 0, 0, self.numPlayers2SphereRadius[numSlots]) ss.setTangible(0) snode = CollisionNode(name) snode.add_solid(ss) snode.set_collide_mask(CIGlobals.WallBitmask) self.snp = self.attach_new_node(snode) self.snp.setZ(3) self.snp.setY(self.numPlayers2SphereY[numSlots]) self.snp.setSx(self.numPlayers2SphereSx[numSlots]) self.snp.setSy(self.numPlayers2SphereSy[numSlots]) self.acceptOnce('enter' + self.snp.node().getName(), self.__handleEnterCollisionSphere)
def setupBoxCollider(self, node, px, py, pz, w, d, h, nm, colliderEventHandler, fromCollisionMask=0, intoCollisionMask=0): hitBox = CollisionBox(Point3(px, py, pz), w, d, h) cnodePath = node.attachNewNode(CollisionNode(nm)) cnodePath.node().addSolid(hitBox) cnodePath.node().setIntoCollideMask(intoCollisionMask) cnodePath.node().setFromCollideMask(fromCollisionMask) cnodePath.show() base.cTrav.addCollider(cnodePath, colliderEventHandler)
def make_collision(solid_from, solid_into): node_from = CollisionNode("from") node_from.add_solid(solid_from) node_into = CollisionNode("into") node_into.add_solid(solid_into) root = NodePath("root") trav = CollisionTraverser() queue = CollisionHandlerQueue() np_from = root.attach_new_node(node_from) np_into = root.attach_new_node(node_into) trav.add_collider(np_from, queue) trav.traverse(root) entry = None for e in queue.get_entries(): if e.get_into() == solid_into: entry = e return (entry, np_from, np_into)
def PlaceSpawnPointOn3dMap(self, row): spawn = Spawn() self.InitSpawnData(spawn, row) spawn.model = loader.loadModel(spawn.modelname) spawn.initmodel() spawn.model.reparentTo(render) spawn.initheadingfromdb(row["Spawn2Heading"]) spawn.placeintoworld(row["Spawn2Y"], row["Spawn2X"], row["Spawn2Z"]) min, macks = spawn.model.getTightBounds() radius = max([macks.getY() - min.getY(), macks.getX() - min.getX()]) / 2 cs = CollisionSphere(row["Spawn2X"], row["Spawn2Y"], row["Spawn2Z"], radius) csNode = spawn.model.attachNewNode(CollisionNode("modelCollide")) csNode.node().addSolid(cs) # TODO: ADD MORE TAGS?? spawn.model.setTag("name", row["NpcName"]) spawn.model.setTag("spawngroup_name", row["spawngroup_name"]) spawn.model.setTag("spawn2id", str(row["Spawn2Id"])) spawn.model.setTag("type", "spawn") globals.picker.makePickable(spawn.model) globals.spawn_list.append(spawn)
class CogdoMazeExit(CogdoGameExit, DirectObject): EnterEventName = 'CogdoMazeDoor_Enter' def __init__(self): CogdoGameExit.__init__(self) self.revealed = False self._players = [] self._initCollisions() def _initCollisions(self): collSphere = CollisionSphere(0, 0, 0, 3.0) collSphere.setTangible(0) self.collNode = CollisionNode(self.getName()) self.collNode.addSolid(collSphere) self.collNP = self.attachNewNode(self.collNode) def destroy(self): self.ignoreAll() CogdoGameExit.destroy(self) def enable(self): self.collNode.setFromCollideMask(ToontownGlobals.WallBitmask) self.accept('enter' + self.getName(), self._handleEnterCollision) def disable(self): self.ignore('enter' + self.getName()) self.collNode.setFromCollideMask(BitMask32(0)) def _handleEnterCollision(self, collEntry): messenger.send(CogdoMazeExit.EnterEventName, [self]) def onstage(self): self.unstash() self.enable() def offstage(self): self.stash() self.disable() def playerEntersDoor(self, player): if player not in self._players: self._players.append(player) self.toonEnters(player.toon) def getPlayerCount(self): return len(self._players) def hasPlayer(self, player): return player in self._players
def placeHealthItems(self): self.placeholder = render.attachNewNode("HealthItem-Placeholder") self.placeholder.setPos(0, 0, 0) # Add the health items to the placeholder node for i in range(5): # Load in the health item model self.healthy = loader.loadModel("models/sphere") self.healthy.setPos(0, 0, 0) self.healthy.reparentTo(self.placeholder) self.placeItem(self.healthy) # Add spherical collision detection healthSphere = CollisionSphere(0, 0, 0, 1) sphereNode = CollisionNode('healthSphere') sphereNode.addSolid(healthSphere) sphereNode.setFromCollideMask(BitMask32.allOff()) sphereNode.setIntoCollideMask(BitMask32.bit(0)) sphereNp = self.healthy.attachNewNode(sphereNode) sphereColHandler = CollisionHandlerQueue() base.cTrav.addCollider(sphereNp, sphereColHandler)
def initKeyDoors(self): i = 0 for keyDoor in self.KeyDoorLogic: for door, value in self.doorControls.iteritems(): if keyDoor == door.getParent().getName(): c = Point3(0,0,0) p1 = Point3(c.getX()-1, c.getY()-0.8, c.getZ()) p2 = Point3(c.getX()+1, c.getY()+0.8, c.getZ()+2) keyDoorBox = CollisionBox(p1, p2) keyDoorBox.setTangible(False) keyDoorColNP = door.getParent().attachNewNode(CollisionNode('keyDoorActivation%d'%i)) keyDoorColNP.node().addSolid(keyDoorBox) keyDoorName = door.getParent().getName() self.accept("playerCollision-in-keyDoorActivation%d"%i, self.__setActivateElement, extraArgs=[True, keyDoorName, "door"]) self.accept("playerCollision-out-keyDoorActivation%d"%i, self.__setActivateElement, extraArgs=[False, keyDoorName, "door"]) i+=1
def initPostsigns(self): objects = self.level.findAllMatches('**/Signpost.*') self.postsigns = {} i = 0 for object in objects: postsphere = CollisionSphere(0, 0, 0.5, 1) postsphere.setTangible(False) postColNP = object.attachNewNode(CollisionNode('postsignInfo%d'%i)) postColNP.node().addSolid(postsphere) self.postsigns.setdefault(object, postColNP) postName = object.getName() self.accept("playerCollision-in-postsignInfo%d"%i, self.__setActivateElement, extraArgs=[True, postName, "postsign"]) self.accept("playerCollision-out-postsignInfo%d"%i, self.__setActivateElement, extraArgs=[False, postName, "postsign"]) i+=1
def placeCollectibles(self): self.placeCol = render.attachNewNode("Collectible-Placeholder") self.placeCol.setPos(0, 0, 0) # Add the health items to the placeCol node for i in range(self.numObjects): # Load in the health item model self.collect = loader.loadModel("models/jack") self.collect.setPos(0, 0, 0) self.collect.reparentTo(self.placeCol) self.placeItem(self.collect) # Add spherical collision detection colSphere = CollisionSphere(0, 0, 0, 1) sphereNode = CollisionNode('colSphere') sphereNode.addSolid(colSphere) sphereNode.setFromCollideMask(BitMask32.allOff()) sphereNode.setIntoCollideMask(BitMask32.bit(0)) sphereNp = self.collect.attachNewNode(sphereNode) sphereColHandler = CollisionHandlerQueue() base.cTrav.addCollider(sphereNp, sphereColHandler)