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


Python BulletWorld.doPhysics方法代码示例

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


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

示例1: TerrainPhysics

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [as 别名]
class TerrainPhysics():
    def __init__(self, ):
        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))


    def setup(self, terrain, player):
        """Bullet has to be started before some things in the program to avoid crashes."""
        self.terrain = terrain
        self.player = player

        # Demo
        spawn = player.attachNewNode("spawnPoint")
        spawn.setPos(0, -5, 7)
        self.demo = TerrainPhysicsDemo2(self.world, spawn)
        taskMgr.add(self.update, 'physics')

    def test(self):
        self.demo.start()

    def update(self, task):
        dt = globalClock.getDt()
        self.world.doPhysics(dt)
        return task.cont
开发者ID:StephenLujan,项目名称:Panda-3d-Procedural-Terrain-Engine,代码行数:27,代码来源:physics.py

示例2: PhysicsSystem

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [as 别名]
class PhysicsSystem(sandbox.EntitySystem):
    """System that interacts with the Bullet physics world"""
    def init(self):
        self.accept("addSpaceship", self.addSpaceship)
        self.world = BulletWorld()

    def begin(self):
        dt = globalClock.getDt()
        self.world.doPhysics(dt)
        #world.doPhysics(dt, 10, 1.0/180.0)

    def process(self, entity):
        pass

    def addSpaceship(self, component, shipName, position, linearVelcocity):
        component.bulletShape = BulletSphereShape(5)
        component.node = BulletRigidBodyNode(shipName)
        component.node.setMass(1.0)
        component.node.addShape(component.bulletShape)
        component.nodePath = universals.solarSystemRoot.attachNewNode(component.node)
        addBody(component.node)
        position = sandbox.get_system(solarSystem.SolarSystemSystem).solarSystemRoot.find("**/Earth").getPos()
        #component.nodePath.setPos(position + Point3(6671, 0, 0))
        component.nodePath.setPos(position)
        #component.node.setLinearVelocity(Vec3(0, 7.72983, 0))
        component.node.setLinearVelocity(linearVelcocity)
开发者ID:croxis,项目名称:itf,代码行数:28,代码来源:physics.py

示例3: __init__

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [as 别名]
class World:
    def __init__(self):
        self.init_bullet()
        self.init_skybox()

    def init_bullet(self):
        self.bullet_world = BulletWorld()

    def update_bullet(self, task):
        dt = ClockObject.getGlobalClock().getDt()
        self.bullet_world.doPhysics(dt)
        return task.cont

    def init_skybox(self):
        # This should probably have its own class..
        self.sky_material = Material()
        self.sky_material.clearAmbient()
        self.sky_material.clearEmission()
        self.sky_material.setAmbient(VBase4(1, 1, 1, 1))

        # This loads "basic_skybox_#" # being 0-6
        # If the skybox was made in spacescape the files must be renamed to
        # work properly, and the 2 and 3 files should be switched.
        self.skybox_texture = loader.loadCubeMap("images/skybox/red_nebula_purple_flares/Red_nebula_#.png")

        # TODO: Figure out a way (if possible) to allow 3d objects to be seen
        # through the skysphere, It already kinda does this, but its weird.

        self.skybox = NodePath(loader.loadModel("models/skybox.x"))
        self.skybox.setLightOff()
        self.skybox.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # self.skybox.setTwoSided(True) BETTER ^
        self.skybox.setScale(5000)
        self.skybox.clearDepthWrite
        self.skybox.setDepthWrite(False)
        self.skybox.setMaterial(self.sky_material, 1)
        self.skybox.setTexture(self.skybox_texture)
        self.skybox.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
        # This makes it so objects behind the skybox are rendered
        self.skybox.setBin("back_to_front", 40)
        # projects the texture as it looks from render
        self.skybox.setTexProjector(TextureStage.getDefault(), render, self.skybox)
        self.skybox.setCompass()
        self.skybox.reparentTo(base.camera)
开发者ID:simmpole,项目名称:Space-Fighter,代码行数:46,代码来源:World.py

