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


Python BulletWorld.getRigidBodies方法代码示例

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


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

示例1: BulletBase

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import getRigidBodies [as 别名]
class BulletBase(object):
    """ Manages Panda3d Bullet physics resources and convenience methods."""

    # Bitmasks for each object type. By setting ghost and static
    # objects to different masks, we can filter ghost-to-static
    # collisions.
    ghost_bit = BitMask32.bit(1)
    static_bit = BitMask32.bit(2)
    dynamic_bit = ghost_bit | static_bit
    bw_types = (BulletBaseCharacterControllerNode, BulletBodyNode,
                BulletConstraint, BulletVehicle)

    def __init__(self):
        self.world = None
        # Parameters for simulation.
        self.sim_par = {"size": 1. / 100, "n_subs": 10, "size_sub": 1. / 1000}
        # Initialize axis constraint so that there aren't constraints.
        self.axis_constraint_fac = Vec3(1, 1, 1)
        self.axis_constraint_disp = Vec3(nan, nan, nan)
        # Attribute names of destructable objects.
        self._destructables = ()

    def init(self):
        """ Initialize world and resources. """
        # Initialize world.
        self.world = BulletWorld()

    def destroy(self):
        """ Destroy all resources."""
        for key in self._destructables:
            getattr(self, key).destroy()

    def setup_debug(self):
        debug_node = BulletDebugNode('Debug')
        debug_node.showWireframe(True)
        debug_node.showConstraints(True)
        debug_node.showBoundingBoxes(True)
        debug_node.showNormals(True)
        self.world.setDebugNode(debug_node)
        return debug_node

    @property
    def bodies(self):
        """ Return all bodies (rigid, soft, and ghost) in self.world."""
        bodies = (self.world.getRigidBodies() + self.world.getSoftBodies() +
                  self.world.getGhosts())
        return bodies

    def _constrain_axis(self, body):
        """ Apply existing axis constraints to a body."""
        # Set displacements.
        for axis, (f, d) in enumerate(zip(self.axis_constraint_fac,
                                          self.axis_constraint_disp)):
            if not f and not isnan(d):
                nodep = NodePath(body)
                pos = nodep.getPos()
                pos[axis] = d
                nodep.setPos(pos)
        try:
            # Linear and angular factors of 0 mean forces in the
            # corresponding axis are scaled to 0.
            body.setLinearFactor(self.axis_constraint_fac)
            # Angular factors restrict rotation about an axis, so the
            # following logic selects the appropriate axes to
            # constrain.
            s = sum(self.axis_constraint_fac)
            if s == 3.:
                v = self.axis_constraint_fac
            elif s == 2.:
                v = -self.axis_constraint_fac + 1
            else:
                v = Vec3.zero()
            body.setAngularFactor(v)
        except AttributeError:
            # The body was not a rigid body (it didn't have
            # setLinearFactor method).
            pass

    def set_axis_constraint(self, axis, on, disp=None):
        """ Sets an axis constraint, so that bodies can/cannot
        move in that direction."""
        # Create the constraint vector.
        self.axis_constraint_fac[axis] = int(not on)
        self.axis_constraint_disp[axis] = disp if disp is not None else nan
        # Iterate over bodies, applying the constraint.
        for body in self.bodies:
            self._constrain_axis(body)

    def attach(self, objs, suppress_deact_warn=False):
        """ Attach Bullet objects to the world."""
        if not self.world:
            raise BulletBaseError("No BulletWorld initialized.")
        # Make sure they're iterable.
        if not isinstance(objs, Iterable):
            objs = [objs]
        elif isinstance(objs, dict):
            objs = objs.itervalues()
        bw_objs = []
        for obj in objs:
            if isinstance(obj, NodePath):
#.........这里部分代码省略.........
开发者ID:jhamrick,项目名称:scenesim,代码行数:103,代码来源:bulletbase.py

