当前位置: 首页>>代码示例>>Python>>正文


Python BulletWorld.attachGhost方法代码示例

本文整理汇总了Python中panda3d.bullet.BulletWorld.attachGhost方法的典型用法代码示例。如果您正苦于以下问题:Python BulletWorld.attachGhost方法的具体用法?Python BulletWorld.attachGhost怎么用?Python BulletWorld.attachGhost使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在panda3d.bullet.BulletWorld的用法示例。


在下文中一共展示了BulletWorld.attachGhost方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PhysicsManager

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachGhost [as 别名]
class PhysicsManager(object):

    num_rigidBodies = 0
    num_ghosts      = 0

    def __init__(self, gravity=(0,0,-9.81) ):
        self.world = BulletWorld()
        self.world.setGravity(Vec3(gravity) )        

        self.addShape = {}
        self.addShape['plane']    = self.__addPlane
        self.addShape['sphere']   = self.__addSphere  
        self.addShape['box']      = self.__addBox
        self.addShape['cylinder'] = self.__addCylinder
        self.addShape['capsule']  = self.__addCapsule
        self.addShape['cone']     = self.__addCone
        self.addShape['hull']     = self.__addConvexHull
        self.addShape['trimesh']  = self.__addTriangleMesh

        #self.composer = Composer()
        self.addShape['compound'] = self.__addCompound

       # self.shapesList = self.addShape.keys()

    def getRigidBodyDefaultProps(self):
        props = {}
        props['mass']         = .0
        props['friction']     = .5
        props['restitution']  = .0
        props['adamping']     = .0
        props['ldamping']     = .0
        props['asleep']       = .08
        props['lsleep']       = 1.
        props['deactivation'] = True
        props['kinematic']    = False
        return props

    def getRigidBody(self, name=None):
        PhysicsManager.num_rigidBodies+=1
        return BulletRigidBodyNode(name or 'rigidbody'+str(PhysicsManager.num_rigidBodies) )

    def createRigidBody(self, shapetype, model, props={}, name=None):
        body = self.getRigidBody(name)
        self.addShape[shapetype](body, model)
        props = dict(self.getRigidBodyDefaultProps().items() + props.items() )
        self.setBodyProps(body, props)
        self.world.attachRigidBody( body )
        return body         

    def getGhost(self, name=None):
        PhysicsManager.num_ghosts+=1
        return BulletGhostNode(name or 'ghost'+str(PhysicsManager.num_ghosts) )

    def createGhost(self, shapetype, size, name=None):        
        ghost = self.getGhost(name)
        self.addShape[shapetype](ghost, size) 
        self.world.attachGhost(ghost)
        return ghost  

    def attachRigidBody(self, body, props):
        self.setBodyProps(body, props)
        self.world.attachRigidBody(body)

    def __addCompound(self, body, model):
        self.createCompound(model,body)   

    def __addSphere(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        size = self.getSize(model)
        shape = BulletSphereShape( max(size)/2 )
        body.addShape(shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addBox(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        size = self.getSize(model)
        shape = BulletBoxShape( size/2 )
        body.addShape(shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addCylinder(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        size = self.getSize(model)
        shape = BulletCylinderShape(max(size.x,size.y)/2, size.z, ZUp)
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addCapsule(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        size = self.getSize(model)
        diam = max(size.x,size.y)
        shape = BulletCapsuleShape(diam/2, size.z-diam, ZUp)       
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addCone(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        size = self.getSize(model)
        shape = BulletConeShape(max(size.x,size.y)/2, size.z, ZUp)
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addConvexHull(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):        
        
        def one():
            geom = model.node().getGeom(0)          
            shape = BulletConvexHullShape()
            shape.addGeom(geom)
            body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )
            return []
#.........这里部分代码省略.........
开发者ID:fredukita,项目名称:Pandark-Project,代码行数:103,代码来源:physicsmanager.py

示例2: BallInMaze

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachGhost [as 别名]

#.........这里部分代码省略.........
    self.ballNP.setLight(render.attachNewNode(ambientLight))
    self.ballNP.setLight(render.attachNewNode(directionalLight))

    m = Material()
    m.setSpecular(Vec4(1,1,1,1))
    m.setShininess(96)
    self.ballNP.setMaterial(m, 1)

    # Startup
    self.startGame()

  def exitGame(self):
    sys.exit()

  def toggleWireframe(self):
    base.toggleWireframe()

  def toggleTexture(self):
    base.toggleTexture()

  def toggleDebug(self):
    if self.debugNP.isHidden():
      self.debugNP.show()
    else:
      self.debugNP.hide()

  def doScreenshot(self):
    base.screenshot('Bullet')

  def startGame(self):
    self.ballNP.setPos(4, -4, 1)
    self.ballNP.node().setLinearVelocity(Vec3(0, 0, 0))
    self.ballNP.node().setAngularVelocity(Vec3(0, 0, 0))

    # Mouse
    p = base.win.getProperties()
    base.win.movePointer(0, p.getXSize()/2, p.getYSize()/2)

    # Add bodies and ghosts
    self.world.attachRigidBody(self.ballNP.node())
    for bodyNP in self.maze:
      self.world.attachRigidBody(bodyNP.node())
    for ghostNP in self.holes:
      self.world.attachGhost(ghostNP.node())

    # Simulation task
    taskMgr.add(self.updateGame, 'updateGame')

  def stopGame(self):

    # Remove bodies and ghosts
    self.world.removeRigidBody(self.ballNP.node())
    for bodyNP in self.maze:
      self.world.removeRigidBody(bodyNP.node())
    for ghostNP in self.holes:
      self.world.removeGhost(ghostNP.node())

    # Simulation task
    taskMgr.remove('updateGame')

  def updateGame(self, task):
    dt = globalClock.getDt()

    # Get mouse position and tilt maze
    if base.mouseWatcherNode.hasMouse():
      mpos = base.mouseWatcherNode.getMouse()
      hpr = Vec3(0, mpos.getY() * -10, mpos.getX() * 10)

      # Maze visual node
      self.mazeNP.setHpr(hpr)

      # Maze body nodes
      for bodyNP in self.maze:
        bodyNP.setHpr(hpr)

    # Update simulation
    self.world.doPhysics(dt)

    # Check if ball is touching a hole
    for holeNP in self.holes:
      if holeNP.node().getNumOverlappingNodes() > 2:
        if (self.ballNP.node() in holeNP.node().getOverlappingNodes()):
          self.looseGame(holeNP)

    return task.cont

  def looseGame(self, holeNP):
    toPos = holeNP.node().getShapePos(0)
    self.stopGame()

    Sequence(
      Parallel(
      LerpFunc(self.ballNP.setX, fromData = self.ballNP.getX(),
               toData = toPos.getX(), duration = .1),
      LerpFunc(self.ballNP.setY, fromData = self.ballNP.getY(),
               toData = toPos.getY(), duration = .1),
      LerpFunc(self.ballNP.setZ, fromData = self.ballNP.getZ(),
               toData = self.ballNP.getZ() - .9, duration = .2)),
      Wait(1),
      Func(self.startGame)).start()
开发者ID:Changuito,项目名称:juan_example,代码行数:104,代码来源:19_BallInMaze.py

示例3: Game

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachGhost [as 别名]
class Game(ShowBase, object):
    """What should be done here:
        Nothing that doesnt have to be.
        If something can have its own class, it should.
        Things that are here that shouldnt be:
            Setting up physics
            Setting up the world
            Menus
            GUI
            World/level things
        Things that are here that should be:
            Setting properties
            Main update loop
            Initalizing things (worlds, physics) Via other classes
        Remember to ask yourself this "Does a X have a Y?"
        So does a game have physics? No, a game has a world,
        and a world has physics.
        An entity is a panda node.

    """

    forceFPS = True
    fsmState = True
    bulletDict = {}
    playerList = {}
    grav_ghost_NP = 0

    def __init__(self):

        #self.gui = loadGui()
        #init_pause_state(self.menu)
        init_pause_state()
        test = World()

        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9))

        self.world.setDebugNode(debugNP.node())

        #Add a gravity region
        self.add_gravity_region(
                (100, 100, 100),
                (100, -400, 0),
                (0, 0, 1000))

        taskMgr.add(self.update_bullet, 'update_bullet')

        self.bulletList = self.loadBulletList()

        base.disableMouse()

        self.loadLevel()
        self.initClasses()
        self.setCamera()
        self.addWinProps()

        #TODO: Fix the healthbars
        #self.gui.healthBar("Player1")
        #self.gui.healthBar("AI1")
        #self.gui.healthBar("AI2")
        #self.gui.healthBar("AI3")

        self.loadStation()

        self.addlight()

        self.createControls()

        taskMgr.add(self.updateMenus, 'MenuUpdater')
        print("Instance of game class running.")

        self.simmpoleXP()
        self.flipsXP()

    def update_bullet(self, task):
        dt = globalClock.getDt()
        self.world.doPhysics(dt)
        return task.cont

    def add_gravity_region(self, size, pos, gravity):
        """Makes a bullet ghost, when a object enters
        its gravity is changed to match the arguments passed
        """
        shape = BulletBoxShape(Vec3(size))

        grav_ghost = BulletGhostNode('Ghost')
        grav_ghost.addShape(shape)
        grav_ghost_NP = render.attachNewNode(grav_ghost)
        grav_ghost_NP.setPos(pos)
        grav_ghost_NP.setCollideMask(BitMask32(0x0f))

        self.world.attachGhost(grav_ghost)
#.........这里部分代码省略.........
开发者ID:simmpole,项目名称:Space-Fighter,代码行数:103,代码来源:SpaceFighter.py

示例4: PhysicsManager

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachGhost [as 别名]
class PhysicsManager(object):    

    def __init__(self,gravity=(0,0,-9.81)):
        self.world = BulletWorld()
        self.world.setGravity(Vec3(gravity))

        self.addShape = {}
        self.addShape['sphere']   = self.__addSphere  
        self.addShape['box']      = self.__addBox
        self.addShape['cylinder'] = self.__addCylinder
        self.addShape['capsule']  = self.__addCapsule
        self.addShape['cone']     = self.__addCone
        self.addShape['hull']     = self.__addConvexHull
        self.addShape['trimesh']  = self.__addTriangleMesh

    def getRigidBodyDefaultProps(self):
        props = {}
        props['mass'] = 1.
        props['friction'] = .5
        props['restitution'] = .0
        props['adamping'] = .0
        props['ldamping'] = .0
        props['asleep'] = .08
        props['lsleep'] = 1.
        props['deactivation'] = True
        props['kinematic'] = False
        return props

    def getRigidBody(self,name=None):
        return BulletRigidBodyNode(name or 'rigidbody')

    def createRigidBody(self,shapetype,sizeOrGeom,props={},pos=(0,0,0),hpr=(0,0,0),scale=(1,1,1),name=None):
        body = self.getRigidBody(name)
        self.addShape[shapetype](body,sizeOrGeom,pos,hpr,scale)
        props = dict(self.getRigidBodyDefaultProps().items() + props.items())
        self.setBodyProps(body, props)
        self.world.attachRigidBody( body )
        return body

    def createGhost(self,name,shape,size):        
        ghost = BulletGhostNode( name )
        self.addShape[shape]( ghost, size ) 
        self.world.attachGhost( ghost )
        return ghost  

    def attachRigidBody(self,body,props):
        self.setBodyProps(body,props)
        self.world.attachRigidBody( body )  

    def __addSphere(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        shape = BulletSphereShape( max(size)/2 )
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addBox(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        shape = BulletBoxShape( size/2 )
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addCylinder(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        shape = BulletCylinderShape(max(size.x,size.y)/2, size.z, ZUp)
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addCapsule(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        diam = max(size.x,size.y)
        shape = BulletCapsuleShape(diam/2, size.z-diam, ZUp)       
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    # def __addAdaptiveShape(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1), type='capsule'):
    #     height = max(size.x,size.y,size.z)
    #     diam = min(size.x,size.y,size.z)
    #     if type == 'capsule':
    #         shape = BulletCapsuleShape(diam/2, height-diam, ZUp)
    #     elif type == 'cylinder':
    #         shape = BulletCylinderShape(diam/2, height, ZUp)
    #     vec = (0,0,0)
    #     if size.x > size.z:vec=(0,0,90)
    #     if size.y > size.x:vec=(0,90,0)
    #     hpr+=vec
    #     body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addCone(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        shape = BulletConeShape(max(size.x,size.y)/2, size.z, ZUp)
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addConvexHull(self, body, geom, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        shape = BulletConvexHullShape()
        shape.addGeom(geom)
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addTriangleMesh(self, body, geom, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1), dynamic=True):
        mesh = BulletTriangleMesh()
        mesh.addGeom(geom)
        shape = BulletTriangleMeshShape(mesh, dynamic=dynamic )
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def __addPlane(self, body, size, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
        shape = BulletPlaneShape(size, 1)
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    def setBodyProps(self,body,props):        
        body.setMass(props['mass'])
#.........这里部分代码省略.........
开发者ID:fredukita,项目名称:Pandark-Project,代码行数:103,代码来源:physicsmanager+-+Copy.py

示例5: Game

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachGhost [as 别名]

#.........这里部分代码省略.........
  def toggleWireframe(self):
    base.toggleWireframe()

  def toggleTexture(self):
    base.toggleTexture()

  def toggleDebug(self):
    if self.debugNP.isHidden():
      self.debugNP.show()
    else:
      self.debugNP.hide()

  def doScreenshot(self):
    base.screenshot('Bullet')

  # ____TASK___

  def processInput(self, dt):
    force = Vec3(0, 0, 0)
    torque = Vec3(0, 0, 0)

    if inputState.isSet('forward'): force.setY( 1.0)
    if inputState.isSet('reverse'): force.setY(-1.0)
    if inputState.isSet('left'):    force.setX(-1.0)
    if inputState.isSet('right'):   force.setX( 1.0)
    if inputState.isSet('turnLeft'):  torque.setZ( 1.0)
    if inputState.isSet('turnRight'): torque.setZ(-1.0)

    force *= 30.0
    torque *= 10.0

    self.boxNP.node().setActive(True)
    self.boxNP.node().applyCentralForce(force)
    self.boxNP.node().applyTorque(torque)

  def update(self, task):
    dt = globalClock.getDt()

    self.processInput(dt)
    self.world.doPhysics(dt)

    # Get nodes overlapping with the ghost object
    if self.ghostNP.node().getNumOverlappingNodes() > 0:
      print self.ghostNP.node().getNumOverlappingNodes(), \
            self.ghostNP.node().getOverlappingNodes()

    return task.cont

  def cleanup(self):
    self.world = None
    self.worldNP.removeNode()

  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

    node = BulletRigidBodyNode('Ground')
    np = self.worldNP.attachNewNode(node)
    np.node().addShape(shape)
    np.setPos(0, 0, 0)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachRigidBody(np.node())

    # Box
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
    np.node().setMass(1.0)
    np.node().addShape(shape)
    np.setPos(0, 0, 4)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachRigidBody(np.node())

    self.boxNP = np
    visualNP = loader.loadModel('models/box.egg')
    visualNP.reparentTo(self.boxNP)

    # Trigger
    shape = BulletBoxShape(Vec3(1, 1, 2))

    np = self.worldNP.attachNewNode(BulletGhostNode('Ghost'))
    np.node().addShape(shape)
    np.setPos(3, 0, 0)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachGhost(np.node())

    self.ghostNP = np
开发者ID:Changuito,项目名称:juan_example,代码行数:104,代码来源:15_Ghost.py

示例6: EccoGame

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachGhost [as 别名]

#.........这里部分代码省略.........
        self.character.setMaxJumpHeight(3.0)
        self.character.setJumpSpeed(25.0)
        self.character.doJump()

    def setupCoins(self):
        # display coins = 0
        textN = TextNode('coin-score')
        textN.setText(str("Coins: " + str(self.coinsCollected)))
        textN.setSlant(0.1)
        textNodePath = self.aspect2d.attachNewNode(textN)
        textNodePath.setPos(0, 0.95, 0.9)
        textNodePath.setScale(0.08)
        randNum = random.sample(range(0, 1500, 200), 6)

        # coins
        for i in range(6):
            randX = random.uniform(-3.0, 3.2)
            randY = float(randNum[i])
            shape = BulletSphereShape(0.3)
            coinNode = BulletGhostNode('Coin-' + str(i))
            coinNode.addShape(shape)
            np = self.render.attachNewNode(coinNode)
            np.setCollideMask(BitMask32.allOff())
            np.setPos(randX, randY, 2)

            # Adding sphere model
            sphereNp = loader.loadModel('models/smiley.egg')
            sphereNp_tex = loader.loadTexture("models/sky/coin_2_tex.jpg")
            sphereNp.setTexture(sphereNp_tex, 1)
            sphereNp.reparentTo(np)
            sphereNp.setScale(0.45)
            sphereNp.hprInterval(2.5, Vec3(360, 0, 0)).loop()

            self.world.attachGhost(coinNode)
            self.coins.append(coinNode)
            print "node name:" + str(coinNode.getName())

    def processContacts(self):
        for coin in self.coins:
            self.testWithSingleBody(coin)

        self.coinsCollected = len(self.dictOfCoins)

    def testWithSingleBody(self, secondNode):
        contactResult = self.world.contactTestPair(self.character, secondNode)

        if contactResult.getNumContacts() > 0:
            self.collectSound.play()
            for contact in contactResult.getContacts():
                cp = contact.getManifoldPoint()
                node0 = contact.getNode0()
                node1 = contact.getNode1()
                self.dictOfCoins[node1.getName()] = 1
                np = self.render.find(node1.getName())
                np.node().removeAllChildren()
                self.world.removeGhost(np.node())

    def setupObstacles(self):
        # Obstacle
        origin = Point3(2, 0, 0)
        size = Vec3(2, 2.75, 1.5)
        shape = BulletBoxShape(size * 0.55)
        randNum1 = random.sample(range(0, 1500, 300), 3)
        randNum2 = random.sample(range(0, 1500, 500), 3)
        for i in range(2):
            randX = random.uniform(-3.5, 3.5)
开发者ID:anto004,项目名称:game-programming,代码行数:70,代码来源:Ecco.py


注:本文中的panda3d.bullet.BulletWorld.attachGhost方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。