本文整理汇总了Python中panda3d.core.CollisionHandlerEvent.addInPattern方法的典型用法代码示例。如果您正苦于以下问题:Python CollisionHandlerEvent.addInPattern方法的具体用法?Python CollisionHandlerEvent.addInPattern怎么用?Python CollisionHandlerEvent.addInPattern使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.core.CollisionHandlerEvent
的用法示例。
在下文中一共展示了CollisionHandlerEvent.addInPattern方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
def __init__(self, model = "cube_nocol", texture = "lava", pos = (0,0,0), scale = (1,1,1), cubetype = "A"):
super(LavaCube, self).__init__(model, texture, pos, scale)
cn = CollisionNode('lava')
cn.setFromCollideMask(COLLISIONMASKS['lava'])
cn.setIntoCollideMask(BitMask32.allOff())
np = self.node.attachNewNode(cn)
cn.addSolid(CollisionSphere(0,0,0,1.1))
h = CollisionHandlerEvent()
h.addInPattern('%fn-into-%in')
h.addOutPattern('%fn-outof-%in')
base.cTrav.addCollider(np, h)
示例2: createPortalCollisions
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
def createPortalCollisions(self):
# Enter the portals
cn = CollisionNode('bluePortal')
cn.setFromCollideMask(COLLISIONMASKS['portals'])
cn.setIntoCollideMask(BitMask32.allOff())
np = self.bluePortal.attachNewNode(cn)
cn.addSolid(CollisionSphere(0,0,0,2))
h = CollisionHandlerEvent()
h.addInPattern('%fn-into-%in')
h.addOutPattern('%fn-outof-%in')
self.base.cTrav.addCollider(np, h)
cn = CollisionNode('orangePortal')
cn.setFromCollideMask(COLLISIONMASKS['portals'])
cn.setIntoCollideMask(BitMask32.allOff())
np = self.orangePortal.attachNewNode(cn)
cn.addSolid(CollisionSphere(0,0,0,2))
h = CollisionHandlerEvent()
h.addInPattern('%fn-into-%in')
h.addOutPattern('%fn-outof-%in')
self.base.cTrav.addCollider(np, h)
示例3: Pickup
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class Pickup(DirectObject):
#Creates health pickup object
def __init__(self, idappend, spawn):
self.id = "pick"+str(idappend)
self.deletePickup = False
self.projectileNode = NodePath('heal'+str(self.id))
self.projectileNode.setScale(1)
self.projectileModel = loader.loadModel("./resources/healthPickup.egg")
self.projectileModel.setColorScale(200, 0, 0, 100)
self.projectileModel.reparentTo(self.projectileNode)
self.projectileNode.reparentTo(render)
self.projectileNode.setPos(spawn)
cs = CollisionSphere(0, 0, 0, .5)
cnode = CollisionNode('heal')
self.colNode = self.projectileModel.attachNewNode(cnode)
self.colNode.node().addSolid(cs)
self.collHand = CollisionHandlerEvent()
self.collHand.addInPattern('pickupin'+str(self.id))
self.collHand.addOutPattern('oot')
base.cTrav.addCollider(self.colNode, self.collHand)
self.accept('pickupin'+str(self.id), self.pickup)
#Detects if the player has picked up the health
def pickup(self, col):
if col.getIntoNodePath().getName() == "cnode":
messenger.send("pickuphealth")
self.deletePickup = True
#Destroys the health pickups from the scene graph
def destroy(self):
self.projectileNode.removeNode()
self.projectileModel.removeNode()
self.colNode.node().clearSolids()
del self
示例4: CogdoFlyingCollisions
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class CogdoFlyingCollisions(GravityWalker):
wantFloorSphere = 0
def __init__(self):
GravityWalker.__init__(self, gravity=0.0)
def initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0):
self.cHeadSphereNodePath = None
self.cFloorEventSphereNodePath = None
self.setupHeadSphere(avatarNodePath)
self.setupFloorEventSphere(avatarNodePath, ToontownGlobals.FloorEventBitmask, avatarRadius)
GravityWalker.initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius, floorOffset, reach)
return
def setupWallSphere(self, bitmask, avatarRadius):
self.avatarRadius = avatarRadius
cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius)
cSphereNode = CollisionNode('Flyer.cWallSphereNode')
cSphereNode.addSolid(cSphere)
cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode)
cSphereNode.setFromCollideMask(bitmask)
cSphereNode.setIntoCollideMask(BitMask32.allOff())
if config.GetBool('want-fluid-pusher', 0):
self.pusher = CollisionHandlerFluidPusher()
else:
self.pusher = CollisionHandlerPusher()
self.pusher.addCollider(cSphereNodePath, self.avatarNodePath)
self.cWallSphereNodePath = cSphereNodePath
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
def setupRay(self, bitmask, floorOffset, reach):
cRay = CollisionRay(0.0, 0.0, 3.0, 0.0, 0.0, -1.0)
cRayNode = CollisionNode('Flyer.cRayNode')
cRayNode.addSolid(cRay)
self.cRayNodePath = self.avatarNodePath.attachNewNode(cRayNode)
cRayNode.setFromCollideMask(bitmask)
cRayNode.setIntoCollideMask(BitMask32.allOff())
self.lifter = CollisionHandlerGravity()
self.lifter.setLegacyMode(self._legacyLifter)
self.lifter.setGravity(self.getGravity(0))
self.lifter.addInPattern('%fn-enter-%in')
self.lifter.addAgainPattern('%fn-again-%in')
self.lifter.addOutPattern('%fn-exit-%in')
self.lifter.setOffset(floorOffset)
self.lifter.setReach(reach)
self.lifter.addCollider(self.cRayNodePath, self.avatarNodePath)
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 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 deleteCollisions(self):
GravityWalker.deleteCollisions(self)
if self.cHeadSphereNodePath != None:
base.cTrav.removeCollider(self.cHeadSphereNodePath)
self.cHeadSphereNodePath.detachNode()
self.cHeadSphereNodePath = None
self.headCollisionsEvent = None
if self.cFloorEventSphereNodePath != None:
base.cTrav.removeCollider(self.cFloorEventSphereNodePath)
self.cFloorEventSphereNodePath.detachNode()
self.cFloorEventSphereNodePath = None
self.floorCollisionEvent = None
#.........这里部分代码省略.........
示例5: World
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class World(DirectObject):
def __init__(self):
#--Collision Handler------------------------------------------------------
self.collHandler = CollisionHandlerEvent()
self.collHandler.addInPattern('%fn-into-%in')
base.cTrav = CollisionTraverser('world traverser')
#--Mouse Control----------------------------------------------------------
base.disableMouse()
self.properties = WindowProperties()
self.properties.setCursorHidden(True)
base.win.requestProperties(self.properties)
#--Register Hud Elements--------------------------------------------------
self.instruction1 = self.addInstruction("[click] to Shoot",2)
self.instruction2 = self.addInstruction("[a] to accelerate", 1)
self.instruction3 = self.addInstruction("[esc] to quit", 0)
self.scoreHud = self.addHudElement("", 0)
self.accuracy = self.addHudElement("", 1)
self.speedHud = self.addHudElement("", 2)
self.bigHud = OnscreenText(text="", style=1, fg=(1,1,1,1), pos=(0,0), align=TextNode.ACenter, scale = .1)
#--Load Objects and Models------------------------------------------------
self.ship = Ship(self.collHandler)
self.loadSkyBox()
game.camera.reparentTo(self.ship.getModel())
#--Start Game-------------------------------------------------------------
self.asteroids = []
self.resetGame()
#--Controls --------------------------------------------------------------
self.keysDown = {'a': 0}
self.controlTask = taskMgr.add(self.gameLoop, "game-control-task")
self.controlTask.lastTime = 0
self.accept("escape", sys.exit, [0])
self.accept("a", self.keyDown, ['a'])
self.accept("a-up", self.keyUp, ['a'])
self.accept("mouse1", self.shoot)
self.accept("space", self.shoot)
self.accept("resetgame", self.gameOver)
if(DEBUG_CONTROLS):
self.accept("0", self.ship.stop)
self.accept("9", self.ship.getModel().setHpr, [0,0,0])
#--Register CollisionEvent Handlers---------------------------------------
self.accept('asteroid-into-bullet', self.bulletAsteroidCollision)
###
# World.shoot:
#
# Dispatch method that overloads the use of the mouse button
##
def shoot(self):
if(self.ship.isAlive()):
self.ship.fireBullet()
self.shots += 1
else:
self.resetGame()
###
# World.gameOver()
#
# Displays "Game Over: <SCORE>" then resets game after 5 seconds
def gameOver(self):
self.bigHud.setText("GAME OVER: " + str(self.score))
taskMgr.doMethodLater(GAME_OVER_DELAY,
self.resetGame,
"reset_game",
[])
###
# World.resetGame
#
# Resets anything that might change during play essentially reloading
##
def resetGame(self):
for asteroid in self.asteroids:
asteroid.remove()
self.score = 0
self.shots = 0
self.hits = 0
self.lifeLength = 0
self.ship.reset()
self.scoreHud.setText("Score : " + str(self.score))
self.accuracy.setText("Hit/Fired : 0/0")
self.speedHud.setText("Speed : 0")
self.bigHud.setText("")
self.loadAsteroids()
###
# World.bulletAsteroidCollision:
#
# Event Handler for collision From Asteroid Into Bullet
#.........这里部分代码省略.........
示例6: __init__
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
#.........这里部分代码省略.........
"eat":"models/trex/trex-eat"})
self.boy.reparentTo(self.render)
self.boy.setPos(0,0,0)
self.boy.setScale(0.5)
self.isMoving = False
self.myAnimControl = self.boy.getAnimControl('run')
base.camera.setPos(self.boy.getX(),self.boy.getY()+10,20)
self.floater = NodePath(PandaNode("floater"))
self.floater.reparentTo(render)
self.cBoy = self.boy.attachNewNode(CollisionNode('cBoyNode'))
self.cBoy.node().addSolid(CollisionSphere(0, 0, 3, 8.5))
#self.cBoy.show()
#self.cPond = self.stall.attachNewNode(CollisionNode('cPond'))
#self.cPond.node().addSolid(CollisionSphere(40, 0, 1, 70))
#self.cPond.show()
# Add the spinCameraTask procedure to the task manager.
#self.taskMgr.add(self.spinCameraTask,"asdsad")
self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
cs1 = CollisionSphere(0, 0, 0, 2)
self.cnodePath1 = render.attachNewNode(CollisionNode('cnode1'))
self.cnodePath1.node().addSolid(cs1)
#self.cnodePath1.setCollideMask(BitMask32(0x10))
#self.cnodePath1.show()
self.taskMgr.add(self.moveSphere1, "sfasdasf")
cs2 = CollisionSphere(0, 0, 0, 1)
self.cnodePath2 = render.attachNewNode(CollisionNode('cnode2'))
self.cnodePath2.node().addSolid(cs2)
#self.cnodePath2.reparentTo(self.render)
#self.cnodePath2.node().setFromCollideMask(BitMask32.bit(0))
#self.cnodePath2.node().setIntoCollideMask(BitMask32.allOff())
#self.cnodePath2.show()
self.taskMgr.add(self.moveSphere2, "sfasd")
handler = CollisionHandlerEvent()
handler.addInPattern('cnode1-into-cnode2')
handler.addAgainPattern('cnode1-again-cnode2')
handler.addOutPattern('cs1-out-cs2')
self.accept('cnode1-into-cnode2', self.collide)
#self.accept('cs1-out-cs2', self.collide)
#self.accept('cnode1-again-cnode2', self.collide)
self.traverser.addCollider(self.cnodePath1, handler)
# Load and transform the panda actor.
self.pandaActor = Actor("models/panda-model",
{"walk": "models/panda-walk4"})
self.pandaActor.setScale(0.005, 0.005, 0.005)
self.pandaActor.reparentTo(self.render)
# Loop its animation.
self.pandaActor.loop("walk")
self.taskMgr.add(self.movePanda, "Sasdas")
self.pandaActor2 = Actor("models/panda-model",{"walk": "models/panda-walk4"})
self.pandaActor2.setScale(0.003, 0.003, 0.003)
self.pandaActor2.reparentTo(self.render)
# Loop its animation.
self.pandaActor2.loop("walk")
self.taskMgr.add(self.movePanda2, "Sak")
self.camera.setPos(0,0,0)
self.camera.setHpr(90,0,0)
self.cTrav1=CollisionTraverser()
self.collisionHandler1 = CollisionHandlerQueue()
self.cTrav1.addCollider(self.cBoy, self.collisionHandler1)
self.taskMgr.add(self.boyMoveTask, "BoyMoveTask")
#self.accept("v",self.switchView)
self.accept("escape", sys.exit)
self.accept("arrow_left", self.setKey, ["left",1])
self.accept("arrow_right", self.setKey, ["right",1])
self.accept("arrow_up", self.setKey, ["forward",1])
#self.accept("a", self.setKey, ["cam-left",1])
#self.accept("s", self.setKey, ["cam-right",1])
self.accept("arrow_left-up", self.setKey, ["left",0])
self.accept("arrow_right-up", self.setKey, ["right",0])
self.accept("arrow_up-up", self.setKey, ["forward",0])
#self.accept("a-up", self.setKey, ["cam-left",0])
#self.accept("s-up", self.setKey, ["cam-right",0])
self.cTrav2=CollisionTraverser()
self.collisionHandler2 = CollisionHandlerQueue()
示例7: MyApp
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.imageObject = OnscreenImage(image = 'earth.jpg', pos = (0, 1, 0))
self.imageObject.setScale(1.9,1,1)
tpRed = TextProperties()
tpRed.setTextColor(1, 1, 1, 1)
tpSlant = TextProperties()
tpSlant.setSlant(0.3)
tpRoman = TextProperties()
cmr12 = loader.loadFont('cmr12.egg')
tpRoman.setFont(cmr12)
tpMgr = TextPropertiesManager.getGlobalPtr()
tpMgr.setProperties("red", tpRed)
tpMgr.setProperties("slant", tpSlant)
tpMgr.setProperties("roman", tpRoman)
self.textObject = OnscreenText(text = '\1red\1\1roman\1\1slant\1Space Collector', pos = (-0.6, 0.4), scale = 0.2)
self.textScore=0
self.b = DirectButton(text = ("Start", "Start", "Start", "disabled"),command=self.beginGame)
self.b.setScale(0.1,0.1,0.1)
self.b.setPos(0.7,0,-0.8)
myMaterial = Material()
myMaterial.setShininess(1000)
myMaterial.setDiffuse(VBase4(0.5,0.5,0.5,1))
myMaterial.setAmbient(VBase4(5,5,5,1))
myMaterial.setSpecular(VBase4(10,10,10,1))
myTexture = loader.loadTexture("maps/grayjumpjetTexture.tif")
self.ship = loader.loadModel("GrayJumpJet")
self.ship.setScale(0.15, 0.3, 0.15)
self.ship.setPos(0,0,0)
self.ship.setTexture(myTexture,1)
self.ship.reparentTo(render)
self.slab = loader.loadModel("box")
self.slab.find("**/Cube;+h").setCollideMask(BitMask32.bit(0))
self.slab.setScale(1.5,10,1)
self.slab.setPos(0,0,-1)
self.slab.setHpr(0,0,0)
self.slab.setMaterial(myMaterial)
self.slab.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
self.slab.setTexProjector(TextureStage.getDefault(), render, self.slab)
self.slab.setTexture(loader.loadTexture("maps/crate_Material_#11_CL.tif"),1)
self.junk = [None]*100
self.loadJunk()
self.createTrack()
base.trackball.node().setPos(0, 20, -4)
self.acceleration=0
self.velocity=0
self.yPos=0
render.setShaderAuto()
self.cTrav = CollisionTraverser()
self.shipGroundRay = CollisionRay()
self.shipGroundRay.setOrigin(0,0,1000)
self.shipGroundRay.setDirection(0,0,-1)
self.shipGroundCol = CollisionNode('shipRay')
self.shipGroundCol.addSolid(self.shipGroundRay)
self.shipGroundCol.setFromCollideMask(BitMask32.bit(0))
self.shipGroundCol.setIntoCollideMask(BitMask32.allOff())
self.shipGroundColNp = self.ship.attachNewNode(self.shipGroundCol)
self.shipGroundHandler = CollisionHandlerQueue()
self.cTrav.addCollider(self.shipGroundColNp, self.shipGroundHandler)
self.collHandEvent = CollisionHandlerEvent()
# add the into pattern with fromObject-into-thisObject
self.collHandEvent.addInPattern( 'into-%in' )
self.accept("into-Junk",self.cHandler)
bkground = loader.loadModel("square")
bkground.reparentTo(camera)
bkground.setScale(300,170,50)
tex = loader.loadTexture("earth2.jpg")
bkground.setTexture(tex,1)
bkground.setPos(0,299,0)
bkground.setHpr(0,90,0)
base.camLens.setFar(300)
self.mySound = loader.loadMusic("coinslot1.wav")
self.timer=60
self.textTimer=0
self.prevY=0
self.prevX=0
self.shipGroundColNp.show()
#self.camGroundColNp.show()
self.collided=1
self.jumpTime=0
self.jumpOn=0
self.curZ=0
self.interval=0
#.........这里部分代码省略.........
示例8: SillyWorld
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class SillyWorld(DirectObject):
def __init__(self):
# start Panda3d
base = ShowBase()
# CollisionTraverser instance must be attached to base,
# and must be called cTrav
base.cTrav = CollisionTraverser()
self.cHand = CollisionHandlerEvent()
self.cHand.addInPattern('into-%in')
# load smiley, which we will control
# notice this is a little trickery. If we parent everything except smiley
# to the camera, and the player is controlling the camera, then everything
# stays fixed in the same place relative to the camera, and when the camera
# moves, the player is given the illusion that he is moving smiley, rather than
# the camera and the rest of the scene.
self.smiley = base.loader.loadModel('smiley')
self.smiley.reparentTo(render)
self.smiley.setName('Smiley')
# Setup a collision solid for this model. Our initCollisionSphere method returns
# the cNodepath and the string representing it. We will use the cNodepath for
# adding to the traverser, and the string to accept it for event handling.
#sColl = self.initCollisionSphere(self.smiley)
sColl = self.initCollisionSphere(self.smiley, True)
print 'smiley', sColl[0]
print 'smiley', sColl[1]
# Add this object to the traverser.
base.cTrav.addCollider(sColl[0], self.cHand)
# load frowney
self.frowney = base.loader.loadModel('frowney')
self.frowney.setName('Frowney')
self.frowney.reparentTo(camera)
# Setup a collision solid for this model.
fColl = self.initCollisionSphere(self.frowney, True)
#print 'frowney', fColl[0]
#print 'frowney', fColl[1]
# Add this object to the traverser.
base.cTrav.addCollider(fColl[0], self.cHand)
# Accept the events sent by the collisions.
# smiley is the object we are 'moving', so by convention
# it is the from object.
# If we instead put smiley as the into object here,
# it would work fine, but then smiley would disappear
# when we collided them.
self.accept('into-' + fColl[1], self.collide)
# set the initial positions of smiley and frowney
self.set_initial_positions()
def set_initial_positions(self):
self.smiley.setPos(0, 25, 0)
self.frowney.setPos(5, 25, 0)
def collide(self, collEntry):
#print('collision')
#print collEntry.getIntoNodePath().getParent()
collEntry.getIntoNodePath().getParent().stash()
#print self.frowney.isStashed()
# if instead of making frowney disappear, you wanted to
# change some aspect of one or both colliding objects,
# you could do soemthing like this:
colliderFROM = collEntry.getFromNodePath().getParent()
#colliderINTO = collEntry.getIntoNodePath().getParent()
# Note that for it to work, you have to
# we now may change the aspect of the two colliding objects
#colliderINTO.setColor(1,1,1,1)
colliderFROM.setScale(1.5)
def initCollisionSphere(self, obj, show=False):
# Get the size of the object for the collision sphere.
bounds = obj.getChild(0).getBounds()
center = bounds.getCenter()
# We are making our radius bigger than our object. It will look strange
# if we don't show the collision sphere, because frowney will disappear
# before the objects appear to touch, but this shows you how you can
# change the sphere separately from the actual object. Of course, you
# can make it the same size as the object if you want.
radius = bounds.getRadius() * 1.1
# Create a collision sphere and name it something understandable.
collSphereStr = 'CollisionHull' + "_" + obj.getName()
cNode = CollisionNode(collSphereStr)
cNode.addSolid(CollisionSphere(center, radius))
cNodepath = obj.attachNewNode(cNode)
if show:
cNodepath.show()
# Return a tuple with the collision node and its corrsponding string so
# that the bitmask can be set.
return (cNodepath, collSphereStr)
示例9: Player
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class Player(DirectObject):
def __init__(self, _main):
self.main = _main
self.name = ""
self.points = 0
self.health = 100.0
self.runSpeed = 1.8
self.keyMap = {
"left":False,
"right":False,
"up":False,
"down":False
}
base.camera.setPos(0,0,0)
self.model = loader.loadModel("Player")
self.model.find('**/+SequenceNode').node().stop()
self.model.find('**/+SequenceNode').node().pose(0)
base.camera.setP(-90)
self.playerHud = Hud()
self.playerHud.hide()
self.model.hide()
# Weapons: size=2, 0=main, 1=offhand
self.mountSlot = []
self.activeWeapon = None
self.isAutoActive = False
self.trigger = False
self.lastShot = 0.0
self.fireRate = 0.0
self.playerTraverser = CollisionTraverser()
self.playerEH = CollisionHandlerEvent()
## INTO PATTERNS
self.playerEH.addInPattern('intoPlayer-%in')
#self.playerEH.addInPattern('colIn-%fn')
self.playerEH.addInPattern('intoHeal-%in')
self.playerEH.addInPattern('intoWeapon-%in')
## OUT PATTERNS
self.playerEH.addOutPattern('outOfPlayer-%in')
playerCNode = CollisionNode('playerSphere')
playerCNode.setFromCollideMask(BitMask32.bit(1))
playerCNode.setIntoCollideMask(BitMask32.bit(1))
self.playerSphere = CollisionSphere(0, 0, 0, 0.6)
playerCNode.addSolid(self.playerSphere)
self.playerNP = self.model.attachNewNode(playerCNode)
self.playerTraverser.addCollider(self.playerNP, self.playerEH)
#self.playerNP.show()
self.playerPusher = CollisionHandlerPusher()
self.playerPusher.addCollider(self.playerNP, self.model)
self.playerPushTraverser = CollisionTraverser()
self.playerPushTraverser.addCollider(self.playerNP, self.playerPusher)
def acceptKeys(self):
self.accept("w", self.setKey, ["up", True])
self.accept("w-up", self.setKey, ["up", False])
self.accept("a", self.setKey, ["left", True])
self.accept("a-up", self.setKey, ["left", False])
self.accept("s", self.setKey, ["down", True])
self.accept("s-up", self.setKey, ["down", False])
self.accept("d", self.setKey, ["right", True])
self.accept("d-up", self.setKey, ["right", False])
# Add mouse btn for fire()
self.accept("mouse1", self.setWeaponTrigger, [True])
self.accept("mouse1-up", self.setWeaponTrigger, [False])
# Killed enemies
self.accept("killEnemy", self.addPoints)
# Game states
self.accept("doDamageToPlayer", self.doDamage)
def ignoreKeys(self):
self.ignore("w")
self.ignore("a")
self.ignore("s")
self.ignore("d")
self.ignore("killEnemy")
self.ignore("mouse1")
self.ignore("mouse1-up")
for item in self.main.itemList:
if item.type == "heal":
self.ignore("intoHeal-" + "itemHeal" + str(item.id))
elif item.type == "gun":
self. ignore("intoWeapon-" + "itemWeapon" + str(item.id))
for enemy in self.main.enemyList:
self.ignore("intoPlayer-" + "colEnemy" + str(enemy.id))
# Add mouse btn for fire to ignore
def setKey(self, action, pressed):
self.keyMap[action] = pressed
def start(self, startPos, playerName):
self.name = playerName
self.points = 0
self.health = 100
#.........这里部分代码省略.........
示例10: MyApp
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
#.........这里部分代码省略.........
self.camera.reparentTo(self.pandaActor)
self.camera.lookAt(self.pandaActor)
self.taskMgr.add(self.spinCameraTask, "zombieTask_SpinCameraTask")
self.taskMgr.doMethodLater(0.01,self.movePandaTask,"zombieTask_movePandaTask")
#Collision Handling
self.cTrav = CollisionTraverser()
self.collisionHandler = CollisionHandlerEvent()
#Add collider for terrain
self.groundCollider = self.environ.find("**/terrain")
#Add walker for panda
self.collision_sphere = CollisionSphere(0,0,1,1)
self.collNode = CollisionNode('pandaWalker')
self.cnodePath = self.pandaActor.attachNewNode(self.collNode)
self.cnodePath.node().addSolid(self.collision_sphere)
#AddZombieDetector for panda
self.zombie_sphere = CollisionSphere(0,0,3,1)
self.zomb_detector_node = CollisionNode('zombieDetector')
self.zomb_detector_NP = self.pandaActor.attachNewNode(self.zomb_detector_node)
self.zomb_detector_NP.node().addSolid(self.zombie_sphere)
#self.zomb_detector_NP.show()
#Add pusher against gravity
self.pusher = PhysicsCollisionHandler()
self.pusher.addCollider(self.cnodePath, self.pandaActorPhysicsP)
self.pusher.addCollider(self.zomb_detector_NP,self.pandaActorPhysicsP)
self.cTrav.addCollider(self.cnodePath,self.pusher)
self.cTrav.addCollider(self.zomb_detector_NP,self.pusher)
self.pusher.addInPattern('%fn-into-%in')
self.pusher.addAgainPattern('%fn-again-%in')
#Add collision handler patterns
self.collisionHandler.addInPattern('%fn-into-%in')
self.collisionHandler.addAgainPattern('%fn-again-%in')
self.abientLight = AmbientLight("ambientLight")
self.abientLight.setColor(Vec4(0.1, 0.1, 0.1, 1))
self.directionalLight = DirectionalLight("directionalLight")
self.directionalLight.setDirection(Vec3(-5, -5, -5))
self.directionalLight.setColor(Vec4((229.0/255), (204.0/255), (255.0/255), 0.7))
self.directionalLight.setSpecularColor(Vec4(0.4, 0.4, 0.4, 0.1))
self.directionalLight.setShadowCaster(True,512,512)
self.render.setLight(self.render.attachNewNode(self.abientLight))
self.render.setLight(self.render.attachNewNode(self.directionalLight))
self.render.setShaderAuto()
#create zombie land
self.zombieland = zombie.Zombies(self)
self.taskMgr.doMethodLater(0.01,self.zombieland.moveZombie, "zombieTask_ZombieMover")
layer2d.incBar(self.health)
self.taskMgr.add(self.game_monitor,"zombieTask_gameMonitor")
self.taskMgr.doMethodLater(2.7,self.music_play, "zombieTask_music")
#Add random useless things:
self.randomthings_.add_random_things()
def music_play(self,task):
self.music.play()
return Task.done
#def get_color(self):
# return self.color[min(len(self.color)-1,self.level)]
示例11: CBShield
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class CBShield(DirectObject):
#Property stuff
creaTime = time.clock()
dur = 5
vec = 0
delta = .15
prevtime = 0
flag = False
#defining the thing fired by whatever gun we have
def __init__(self, camera, look, id):
#nodepath of the projectile, give it a trajectory
self.projectileNode = NodePath('projectile'+str(id))
self.projectileNode.setTransparency(TransparencyAttrib.MAlpha)
self.projectileNode.reparentTo(render)
#by passing the camera node form the camMov object, all projectiles are spawned 5 units in front of the camera
self.projectileNode.setHpr(look, 0, 0, 0)
self.projectileNode.setPos(camera,-1,10, 3)
#fix z position to line up with gun
self.projectileNode.setScale(.1)
projectileModel = loader.loadModel("./resources/cubeShot.egg")
projectileModel.setColorScale(0, 0, 0, .5)
projectileModel.setSz(50)
projectileModel.setSy(1)
projectileModel.setSx(50)
projectileModel.reparentTo(self.projectileNode)
#must calculate unit vector based on direction
dir = render.getRelativeVector(look, Vec3(0, 1, 0))
#speed up or slow down projectiles here
dir = dir*10
self.vec = dir
#base.cTrav = CollisionTraverser()
cs = CollisionSphere(0, 0, 0, 25)
cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
cnodepath.node().addSolid(cs)
self.collHand = CollisionHandlerEvent()
self.collHand.addInPattern('into'+str(id))
self.collHand.addOutPattern('outof')
#cTrav has the distinction of global colider handler
base.cTrav.addCollider(cnodepath, self.collHand)
self.acceptOnce('into'+str(id), self.hit)
#deal with colliding or special effects here.
#wanted projectiles to be short lived
#so i will make them delete themselves after impact or time expired
#writing a task that will rek the projectiles at the end of time
self.damage = 20
def placeTask(self, task):
#curtime = time.clock()
#self.delta = curtime-self.prevtime
if self.flag:
return task.done
#prevtime = time.clock()
if task.time < self.dur:
return task.cont
else:
self.flag = True
return task.done
def hit(self, collEntry):
#throw out a custom message for what hit
if collEntry.getIntoNodePath().getName() != 'projNode':
temp = collEntry.getIntoNodePath().getName()
messenger.send(temp, [self.damage])
#remove the impacting projectile
collEntry.getFromNodePath().getParent().getParent().removeNode()
self.flag = True
del self
示例12: ChargeProjectile
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class ChargeProjectile(DirectObject):
dur = 2
delta = .15
flag = False
def __init__(self, spawn, taregt, id):
self.projectileNode = NodePath('projectile'+str(id))
self.projectileNode.reparentTo(render)
self.projectileNode.setPos(spawn,0,-10, 0)
self.projectileNode.setScale(1.5)
self.projectileModel = Actor("./resources/sphereShot",{"grow":"./resources/sphereShot-grow"})
self.projectileModel.setColorScale(200, 0, 255, 100)
self.projectileModel.reparentTo(self.projectileNode)
self.projectileNode.setHpr(spawn, 0, 0, 0)
dir = render.getRelativeVector(spawn, Vec3(0, 1, 0))
self.vec = dir*-100
cs = CollisionSphere(0, 0, 0, 2.5)
cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
cnodepath.node().addSolid(cs)
self.collHand = CollisionHandlerEvent()
self.collHand.addInPattern('bossProjectileinto'+str(id))
self.collHand.addOutPattern('outof')
base.cTrav.addCollider(cnodepath, self.collHand)
self.acceptOnce('bossProjectileinto'+str(id), self.hit)
self.damage = 15
def moveTask(self, task):
if self.flag:
return task.done
velx = self.vec.x*self.delta
vely = self.vec.y*self.delta
velz = self.vec.z*self.delta
x = self.projectileNode.getX()
y = self.projectileNode.getY()
z = self.projectileNode.getZ()
self.projectileNode.setPos(x+velx, y+vely, z+velz)
if task.time < self.dur:
return task.cont
else:
self.flag = True
return task.done
def hit(self, collEntry):
#throw out a custom message for what hit
if collEntry.getIntoNodePath().getName() != 'projNode':
temp = collEntry.getIntoNodePath().getName()
print temp
messenger.send(temp, [self.damage])
#remove the impacting projectile
collEntry.getFromNodePath().getParent().getParent().removeNode()
self.flag = True
del self
def wait(self, task):
if task.time > 2.24:
return task.done
return task.cont
示例13: MHBProjectile
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class MHBProjectile(DirectObject):
#Property stuff
creaTime = time.clock()
dur = .5
vec = 0
delta = .15
prevtime = 0
flag = False
#defining the thing fired by whatever gun we have
def __init__(self, camera, look, id, model):
self.id = id
#nodepath of the projectile, give it a trajectory
self.projectileNode = NodePath('projectile'+str(id))
self.projectileNode.reparentTo(render)
#by passing the camera node form the camMov object, all projectiles are spawned 5 units in front of the camera
self.projectileNode.setHpr(look, 0, 0, 0)
self.projectileNode.setPos(camera,0,3, 3)
#fix z position to line up with gun
self.projectileNode.setScale(.1)
projectileModel = loader.loadModel("./resources/cubeShot.egg")
projectileModel.setColor(255, 0, 0)
projectileModel.reparentTo(self.projectileNode)
#must calculate unit vector based on direction
dir = render.getRelativeVector(look, Vec3(0, 1, 0))
#speed up or slow down projectiles here
dir = dir*10
self.vec = dir
#Balance vectors when magnitude in direction is low
if self.vec.x < 2:
self.vec.x += random.randint(-1,1)
if self.vec.z < 2:
self.vec.z += random.randint(-1,1)
if self.vec.y < 2:
self.vec.y += random.randint(-1,1)
#Random vector displacements
self.vec.x *= random.uniform(.5,1)
self.vec.y *= random.uniform(.5,1)
self.vec.z *= random.uniform(.5,1)
#base.cTrav = CollisionTraverser()
cs = CollisionSphere(0, 0, 0, 2.5)
self.cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
self.cnodepath.node().addSolid(cs)
self.collHand = CollisionHandlerEvent()
self.cnodepath.setTag('tag', str(self.cnodepath))
self.collHand.addInPattern('%(tag)ix-into'+str(id))
self.collHand.addOutPattern('outof')
#cTrav has the distinction of global colider handler
base.cTrav.addCollider(self.cnodepath, self.collHand)
self.acceptOnce(self.cnodepath.getTag('self')+'-into'+str(id), self.hit)
#deal with colliding or special effects here.
#wanted projectiles to be short lived
# so i will make them delete themselves after impact or time expired
# writing a task that will rek the projectiles at the end of time
self.damage = 1.1
def moveTask(self, task):
#curtime = time.clock()
#self.delta = curtime-self.prevtime
if self.flag:
self.ignore(self.cnodepath.getTag('self')+'-into'+str(self.id))
return task.done
velx = self.vec.x*self.delta
vely = self.vec.y*self.delta
velz = self.vec.z*self.delta
x = self.projectileNode.getX()
y = self.projectileNode.getY()
z = self.projectileNode.getZ()
self.projectileNode.setPos(x+velx, y+vely, z+velz)
#prevtime = time.clock()
self.cnodepath.setTag('tag', str(self))
if task.time < self.dur:
return task.cont
else:
self.flag = True
return task.done
def hit(self, collEntry):
# throw out a custom message for what hit
if collEntry.getIntoNodePath().getName() != 'projNode':
temp = collEntry.getIntoNodePath().getName()
messenger.send(temp, [self.damage])
#.........这里部分代码省略.........
示例14: DistributedIceGame
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
#.........这里部分代码省略.........
def exitCleanup(self):
pass
def __placeToon(self, avId):
toon = self.getAvatar(avId)
if toon:
toon.setPos(0, 0, 0)
toon.setHpr(0, 0, 0)
def moveCameraToTop(self):
camera.reparentTo(render)
p = self.cameraThreeQuarterView
camera.setPosHpr(p[0], p[1], p[2], p[3], p[4], p[5])
def setupTire(self, avId, index):
tireNp, tireBody, tireOdeGeom = self.createTire(index)
self.tireDict[avId] = {'tireNodePath': tireNp,
'tireBody': tireBody,
'tireOdeGeom': tireOdeGeom}
if avId <= 0:
tireBlocker = tireNp.find('**/tireblockermesh')
if not tireBlocker.isEmpty():
tireBlocker.hide()
if avId == self.localAvId:
tireNp = self.tireDict[avId]['tireNodePath']
self.treasureSphereName = 'treasureCollider'
self.treasureCollSphere = CollisionSphere(0, 0, 0, IceGameGlobals.TireRadius)
self.treasureCollSphere.setTangible(0)
self.treasureCollNode = CollisionNode(self.treasureSphereName)
self.treasureCollNode.setFromCollideMask(ToontownGlobals.PieBitmask)
self.treasureCollNode.addSolid(self.treasureCollSphere)
self.treasureCollNodePath = tireNp.attachNewNode(self.treasureCollNode)
self.treasureHandler = CollisionHandlerEvent()
self.treasureHandler.addInPattern('%fn-intoTreasure')
base.cTrav.addCollider(self.treasureCollNodePath, self.treasureHandler)
eventName = '%s-intoTreasure' % self.treasureCollNodePath.getName()
self.notify.debug('eventName = %s' % eventName)
self.accept(eventName, self.toonHitSomething)
def setupForceArrow(self, avId):
arrow = loader.loadModel('phase_4/models/minigames/ice_game_arrow')
priority = 0
if avId < 0:
priority = -avId
else:
priority = self.avIdList.index(avId)
if avId == self.localAvId:
priority = 10
self.forceArrowDict[avId] = arrow
def hideForceArrows(self):
for forceArrow in self.forceArrowDict.values():
forceArrow.hide()
def showForceArrows(self, realPlayersOnly = True):
for avId in self.forceArrowDict:
if realPlayersOnly:
if avId > 0:
self.forceArrowDict[avId].show()
else:
self.forceArrowDict[avId].hide()
else:
self.forceArrowDict[avId].show()
def localForceArrow(self):
if self.localAvId in self.forceArrowDict:
示例15: World
# 需要导入模块: from panda3d.core import CollisionHandlerEvent [as 别名]
# 或者: from panda3d.core.CollisionHandlerEvent import addInPattern [as 别名]
class World(DirectObject):
def __init__( self ):
# Initialize the traverser.
base.cTrav = CollisionTraverser()
# Initialize the handler.
self.collHandEvent = CollisionHandlerEvent()
self.collHandEvent.addInPattern('into-%in')
self.collHandEvent.addOutPattern('outof-%in')
# Make a variable to store the unique collision string count.
self.collCount = 0
# Load a model. Reparent it to the camera so we can move it.
s = loader.loadModel('smiley')
s.reparentTo(camera)
s.setPos(0, 25, 0)
# Setup a collision solid for this model.
sColl = self.initCollisionSphere(s, True)
# Add this object to the traverser.
base.cTrav.addCollider(sColl[0], self.collHandEvent)
# Accept the events sent by the collisions.
self.accept('into-' + sColl[1], self.collide3)
self.accept('outof-' + sColl[1], self.collide4)
print(sColl[1])
# Load another model.
t = loader.loadModel('smiley')
t.reparentTo(render)
t.setPos(5, 25, 0)
# Setup a collision solid for this model.
tColl = self.initCollisionSphere(t, True)
# Add this object to the traverser.
base.cTrav.addCollider(tColl[0], self.collHandEvent)
# Accept the events sent by the collisions.
self.accept('into-' + tColl[1], self.collide)
self.accept('outof-' + tColl[1], self.collide2)
print(tColl[1])
print("WERT")
def collide(self, collEntry):
print("WERT: object has collided into another object")
Sequence(Func(collEntry.getFromNodePath().getParent().setColor,
VBase4(1, 0, 0, 1)),
Wait(0.2),
Func(collEntry.getFromNodePath().getParent().setColor,
VBase4(0, 1, 0, 1)),
Wait(0.2),
Func(collEntry.getFromNodePath().getParent().setColor,
VBase4(1, 1, 1, 1))).start()
def collide2(self, collEntry):
print("WERT.: object is no longer colliding with another object")
def collide3(self, collEntry):
print("WERT2: object has collided into another object")
def collide4(self, collEntry):
print("WERT2: object is no longer colliding with another object")
def initCollisionSphere(self, obj, show=False):
# Get the size of the object for the collision sphere.
bounds = obj.getChild(0).getBounds()
center = bounds.getCenter()
radius = bounds.getRadius() * 1.1
# Create a collision sphere and name it something understandable.
collSphereStr = 'CollisionHull' + str(self.collCount) + "_" + obj.getName()
self.collCount += 1
cNode = CollisionNode(collSphereStr)
cNode.addSolid(CollisionSphere(center, radius))
cNodepath = obj.attachNewNode(cNode)
if show:
cNodepath.show()
# Return a tuple with the collision node and its corrsponding string so
# that the bitmask can be set.
return (cNodepath, collSphereStr)