示例4: GameState

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [as 别名]
class GameState(ShowBase):
    def __init__(self):
        loadPrcFile("server-config.prc")
        ShowBase.__init__(self)
        self.__rotations = {}

        # Panda pollutes the global namespace.  Some of the extra globals can be referred to in nicer ways
        # (for example self.render instead of render).  The globalClock object, though, is only a global!  We
        # create a reference to it here, in a way that won't upset PyFlakes.
        self.globalClock = __builtins__["globalClock"]

        # Set up physics: the ground plane and the capsule which represents the player.
        self.world = BulletWorld()

        # The ground first:
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        node = BulletRigidBodyNode("Ground")
        node.addShape(shape)
        np = self.render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)

        # Create a task to update the scene regularly.
        self.taskMgr.add(self.update, "UpdateTask")

    # Update the scene by turning objects if necessary, and processing physics.
    def update(self, task):
        asyncore.loop(timeout=0.1, use_poll=True, count=1)
        Player.update_all()

        for node, angular_velocity in self.__rotations.iteritems():
            node.setAngularMovement(angular_velocity)

        dt = self.globalClock.getDt()
        self.world.doPhysics(dt)
        return task.cont

    def set_angular_velocity(self, node, angular_velocity):
        if angular_velocity != 0:
            self.__rotations[node] = angular_velocity
        elif node in self.__rotations:
            del self.__rotations[node]
开发者ID:SidDark,项目名称:friendlyfruit,代码行数:44,代码来源:gamestate.py

示例5: PhysicsMgr

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

    def __init__(self, _game, _gravity=(0, 0, -9)):

    	self.game = _game
    	self.physicsWorld = BulletWorld()
    	self.physicsWorld.setGravity(Vec3(_gravity))

    def startPhysics(self):
    	taskMgr.add(self.updatePhysics, "update-physics")

    def stopPhysics(self):
    	taskMgr.remove("update-physics")

    def setPhysicsDebug(self, _bool=False):
        debugNode = BulletDebugNode('Debug')
        self.debugNP = render.attachNewNode(debugNode)

        if _bool:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            self.debugNP = render.attachNewNode(debugNode)
            self.physicsWorld.setDebugNode(self.debugNP.node())
            self.debugNP.show()
        else:
            self.debugNP.hide()
            #debugNode = None

    def updatePhysics(self, task):
    	dt = globalClock.getDt()
        self.physicsWorld.doPhysics(dt, 5, 1.0/240.0)

        return task.cont
开发者ID:grimfang,项目名称:lext,代码行数:38,代码来源:physicsManager.py