示例2: Balls

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import getRigidBodies [as 别名]
class Balls(ShowBase):
  def __init__(self):
    ShowBase.__init__(self)
    self.title = OnscreenText(text="0 balls",
      parent=base.a2dBottomRight, align=TextNode.ARight,
      fg=(1, 1, 1, 1), pos=(-0.1, 0.1), scale=.08,
      shadow=(0, 0, 0, 0.5))
    # exit on esc
    self.accept('escape', sys.exit)
    # disable standart mouse based camera control
    self.disableMouse()
    # set camera position
    self.camera.setPos(0, -30, 25)
    self.camera.lookAt(0, 0, 0)
    #
    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))

    self.taskMgr.add(self.updateWorld, 'updateWorld')
    self.setupLight()
    # down
    self.makePlane(0, Vec3(0, 0, 1), (0, 0, 0), (0, 0, 0))
    # up
    self.makePlane(1, Vec3(0, 0, -1), (0, 0, 10), (0, 0, 0))
    # left
    self.makePlane(2, Vec3(1, 0, 0), (-5, 0, 5), (0, 0, 90))
    # right
    self.makePlane(3, Vec3(-1, 0, 0), (5, 0, 5), (0, 0, -90))
    # top
    self.makePlane(4, Vec3(0, 1, 0), (0, -5, 5), (0, 90, 0))
    # buttom
    self.makePlane(5, Vec3(0, -1, 0), (0, 5, 5), (0, -90, 0))

    self.accept('mouse1', self.pickBall)
    self.accept('mouse3', self.releaseBall)
    self.accept('arrow_up', partial(self.rotateCube, hpr = (0, ROTATE_SPEED, 0)))
    self.accept('arrow_down', partial(self.rotateCube, hpr = (0, -ROTATE_SPEED, 0)))
    self.accept('arrow_left', partial(self.rotateCube, hpr = (0, 0, -ROTATE_SPEED)))
    self.accept('arrow_right', partial(self.rotateCube, hpr = (0, 0, ROTATE_SPEED)))
    self.accept('space', self.shakeBalls)
    self.accept('page_up', self.addRandomBall)
    self.accept('page_down', self.rmBall)

    self.ballCnt = 0
    self.ballColors = {}
    for num in xrange(DEFAULT_BALLS):
      self.addRandomBall()
    self.picked = set([])

  def setupLight(self):
    ambientLight = AmbientLight("ambientLight")
    ambientLight.setColor((.8, .8, .8, 1))
    directionalLight = DirectionalLight("directionalLight")
    directionalLight.setDirection(LVector3(0, 45, -45))
    directionalLight.setColor((0.2, 0.2, 0.2, 1))
    render.setLight(render.attachNewNode(directionalLight))
    render.setLight(render.attachNewNode(ambientLight))

  def updateWorld(self, task):
    dt = globalClock.getDt()
    # bug #1455084, simple doPhysics(dt) does nothing
    # looks like fixed already
    self.world.doPhysics(dt, 1, 1. / 60.)
    return task.cont

  def rayCollision(self):
    if self.mouseWatcherNode.hasMouse():
      mouse = self.mouseWatcherNode.getMouse()
      pointFrom, pointTo = Point3(), Point3()
      self.camLens.extrude(mouse, pointFrom, pointTo)
      pointFrom = render.getRelativePoint(self.cam, pointFrom)
      pointTo = render.getRelativePoint(self.cam, pointTo)
      hits = self.world.rayTestAll(pointFrom, pointTo).getHits()
      return sorted(hits, key = lambda x: (x.getHitPos() - pointFrom).length())
    return []

  def pickBall(self):
      hits = self.rayCollision()
      for hit in hits:
        hit_node = hit.getNode()
        if 'ball' in hit_node.getName():
          self.picked.add(hit_node.getName())
          NodePath(hit_node.getChild(0).getChild(0)).setColor(HIGHLIGHT)

  def releaseBall(self):
    hits = self.rayCollision()
    if hits:
      foundBall = False
      for picked in hits:
        hit_node = picked.getNode()
        if 'ball' in hit_node.getName():
          foundBall = True
          x, y, z = picked.getHitPos()
          bodies = self.world.getRigidBodies()
          for elem in bodies:
            name = elem.getName()
            if name in self.picked:
              # apply some physics
              node = NodePath(elem.getChild(0).getChild(0))
              node_x, node_y, node_z = node.getPos(render)
