本文整理汇总了Python中panda3d.bullet.BulletWorld.setGravity方法的典型用法代码示例。如果您正苦于以下问题:Python BulletWorld.setGravity方法的具体用法?Python BulletWorld.setGravity怎么用?Python BulletWorld.setGravity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.bullet.BulletWorld
的用法示例。
在下文中一共展示了BulletWorld.setGravity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TerrainPhysics
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [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
示例2: __init__
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class TestApplication:
def __init__(self):
self.setupPhysics()
self.clock_ = ClockObject()
def sim(self):
while True:
try:
time.sleep(LOOP_DELAY)
self.clock_.tick()
self.physics_world_.doPhysics(self.clock_.getDt(), 5, 1.0/180.0)
# printing location of first box
print "Box 0: %s"%(str(self.boxes_[0].getPos()))
except KeyboardInterrupt:
print "Simulation finished"
sys.exit()
def setupPhysics(self):
# setting up physics world and parent node path
self.physics_world_ = BulletWorld()
self.world_node_ = NodePath()
self.physics_world_.setGravity(Vec3(0, 0, -9.81))
# setting up ground
self.ground_ = self.world_node_.attachNewNode(BulletRigidBodyNode('Ground'))
self.ground_.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 0))
self.ground_.setPos(0,0,0)
self.ground_.setCollideMask(BitMask32.allOn())
self.physics_world_.attachRigidBody(self.ground_.node())
self.boxes_ = []
num_boxes = 20
side_length = 0.2
size = Vec3(side_length,side_length,side_length)
start_pos = Vec3(-num_boxes*side_length,0,10)
for i in range(0,20):
self.addBox("name %i"%(i),size,start_pos + Vec3(i*2*side_length,0,0))
def addBox(self,name,size,pos):
# Box (dynamic)
box = self.world_node_.attachNewNode(BulletRigidBodyNode(name))
box.node().setMass(1.0)
box.node().addShape(BulletBoxShape(size))
box.setPos(pos)
box.setCollideMask(BitMask32.allOn())
self.physics_world_.attachRigidBody(box.node())
self.boxes_.append(box)
示例3: PhysicsMgr
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [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
示例4: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [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
示例5: BulletWorld
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
import direct.directbase.DirectStart
from panda3d.core import Vec3
from panda3d.bullet import BulletWorld
from panda3d.bullet import BulletPlaneShape
from panda3d.bullet import BulletRigidBodyNode
from panda3d.bullet import BulletBoxShape
base.cam.setPos(0, -10, 0)
base.cam.lookAt(0, 0, 0)
# World
world = BulletWorld()
world.setGravity(Vec3(0, 0, -9.81))
# Plane
shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
node = BulletRigidBodyNode('Ground')
node.addShape(shape)
np = render.attachNewNode(node)
np.setPos(0, 0, -2)
world.attachRigidBody(node)
# Box
shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
node = BulletRigidBodyNode('Box')
node.setMass(1.0)
node.addShape(shape)
np = render.attachNewNode(node)
np.setPos(0, 0, 2)
world.attachRigidBody(node)
model = loader.loadModel('models/box.egg')
示例6: Balls
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [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)
#.........这里部分代码省略.........
示例7: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
#.........这里部分代码省略.........
force = self.hLeg.getTotalForce()
t = self.hLeg.getTotalTorque()
self.hLegText.setText("High Leg:\nForce: %0.2f,%0.2f,%0.2f\nTorque: %0.2f,%0.2f,%0.2f" % (force.x, force.y, force.z, t.x,t.y,t.z))
force = self.lLeg.getTotalForce()
t = self.lLeg.getTotalTorque()
self.lLegText.setText("Low Leg:\nForce: %0.2f,%0.2f,%0.2f\nTorque: %0.2f,%0.2f,%0.2f" % (force.x, force.y, force.z, t.x,t.y,t.z))
f = self.foot.getTotalForce()
t = self.foot.getTotalTorque()
self.footText.setText("Foot:\nForce: %0.2f,%0.2f,%0.2f\nTorque: %0.2f,%0.2f,%0.2f" % (f.x,f.y,f.z, t.x,t.y,t.z))
dt = globalClock.getDt()
self.world.doPhysics(dt, 20, 1.0/180.0)
return task.cont
def cleanup(self):
self.worldNP.removeNode()
self.worldNP = None
self.world = None
def setup(self):
self.worldNP = render.attachNewNode('World')
# World
self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
self.debugNP.show()
self.debugNP.node().showWireframe(True)
self.debugNP.node().showConstraints(True)
self.debugNP.node().showBoundingBoxes(False)
self.debugNP.node().showNormals(True)
self.world = BulletWorld()
self.world.setGravity(Vec3(0, 0, -9.81))
self.world.setDebugNode(self.debugNP.node())
# Box 0
shape = BulletBoxShape(Vec3(1, 1, 1))
body0 = BulletRigidBodyNode('Box 0')
bodyNP = self.worldNP.attachNewNode(body0)
bodyNP.node().addShape(shape)
bodyNP.setCollideMask(BitMask32.allOn())
bodyNP.setPos(0, 0, 12.2)
visNP = loader.loadModel('models/box.egg')
visNP.clearModelNodes()
visNP.reparentTo(bodyNP)
self.world.attachRigidBody(body0)
# Box A
shape = BulletBoxShape(Vec3(0.1, 0.1, 5))
self.hLeg = BulletRigidBodyNode('Box A')
bodyNP = self.worldNP.attachNewNode(self.hLeg)
bodyNP.node().addShape(shape)
bodyNP.node().setMass(1.0)
bodyNP.node().setDeactivationEnabled(False)
bodyNP.setCollideMask(BitMask32.allOn())
bodyNP.setPos(0, 0, 5.1)
visNP = loader.loadModel('models/box.egg')
visNP.clearModelNodes()
visNP.setScale(Vec3(0.2, 0.2, 10))
visNP.reparentTo(bodyNP)
示例8: App
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class App(ShowBase):
def __init__(self, args):
ShowBase.__init__(self)
headless = args["--headless"]
width = args["--width"]
height = args["--height"]
self.save_path = args["<save_path>"]
globalClock.setMode(ClockObject.MNonRealTime)
globalClock.setDt(0.02) # 20ms per frame
self.setBackgroundColor(0.9, 0.9, 0.9)
self.createLighting()
if not headless:
self.setupCamera(width, height, Vec3(0, -20, 0), Vec3(0, 0, 0))
self.world = BulletWorld()
self.world.setGravity(Vec3(0, 0, -9.81))
self.setupDebug()
self.createPlane(Vec3(0, 0, -11))
self.animated_rig = ExposedJointRig("walking", {"walk": "walking-animation.egg"})
self.animated_rig.reparentTo(self.render)
self.animated_rig.setPos(0, 0, 0)
self.animated_rig.setScale(0.1, 0.1, 0.1)
self.animated_rig.createLines(VBase4(0.5, 0.75, 1.0, 1.0))
self.physical_rig = RigidBodyRig()
self.physical_rig.reparentTo(self.render)
self.physical_rig.setPos(0, 0, 0)
self.physical_rig.setScale(0.1, 0.1, 0.1)
self.physical_rig.createColliders(self.animated_rig)
self.physical_rig.createConstraints(offset_scale=0.1)
self.physical_rig.setCollideMask(BitMask32.bit(1))
self.physical_rig.attachRigidBodies(self.world)
self.physical_rig.attachConstraints(self.world)
self.disableCollisions()
# self.setAnimationFrame(0)
self.physical_rig.matchPose(self.animated_rig)
self.frame_count = self.animated_rig.getNumFrames("walk")
self.babble_count = 10
self.train_count = self.frame_count * self.babble_count * 1000
self.test_count = self.frame_count * self.babble_count * 100
widgets = [
progressbar.SimpleProgress(),
" ",
progressbar.Percentage(),
" ",
progressbar.Bar(),
" ",
progressbar.FileTransferSpeed(format="%(scaled)5.1f/s"),
" ",
progressbar.ETA(),
" ",
progressbar.Timer(format="Elapsed: %(elapsed)s"),
]
self.progressbar = progressbar.ProgressBar(widgets=widgets, max_value=self.train_count + self.test_count)
self.progressbar.start()
self.X_train = []
self.Y_train = []
self.X_test = []
self.Y_test = []
self.accept("escape", sys.exit)
self.taskMgr.add(self.update, "update")
def disableCollisions(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, pos, look):
self.cam.setPos(pos)
self.cam.lookAt(look)
self.cam.node().setLens(self.createLens(width / height))
#.........这里部分代码省略.........
示例9: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class Game(DirectObject):
def __init__(self):
base.setBackgroundColor(0.1, 0.1, 0.8, 1)
base.setFrameRateMeter(True)
base.cam.setPos(0, -60, 20)
base.cam.lookAt(0, 0, 0)
# Light
alight = AmbientLight('ambientLight')
alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
alightNP = render.attachNewNode(alight)
dlight = DirectionalLight('directionalLight')
dlight.setDirection(Vec3(1, 1, -1))
dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
dlightNP = render.attachNewNode(dlight)
render.clearLight()
render.setLight(alightNP)
render.setLight(dlightNP)
# Input
self.accept('escape', self.doExit)
self.accept('r', self.doReset)
self.accept('f1', self.toggleWireframe)
self.accept('f2', self.toggleTexture)
self.accept('f3', self.toggleDebug)
self.accept('f5', self.doScreenshot)
# Task
taskMgr.add(self.update, 'updateWorld')
# Physics
self.setup()
# _____HANDLER_____
def doExit(self):
self.cleanup()
sys.exit(1)
def doReset(self):
self.cleanup()
self.setup()
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 update(self, task):
dt = globalClock.getDt()
self.world.doPhysics(dt, 10, 0.008)
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.debugNP.showTightBounds()
#self.debugNP.showBounds()
self.world = BulletWorld()
self.world.setGravity(Vec3(0, 0, -9.81))
self.world.setDebugNode(self.debugNP.node())
# Ground
p0 = Point3(-20, -20, 0)
p1 = Point3(-20, 20, 0)
p2 = Point3(20, -20, 0)
p3 = Point3(20, 20, 0)
mesh = BulletTriangleMesh()
mesh.addTriangle(p0, p1, p2)
mesh.addTriangle(p1, p2, p3)
shape = BulletTriangleMeshShape(mesh, dynamic=False)
np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh'))
#.........这里部分代码省略.........
示例10: TestApplication
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class TestApplication(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.setupRendering()
self.setupControls()
self.setupPhysics()
self.clock_ = ClockObject()
self.controlled_obj_index_ = 0
self.kinematic_mode_ = False
# Task
taskMgr.add(self.update, 'updateWorld')
def setupRendering(self):
self.setBackgroundColor(0.1, 0.1, 0.8, 1)
self.setFrameRateMeter(True)
# Light
alight = AmbientLight('ambientLight')
alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
alightNP = self.render.attachNewNode(alight)
dlight = DirectionalLight('directionalLight')
dlight.setDirection(Vec3(1, 1, -1))
dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
dlightNP = self.render.attachNewNode(dlight)
self.render.clearLight()
self.render.setLight(alightNP)
self.render.setLight(dlightNP)
def setupControls(self):
# Input (Events)
self.accept('escape', self.doExit)
self.accept('r', self.doReset)
self.accept('f1', self.toggleWireframe)
self.accept('f2', self.toggleTexture)
self.accept('f3', self.toggleDebug)
self.accept('f5', self.doScreenshot)
self.accept('n', self.selectNextControlledObject)
self.accept('k',self.toggleKinematicMode)
self.accept('p',self.printInfo)
self.accept('q',self.zoomIn)
self.accept('a',self.zoomOut)
self.accept('s',self.toggleRightLeft)
# Inputs (Polling)
self.input_state_ = InputState()
self.input_state_.watchWithModifiers("right","arrow_right")
self.input_state_.watchWithModifiers('left', 'arrow_left')
self.input_state_.watchWithModifiers('jump', 'arrow_up')
self.input_state_.watchWithModifiers('stop', 'arrow_down')
self.input_state_.watchWithModifiers('roll_right', 'c')
self.input_state_.watchWithModifiers('roll_left', 'z')
self.input_state_.watchWithModifiers('roll_stop', 'x')
self.title = addTitle("Panda3D: Sprite Animation")
self.inst1 = addInstructions(0.06, "ESC: Quit")
self.inst2 = addInstructions(0.12, "Up/Down: Jump/Stop")
self.inst3 = addInstructions(0.18, "Left/Right: Move Left / Move Rigth")
self.inst4 = addInstructions(0.24, "z/x/c : Rotate Left/ Rotate Stop / Rotate Right")
self.inst5 = addInstructions(0.30, "n: Select Next Character")
self.inst6 = addInstructions(0.36, "k: Toggle Kinematic Mode")
self.inst7 = addInstructions(0.42, "q/a: Zoom in / Zoom out")
self.inst7 = addInstructions(0.48, "s: Toggle Rigth|Left ")
self.inst7 = addInstructions(0.54, "p: Print Info")
def printInfo(self):
self.sprt_animator_.printInfo()
def setupPhysics(self):
# setting up physics world and parent node path
self.physics_world_ = BulletWorld()
self.world_node_ = self.render.attachNewNode('world')
self.cam.reparentTo(self.world_node_)
self.physics_world_.setGravity(Vec3(0, 0, -9.81))
self.debug_node_ = self.world_node_.attachNewNode(BulletDebugNode('Debug'))
self.debug_node_.show()
self.debug_node_.node().showWireframe(True)
self.debug_node_.node().showConstraints(True)
self.debug_node_.node().showBoundingBoxes(False)
self.debug_node_.node().showNormals(True)
# setting up ground
self.ground_ = self.world_node_.attachNewNode(BulletRigidBodyNode('Ground'))
self.ground_.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 0))
self.ground_.setPos(0,0,0)
self.ground_.setCollideMask(BitMask32.allOn())
self.physics_world_.attachRigidBody(self.ground_.node())
self.object_nodes_ = []
self.controlled_objects_=[]
#.........这里部分代码省略.........
示例11: World
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [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
示例12: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class Game(DirectObject):
def __init__(self):
base.setBackgroundColor(0.1, 0.1, 0.8, 1)
base.setFrameRateMeter(True)
base.cam.setPos(0, -40, 10)
base.cam.lookAt(0, 0, 0)
# Light
alight = AmbientLight('ambientLight')
alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
alightNP = render.attachNewNode(alight)
dlight = DirectionalLight('directionalLight')
dlight.setDirection(Vec3(5, 0, -2))
dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
dlightNP = render.attachNewNode(dlight)
render.clearLight()
render.setLight(alightNP)
render.setLight(dlightNP)
# Input
self.accept('escape', self.doExit)
self.accept('r', self.doReset)
self.accept('f1', self.toggleWireframe)
self.accept('f2', self.toggleTexture)
self.accept('f3', self.toggleDebug)
self.accept('f5', self.doScreenshot)
# Task
taskMgr.add(self.update, 'updateWorld')
# Physics
self.setup()
# _____HANDLER_____
def doExit(self):
self.cleanup()
sys.exit(1)
def doReset(self):
self.cleanup()
self.setup()
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 update(self, task):
dt = globalClock.getDt()
self.world.doPhysics(dt, 10, 0.004)
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())
# Soft body world information
info = self.world.getWorldInfo()
info.setAirDensity(1.2)
info.setWaterDensity(0)
info.setWaterOffset(0)
info.setWaterNormal(Vec3(0, 0, 0))
# Softbody
def make(p1):
n = 8
p2 = p1 + Vec3(10, 0, 0)
bodyNode = BulletSoftBodyNode.makeRope(info, p1, p2, n, 1)
bodyNode.setTotalMass(50.0)
#.........这里部分代码省略.........
示例13: Application
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class Application(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.world = BulletWorld()
self.world.setGravity(Vec3(0, 0, -9.81))
self.height = 85.0
self.img = PNMImage(Filename('height1.png'))
self.shape = BulletHeightfieldShape(self.img, self.height, ZUp)
self.offset = self.img.getXSize() / 2.0 - 0.5
self.terrain = GeoMipTerrain('terrain')
self.terrain.setHeightfield(self.img)
self.terrain.setColorMap("grass.png")
self.terrainNP = self.terrain.getRoot()
self.terrainNP.setSz(self.height)
self.terrainNP.setPos(-self.offset, -self.offset, -self.height / 2.0)
self.terrain.getRoot().reparentTo(render)
self.terrain.generate()
self.node = BulletRigidBodyNode('Ground')
self.node.addShape(self.shape)
self.np = render.attachNewNode(self.node)
self.np.setPos(0, 0, 0)
self.world.attachRigidBody(self.node)
self.info = self.world.getWorldInfo()
self.info.setAirDensity(1.2)
self.info.setWaterDensity(0)
self.info.setWaterOffset(0)
self.info.setWaterNormal(Vec3(0, 0, 0))
self.cam.setPos(20, 20, 20)
self.cam.setHpr(0, 0, 0)
self.model = loader.loadModel('out6.egg')
#self.model.setPos(0.0, 0.0, 0.0)
self.model.flattenLight()
min, max = self.model.getTightBounds()
size = max
mmax = size[0]
if size[1] > mmax:
mmax = size[1]
if size[2] > mmax:
mmax = size[2]
self.rocketScale = 20.0/mmax / 2
shape = BulletBoxShape(Vec3(size[0]*self.rocketScale, size[1]*self.rocketScale, size[2]*self.rocketScale))
self.ghostshape = BulletBoxShape(Vec3(size[0]*self.rocketScale, size[1]*self.rocketScale, size[2]*self.rocketScale))
self.ghost = BulletRigidBodyNode('Ghost')
self.ghost.addShape(self.ghostshape)
self.ghostNP = render.attachNewNode(self.ghost)
self.ghostNP.setPos(19.2220401046, 17.5158313723, 35.2665607047 )
#self.ghostNP.setCollideMask(BitMask32(0x0f))
self.model.setScale(self.rocketScale)
self.world.attachRigidBody(self.ghost)
self.model.copyTo(self.ghostNP)
self.rocketnode = BulletRigidBodyNode('rocketBox')
self.rocketnode.setMass(1.0)
self.rocketnode.addShape(shape)
self.rocketnp = render.attachNewNode(self.rocketnode)
self.rocketnp.setPos(0.0, 0.0, 40.0)
tex = loader.loadTexture('crate.jpg')
self.model.find('**/Line001').setTexture(tex, 1)
#self.rocketnp.setTexture(tex)
self.model.setScale(self.rocketScale)
self.world.attachRigidBody(self.rocketnode)
self.model.copyTo(self.rocketnp)
self.hh = 35.0
print self.ghostNP.getPos()
self.accept('w', self.eventKeyW)
self.accept('r', self.eventKeyR)
self.taskMgr.add(self.update, 'update')
self.massive = self.getdata('data.txt')
self.massiveResampled = self.resample(self.massive)
self.posInArray = 0
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.timerNow = 0.0
self.taskMgr.add(self.timerTask, 'timerTask')
def checkGhost(self):
'''
ghost = self.ghostNP.node()
if ghost.getNumOverlappingNodes() > 1:
print ghost.getNumOverlappingNodes()
for node in ghost.getOverlappingNodes():
print node
'''
result = self.world.contactTest(self.ghost)
for contact in result.getContacts():
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
class PhysicsManager:
def __init__(self, root_nodepath, world):
self.world = BulletWorld()
self.world.setGravity((0, 0, -9.81))
self._timestep = 1 / world.tick_rate
# # Seems that this does not function
# on_contact_added = PythonCallbackObject(self._on_contact_added)
# self.world.set_contact_added_callback(on_contact_added)
# on_filter = PythonCallbackObject(self._filter_collision)
# self.world.set_filter_callback(on_filter)
self.listener = DirectObject()
self.listener.accept('bullet-contact-added', self._on_contact_added)
self.listener.accept('bullet-contact-destroyed', self._on_contact_removed)
self.tracked_contacts = defaultdict(int)
self.existing_collisions = set()
# Debugging info
debug_node = BulletDebugNode('Debug')
debug_node.showWireframe(True)
debug_node.showConstraints(True)
debug_node.showBoundingBoxes(False)
debug_node.showNormals(False)
# Add to world
self.debug_nodepath = root_nodepath.attachNewNode(debug_node)
self.world.set_debug_node(debug_node)
self.debug_nodepath.show()
def _on_contact_removed(self, node_a, node_b):
self.tracked_contacts[(node_a, node_b)] -= 1
def _on_contact_added(self, node_a, node_b):
self.tracked_contacts[(node_a, node_b)] += 1
def _dispatch_collisions(self):
# Dispatch collisions
existing_collisions = self.existing_collisions
for pair, contact_count in self.tracked_contacts.items():
# If is new collision
if contact_count > 0 and pair not in existing_collisions:
existing_collisions.add(pair)
# Dispatch collision
node_a, node_b = pair
entity_a = node_a.get_python_tag("entity")
entity_b = node_b.get_python_tag("entity")
if not (entity_a and entity_b):
continue
contact_result = ContactResult(self.world, node_a, node_b)
entity_a.messenger.send("collision_started", entity=entity_b, contacts=contact_result.contacts_a)
entity_b.messenger.send("collision_started", entity=entity_a, contacts=contact_result.contacts_b)
# Ended collision
elif contact_count == 0 and pair in existing_collisions:
existing_collisions.remove(pair)
# Dispatch collision
node_a, node_b = pair
entity_a = node_a.get_python_tag("entity")
entity_b = node_b.get_python_tag("entity")
if not (entity_a and entity_b):
continue
entity_a.messenger.send("collision_stopped", entity_b)
entity_b.messenger.send("collision_stopped", entity_a)
def add_entity(self, entity, component):
body = component.body
self.world.attach_rigid_body(body)
body.set_python_tag("entity", entity)
def remove_entity(self, entity, component):
body = component.body
self.world.remove_rigid_body(body)
body.clear_python_tag("entity")
def tick(self):
self.world.do_physics(self._timestep)
self._dispatch_collisions()
def resimulate_pawn(self, pawn):
pass
示例15: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import setGravity [as 别名]
#.........这里部分代码省略.........
v.normalize()
v *= 100.0
# Create bullet
shape = BulletSphereShape(0.3)
body = BulletRigidBodyNode('Bullet')
bodyNP = self.worldNP.attachNewNode(body)
bodyNP.node().addShape(shape)
bodyNP.node().setMass(1.0)
bodyNP.node().setLinearVelocity(v)
bodyNP.node().setCcdMotionThreshold(1e-7);
bodyNP.node().setCcdSweptSphereRadius(0.50);
bodyNP.setCollideMask(BitMask32.allOn())
bodyNP.setPos(pFrom)
visNP = loader.loadModel('models/ball.egg')
visNP.setScale(0.8)
visNP.reparentTo(bodyNP)
self.world.attachRigidBody(bodyNP.node())
# Remove the bullet again after 2 seconds
taskMgr.doMethodLater(2, self.doRemove, 'doRemove',
extraArgs=[bodyNP],
appendTask=True)
def doRemove(self, bodyNP, task):
self.world.removeRigidBody(bodyNP.node())
bodyNP.removeNode()
return task.done
# ____TASK___
def update(self, task):
dt = globalClock.getDt()
self.world.doPhysics(dt, 20, 1.0/180.0)
return task.cont
def cleanup(self):
self.worldNP.removeNode()
self.worldNP = None
self.world = None
def setup(self):
self.worldNP = render.attachNewNode('World')
# World
self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
self.debugNP.show()
self.debugNP.node().showWireframe(True)
self.debugNP.node().showConstraints(True)
self.debugNP.node().showBoundingBoxes(False)
self.debugNP.node().showNormals(False)
self.world = BulletWorld()
self.world.setGravity(Vec3(0, 0, -9.81))
self.world.setDebugNode(self.debugNP.node())
# Box A
shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
bodyA = BulletRigidBodyNode('Box A')
bodyNP = self.worldNP.attachNewNode(bodyA)
bodyNP.node().addShape(shape)
bodyNP.setCollideMask(BitMask32.allOn())
bodyNP.setPos(-2, 0, 1)
visNP = loader.loadModel('models/box.egg')
visNP.clearModelNodes()
visNP.reparentTo(bodyNP)
self.world.attachRigidBody(bodyA)
# Box B
shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
bodyB = BulletRigidBodyNode('Box B')
bodyNP = self.worldNP.attachNewNode(bodyB)
bodyNP.node().addShape(shape)
bodyNP.node().setMass(1.0)
bodyNP.node().setDeactivationEnabled(False)
bodyNP.setCollideMask(BitMask32.allOn())
bodyNP.setPos(2, 0, 1)
visNP = loader.loadModel('models/box.egg')
visNP.clearModelNodes()
visNP.reparentTo(bodyNP)
self.world.attachRigidBody(bodyB)
# Hinge
pivotA = Point3(2, 0, 0)
pivotB = Point3(-4, 0, 0)
axisA = Vec3(0, 0, 1)
axisB = Vec3(0, 0, 1)
hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
hinge.setDebugDrawSize(2.0)
hinge.setLimit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
self.world.attachConstraint(hinge)