本文整理汇总了Python中panda3d.bullet.BulletWorld.attachRigidBody方法的典型用法代码示例。如果您正苦于以下问题:Python BulletWorld.attachRigidBody方法的具体用法?Python BulletWorld.attachRigidBody怎么用?Python BulletWorld.attachRigidBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.bullet.BulletWorld
的用法示例。
在下文中一共展示了BulletWorld.attachRigidBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rayHit
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
def rayHit(pfrom, pto, geom):
"""
NOTE: this function is quite slow
find the nearest collision point between vec(pto-pfrom) and the mesh of nodepath
:param pfrom: starting point of the ray, Point3
:param pto: ending point of the ray, Point3
:param geom: meshmodel, a panda3d datatype
:return: None or Point3
author: weiwei
date: 20161201
"""
bulletworld = BulletWorld()
facetmesh = BulletTriangleMesh()
facetmesh.addGeom(geom)
facetmeshnode = BulletRigidBodyNode('facet')
bullettmshape = BulletTriangleMeshShape(facetmesh, dynamic=True)
bullettmshape.setMargin(0)
facetmeshnode.addShape(bullettmshape)
bulletworld.attachRigidBody(facetmeshnode)
result = bulletworld.rayTestClosest(pfrom, pto)
if result.hasHit():
return result.getHitPos()
else:
return None
示例2: __init__
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [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: genAvailableFAGsSgl
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
def genAvailableFAGsSgl(base, basepath, baseMat4, objpath, objMat4, gdb, handpkg):
"""
find the collision freeairgrips of objpath without considering rotation
:param base: panda base
:param basepath: the path of base object
:param objpath: the path of obj object, the object to be assembled
:param baseMat4, objMat4: all in world coordinates, not relative
:param gdb: grasp db
:param handpkg: hand package
:return: [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]
author: weiwei
date: 20170307
"""
bulletworld = BulletWorld()
robothand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1])
basetrimesh = trimesh.load_mesh(basepath)
basenp = pg.packpandanp(basetrimesh.vertices, basetrimesh.face_normals, basetrimesh.faces)
basenp.setMat(baseMat4)
basebullnode = cd.genCollisionMeshNp(basenp, base.render)
bulletworld.attachRigidBody(basebullnode)
dbobjname = os.path.splitext(os.path.basename(objpath))[0]
objfag = Fag(gdb, dbobjname, handpkg)
assgripcontacts = []
assgripnormals = []
assgriprotmat4s = []
assgripjawwidth = []
assgripidfreeair = []
for i, rotmat in enumerate(objfag.freegriprotmats):
assgrotmat = rotmat*objMat4
robothand.setMat(assgrotmat)
# detect the collisions when hand is open!
robothand.setJawwidth(robothand.jawwidthopen)
hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp)
result0 = bulletworld.contactTest(hndbullnode)
robothand.setJawwidth(objfag.freegripjawwidth[i])
hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp)
result1 = bulletworld.contactTest(hndbullnode)
if (not result0.getNumContacts()) and (not result1.getNumContacts()):
cct0 = objMat4.xformPoint(objfag.freegripcontacts[i][0])
cct1 = objMat4.xformPoint(objfag.freegripcontacts[i][1])
cctn0 = objMat4.xformPoint(objfag.freegripnormals[i][0])
cctn1 = objMat4.xformPoint(objfag.freegripnormals[i][1])
assgripcontacts.append([cct0, cct1])
assgripnormals.append([cctn0, cctn1])
assgriprotmat4s.append(assgrotmat)
assgripjawwidth.append(objfag.freegripjawwidth[i])
assgripidfreeair.append(objfag.freegripids[i])
return [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]
示例4: GameState
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [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]
示例5: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [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
示例6: BulletWorld
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
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')
model.flattenLight()
model.reparentTo(np)
# Update
def update(task):
示例7: Balls
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
#.........这里部分代码省略.........
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)
ix = (x - node_x)
iy = (y - node_y)
dir = atan2(iy, ix)
dx, dy = SPEED * cos(dir), SPEED * sin(dir)
elem.applyCentralImpulse(LVector3(dx, dy, z))
node.setColor(self.ballColors[elem.getName()])
if foundBall:
self.picked = set([])
def rotateCube(self, hpr = (0, 0, 0)):
# h, p, r = z, x, y
# FIXME: something completely wrong goes here
# need some time to figure it out
planes = render.findAllMatches('**/plane*')
for plane in planes:
oldParent = plane.getParent()
pivot = render.attachNewNode('pivot')
pivot.setPos(render, 0, 0, 5)
plane.wrtReparentTo(pivot)
pivot.setHpr(render, Vec3(hpr))
if oldParent.getName() != 'render':
oldParent.removeNode()
def shakeBalls(self):
balls = filter(lambda x: 'ball' in x.getName(), self.world.getRigidBodies())
for ball in balls:
dx = uniform(-SHAKE_SPEED, SHAKE_SPEED)
dy = uniform(-SHAKE_SPEED, SHAKE_SPEED)
dz = uniform(-SHAKE_SPEED, SHAKE_SPEED)
ball.applyCentralImpulse(LVector3(dx, dy, dz))
def updateBallsCounter(self, num):
self.ballCnt += num
self.title.setText('%d balls' % (self.ballCnt))
def addRandomBall(self):
planes = render.findAllMatches('**/plane*')
x, y, z = zip(*[tuple(plane.getPos()) for plane in planes])
xPos = uniform(min(x), max(x))
yPos = uniform(min(y), max(y))
zPos = uniform(min(z), max(z))
self.makeBall(self.ballCnt, (xPos, yPos, zPos))
self.updateBallsCounter(1)
def rmBall(self):
if self.ballCnt != 0:
ball = render.find('**/ball_' + str(self.ballCnt - 1))
self.ballColors.pop(ball.getName())
ball.removeNode()
self.updateBallsCounter(-1)
def makePlane(self, num, norm, pos, hpr):
shape = BulletPlaneShape(norm, 0)
node = BulletRigidBodyNode('plane_' + str(num))
node.addShape(shape)
physics = render.attachNewNode(node)
physics.setPos(*pos)
self.world.attachRigidBody(node)
model = loader.loadModel('models/square')
model.setScale(10, 10, 10)
model.setHpr(*hpr)
model.setTransparency(TransparencyAttrib.MAlpha)
model.setColor(1, 1, 1, 0.25)
model.reparentTo(physics)
def makeColor(self):
return (random(), random(), random(), 1)
def makeBall(self, num, pos = (0, 0, 0)):
shape = BulletSphereShape(0.5)
node = BulletRigidBodyNode('ball_' + str(num))
node.setMass(1.0)
node.setRestitution(.9)
node.setDeactivationEnabled(False)
node.addShape(shape)
physics = render.attachNewNode(node)
physics.setPos(*pos)
self.world.attachRigidBody(node)
model = loader.loadModel('models/ball')
color = self.makeColor()
model.setColor(color)
self.ballColors['ball_' + str(num)] = color
model.reparentTo(physics)
示例8: step_physics
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
def step_physics(task):
dt = globalClock.getDt()
physics.doPhysics(dt)
return task.cont
s.taskMgr.add(step_physics, 'physics simulation')
# A physical object in the simulation
node = BulletRigidBodyNode('Box')
node.setMass(1.0)
node.addShape(BulletSphereShape(1))
# Attaching the physical object in the scene graph and adding
# a visible model to it
np = s.render.attachNewNode(node)
np.set_pos(0, 0, 0)
np.set_hpr(45, 0, 45)
m = loader.loadModel("models/smiley")
m.reparentTo(np)
physics.attachRigidBody(node)
# Let's actually see what's happening
base.cam.setPos(0, -10, 0)
base.cam.lookAt(0, 0, 0)
# Give the object a nudge and run the program
# the impulse vector is in world space, the position at which it is
# applied is in object space.
node.apply_impulse(Vec3(0, 0, 1), Point3(1, 0, 0))
node.apply_impulse(Vec3(0, 0, -1), Point3(-1, 0, 0))
s.run()
示例9: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
#.........这里部分代码省略.........
self.debugNP.hide()
def doScreenshot(self):
base.screenshot('Bullet')
def doSelect(self, i):
self.boxNP = self.boxes[i]
# ____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)
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), -1)
np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
np.node().addShape(shape)
np.setPos(0, 0, -1)
np.setCollideMask(BitMask32.bit(0))
self.world.attachRigidBody(np.node())
# Boxes
self.boxes = [None,]*6
for i in range(6):
shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))
np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-1'))
np.node().setMass(1.0)
np.node().addShape(shape)
self.world.attachRigidBody(np.node())
self.boxes[i] = np
visualNP = loader.loadModel('models/box.egg')
visualNP.reparentTo(np)
self.boxes[0].setPos(-3, -3, 0)
self.boxes[1].setPos( 0, -3, 0)
self.boxes[2].setPos( 3, -3, 0)
self.boxes[3].setPos(-3, 3, 0)
self.boxes[4].setPos( 0, 3, 0)
self.boxes[5].setPos( 3, 3, 0)
self.boxes[0].setCollideMask(BitMask32.bit(1))
self.boxes[1].setCollideMask(BitMask32.bit(2))
self.boxes[2].setCollideMask(BitMask32.bit(3))
self.boxes[3].setCollideMask(BitMask32.bit(1))
self.boxes[4].setCollideMask(BitMask32.bit(2))
self.boxes[5].setCollideMask(BitMask32.bit(3))
self.boxNP = self.boxes[0]
self.world.setGroupCollisionFlag(0, 1, True)
self.world.setGroupCollisionFlag(0, 2, True)
self.world.setGroupCollisionFlag(0, 3, True)
self.world.setGroupCollisionFlag(1, 1, False)
self.world.setGroupCollisionFlag(1, 2, True)
示例10: LabTask03
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
#.........这里部分代码省略.........
v.normalize()
v *= 70.0 * ratio
torqueOffset = random.random() * 10
#create bullet
shape = BulletSphereShape(0.5)
shape01 = BulletSphereShape(0.5)
shape02 = BulletSphereShape(0.5)
shape03 = BulletSphereShape(0.5)
body = BulletRigidBodyNode('Candle')
bodyNP = self.worldNP.attachNewNode(body)
bodyNP.node().addShape(shape, TransformState.makePos(Point3(0,0,0)))
bodyNP.node().addShape(shape01, TransformState.makePos(Point3(0,0.5,-0.5)))
bodyNP.node().addShape(shape02,TransformState.makePos(Point3(0,1,-1)))
bodyNP.node().addShape(shape03,TransformState.makePos(Point3(0,1.5,-1.5)))
bodyNP.node().setMass(100)
bodyNP.node().setFriction(1.0)
bodyNP.node().setLinearVelocity(v)
bodyNP.node().applyTorque(v*torqueOffset)
bodyNP.setPos(self.pFrom)
bodyNP.setCollideMask(BitMask32.allOn())
visNP = loader.loadModel('models/projectile.X')
visNP.setScale(0.7)
visNP.clearModelNodes()
visNP.reparentTo(bodyNP)
#self.bird = bodyNP.node()
if ccd:
bodyNP.node().setCcdMotionThreshold(1e-7)
bodyNP.node().setCcdSweptSphereRadius(0.5)
self.world.attachRigidBody(bodyNP.node())
#remove the bullet again after 1 sec
self.bullets = bodyNP
taskMgr.doMethodLater(5, self.removeBullet, 'removeBullet', extraArgs=[bodyNP],
appendTask = True)
def removeBullet(self, bulletNP, task):
self.cameraState = 'STAY'
self.fire = True
self.world.removeRigidBody(bulletNP.node())
bulletNP.removeNode()
if(self.attempts <= 0 and len(self.snowmans)>0):
self.gameState = 'LOSE'
self.doContinue()
return task.done
# ____TASK___
def processInput(self, dt):
force = Vec3(0, 0, 0)
torque = Vec3(0, 0, 0)
#print self.pTo.getY()
if inputState.isSet('forward'):
if(self.pTo.getZ() < 40):
self.pTo.addZ(0.5)
if inputState.isSet('reverse'):
if(self.pTo.getZ() > 0 ):
self.pTo.addZ(-0.5)
if inputState.isSet('left'):
if(self.pTo.getY() < 100):
示例11: __init__
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
#.........这里部分代码省略.........
#RPM limit
if self.RPM > 6000:
self.RPM = 6000
#Controls
inputState.watchWithModifiers("F", "arrow_up")
inputState.watchWithModifiers("B", "arrow_down")
inputState.watchWithModifiers("L", "arrow_left")
inputState.watchWithModifiers("R", "arrow_right")
do = DirectObject()
do.accept("escape", show_menu)
do.accept("1", V1)
do.accept("2", V2)
do.accept("3", V3)
do.accept("page_up", up)
do.accept("page_down", down)
do.accept("x-repeat", start_function)
do.accept("x", stop_function)
do.accept("p", parkingbrake)
do.accept("backspace", rotate)
do.accept("enter", horn)
do.accept("f12", take_screenshot)
do.accept("h", headlights)
#The ground
self.ground = BulletPlaneShape(Vec3(0, 0, 1,), 1)
self.ground_node = BulletRigidBodyNode("The ground")
self.ground_node.addShape(self.ground)
self.ground_np = render.attachNewNode(self.ground_node)
self.ground_np.setPos(0, 0, -2)
scene.attachRigidBody(self.ground_node)
self.ground_model = loader.loadModel("Models/plane.egg")
self.ground_model.reparentTo(render)
self.ground_model.setPos(0,0,-1)
self.ground_model.setScale(3)
self.ground_tex = loader.loadTexture("Textures/ground.png")
self.ground_tex2 = loader.loadTexture("Textures/ground2.png")
self.ground_tex3 = loader.loadTexture("Textures/ground3.png")
self.ground_model.setTexture(self.ground_tex, 1)
#The car
Car_shape = BulletBoxShape(Vec3(1, 2.0, 1.0))
Car_node = BulletRigidBodyNode("The Car")
Car_node.setMass(1200.0)
Car_node.addShape(Car_shape)
Car_np = render.attachNewNode(Car_node)
Car_np.setPos(0,0,3)
Car_np.setHpr(0,0,0)
Car_np.node().setDeactivationEnabled(False)
scene.attachRigidBody(Car_node)
Car_model = loader.loadModel("Models/Car.egg")
Car_model.reparentTo(Car_np)
Car_tex = loader.loadTexture("Textures/Car1.png")
Car_model.setTexture(Car_tex, 1)
self.Car_sim = BulletVehicle(scene, Car_np.node())
self.Car_sim.setCoordinateSystem(ZUp)
scene.attachVehicle(self.Car_sim)
#The inside of the car
Car_int = loader.loadModel("Models/inside.egg")
示例12: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
#.........这里部分代码省略.........
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()
#dt *= 0.01
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.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'))
np.node().addShape(shape)
np.setPos(0, 0, -2)
np.setCollideMask(BitMask32.allOn())
self.world.attachRigidBody(np.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 makeSB(pos, hpr):
import torus
geom = torus.makeGeom()
#geom = loader.loadModel('models/torus.egg') \
# .findAllMatches('**/+GeomNode').getPath(0).node() \
# .modifyGeom(0)
geomNode = GeomNode('')
geomNode.addGeom(geom)
node = BulletSoftBodyNode.makeTriMesh(info, geom)
node.linkGeom(geomNode.modifyGeom(0))
node.generateBendingConstraints(2)
node.getCfg().setPositionsSolverIterations(2)
node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFVertexFaceSoftSoft, True)
node.randomizeConstraints()
node.setTotalMass(50, True)
softNP = self.worldNP.attachNewNode(node)
softNP.setPos(pos)
softNP.setHpr(hpr)
self.world.attachSoftBody(node)
geomNP = softNP.attachNewNode(geomNode)
makeSB(Point3(-3, 0, 4), (0, 0, 0))
makeSB(Point3(0, 0, 4), (0, 90, 90))
makeSB(Point3(3, 0, 4), (0, 0, 0))
示例13: TestApplication
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [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_=[]
#.........这里部分代码省略.........
示例14: Game
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [as 别名]
#.........这里部分代码省略.........
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)
bodyNP = self.worldNP.attachNewNode(bodyNode)
self.world.attachSoftBody(bodyNode)
# Render option 1: Line geom
#geom = BulletSoftBodyNode.makeGeomFromLinks(bodyNode)
#bodyNode.linkGeom(geom)
#visNode = GeomNode('')
#visNode.addGeom(geom)
#visNP = bodyNP.attachNewNode(visNode)
# Render option 2: NURBS curve
curve = NurbsCurveEvaluator()
curve.reset(n + 2)
bodyNode.linkCurve(curve)
visNode = RopeNode('')
visNode.setCurve(curve)
visNode.setRenderMode(RopeNode.RMTube)
visNode.setUvMode(RopeNode.UVParametric)
visNode.setNumSubdiv(4)
visNode.setNumSlices(8)
visNode.setThickness(0.4)
visNP = self.worldNP.attachNewNode(visNode)
#visNP = bodyNP.attachNewNode(visNode) # --> renders with offset!!!
visNP.setTexture(loader.loadTexture('models/iron.jpg'))
#bodyNP.showBounds()
#visNP.showBounds()
return bodyNP
np1 = make(Point3(-2, -1, 8))
np2 = make(Point3(-2, 1, 8))
# Box
shape = BulletBoxShape(Vec3(2, 2, 6))
boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
boxNP.node().setMass(50.0)
boxNP.node().addShape(shape)
boxNP.setPos(10, 0, 8)
boxNP.setCollideMask(BitMask32.allOn())
self.world.attachRigidBody(boxNP.node())
np1.node().appendAnchor(np1.node().getNumNodes() - 1, boxNP.node())
np2.node().appendAnchor(np1.node().getNumNodes() - 1, boxNP.node())
visNP = loader.loadModel('models/box.egg')
visNP.clearModelNodes()
visNP.setScale(4, 4, 12)
visNP.reparentTo(boxNP)
示例15: Application
# 需要导入模块: from panda3d.bullet import BulletWorld [as 别名]
# 或者: from panda3d.bullet.BulletWorld import attachRigidBody [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():
#.........这里部分代码省略.........