#.........这里部分代码省略.........
开发者ID:r3t,项目名称:master-term1-gamedev,代码行数:103,代码来源:main.py

示例3: PhysicsManager

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

#.........这里部分代码省略.........
    def __addTriangleMesh(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1), dynamic=True):        
        
        mesh = BulletTriangleMesh()
      
        def one():
            geom = model.node().getGeom(0)            
            mesh.addGeom(geom)
            return []

        children =  model.findAllMatches('**/+GeomNode') or one()

        model.flattenLight()

        for piece in children:
            geom = piece.node().getGeom(0)
            mesh.addGeom(geom)

        shape = BulletTriangleMeshShape(mesh, dynamic=dynamic )
        body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )

    # def __addPlane(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ):
    #     shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
    #     node = BulletRigidBodyNode(model.getName())
    #     node.addShape(shape)
    #     np = render.attachNewNode(node)
    #     np.setPos( pos )
    #     model.reparentTo(np)
    #     self.world.attachRigidBody(node)

    def setBodyProps(self, body, props):        
        body.setMass( props['mass'] )
        body.setFriction( props['friction'] )
        body.setRestitution( props['restitution'] )
        body.setAngularDamping( props['adamping'] )
        body.setLinearDamping( props['ldamping'] )
        body.setAngularSleepThreshold( props['asleep'] )
        body.setLinearSleepThreshold( props['lsleep'] )
        if not props['deactivation']:
            body.setDeactivationEnabled( False )
        body.setKinematic( props['kinematic'] )

    def characterController(self, name, height, mass, radius, step_height):
        shape = BulletCapsuleShape(radius, height - 2*radius, ZUp)
        body = BulletRigidBodyNode(name)
        body.setMass(mass)
        body.addShape(shape)
        return BulletCharacterControllerNode(shape, step_height, name)
    
    def debug(self):
        from panda3d.bullet import BulletDebugNode
        debugNP = render.attachNewNode(BulletDebugNode('Debug') )
        #debugNP.show()
        debugNP.node().showWireframe(True)
        debugNP.node().showConstraints(True)
        debugNP.node().showBoundingBoxes(False)
        debugNP.node().showNormals(False)        
        self.world.setDebugNode(debugNP.node())
        return debugNP

    def getSize(self,model):        
        hpr = model.getHpr()
        model.setHpr(0,0,0)
        minLimit, maxLimit = model.getTightBounds()
        model.setHpr(hpr) 
        return maxLimit - minLimit

    def setShape(self, model, body):        
        #To Re-Do
        name = model.getName()

        pos,hpr,scale = model.getPos(), model.getHpr(), model.getScale()    

        shapetype = re.findall("[-a-z]+",name.lower())[0].split('-')

        shapetype = filter(None,shapetype)
        
        if shapetype[0] in self.addShape.keys():
            self.addShape[shapetype[0]](body,model,pos,hpr,scale)

        not '-' in name or model.remove()

    def createCompound(self, model, body):
        children = model.find('**/*').getChildren() or model.getChildren()

        [self.setShape(child,body) for child in children]

    def cleanup(self):
        rbs = self.world.getRigidBodies()
        for body in rbs:
            self.world.removeRigidBody(body)
            print 'PhysicsManager: removing rigidbody'

    def destroy(self):
        self.cleanup()
        del self.addShape
        del self.world
        print 'destroy PhysicsManager'

    def __del__(self):
        print 'delete PhysicsManager'
开发者ID:fredukita,项目名称:Pandark-Project,代码行数:104,代码来源:physicsmanager.py


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