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 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 __init__(self, nick): self.player = player.Player(nick=nick) self.controller = controller.ClientController(self.player) self.handgui = hand.HandGUI(self.player.hand) camera.setPos(0, -20, 0) self.accept("turn_time_changed", self.update_turn_time) self.turn_timer = TurnTimer() # Mouse detection: base.cTrav = CollisionTraverser() self.mouse_ray_handler = CollisionHandlerQueue() mouse_ray_node = CollisionNode('mouse_ray') mouse_ray_np = camera.attachNewNode(mouse_ray_node) mouse_ray_node.setFromCollideMask(GeomNode.getDefaultCollideMask()) mouse_ray_node.setIntoCollideMask(0) self.mouse_ray = CollisionRay() mouse_ray_node.addSolid(self.mouse_ray) base.cTrav.addCollider(mouse_ray_np, self.mouse_ray_handler) self.mouse_overed_entry = None self.accept("mouse_enter", self.enlarge_entry) self.accept("mouse_leave", self.shrink_entry) self.accept("p-up", self.change_card_picture) taskMgr.doMethodLater(0.1, self.check_mouse_over, "check_mouse_over")
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 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 startSeeking(self): if not self.avatar: return self.cleanupShadow() self.buildShadow() scale = self.dropShadow.getScale() if scale < 1.0: self.maxDistance += 40 x, y, z = self.avatar.getPos(render) self.dropShadow.reparentTo(render) self.dropShadow.setPos(x, y + 5, z + 2) self.cameraNode = CollisionNode('coll_camera') self.cameraNode.setFromCollideMask(CIGlobals.WallBitmask) self.cameraRay = CollisionRay() self.cameraNode.addSolid(self.cameraRay) self.cameraNP = camera.attachNewNode(self.cameraNode) base.cTrav.addCollider(self.cameraNP, CollisionHandlerQueue()) if not self.legacyMode: shadowNode = CollisionNode('coll_shadow') self.shadowRay = CollisionRay(0, 0, 6, 0, 0, -1) shadowNode.addSolid(self.shadowRay) shadowNode.setFromCollideMask(CIGlobals.FloorBitmask) self.shadowNP = self.dropShadow.attachNewNode(shadowNode) base.cTrav.addCollider(self.shadowNP, self.collHdlFl) base.taskMgr.add(self.__moveShadow, self.moveShadowTaskName) self.avatar.acceptOnce('mouse1', self.locationChosen)
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 __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 __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 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 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 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 loadVirtualSuit(self): dna = SuitDNA.SuitDNA() dna.newSuit(self.getSuitName()) self.virtualSuit = Suit.Suit() self.virtualSuit.reparentTo(self) self.virtualSuit.setDNA(dna) self.virtualSuit.setPos(self, 0.0, 2.5, 0.0) self.virtualSuit.makeSkeleton(wantNameInfo=False) self.virtualSuit.makeVirtual() self.virtualSuit.hideName() anims = self.generateSuitAnimDict() self.virtualSuit.loadAnims(anims) self.virtualSuit.loop('walk', 0) synergyBox = CollisionBox(0, 3.5, 10, 1) synergyBox.setTangible(0) synergyNode = CollisionNode(self.uniqueName('SynergyAttack')) synergyNode.setTag('damage', '10') synergyNode.addSolid(synergyBox) synergyNode.setIntoCollideMask(WallBitmask) self.synergyColl = self.virtualSuit.attachNewNode(synergyNode) self.synergyColl.setPos(0.0, 9.0, 0.0) self.synergyColl.stash() self.synergySfx = loader.loadSfx('phase_5/audio/sfx/SA_synergy.ogg') self.teeOffSfx = loader.loadSfx('phase_5/audio/sfx/SA_tee_off.ogg') self.writeOffSfx = loader.loadSfx('phase_5/audio/sfx/SA_writeoff_pen_only.ogg') self.dingSfx = loader.loadSfx('phase_5/audio/sfx/SA_writeoff_ding_only.ogg')
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 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 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
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)
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 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
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/trex") self.collect.setPos(0,0,0) self.collect.reparentTo(self.placeCol) self.collect.setScale(0.1) self.tex3= loader.loadTexture("models/Face.jpg") self.collect.setTexture(self.tex3,1) 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()
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.foodchick = loader.loadModel("models/chicken2") self.foodchick.setPos(0,0,0) self.foodchick.reparentTo(self.placeholder) #self.tex2=self.setTexture("models/orange.jpg") #self.foodchick.setTexture(self.tex2,1) #self.tex2= loader.loadTexture("models/orange.jpg") #self.foodchick.setTexture(self.tex1,1) self.placeItem(self.foodchick) # 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.foodchick.attachNewNode(sphereNode) sphereColHandler = CollisionHandlerQueue()
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 initCollisionRay(self, originZ, dirZ): ray = CollisionRay(0,0,originZ,0,0,dirZ) collNode = CollisionNode('playerRay') collNode.addSolid(ray) collNode.setFromCollideMask(BitMask32.bit(1)) collNode.setIntoCollideMask(BitMask32.allOff()) collRayNP = self.playerNode.attachNewNode(collNode) collRayNP.show() return collRayNP
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 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 attachCollisionRay(self, name, ox, oy, oz, dx, dy, dz, fromCollide, intoCollide): from panda3d.core import CollisionRay from panda3d.core import CollisionNode coll = CollisionRay(ox, oy, oz, dx, dy, dz) collNode = CollisionNode(name) collNode.addSolid(coll) collNode.setFromCollideMask(fromCollide) collNode.setIntoCollideMask(intoCollide) collNodePath = self.attachNewNode(collNode) return collNodePath
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 attachCollisionSegment(self, name, ax, ay, az, bx, by, bz, fromCollide, intoCollide): from panda3d.core import CollisionSegment from panda3d.core import CollisionNode coll = CollisionSegment(ax, ay, az, bx, by, bz) collNode = CollisionNode(name) collNode.addSolid(coll) collNode.setFromCollideMask(fromCollide) collNode.setIntoCollideMask(intoCollide) collNodePath = self.attachNewNode(collNode) return collNodePath
def colRay(parent, origin=(0,0,0.1), direction=(0,0,-1)): ray = CollisionRay() ray.setOrigin(origin) ray.setDirection(direction) col = CollisionNode(parent.getName()+"-ray") col.addSolid(ray) col.setIntoCollideMask(CollideMask.allOff()) colNode = parent.attachNewNode(col) handler = CollisionHandlerQueue() base.cTrav.addCollider(colNode, handler) #colNode.show() return handler
def buildCollisions(self): gagSph = CollisionSphere(0, 1.5, 0, 2) gagSensor = CollisionNode('gagSensor') gagSensor.addSolid(gagSph) sensorNP = self.gag.attachNewNode(gagSensor) sensorNP.setCollideMask(BitMask32(0)) sensorNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask) event = CollisionHandlerEvent() event.set_in_pattern("%fn-into") event.set_out_pattern("%fn-out") base.cTrav.addCollider(sensorNP, event) self.avatar.acceptOnce('gagSensor-into', self.onCollision)
def buildCollisions(self): pieSphere = CollisionSphere(0, 0, 0, 1) pieSensor = CollisionNode('turretGagSensor' + str(id(self))) pieSensor.addSolid(pieSphere) pieNP = self.gag.attachNewNode(pieSensor) pieNP.setCollideMask(BitMask32(0)) pieNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask) event = CollisionHandlerEvent() event.set_in_pattern('%fn-into') event.set_out_pattern('%fn-out') base.cTrav.addCollider(pieNP, event)
def buildCollisions(self, entity): pieSphere = CollisionSphere(0, 0, 0, 1) pieSensor = CollisionNode('gagSensor') pieSensor.addSolid(pieSphere) pieNP = entity.attachNewNode(pieSensor) pieNP.setCollideMask(BitMask32(0)) pieNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask) event = CollisionHandlerEvent() event.set_in_pattern('%fn-into') event.set_out_pattern('%fn-out') base.cTrav.add_collider(pieNP, event) self.avatar.acceptOnce('gagSensor-into', self.onCollision)
def gen_pointcloud_cdnp(objtrm, name='cdnp_pointcloud', radius=0.02): """ :param obstacle: :return: author: weiwei date: 20191210 """ collision_node = CollisionNode(name) for sglpnt in objtrm.vertices: collision_node.addSolid( CollisionSphere(sglpnt[0], sglpnt[1], sglpnt[2], radius=radius)) return collision_node
def loadLever(self): self.lever = self.root.attachNewNode('%sLever' % self.activityName) self.leverModel = self.party.defaultLeverModel.copyTo(self.lever) self.controlColumn = NodePath('cc') column = self.leverModel.find('**/column') column.getChildren().reparentTo(self.controlColumn) self.controlColumn.reparentTo(column) self.stickHinge = self.controlColumn.attachNewNode('stickHinge') self.stick = self.party.defaultStickModel.copyTo(self.stickHinge) self.stickHinge.setHpr(0.0, 90.0, 0.0) self.stick.setHpr(0, -90.0, 0) self.stick.flattenLight() self.bottom = self.leverModel.find('**/bottom') self.bottom.wrtReparentTo(self.controlColumn) self.bottomPos = self.bottom.getPos() cs = CollisionSphere(0.0, 1.35, 2.0, 1.0) cs.setTangible(False) cn = CollisionNode(self.leverTriggerEvent) cn.addSolid(cs) cn.setIntoCollideMask(OTPGlobals.WallBitmask) self.leverTrigger = self.root.attachNewNode(cn) self.leverTrigger.reparentTo(self.lever) self.leverTrigger.stash() cs = CollisionTube(0.0, 2.7, 0.0, 0.0, 2.7, 3.0, 1.2) cn = CollisionNode('levertube') cn.addSolid(cs) cn.setIntoCollideMask(OTPGlobals.WallBitmask) self.leverTube = self.leverModel.attachNewNode(cn) host = base.cr.doId2do.get(self.party.partyInfo.hostId) if host is None: self.notify.debug( '%s loadLever : Host has left the game before lever could be created.' % self.activityName) return else: scale = host.getGeomNode().getChild(0).getSz(render) self.leverModel.setScale(scale) self.controlColumn.setPos(0, 0, 0) host.setPosHpr(self.lever, 0, 0, 0, 0, 0, 0) host.pose('leverNeutral', 0) host.update() pos = host.rightHand.getPos(self.controlColumn) self.controlColumn.setPos(pos[0], pos[1], pos[2] - 1) self.bottom.setZ(host, 0.0) self.bottom.setPos(self.bottomPos[0], self.bottomPos[1], self.bottom.getZ()) lookAtPoint = Point3(0.3, 0, 0.1) lookAtUp = Vec3(0, -1, 0) self.stickHinge.lookAt(host.rightHand, lookAtPoint, lookAtUp) host.play('walk') host.update() return
def genSuccession(self, axis, distance, direction=None): axis_index = (self.axis_index_dic[axis]) col_index = (self.axis_index_dic[axis] + 1) % len(self.axis_index_dic) row_index = (self.axis_index_dic[axis] + 2) % len(self.axis_index_dic) ast_location = [] for ast_column in range( self.field_expanse[col_index][0], self.field_expanse[col_index][1] + self.succession_interval[col_index], self.succession_interval[col_index]): for ast_row in range( self.field_expanse[row_index][0], self.field_expanse[row_index][1] + self.succession_interval[row_index], self.succession_interval[row_index]): ast_location = [0, 0, 0] ast_location[axis_index] = distance ast_location[col_index] = ast_column ast_location[row_index] = ast_row model_ref = choice(Asteroid.ASTEROID_MODELS) asteroid = Asteroid(loader.loadModel(model_ref.modelPath), ast_location, self.deviation_factor, 1, .1) bound = asteroid.objectNP.getBounds() bound_center = bound.getCenter() bound_radius = bound.getRadius() asteroidSphere = CollisionSphere( bound_center[0] - asteroid.objectNP.getX(), bound_center[1] - asteroid.objectNP.getY(), bound_center[2] - asteroid.objectNP.getZ(), bound_radius * model_ref.radialScale) asteroidSphereNode = CollisionNode(Asteroid.COLLISION_NAME) asteroidSphereNode.addSolid(asteroidSphere) asteroidSphereNode.setFromCollideMask(BitMask32.allOff()) asteroidSphereNode.setIntoCollideMask(BitMask32.bit(0)) pandaBodySphereNodepath = asteroid.objectNP.attachNewNode( asteroidSphereNode) asteroid.orient() self.asteroids.append(asteroid)
def __init__(self, pos): Enemy.__init__(self, pos, "Models/Misc/simpleEnemy", { "stand" : "Models/Misc/simpleEnemy-stand", "walk" : "Models/Misc/simpleEnemy-walk", "attack" : "Models/Misc/simpleEnemy-attack", "die" : "Models/Misc/simpleEnemy-die", "spawn" : "Models/Misc/simpleEnemy-spawn" }, 3.0, 7.0, "walkingEnemy") self.attackDistance = 0.75 self.attackDelay = 0.3 self.attackDelayTimer = 0 self.attackWaitTimer = 0 self.acceleration = 100.0 mask = BitMask32() mask.setBit(2) self.collider.node().setIntoCollideMask(mask) self.attackSegment = CollisionSegment(0, 0, 0, 1, 0, 0) segmentNode = CollisionNode("enemyAttackSegment") segmentNode.addSolid(self.attackSegment) mask = BitMask32() mask.setBit(1) segmentNode.setFromCollideMask(mask) mask = BitMask32() segmentNode.setIntoCollideMask(mask) self.attackSegmentNodePath = render.attachNewNode(segmentNode) self.segmentQueue = CollisionHandlerQueue() base.cTrav.addCollider(self.attackSegmentNodePath, self.segmentQueue) self.attackDamage = -1 self.deathSound = loader.loadSfx("Sounds/enemyDie.ogg") self.attackSound = loader.loadSfx("Sounds/enemyAttack.ogg") self.yVector = Vec2(0, 1) self.actor.play("spawn")
def setupCollisions(self): """Setup the collision solids for all fields. NOTE: This can be removed once blend2bam supports invisible collision model export""" for field in BoardMap.gameMap: # create a sphere collision solid cs = CollisionSphere(0, 0, 0, 0.01) cn = CollisionNode("{}-collision".format(field.name)) cn.addSolid(cs) fieldNP = self.boardScene.find("**/{}".format(field.name)) field.collisionNP = fieldNP.attachNewNode(cn) field.collisionNP.setCollideMask(BitMask32(0x80))
def generateCollisionObject(self): colliderNode = CollisionNode("projectile") solid = CollisionSphere(0, 0, 0, self.size) solid.setTangible(False) colliderNode.addSolid(solid) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(MASK_WALLS | self.mask) colliderNode.setIntoCollideMask(0) Common.framework.pusher.addCollider(self.colliderNP, self.root) Common.framework.traverser.addCollider(self.colliderNP, Common.framework.pusher)
def __initCollisions(self): collSphere = CollisionSphere(0, 0, 0, Globals.PlayerCollisionRadius) collSphere.setTangible(0) self.mazeCollisionName = Globals.LocalPlayerCollisionName collNode = CollisionNode(self.mazeCollisionName) collNode.addSolid(collSphere) collNodePath = self.toon.attachNewNode(collNode) collNodePath.hide() handler = CollisionHandlerEvent() handler.addInPattern('%fn-into-%in') base.cTrav.addCollider(collNodePath, handler) self.handler = handler self._collNodePath = collNodePath
def addCollisionSphere(self, radius): """Create a collision sphere and adds it to the node's tree. The sphere is centered at the center of the object. """ center = self.getBounds().getCenter() collisionSphere = CollisionSphere(center, radius) collisionNode = CollisionNode(self.name + '_collision_node') collisionNode.addSolid(collisionSphere) self.collider = self.actor.attachNewNode(collisionNode) self.model.setCollideMask(BitMask32.allOff())
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 getFlyBallBubble(self): if self.__flyBallBubble == None: bubble = CollisionSphere(0, 0, 0, GolfGlobals.GOLF_BALL_RADIUS) node = CollisionNode('flyBallBubble') node.addSolid(bubble) node.setFromCollideMask(ToontownGlobals.PieBitmask | ToontownGlobals.CameraBitmask | ToontownGlobals.FloorBitmask) node.setIntoCollideMask(BitMask32.allOff()) self.__flyBallBubble = NodePath(node) self.flyBallHandler = CollisionHandlerEvent() self.flyBallHandler.addInPattern('flyBallHit-%d' % self.index) return self.__flyBallBubble
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 create_collider(self): """Creates the collider and attaches it to its actor's node. Returns: The collider. """ collider_name = self.__class__.__name__ collider_node = CollisionNode(collider_name) collider_node.addSolid(CollisionSphere(0, 0, 0, 0.3)) collider = self.actor.attachNewNode(collider_node) collider.setPythonTag("owner", self) collider.show() # So it's visible for debugging return collider
def setupFloorEventSphere(self, avatarNodePath, bitmask, avatarRadius): cSphere = CollisionSphere(0.0, 0.0, 0.0, 0.75) cSphereNode = CollisionNode('Flyer.cFloorEventSphere') cSphereNode.addSolid(cSphere) cSphereNodePath = avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.floorCollisionEvent = CollisionHandlerEvent() self.floorCollisionEvent.addInPattern('%fn-enter-%in') self.floorCollisionEvent.addAgainPattern('%fn-again-%in') self.floorCollisionEvent.addOutPattern('%fn-exit-%in') base.cTrav.addCollider(cSphereNodePath, self.floorCollisionEvent) self.cFloorEventSphereNodePath = cSphereNodePath
def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName): self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(render) self.actor.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.maxSpeed = maxSpeed self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0 self.walking = False colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, 0.3)) self.collider = self.actor.attachNewNode(colliderNode) self.collider.setPythonTag("owner", self)
def buildProjCollisions(self): gagSph = CollisionSphere(0, 0, 0, 1) gagSph.setTangible(0) gagNode = CollisionNode('projSensor') gagNode.addSolid(gagSph) gagNP = self.gag.attach_new_node(gagNode) gagNP.setScale(0.75, 0.8, 0.75) gagNP.setPos(0.0, 0.1, 0.5) gagNP.setCollideMask(BitMask32.bit(0)) gagNP.node().setFromCollideMask(CIGlobals.FloorBitmask) event = CollisionHandlerEvent() event.set_in_pattern('%fn-into') event.set_out_pattern('%fn-out') base.cTrav.addCollider(gagNP, event)
def setupCollisions(self): sphere = CollisionSphere(0, 0, 0, 0.1) collnode = CollisionNode('bulletCollNode-' + str(id(self))) collnode.addSolid(sphere) self.collnp = self.bullet.attachNewNode(collnode) self.collnp.setCollideMask(BitMask32(0)) self.collnp.node().setFromCollideMask( CIGlobals.WallBitmask | CIGlobals.FloorBitmask | CIGlobals.EventBitmask ) #self.collnp.show() event = CollisionHandlerEvent() event.setInPattern('%fn-into') event.setOutPattern('%fn-out') base.cTrav.addCollider(self.collnp, event)
def initSensors(self, n, h): origin = Point3(0.0, 0.0, h) angles = [math.pi * t / (n - 1) for t in range(n)] sensors = [Vec3(math.sin(ang), math.cos(ang), h) for ang in angles] # Create collision nodes for sensors sensorNode = CollisionNode('sensor') sensorRay = CollisionRay(origin, Vec3(1.0, 0.0, 0.0)) sensorNode.addSolid(sensorRay) # Add collision node to car and handler sensorNodePath = self.car.attachNewNode(sensorNode) self.base.cTrav.addCollider(sensorNodePath, self.collisionHandler) self.base.taskMgr.add(self.checkCollisions, "CheckCollisionsTask")
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) # Show the collision node, which makes the solids show up. collisionNodepath.show() return collisionNodepath
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 setupHeadSphere(self, avatarNodePath): collSphere = CollisionSphere(0, 0, 0, 1) collSphere.setTangible(1) collNode = CollisionNode('Flyer.cHeadCollSphere') collNode.setFromCollideMask(ToontownGlobals.CeilingBitmask) collNode.setIntoCollideMask(BitMask32.allOff()) collNode.addSolid(collSphere) self.cHeadSphereNodePath = avatarNodePath.attachNewNode(collNode) self.cHeadSphereNodePath.setZ(base.localAvatar.getHeight() + 1.0) self.headCollisionEvent = CollisionHandlerEvent() self.headCollisionEvent.addInPattern('%fn-enter-%in') self.headCollisionEvent.addOutPattern('%fn-exit-%in') base.cTrav.addCollider(self.cHeadSphereNodePath, self.headCollisionEvent)
def setupEventSphere(self, bitmask, avatarRadius): self.avatarRadius = avatarRadius cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius * 1.04) cSphere.setTangible(0) cSphereNode = CollisionNode('Flyer.cEventSphereNode') cSphereNode.addSolid(cSphere) cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.event = CollisionHandlerEvent() self.event.addInPattern('enter%in') self.event.addOutPattern('exit%in') self.cEventSphereNodePath = cSphereNodePath
class Mouse(object): def __init__(self, base): self.base = base if settings.mouse_over: taskMgr.add(self.mouse_task, 'mouse-task') self.picker = CollisionTraverser() self.pq = CollisionHandlerQueue() self.pickerNode = CollisionNode('mouseRay') self.pickerNP = self.base.cam.attachNewNode(self.pickerNode) self.pickerNode.setFromCollideMask( CollisionNode.getDefaultCollideMask() | GeomNode.getDefaultCollideMask()) self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) self.picker.addCollider(self.pickerNP, self.pq) #self.picker.showCollisions(render) self.over = None def find_over(self): over = None if self.base.mouseWatcherNode.hasMouse(): mpos = self.base.mouseWatcherNode.getMouse() self.pickerRay.setFromLens(self.base.camNode, mpos.getX(), mpos.getY()) self.picker.traverse(render) if self.pq.getNumEntries() > 0: self.pq.sortEntries() np = self.pq.getEntry(0).getIntoNodePath().findNetPythonTag( 'owner') owner = np.getPythonTag('owner') over = owner np = self.pq.getEntry(0).getIntoNodePath().findNetPythonTag( 'patch') if np is not None: self.patch = np.getPythonTag('patch') else: self.patch = None return over def get_over(self): if settings.mouse_over: over = self.over else: over = self.find_over() return over def mouse_task(self, task): if self.mouseWatcherNode.hasMouse(): self.over = self.find_over() return Task.cont
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 collisionInit(self): self.pusher.addCollider(self.player.collider, self.player.actor) self.cTrav.addCollider(self.player.collider, self.pusher) self.pusher.setHorizontal(True) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0)