示例6: Game

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [as 别名]
class Game(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        #Camera pos
        self.cam.setPos(0, 0, 20)

        self.world_create(1000, 1000)

    def world_create(self, sizex, sizey):
        self.worldNP = self.render.attachNewNode('World')

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

        self.shape = BulletPlaneShape(Vec3(0, 0, 1), 1)

        self.groundNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Floor'))
        self.groundNP.node().addShape(self.shape)

        self.world.attachRigidBody(self.groundNP.node())

        # Load model
        self.ground = self.loader.loadModel("Models/floor_basic.egg")
        self.ground.reparentTo(self.groundNP)

        # Scale and position model
        self.ground.setScale(sizex, sizey, 0)
        self.ground.setPos(0, 0, 0)

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

    def update(self, task):
        dt = globalClock.getDt()
        self.world.doPhysics(dt, 10, 1.0/180.0)
        return Task.cont
开发者ID:2M1R,项目名称:YABG,代码行数:38,代码来源:YetAnotherBallGame.py

示例7: TestApplication

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

#.........这里部分代码省略.........
    for i in range(0,len(platform_details)):
      p = platform_details[i]
      topleft = (p[0],p[1])
      size = Vec3(p[2],p[3],p[4])
      self.addPlatform(topleft, size,'Platform%i'%(i))


  def addPlatform(self,topleft,size,name):

    # Visual
    visual = loader.loadModel('models/box.egg')
    visual.setTexture(loader.loadTexture('models/iron.jpg'))
    bounds = visual.getTightBounds()
    extents = Vec3(bounds[1] - bounds[0])
    scale_factor = 1/max([extents.getX(),extents.getY(),extents.getZ()])
    visual.setScale(size.getX()*scale_factor,size.getY()*scale_factor,size.getZ()*scale_factor)
    
    # Box (static)
    platform = self.world_node_.attachNewNode(BulletRigidBodyNode(name))
    platform.node().setMass(0)
    platform.node().addShape(BulletBoxShape(size/2))
    platform.setPos(Vec3(topleft[0] + 0.5*size.getX(),0,topleft[1]-0.5*size.getZ()))
    platform.setCollideMask(BitMask32.allOn())
    visual.instanceTo(platform)

    self.physics_world_.attachRigidBody(platform.node())
    self.object_nodes_.append(platform)

  def update(self, task):

    self.clock_.tick()
    dt = self.clock_.getDt()
    self.processInput(dt)    
    self.physics_world_.doPhysics(dt, 5, 1.0/180.0)
    self.updateCamera()
  

    

    return task.cont 

  def processInput(self,dt):
  
    activate = False
    obj = self.controlled_objects_[self.controlled_obj_index_]

    if self.kinematic_mode_:
      obj.node().setKinematic(True)
      return
    else:
      obj.node().setKinematic(False)

    vel = obj.node().getLinearVelocity()
    w = obj.node().getAngularVelocity()

  
    if self.input_state_.isSet('right'): 
      vel.setX(2)
      activate = True

    if self.input_state_.isSet('left'): 
      vel.setX(-2)
      activate = True

    if self.input_state_.isSet('jump'): 
      vel.setZ(4)
开发者ID:jrgnicho,项目名称:platformer_games_project,代码行数:70,代码来源:test_sprite_animation.py

示例8: BulletBase

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

#.........这里部分代码省略.........
            # Remove the objects from the world.
            try:
                self.world.remove(obj)
            except AttributeError:
                DeprecationWarning("Upgrade to Panda3d 1.9.")
                for attr in ("removeRigidBody", "removeConstraint",
                             "removeGhost"):
                    remove = getattr(self.world, attr)
                    try:
                        remove(obj)
                    except TypeError:
                        pass
                    else:
                        break

    def remove_all(self):
        """ Remove all objects from world."""
        objs = (self.world.getCharacters() + self.world.getConstraints() +
                self.world.getGhosts() + self.world.getRigidBodies() +
                self.world.getSoftBodies() + self.world.getVehicles())
        self.remove(objs)

    @property
    def gravity(self):
        """ Get gravity on self.world. """
        return self.world.getGravity()

    @gravity.setter
    def gravity(self, gravity):
        """ Set gravity on self.world. """
        self.world.setGravity(Vec3(*gravity))

    def step(self, *args, **kwargs):
        """ Wrapper for BulletWorld.doPhysics."""
        # Defaults.
        dt = args[0] if len(args) > 0 else self.sim_par["size"]
        n_subs = args[1] if len(args) > 1 else self.sim_par["n_subs"]
        size_sub = args[2] if len(args) > 2 else self.sim_par["size_sub"]
        force = kwargs.get("force", None)
        if force:
            bodies, vecpos, dur = force
            dt0 = np.clip(dur, 0., dt)
            n_subs0 = int(np.ceil(n_subs * dt0 / dt))
            dt1 = dt - dt0
            n_subs1 = n_subs - n_subs0 + 1
            for body in bodies:
                body.applyForce(Vec3(*vecpos[0]), Point3(*vecpos[1]))
            # With force.
            self.world.doPhysics(dt0, n_subs0, size_sub)
            for body in bodies:
                body.clearForces()
        else:
            dt1 = dt
            n_subs1 = n_subs
        # With no force.
        self.world.doPhysics(dt1, n_subs1, size_sub)

    @staticmethod
    def attenuate_velocities(bodies, linvelfac=0., angvelfac=0.):
        """ Zeros out the bodies' linear and angular velocities."""
        # Iterate through bodies, re-scaling their velocity vectors
        for body in bodies:
            linvel0 = body.getLinearVelocity()
            angvel0 = body.getAngularVelocity()
            # .normalize() returns True if the length is > 0
            if linvel0.normalize():
开发者ID:jhamrick,项目名称:scenesim,代码行数:70,代码来源:bulletbase.py

示例9: World

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [as 别名]
class World():
    CULLDISTANCE = 10
    def __init__(self, size):
        self.bw = BulletWorld()
        self.bw.setGravity(0,0,0)
        self.size = size
        self.perlin = PerlinNoise2()

        #utilities.app.accept('bullet-contact-added', self.onContactAdded) 
        #utilities.app.accept('bullet-contact-destroyed', self.onContactDestroyed) 

        self.player = Player(self)
        self.player.initialise()

        self.entities = list()
        self.bgs = list()
        self.makeChunk(Point2(0,0), Point2(3.0, 3.0)) 

        self.cmap = buildMap(self.entities, self.player.location)

        self.mps = list()

        self.entities.append(Catcher(Point2(10, 10), self.player, self.cmap, self))

    def update(self, timer):
        dt = globalClock.getDt()
        self.bw.doPhysics(dt, 5, 1.0/180.0)
        
        self.doHits(Flame)

        self.doHits(Catcher)

        for entity in self.entities:
            if entity.remove == True:
                entity.destroy()
                self.entities.remove(entity)

        self.player.update(dt)
        self.cmap = buildMap(self.entities, self.player.location)

        for entity in self.entities:
            entity.update(dt)

    def doHits(self, hit_type):
        for entity in self.entities:
            if isinstance(entity, hit_type):
                ctest = self.bw.contactTest(entity.bnode)
                if ctest.getNumContacts() > 0:
                    entity.removeOnHit()
                    mp =  ctest.getContacts()[0].getManifoldPoint()
                    if isinstance(ctest.getContacts()[0].getNode0().getPythonTag("entity"), hit_type):
                        ctest.getContacts()[0].getNode1().getPythonTag("entity").hitby(hit_type, mp.getIndex0())
                    else:    
                        ctest.getContacts()[0].getNode0().getPythonTag("entity").hitby(hit_type, mp.getIndex0())

    def makeChunk(self, pos, size):
        self.bgs.append(utilities.loadObject("stars", depth=100, scaleX=200, scaleY=200.0, pos=Point2(pos.x*worldsize.x,pos.y*worldsize.y)))
        genFillBox(self, Point2(5,5), 3, 6, 'metalwalls')
        genBox(self, Point2(10,5), 2, 2, 'metalwalls')
        #self.entities[0].bnode.applyTorque(Vec3(0,50,10))

    def addEntity(self, entity):
        self.entities.append(entity)

    def onContactAdded(self, node1, node2):
        e1 = node1.getPythonTag("entity")
        e2 = node2.getPythonTag("entity")

        if isinstance(e1, Flame):
            e1.remove = True
        if isinstance(e2, Flame):
            e2.remove = True

        print "contact"
    
    def onContactDestroyed(self, node1, node2):
        return
开发者ID:michaeltchapman,项目名称:gravbot,代码行数:79,代码来源:world.py

示例10: Balls

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [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

示例11: RollingEve

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

#.........这里部分代码省略.........
		self.taskMgr.add(self.update_world,'update')
		self.taskMgr.add(self.update_camera,'cam-update')  
      	
	def update_camera(self,task):
		if self.camera_views['normal'] is True:
			self.normal_view()
		elif self.camera_views['top'] is True:
			self.top_view()
		elif self.camera_views['right'] is True:
			self.right_view()
		elif self.camera_views['left'] is True:
			self.left_view()
		elif self.camera_views['first_person'] is True:
			self.first_person()
			if inputState.isSet('camera_up'):
				if base.camera.getP() < 45:
					base.camera.setP(base.camera.getP() + 1)
			if inputState.isSet('camera_down'):
				if base.camera.getP() > -90:
					base.camera.setP(base.camera.getP() - 1)
		return task.cont
		

	#	WORLD UPDATE TASK	#
	def update_world(self,task):
		check = self.eve.currentControllerNode.isOnGround()				# Task that updates physics world every frame
        	dt = globalClock.getDt()
       		self.eve.updateEveAnim()
		

		# Update info on stats frame		
		self.interface.bar['text'] = str(int(self.eve.health)) + ' / 100'
		self.interface.bar['value'] = int(self.eve.health)
		self.world.doPhysics(dt, 10, 1/180.0)		# Update physics world
		if check == False and self.eve.currentControllerNode.isOnGround() is True:
			self.eve.finishJump()
			self.eve.state['jumping'] = False
		
		if self.current_level == 'L1':
			death = -26
		elif self.current_level == 'L2':
			death = 900


		if self.eve.currentNP.getZ() < death:
			self.eve.health -= 10	# Damage taken for falling off the map
			if self.eve.health > 0:
				self.eve.reset()
				self.eve.currentNP.setH(90)
			else:
				self.interface.hide_game_interface()
				self.interface.game_over()
				self.user.add_to_leaderboard(self.current_level)
				return task.done
		if self.levelFinish is True:
			if self.complete.status() is not self.complete.PLAYING and self.alreadyPlayed is False:
				self.interface.hide_game_interface()
				self.alreadyPlayed = True
				self.complete.play()
			self.interface.level_passed()
			self.user.add_to_leaderboard(self.current_level)
			return task.done

		if self.eve.health <= 0 or self.game_over is True:		
			self.interface.hide_game_interface()
			self.interface.game_over()
开发者ID:cgaldamez14,项目名称:rolling-eve,代码行数:70,代码来源:main.py

示例12: World

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

#.........这里部分代码省略.........
        #    steering += dt * steeringIncrement
        #    steering = min(steering, steeringClamp)
        #
        #if (self.keyMap["right"] != 0):
        #    steering -= dt * steeringIncrement
        #    steering = max(steering, -steeringClamp)
        #
        # Apply steering to front wheels
        #self.mainCharRef.vehicle.setSteeringValue(steering, 0)
        #self.mainCharRef.vehicle.setSteeringValue(steering, 1)
        #
        # Apply engine and brake to rear wheels
        #self.mainCharRef.vehicle.applyEngineForce(engineForce, 2)
        #self.mainCharRef.vehicle.applyEngineForce(engineForce, 3)
        #self.mainCharRef.vehicle.setBrake(brakeForce, 2)
        #self.mainCharRef.vehicle.setBrake(brakeForce, 3)

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.
        #if (self.keyMap["forward"] != 0) or (self.keyMap["backward"] != 0) or (self.keyMap["left"] != 0) or (
        #            self.keyMap["right"] != 0):
        #    if self.isMoving is False:
        #        self.mainCharRef.run()
        #        self.isMoving = True
        #
        #else:
        #    if self.isMoving:
        #        self.mainCharRef.walk()
        #        self.isMoving = False

        dt = globalClock.getDt()

        self.mainCharRef.processInput(inputState, dt)
        self.bulletWorld.doPhysics(dt, 10, 0.02)

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        #camvec = self.mainChar.getPos() - base.camera.getPos()
        #camvec.setZ(0)
        #camdist = camvec.length()
        #camvec.normalize()
        #if (camdist > 10.0):
        #    base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10))
        #    camdist = 10.0
        #if (camdist < 5.0):
        #    base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist))
        #    camdist = 5.0

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        #self.floater.setPos(self.mainChar.getPos())
        #self.floater.setZ(self.mainChar.getZ() + 2.0)
        #base.camera.lookAt(self.floater)

        self.bulletWorld.doPhysics(dt)

        return task.cont

    def startConnection(self):
        """Create a connection to the remote host.

        If a connection cannot be created, it will ask the user to perform
        additional retries.
开发者ID:2015-CS454,项目名称:rr-team,代码行数:70,代码来源:Main+-+Copie.py

示例13: App

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

#.........这里部分代码省略.........
        self.createPlane()

        self.animated_rig = ExposedJointRig('walking', { 'walk': 'walking-animation.egg' })
        self.animated_rig.reparentTo(self.render)
        self.animated_rig.setPos(0, 0, -98)
        self.animated_rig.createLines(VBase4(0.5, 0.75, 1.0, 1.0))
        self.animated_rig.pose('walk', 0)

        self.physical_rig = RigidBodyRig()
        self.physical_rig.reparentTo(self.render)
        self.physical_rig.setPos(0, 0, -98)
        self.physical_rig.createColliders(self.animated_rig)
        self.physical_rig.createConstraints()
        self.physical_rig.setCollideMask(BitMask32.bit(1))
        self.physical_rig.attachRigidBodies(self.world)
        self.physical_rig.attachConstraints(self.world)

        self.control_rig = ControlJointRig('walking')
        self.control_rig.reparentTo(self.render)
        self.control_rig.setPos(0, 0, -98)
        self.control_rig.createLines(VBase4(1.0, 0.75, 0.5, 1.0))
        self.control_rig.matchPose(self.animated_rig)

        self.disable_collisions()

        self.is_paused = True

        self.accept('escape', sys.exit)
        self.accept('space', self.toggle_pause)

    def toggle_pause(self):
        if self.is_paused:
            self.is_paused = False
            self.taskMgr.add(self.update, 'update')
        else:
            self.is_paused = True
            self.taskMgr.remove('update')

    def disable_collisions(self):
        for i in range(32):
            self.world.setGroupCollisionFlag(i, i, False)
        self.world.setGroupCollisionFlag(0, 1, True)

    def setupDebug(self):
        node = BulletDebugNode('Debug')
        node.showWireframe(True)

        self.world.setDebugNode(node)

        np = self.render.attachNewNode(node)
        np.show()

    def createLens(self, aspect_ratio, fov=60.0, near=1.0, far=1000.0):
        lens = PerspectiveLens()
        lens.setFov(fov)
        lens.setAspectRatio(aspect_ratio)
        lens.setNearFar(near, far)
        return lens

    def setupCamera(self, width, height):
        self.cam.setPos(-200, -100, 0)
        self.cam.lookAt(0, -100, 0)
        self.cam.node().setLens(self.createLens(width / height))

    def createLighting(self):
        light = DirectionalLight('light')
        light.set_color(VBase4(0.2, 0.2, 0.2, 1))

        np = self.render.attach_new_node(light)
        np.setPos(0, -200, 0)
        np.lookAt(0, 0, 0)

        self.render.set_light(np)

        light = AmbientLight('ambient')
        light.set_color(VBase4(0.4, 0.4, 0.4, 1))

        np = self.render.attachNewNode(light)

        self.render.setLight(np)

    def createPlane(self):
        rb = BulletRigidBodyNode('Ground')
        rb.addShape(BulletPlaneShape(Vec3(0, 0, 1), 1))
        rb.setFriction(1.0)

        np = self.render.attachNewNode(rb)
        np.setPos(Vec3(0, 0, -100))
        np.setCollideMask(BitMask32.bit(0))

        self.world.attachRigidBody(rb)

        return np

    def update(self, task):
        self.animated_rig.pose('walk', globalClock.getFrameCount() * 0.5)
        self.physical_rig.matchPose(self.animated_rig)
        self.control_rig.matchPhysicalPose(self.physical_rig)
        self.world.doPhysics(globalClock.getDt(), 10, 1.0 / 180.0)
        return task.cont
开发者ID:BarkingMouseStudio,项目名称:python-experiments,代码行数:104,代码来源:app.py

示例14: BallInMaze

# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import doPhysics [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

示例15: SMWorld

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

#.........这里部分代码省略.........
				lineCount = len(metaLines)
				self.snowflakeCount = lineCount - 2
			
				# First Line: Player's starting position
				# EX: 50,50,50 (NO SPACES)
				playerLine = metaLines[0]
				playerPosList = playerLine.split(",")
				playerInitX = int(playerPosList[0])
				playerInitY = int(playerPosList[1])
				playerInitZ = int(playerPosList[2])
				self.playerObj.playerNP.setPos(playerInitX, playerInitY, playerInitZ)
				self.playerObj.startX = playerInitX
				self.playerObj.startY = playerInitY
				self.playerObj.startZ = playerInitZ
			
				# 2nd Line: Deathzone Height
				# ONE INTEGER
				self.deathHeight = int(metaLines[1])
			
				
				self.snowflakePositions = []
				print("Snowflake Count: " + str(self.snowflakeCount))
				for i in xrange(0, self.snowflakeCount):
					sfline = metaLines[i+2]
					sfList = sfline.split(",")
					sfx = int(sfList[0])
					sfy = int(sfList[1])
					sfz = int(sfList[2])
					self.snowflakePositions.append(Point3(sfx, sfy, sfz))
					print("New snowflake to add: (" + str(sfx) + "," + str(sfy) + "," + str(sfz) + ")")
				self.snowflakeCounter.setMaxValue(self.snowflakeCount)
				
				#load new map
				self.mapName = str(self.mapID)
				self.heightMap = self.setupHeightmap(self.mapName)
				self.deathZone = self.setupDeathzone(self.deathHeight)
					
				
				self.loadingText.cleanup() 
			else:
				taskMgr.remove('UpdateTask')
				self.endImage=OnscreenImage(image = "../res/icons/endgame1.png", pos = (0.0, 0.0, 0.0), scale = (1.35, 2, 1))
				
		
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Update the debug text.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def updateStats(self):
		pos = self.playerObj.getPosition()
		x = pos.getX()
		y = pos.getY()
		z = pos.getZ()
		vel = self.playerObj.getVelocity()
		vx = str(round(vel.getX(), 1))
		vy = str(round(vel.getY(), 1))
		vz = str(round(vel.getZ(), 1))
		sx = str(round(x, 1))
		sy = str(round(y, 1))
		sz = str(round(z, 1))
		rx = str(round(self.downRayTest.getX(), 2))
		ry = str(round(self.downRayTest.getY(), 2))
		rz = str(round(self.terrSteepness, 2))
		fric = str(round(self.playerObj.getFriction(), 2))
		ip = str(round(self.playerObj.getIceCoefficient(), 2))
		sp = str(round(self.playerObj.getSnowCoefficient(), 2))
		tHeight = str(round(self.getTerrainHeight(Point3(x, y, z)), 1))
		self.textObj.editText("yetiPos", "Position: (" + sx + ", " + sy + ", " + sz + ")")
		self.textObj.editText("yetiVel", "Velocity: (" + vx + ", " + vy + ", " + vz + ")")
		self.textObj.editText("yetiFric", "Friction: " + fric)
		self.textObj.editText("onIce", "Ice(%): " + ip)
		self.textObj.editText("onSnow", "Snow(%): " + sp)
		self.textObj.editText("terrHeight", "T Height: " + tHeight)
		self.textObj.editText("terrSteepness", "Steepness: " + rz)

	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# throw Snowball
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	def throw(self):
		self.throwing = True
		size = self.ballObj.getSize()
		#zoom camera and grab pos you wish to throw
		self.camObj.aimMode()
		taskMgr.add(self.controlCamera, "camera-task")
		rotation = self.camObj.getH()
		pitch =self.camObj.getP()
		self.ballObj.throwBall(size, pitch, rotation)
		#fix camera
		#self.throwing = False
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Update the world. Called every frame.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def update(self, task):
		dt = globalClock.getDt()
		self.worldBullet.doPhysics(dt)
		# self.goat1.AIUpdate()
		# self.goat2.AIUpdate()
		self.playerMove()
		return task.cont
开发者ID:tbackus127,项目名称:AbominableSnowmanGame,代码行数:104,代码来源:SMWorld.py


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