class HLodDynamicObject(NodePath): def __init__(self, name, scene, visibleLODsDict={"eggfileName":("maxFar","minNear")}, collisionEgg=None, x0=0, y0=0, z0=0, parent=None, margin=0.02, mass=0, directRender=True, convex=True): self.name = name self.scene = scene NodePath.__init__(self,LODNode(name+"_LODNode")) ###LOD### for k in visibleLODsDict.keys(): v=base.loader.loadModel(k) v.reparentTo(self) self.node().addSwitch(visibleLODsDict[k][0],visibleLODsDict[k][1]) ######### self.body = BulletRigidBodyNode(self.name + "_RigidBody") self.attachNewNode(self.body) if collisionEgg != None: m = self.scene.Base.loader.loadModel(collisionEgg) if convex: sTuple = modelToConvex(m) else: sTuple = modelToShape(m) sTuple[0].setMargin(margin) self.body.addShape(sTuple[0], sTuple[1]) self.body.setMass(mass) self.body.setPythonTag("name", self.name + "_RigidBody") self.scene.world.attachRigidBody(self.body) self.setPos(x0, y0, z0) if directRender: self.reparentTo(self.scene.Base.render) elif parent != None: self.reparentTo(parent)
class Modulo(object): def __init__(self, world, x, y, w, h, parent_node): self._model = None self._initPhysics(world, x, y, w, h, parent_node) self._loadModel(x, y, h) def remove(self): if self._model is not None: self._model.remove() def _loadModel(self, x, y, h): self._model = loader.loadModel("../data/models/modulo.egg") self._model.setPos(0, 0, 0) self._model.reparentTo(self._modulo_node) def _initPhysics(self, world, x, y, w, h, parent_node): shape = BulletBoxShape(Vec3(w * 0.5, w * 0.5, h * 0.5)) self._rb_node = BulletRigidBodyNode('Box') self._rb_node.setMass(0) self._rb_node.addShape(shape) #self._rb_node.setAngularFactor(Vec3(0,0,0)) #self._rb_node.setDeactivationEnabled(False, True) world.attachRigidBody(self._rb_node) self._modulo_node = parent_node.attachNewNode(self._rb_node) self._modulo_node.setPos(x, y, h / 2.0)
def genHand(self, handz=100.0): # fgr0 boxx = 5.0 boxy = 2.0 boxz = 20.0 boxpx = 0.0 boxpy = 10.0 boxpz = handz shape = BulletBoxShape(Vec3(boxx, boxy, boxz)) # the parameters are half extends node = BulletRigidBodyNode('fgr0') node.addShape(shape) node.setTransform(TransformState.makePos(VBase3(boxpx, boxpy, boxpz))) self.bltWorld.attachRigidBody(node) base.pggen.plotBox(self.base.render, pos=[boxpx, boxpy, boxpz], x=boxx * 2.0, y=boxy * 2.0, z=boxz * 2.0, rgba=None) # fgr1 boxx = 5.0 boxy = 2.0 boxz = 20.0 boxpx = 0.0 boxpy = -10.0 boxpz = handz shape = BulletBoxShape(Vec3(boxx, boxy, boxz)) # the parameters are half extends node = BulletRigidBodyNode('fgr1') node.addShape(shape) node.setTransform(TransformState.makePos(VBase3(boxpx, boxpy, boxpz))) self.bltWorld.attachRigidBody(node) base.pggen.plotBox(self.base.render, pos=[boxpx, boxpy, boxpz], x=boxx * 2.0, y=boxy * 2.0, z=boxz * 2.0, rgba=None)
class Ball(object): def __init__(self, render, world, loader, player): self.render = render self.world = world self.loader = loader self.player = player self.dropHeight = 5 self.createItem() def createItem(self): self.collisionShape = BulletSphereShape(0.5) self.actor = BulletRigidBodyNode('Ball') self.actor.setMass(5.0) self.actor.addShape(self.collisionShape) self.np = self.render.attachNewNode(self.actor) self.np.setCollideMask(BitMask32.allOff()) self.x = self.player.getCharacterNP().getX() self.y = self.player.getCharacterNP().getY() self.z = self.player.getCharacterNP().getZ() + self.dropHeight self.np.setPos(self.x, self.y, self.z) self.world.attachRigidBody(self.actor) self.actorModelNP = self.loader.loadModel('models/sphere/ball.egg') self.actorModelNP.reparentTo(self.np) self.actorModelNP.setScale(0.5) self.actorModelNP.setPos(0, 0, 0) def getActor(self): return self.actor def getNP(self): return self.np
def genHand(self, handz=100.0): # fgr0 boxx = 5.0 boxy = 2.0 boxz = 20.0 boxpx = 0.0 boxpy = 10.0 boxpz = handz shape = BulletBoxShape(Vec3(boxx, boxy, boxz)) # the parameters are half extends node = BulletRigidBodyNode('fgr0') node.addShape(shape) node.setTransform(TransformState.makePos(VBase3(boxpx, boxpy, boxpz))) self.bltWorld.attachRigidBody(node) pg.plotBox(self.base.render, pos=[boxpx, boxpy, boxpz], x=boxx * 2.0, y=boxy * 2.0, z=boxz * 2.0, rgba=None) # fgr1 boxx = 5.0 boxy = 2.0 boxz = 20.0 boxpx = 0.0 boxpy = -10.0 boxpz = handz shape = BulletBoxShape(Vec3(boxx, boxy, boxz)) # the parameters are half extends node = BulletRigidBodyNode('fgr1') node.addShape(shape) node.setTransform(TransformState.makePos(VBase3(boxpx, boxpy, boxpz))) self.bltWorld.attachRigidBody(node) pg.plotBox(self.base.render, pos=[boxpx, boxpy, boxpz], x=boxx * 2.0, y=boxy * 2.0, z=boxz * 2.0, rgba=None)
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
def genCollisionMeshNp(nodepath, basenodepath=None, name='autogen'): """ generate the collision mesh of a nodepath using nodepath this function suppose the nodepath is a single model with one geomnode :param nodepath: the panda3d nodepath of the object :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ geomnodepath = nodepath.find("**/+GeomNode") geombullnode = BulletRigidBodyNode(name) geom = geomnodepath.node().getGeom(0) geomtf = nodepath.getTransform(base.render) if basenodepath is not None: geomtf = nodepath.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def genCollisionMeshMultiNp(nodepath, basenodepath=None, name='autogen'): """ generate the collision mesh of a nodepath using nodepath this function suppose the nodepath has multiple models with many geomnodes use genCollisionMeshMultiNp instead of genCollisionMeshNp for generality :param nodepath: the panda3d nodepath of the object :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ gndcollection = nodepath.findAllMatches("**/+GeomNode") geombullnode = BulletRigidBodyNode(name) for gnd in gndcollection: geom = gnd.node().getGeom(0) geomtf = gnd.getTransform(base.render) if basenodepath is not None: geomtf = gnd.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
def demoContinue(self): if self.newObjects < self.NrObjectToDrop: node = BulletRigidBodyNode('Box') node.setMass(1.0) node.addShape(self.shape) np = self.rbcnp.attachNewNode(node) np.setPos(self.spawnNP.getPos(render)) np.setHpr(randint(-45, 45), randint(-45, 45), randint(-45, 45)) self.world.attachRigidBody(node) bNP = self.model.copyTo(np) #bNP.setPos(self.spawnNP.getPos()) #bNP.setColor(random(), random(), random(), 1) #bNP.setHpr(randint(-45, 45), randint(-45, 45), randint(-45, 45)) #self.setUntextured(bNP) #bNP.setTexureOff() #np.setScale(10) np.flattenStrong() self.objects.append(np) self.newObjects += 1 self.rbcnp.node().collect() if self.newObjects < self.NrObjectToDrop: return False else: self.running = False return True
def __init__(self): PhysicsNodePath.__init__(self, 'can') self.shapeGroup = BitMask32.allOn() sph = BulletBoxShape(Vec3(2, 2, 2)) rbnode = BulletRigidBodyNode('can_body') rbnode.setMass(100.0) rbnode.addShape(sph, TransformState.makePos(Point3(0, 0, 1))) rbnode.setCcdMotionThreshold(1e-7) rbnode.setCcdSweptSphereRadius(0.5) self.mdl = loader.loadModel("phase_5/models/props/safe-mod.bam") self.mdl.setScale(6) self.mdl.setZ(-1) self.mdl.reparentTo(self) self.mdl.showThrough(CIGlobals.ShadowCameraBitmask) self.setupPhysics(rbnode) #self.makeShadow(0.2) self.reparentTo(render) self.setPos(base.localAvatar.getPos(render) + (0, 0, 20)) self.setQuat(base.localAvatar.getQuat(render))
def __init__(self): PhysicsNodePath.__init__(self, 'can') self.shapeGroup = BitMask32.allOn() sph = BulletCylinderShape(0.5, 1.2, ZUp) rbnode = BulletRigidBodyNode('can_body') rbnode.setMass(10.0) rbnode.addShape(sph) rbnode.setCcdMotionThreshold(1e-7) rbnode.setCcdSweptSphereRadius(0.5) self.mdl = loader.loadModel("phase_5/models/props/can.bam") self.mdl.setScale(11.0) self.mdl.setZ(-0.55) self.mdl.reparentTo(self) self.mdl.showThrough(CIGlobals.ShadowCameraBitmask) self.setupPhysics(rbnode) #self.makeShadow(0.2) self.reparentTo(render) self.setPos(base.localAvatar.getPos(render)) self.setQuat(base.localAvatar.getQuat(render)) dir = self.getQuat(render).xform(Vec3.forward()) amp = 10 self.node().setLinearVelocity(dir * amp)
class RocketPhys(Phys): def __init__(self, mdt, parent): Phys.__init__(self, mdt) self.parent = parent def fire(self): self.node = BulletRigidBodyNode('Box') self.node.setMass(10000) self.node.addShape(BulletSphereShape(.5)) self.np = self.parent.attachNewNode(self.node) self.np.setPos(0, 0, 1.5) eng.attach_rigid_body(self.node) self.mdt.gfx.gfx_np.reparentTo(self.np) self.mdt.gfx.gfx_np.setPos(0, 0, 0) rot_mat = Mat4() rot_mat.setRotateMat(self.parent.get_h(), (0, 0, 1)) self.node.setLinearVelocity(rot_mat.xformVec((0, 30, 0))) # continue to apply after firing def destroy(self): if hasattr(self, 'node'): # has not been fired eng.remove_rigid_body(self.node) self.np = self.np.remove_node() self.parent = None Phys.destroy(self)
class DynamicNp(DynamicObject): def __init__(self, name, model, game, pos): self.name = name self.game = game self.model = model self.geomNode = self.model.node() self.geom = self.geomNode.getGeom(0) # with triangle mesh it crashes #mesh = BulletTriangleMesh() #mesh.addGeom(self.geom) #self.shape = BulletTriangleMeshShape(mesh, dynamic=True) # with convex hull self.shape = BulletConvexHullShape() self.shape.addGeom(self.geom) self.node = BulletRigidBodyNode(self.name) self.node.setMass(10.0) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) self.slice_able = True
def init_objects(self): # Make Playfer Box shape = BulletBoxShape(Vec3(0.25, 0.25, 0.25)) node = BulletRigidBodyNode('Playfer Box') node.setMass(110.0) node.setFriction(1.0) node.addShape(shape) node.setAngularDamping(0.0) np = render.attachNewNode(node) np.setPos(-1.4, 1.7, -1.7) self.world.attachRigidBody(node) playferboxmodel = loader.loadModel('../data/mod/playferbox.egg') playferboxmodel.reparentTo(np) # Make Pendlepot shape = BulletBoxShape(Vec3(0.2, 0.15, 0.1)) node = BulletRigidBodyNode('Pendlepot') node.setMass(5.0) node.setFriction(1.0) node.addShape(shape) node.setAngularDamping(0.0) np = render.attachNewNode(node) np.setPos(-1.4, 1.7, -1.5) self.world.attachRigidBody(node) pendlepotmodel = loader.loadModel('../data/mod/pendlepot.egg') pendlepotmodel.reparentTo(np)
class DynamicModel(DynamicObject): def __init__(self, name, modelPath, game, pos): self.name = name self.modelPath = modelPath self.game = game self.model = self.game.loader.loadModel(self.modelPath) geomNodes = self.model.findAllMatches('**/+GeomNode') self.geomNode = geomNodes.getPath(0).node() self.geom = self.geomNode.getGeom(0) self.shape = BulletConvexHullShape() self.shape.addGeom(self.geom) self.node = BulletRigidBodyNode(self.name) self.node.setMass(10.0) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) self.slice_able = True
def createBody(self, _count, _type, _pos=(0, 0, 0)): radius = 0.4 shape = BulletSphereShape(radius) name = _type + "Dude" + str(_count) node = BulletRigidBodyNode(name) node.setMass(2.0) node.addShape(shape) #node.setDeactivationEnabled(False) np = render.attachNewNode(node) np.setCollideMask(BitMask32.allOn()) self.parent.physics_world.attachRigidBody(node) np.setPos(_pos) #model = loader.loadModel("assets/dude") #model.reparentTo(np) #model.setScale(0.4) dudeID = [1, 2, 3] tex = loader.loadTexture("dudes/dude{}_good.png".format( choice(dudeID))) cm = CardMaker('spritesMaker') sprite = NodePath(cm.generate()) sprite.setTexture(tex) sprite.reparentTo(np) sprite.setPos(-0.4, 0, -0.4) sprite.setCompass(render) sprite.setTransparency(1) sprite.setScale(0.8) return name, np
def genBulletCDMeshList(objcmlist, basenodepath=None, name='autogen'): """ generate the collision mesh of a nodepath using nodepathlist this function suppose the nodepathlist is a list of models with many geomnodes "Multi" means each nodepath in the nodepath list may have multiple nps (parent-child relations) use genCollisionMeshMultiNp instead if the meshes have parent-child relations :param nodepathlist: panda3d nodepathlist :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20190514 """ geombullnode = BulletRigidBodyNode(name) for objcm in objcmlist: gndcollection = objcm.objnp.findAllMatches("+GeomNode") for gnd in gndcollection: geom = copy.deepcopy(gnd.node().getGeom(0)) geomtf = gnd.getTransform(base.render) if basenodepath is not None: geomtf = gnd.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
class DynamicPlatform(DynamicObject): def __init__(self, name, game, x, y, z, pos): self.name = name self.game = game self.shape = BulletBoxShape(Vec3(x, y, z)) self.node = BulletRigidBodyNode(self.name) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) #self.model = self.game.loader.loadModel("models/crate.egg") #self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) #self.node.setFriction(5) #self.debugOff() self.speedVec = Vec3(0,0,0) self.lastPos = Vec3(self.getPos()) self.slice_able = False #self.node.setCcdMotionThreshold(1e-7) #self.node.setCcdSweptSphereRadius(0.5) def update(self, dt): return
def genBulletBoxes(env,world): boxes = list() for np in listNodes(env,"Collision_box_"): geom = np.node().getGeom(0) # get the minimum and maximum points vdata = geom.getVertexData() vertices = GeomVertexReader(vdata,'vertex') vmin = LPoint3() vmax = LPoint3() np.calcTightBounds(vmin,vmax) #Create the bullet box with center at (0,0) norm = vmax-vmin hnorm = LVecBase3(norm[0]*.5,norm[1]*.5,norm[2]*.5) shape = BulletBoxShape(hnorm) # create the surrounding nodes node = BulletRigidBodyNode('env') node.addShape(shape) enp = env.attachNewNode(node) enp.setPos(vmin+hnorm) # attach it to the world and save it for later world.attachRigidBody(node) boxes.append(enp.node()) # clean up the environment higherarchy np.removeNode() return boxes
def setupPhysics(self, radius=None, height=None): if not radius: radius = self.getWidth() if not height: height = self.getHeight() self.notify.debug("setupPhysics(r{0}, h{1}) hitboxData: {2}".format( radius, height, self.hitboxData)) # When the height is passed into BulletCapsuleShape, it's # talking about the height only of the cylinder part. # But what we want is the height of the entire capsule. #height -= (radius * 2) # The middle of the capsule is the origin by default. Push the capsule shape up # so the very bottom of the capsule is the origin. zOfs = (height / 2.0) + radius capsule = BulletCapsuleShape(radius, height) bodyNode = BulletRigidBodyNode('avatarBodyNode') bodyNode.addShape(capsule, TransformState.makePos(Point3(0, 0, zOfs))) bodyNode.setKinematic(True) bodyNode.setPythonTag("avatar", self) BasePhysicsObject.setupPhysics(self, bodyNode, True) self.stopWaterCheck()
class StaticTerrain(BulletObject): def __init__(self, game, imgPath, height): self.game = game self.img = PNMImage(Filename(imgPath)) self.shape = BulletHeightfieldShape(self.img, height, 2) self.node = BulletRigidBodyNode('Ground') self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(0, 0, 0) self.np.setScale(1, 1, 1) self.game.world.attachRigidBody(self.node) self.terrain = GeoMipTerrain('terrain') self.terrain.setHeightfield(self.img) self.terrain.generate() self.terrainNP = self.terrain.getRoot() self.offset = self.img.getXSize() / 2.0 - 0.5 self.terrainNP.setSz(height) self.terrainNP.setPos(-self.offset, -self.offset, -height / 2.0) #self.terrainNP.flattenStrong() self.terrainNP.reparentTo(self.np) self.terrainNP.show() self.debugOff() self.slice_able = False self.terrain.setBlockSize(32) self.terrain.setNear(100) self.terrain.setFar(400) self.terrain.setFocalPoint(self.game.playerNp) def update(self, dt=0.1): self.terrain.update()
def __init__(self): ShowBase.__init__(self) loadPrcFileData('', 'bullet-enable-contact-events true') world = BulletWorld() self.world = world world.setGravity(Vec3(0, 0, -9.81)) base.cam.setPos(0,-50,1) # Cameras base.camNode.setActive(0) self.cam1 = base.makeCamera(base.win, displayRegion=(0,.5,0.5,1)) self.cam2 = base.makeCamera(base.win, displayRegion=(.5,1,0.5,1)) self.cam1.setPos(-10,-50,1) self.cam2.setPos(10,-50,1) # base.camList[0].setPos(0,-100, 1) # Plane shape = BulletPlaneShape(Vec3(0, 0, 1), 1) node = BulletRigidBodyNode('Ground') node.addShape(shape) np = render.attachNewNode(node) np.setPos(0, 0, 0) self.world.attachRigidBody(node) scene = loader.loadModel('Ground2/Ground2') scene.reparentTo(render) self.newGame() taskMgr.add(self.update, 'update')
class DynamicModel(DynamicObject): def __init__(self, name, modelPath, game, pos): self.name = name self.modelPath = modelPath self.game = game self.model = self.game.loader.loadModel(self.modelPath) geomNodes = self.model.findAllMatches('**/+GeomNode') self.geomNode = geomNodes.getPath(0).node() self.geom = self.geomNode.getGeom(0) self.shape = BulletConvexHullShape() self.shape.addGeom(self.geom) self.node = BulletRigidBodyNode(self.name) self.node.setMass(10.0) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) self.slice_able = True
class DynamicNp(DynamicObject): def __init__(self, name, model, game, pos): self.name = name self.game = game self.model = model self.geomNode = self.model.node() self.geom = self.geomNode.getGeom(0) # with triangle mesh it crashes #mesh = BulletTriangleMesh() #mesh.addGeom(self.geom) #self.shape = BulletTriangleMeshShape(mesh, dynamic=True) # with convex hull self.shape = BulletConvexHullShape() self.shape.addGeom(self.geom) self.node = BulletRigidBodyNode(self.name) self.node.setMass(10.0) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) self.slice_able = True
def load_world(self): stairwell = loader.loadModel('../data/mod/jcmbstairs.egg') stairwell.reparentTo(render) stairwell_shape = self.egg_to_BulletTriangleMeshShape(stairwell) stairwellnode = BulletRigidBodyNode('stairwell') stairwellnode.addShape(stairwell_shape) self.world.attachRigidBody(stairwellnode)
def newGame(self): # Instantiates dabba in the world. # Makes it rigid too. boxmodel = loader.loadModel("models/misc/rgbCube.egg") boxmodel.setPos(-0.5, -0.5, -0.5) boxmodel.flattenLight() shape3 = BulletBoxShape(Vec3(0.5,0.5,0.5)) playerNode = BulletRigidBodyNode('Player') playerNode.addShape(shape3) playerNode.setMass(1.0) playerNP = render.attachNewNode(playerNode) playerNP.setPos(0, 0, 10) playerNP.node().notifyCollisions(True) self.playerNP = playerNP self.world.attachRigidBody(playerNP.node()) self.playerNode = playerNode boxmodel.copyTo(playerNP) # Connects cam to dabba self.cam1.reparentTo(playerNP) self.cam2.reparentTo(playerNP) self.cam1.setPos(1-0.7,-12,0) self.cam2.setPos( 1+0.7,-12,0) base.accept('u',self.up) base.accept('j',self.down) base.accept('w',self.forward) base.accept('s',self.back) base.accept('a',self.rotLeft) base.accept('d',self.rotRight) base.accept('t',self.rotUp) base.accept('g',self.rotDown) base.acceptOnce('bullet-contact-added', self.onContactAdded)
def setupPlayer(self, x, y, z): yetiHeight = 7 yetiRadius = 2 yetiShape = BulletCapsuleShape(yetiRadius, yetiHeight - 2 * yetiRadius, ZUp) modelPrefix = "../res/models/yeti_" self.yetiModel = Actor("../res/models/yeti.egg", {"idle":"../res/models/yeti_idle.egg", "walk":"../res/models/yeti_walking.egg"}) self.yetiModel.setH(90) self.yetiModel.setPos(0, 0, SNOW_HEIGHT) playerNode = BulletRigidBodyNode("Player") playerNode.setMass(MASS) playerNode.addShape(yetiShape) # Without this set to 0,0,0, the Yeti would wobble like a Weeble but not fall down. playerNode.setAngularFactor(Vec3(0,0,0)) # Without this disabled, things will weld together after a certain amount of time. It's really annoying. playerNode.setDeactivationEnabled(False) playerNP = self.worldNP.attachNewNode(playerNode) playerNP.setPos(x, y, z) playerNP.setH(270) self.yetiModel.reparentTo(playerNP) self.bulletWorld.attachRigidBody(playerNP.node()) # Hopefully Brandon will get those animation files to me so I can convert them. # self.setAnimation('idle') return playerNP
def construirePlancher(self): #Optimisation... on attache les objets statiques au même noeud et on utiliser #la méthode flattenStrong() pour améliorer les performances. self.noeudOptimisation = NodePath('NoeudOptimisation') self.noeudOptimisation.reparentTo(render) #Construction du plancher # On charge les tuiles qui vont former le plancher for i in range(0, self.map_nb_tuile_x): for j in range(0, self.map_nb_tuile_y): modele = loader.loadModel("../asset/Floor/Floor") # Reparentage du modèle à la racine de la scène modele.reparentTo(self.noeudOptimisation) self.placerSurGrille(modele, i, j) #Construction du plancher si on tombe #Un plan devrait marche mais j'ai un bug de collision en continu... shape = BulletBoxShape(Vec3(50, 50, 5)) node = BulletRigidBodyNode('Frontfiere sol') node.addShape(shape) np = render.attachNewNode(node) np.setTag("EntiteTankem", "LimiteJeu") np.setPos(Vec3(0, 0, -9.0)) self.mondePhysique.attachRigidBody(node) #Construction de l'aire de jeu sur laquelle on joue shape = BulletBoxShape( Vec3(-self.position_depart_x, -self.position_depart_y, 2)) node = BulletRigidBodyNode('Plancher') node.addShape(shape) np = render.attachNewNode(node) np.setTag("EntiteTankem", "Plancher") HACK_VALUE = 0.02 #Optimisation de collision, les masques ne marchent pas np.setZ(-2.00 - HACK_VALUE) self.mondePhysique.attachRigidBody(node)
class StaticModel(BulletObject): def __init__(self, name, modelPath, displayModelPath, game, pos): self.name = name self.modelPath = modelPath self.game = game self.model = self.game.loader.loadModel(self.modelPath) geomNodes = self.model.findAllMatches('**/+GeomNode') self.geomNode = geomNodes.getPath(0).node() self.geom = self.geomNode.getGeom(0) #self.shape = BulletConvexHullShape() #self.shape.addGeom(self.geom) mesh = BulletTriangleMesh() mesh.addGeom(self.geom) self.shape = BulletTriangleMeshShape(mesh, dynamic=False) self.node = BulletRigidBodyNode(self.name) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) #self.model.reparentTo(self.np) self.displayModel = self.game.loader.loadModel(displayModelPath) self.displayModel.reparentTo(self.np) self.displayModel.setTwoSided(True) self.slice_able = False
def newGame(self): boxmodel = loader.loadModel("models/box.egg") boxmodel.setPos(-0.5, -0.5, -0.5) boxmodel.flattenLight() shape3 = BulletBoxShape(Vec3(0.5,0.5,0.5)) playerNode = BulletRigidBodyNode('Player') playerNode.addShape(shape3) playerNode.setMass(1.0) playerNP = render.attachNewNode(playerNode) playerNP.setPos(0, 0, 10) playerNP.node().notifyCollisions(True) self.playerNP = playerNP self.world.attachRigidBody(playerNP.node()) self.playerNode = playerNode boxmodel.copyTo(playerNP) # self.base.cam.reparentTo(playerNP) # base.cam.setPos(0,-10,0) self.cam1.reparentTo(playerNP) self.cam2.reparentTo(playerNP) self.cam1.setPos(-1,-10,0) self.cam2.setPos( 1,-10,0) base.accept('u',self.up) base.accept('w',self.forward) base.accept('s',self.back) base.accept('a',self.rotLeft) base.accept('d',self.rotRight) base.accept('t',self.rotUp) base.accept('g',self.rotDown) base.acceptOnce('bullet-contact-added', self.onContactAdded)
class DynamicPlatform(DynamicObject): def __init__(self, name, game, x, y, z, pos): self.name = name self.game = game self.shape = BulletBoxShape(Vec3(x, y, z)) self.node = BulletRigidBodyNode(self.name) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) #self.model = self.game.loader.loadModel("models/crate.egg") #self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) #self.node.setFriction(5) #self.debugOff() self.speedVec = Vec3(0, 0, 0) self.lastPos = Vec3(self.getPos()) self.slice_able = False #self.node.setCcdMotionThreshold(1e-7) #self.node.setCcdSweptSphereRadius(0.5) def update(self, dt): return
def genBulletCDMeshMultiNp(nodepath, basenodepath=None, name='autogen'): """ generate the BulletCD mesh of a nodepath using nodepath this function suppose the nodepath has multiple models with many geomnodes use genBulletCDMeshMultiNp instead of genBulletCDMeshNp for generality :param nodepath: the panda3d nodepath of the object :param basenodepath: the nodepath to compute relative transform, identity if none :param name: the name of the rigidbody :return: bulletrigidbody author: weiwei date: 20161212, tsukuba """ gndcollection = nodepath.findAllMatches("**/+GeomNode") geombullnode = BulletRigidBodyNode(name) for gnd in gndcollection: geom = gnd.node().getGeom(0) geomtf = gnd.getTransform(base.render) if basenodepath is not None: geomtf = gnd.getTransform(basenodepath) geombullmesh = BulletTriangleMesh() geombullmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(geombullmesh, dynamic=True) bullettmshape.setMargin(0) geombullnode.addShape(bullettmshape, geomtf) return geombullnode
class StaticTerrain(BulletObject): def __init__(self, game, imgPath, height): self.game = game self.img = PNMImage(Filename(imgPath)) self.shape = BulletHeightfieldShape(self.img, height, 2) self.node = BulletRigidBodyNode('Ground') self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(0, 0, 0) self.np.setScale(1, 1, 1) self.game.world.attachRigidBody(self.node) self.terrain = GeoMipTerrain('terrain') self.terrain.setHeightfield(self.img) self.terrain.generate() self.terrainNP = self.terrain.getRoot() self.offset = self.img.getXSize() / 2.0 - 0.5 self.terrainNP.setSz(height) self.terrainNP.setPos(-self.offset,-self.offset,-height/2.0) #self.terrainNP.flattenStrong() self.terrainNP.reparentTo(self.np) self.terrainNP.show() self.debugOff() self.slice_able = False self.terrain.setBlockSize(32) self.terrain.setNear(100) self.terrain.setFar(400) self.terrain.setFocalPoint(self.game.playerNp) def update(self, dt=0.1): self.terrain.update()
def getPhysBody(self): from panda3d.bullet import BulletRigidBodyNode, BulletBoxShape from panda3d.core import TransformState bnode = BulletRigidBodyNode('entity-phys') bnode.setMass(self.mass) bnode.setCcdMotionThreshold(1e-7) bnode.setCcdSweptSphereRadius(0.5) if self.solidType == self.SOLID_MESH: convexHull = PhysicsUtils.makeBulletConvexHullFromCollisionSolids( self.model.find("**/+CollisionNode").node()) bnode.addShape(convexHull) elif self.solidType == self.SOLID_BBOX: mins = Point3() maxs = Point3() self.calcTightBounds(mins, maxs) extents = PhysicsUtils.extentsFromMinMax(mins, maxs) tsCenter = TransformState.makePos( PhysicsUtils.centerFromMinMax(mins, maxs)) shape = BulletBoxShape(extents) bnode.addShape(shape, tsCenter) return bnode
def build_node_path(self, parent_node_path, bullet_world): land_geom = self.__build_land_mesh() ocean_geom = self.__build_ocean_mesh() land_mesh = BulletTriangleMesh() land_mesh.addGeom(land_geom) land_shape = BulletTriangleMeshShape(land_mesh, dynamic=False) ocean_shape = BulletSphereShape(self.__radius) land_bullet_node = BulletRigidBodyNode('land collider') land_bullet_node.addShape(land_shape) bullet_world.attachRigidBody(land_bullet_node) land_bullet_node_path = parent_node_path.attachNewNode( land_bullet_node) ocean_bullet_node = BulletGhostNode('ocean collider') ocean_bullet_node.addShape(ocean_shape) bullet_world.attachGhost(ocean_bullet_node) ocean_bullet_node_path = land_bullet_node_path.attachNewNode( ocean_bullet_node) land_node = GeomNode('land') land_node.addGeom(land_geom) land_node_path = land_bullet_node_path.attachNewNode(land_node) ocean_node = GeomNode('ocean') ocean_node.addGeom(ocean_geom) ocean_node_path = ocean_bullet_node_path.attachNewNode(ocean_node) ocean_node_path.setTransparency(TransparencyAttrib.MAlpha) self.__node_path = land_bullet_node_path land_bullet_node.setPythonTag('planet', self) return land_bullet_node_path
def isRayHitMeshAll(self, pfrom, pto, objcm): """ :param pfrom: :param pto: :param objcm: :return: author: weiwei date: 20190805 """ geom = base.pg.packpandageom_fn(objcm.trimesh.vertices, objcm.trimesh.face_normals, objcm.trimesh.faces) targetobjmesh = BulletTriangleMesh() targetobjmesh.addGeom(geom) bullettmshape = BulletTriangleMeshShape(targetobjmesh, dynamic=True) bullettmshape.setMargin(1e-6) targetobjmeshnode = BulletRigidBodyNode('facet') targetobjmeshnode.addShape(bullettmshape) self.world.attach(targetobjmeshnode) result = self.world.rayTestAll(base.pg.npToV3(pfrom), base.pg.npToV3(pto)) self.world.removeRigidBody(targetobjmeshnode) if result.hasHits(): allhits = [] for hit in result.getHits(): allhits.append([hit.getHitPos(), -hit.getHitNormal()]) return allhits else: return []
def _add_side_walk2bullet(self, lane_start, lane_end, middle, radius=0.0, direction=0): length = norm(lane_end[0] - lane_start[0], lane_end[1] - lane_start[1]) body_node = BulletRigidBodyNode(BodyName.Side_walk) body_node.setActive(False) body_node.setKinematic(False) body_node.setStatic(True) side_np = self.side_walk_node_path.attachNewNode(body_node) shape = BulletBoxShape(Vec3(1 / 2, 1 / 2, 1 / 2)) body_node.addShape(shape) body_node.setIntoCollideMask(BitMask32.bit(Block.LANE_LINE_COLLISION_MASK)) self.dynamic_nodes.append(body_node) if radius == 0: factor = 1 else: if direction == 1: factor = (1 - self.SIDE_WALK_LINE_DIST / radius) else: factor = (1 + self.SIDE_WALK_WIDTH / radius) * (1 + self.SIDE_WALK_LINE_DIST / radius) direction_v = lane_end - lane_start vertical_v = (-direction_v[1], direction_v[0]) / numpy.linalg.norm(direction_v) middle += vertical_v * (self.SIDE_WALK_WIDTH / 2 + self.SIDE_WALK_LINE_DIST) side_np.setPos(panda_position(middle, 0)) theta = -numpy.arctan2(direction_v[1], direction_v[0]) side_np.setQuat(LQuaternionf(numpy.cos(theta / 2), 0, 0, numpy.sin(theta / 2))) side_np.setScale( length * factor, self.SIDE_WALK_WIDTH, self.SIDE_WALK_THICKNESS * (1 + 0.1 * numpy.random.rand()) ) if self.render: side_np.setTexture(self.ts_color, self.side_texture) self.side_walk.instanceTo(side_np)
def bulletRayHit(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(1e-6) facetmeshnode.addShape(bullettmshape) bulletworld.attach(facetmeshnode) result = bulletworld.rayTestClosest(pfrom, pto) if result.hasHit(): return result.getHitPos() else: return None
def fire(self, shooterPosition, targetPosition): print("fire balls") # create bullet rigid body node sphereBRBN = BulletRigidBodyNode('Ball') # set physics properties sphereBRBN.setMass(1.0) sphereBRBN.addShape(BulletSphereShape(0.2)) # attach to render and get a nodePath in render hierarchic sphere = self.render.attachNewNode(sphereBRBN) # set starting position of fire ball pos = shooterPosition pos.setZ(pos.getZ() + 1) sphere.setPos(pos) # load texture of fireball and set size then add to nodePath smileyFace = self.loader.loadModel("models/smiley") smileyFace.setScale(0.2) smileyFace.reparentTo(sphere) # add rigid body to physics world self.world.attachRigidBody(sphereBRBN) # apply the force so it moves shootingDirection = targetPosition - pos shootingDirection.normalize() sphereBRBN.applyCentralForce(shootingDirection * 1000) self.fireballs.append(sphereBRBN) self.cleanUp()
class StaticModel(BulletObject): def __init__(self, name, modelPath, displayModelPath, game, pos): self.name = name self.modelPath = modelPath self.game = game self.model = self.game.loader.loadModel(self.modelPath) geomNodes = self.model.findAllMatches('**/+GeomNode') self.geomNode = geomNodes.getPath(0).node() self.geom = self.geomNode.getGeom(0) #self.shape = BulletConvexHullShape() #self.shape.addGeom(self.geom) mesh = BulletTriangleMesh() mesh.addGeom(self.geom) self.shape = BulletTriangleMeshShape(mesh, dynamic=False) self.node = BulletRigidBodyNode(self.name) self.node.addShape(self.shape) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) #self.model.reparentTo(self.np) self.displayModel = self.game.loader.loadModel(displayModelPath) self.displayModel.reparentTo(self.np) self.displayModel.setTwoSided(True) self.slice_able = False
def create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from direct.actor.Actor import Actor from panda3d.bullet import BulletRigidBodyNode, BulletCapsuleShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["TestAI"]["lp_char_bs.egg"])) model = Actor(f) bullet_node = BulletRigidBodyNode("TestAIBulletNode") bullet_nodepath = NodePath(bullet_node) bullet_node.set_angular_factor((0, 0, 1)) shape = BulletCapsuleShape(0.3, 1.4, 2) bullet_node.addShape(shape) bullet_node.setMass(1.0) model.reparentTo(bullet_nodepath) model.set_hpr(180, 0, 0) model.set_pos(0, 0, -1) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) bullet_nodepath.set_python_tag("actor", model) return bullet_nodepath
def __init__(self,mainReference): super(Player, self).__init__(mainReference) # setting player HP self.healthPoints = 100 # fine tuning the camera properties self.mainRef.camLens.setFov(50) self.mainRef.camLens.setNear(0.02) self.mainRef.camLens.setFar(80.0) self.currentRegionID = 1 # dummy nodepath for our player; we will attach everything to it # player bullet node - NOTE: for detecting collision with attacks, only playerNode = BulletRigidBodyNode('Player_NP') playerNode.addShape( BulletCapsuleShape(0.3, 1, ZUp) ) # adicionar node no lugar da string self.mainRef.world.attachRigidBody(playerNode) self.playerNP = self.mainRef.render.attachNewNode(playerNode) # this collision mask will only avoid CharacterBody collision on itself self.playerNP.setCollideMask(BitMask32(0x7FFFFFFF)) # notify collision contacts self.playerNP.node().notifyCollisions(True) self.playerHeadNP = NodePath("empty") # This node is intended to be a placeholder for the camera (maintainability only) self.playerHeadNP.reparentTo( self.playerNP ) self.playerHeadNP.setPos(0, 0, 1.35) # self.mainRef.camera.setPos(0, -4, 0) self.mainRef.camera.reparentTo( self.playerHeadNP ) # NodePath position self.playerNP.setPos(0,0,1.0) # setting player's character body self.playerBody = CharacterBody(self.mainRef, self.playerNP.getPos(), 0.38, 0.5) self.playerBody.charBodyNP.reparentTo(self.playerNP) # setting our movementHandler self.movementHandler = MovementHandler(self.mainRef) self.movementHandler.registerFPSMovementInput() # attach default weapon self.activeWeapon = Glock(self.mainRef.camera) # adding the shoot event self.mainRef.accept("mouse1", self.shootBullet) # adding the reload event self.mainRef.accept("mouse3", self.reloadWeapon) # player boolean to authorize player HP decrease when zombie contact happens self.canLoseHP = True
def setupDeathzone(self, height): planeShape = BulletPlaneShape(Vec3(0, 0, 1), 1) planeNode = BulletRigidBodyNode('DeathZone') planeNode.addShape(planeShape) planeNP = render.attachNewNode(planeNode) planeNP.setPos(0, 0, height) self.worldBullet.attachRigidBody(planeNode) return planeNP
def addGround(self): boxx = 500.0 boxy = 500.0 boxz = 1.0 shape = BulletBoxShape(Vec3(boxx, boxy, boxz)) # the parameters are half extends node = BulletRigidBodyNode('Ground') node.addShape(shape) self.bltWorld.attachRigidBody(node) pg.plotBox(self.base.render, pos = [0,0,-1.0], x = boxx*2.0, y = boxy*2.0, z = boxz*2.0, rgba=None)
def initBullet(self): self.world = BulletWorld() #self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setGravity(Vec3(0, 0, -1.62)) groundShape = BulletPlaneShape(Vec3(0, 0, 1), 0) groundNode = BulletRigidBodyNode('Ground') groundNode.addShape(groundShape) self.world.attachRigidBody(groundNode)
def createGround(self, terrainData): """Create ground using a heightmap""" # Create heightfield for physics heightRange = terrainData["heightRange"] # Image needs to have dimensions that are a power of 2 + 1 heightMap = PNMImage(self.basePath + terrainData["elevation"]) xdim = heightMap.getXSize() ydim = heightMap.getYSize() shape = BulletHeightfieldShape(heightMap, heightRange, ZUp) shape.setUseDiamondSubdivision(True) np = self.outsideWorldRender.attachNewNode(BulletRigidBodyNode("terrain")) np.node().addShape(shape) np.setPos(0, 0, 0) self.physicsWorld.attachRigidBody(np.node()) # Create graphical terrain from same height map terrain = GeoMipTerrain("terrain") terrain.setHeightfield(heightMap) terrain.setBlockSize(32) terrain.setBruteforce(True) rootNP = terrain.getRoot() rootNP.reparentTo(self.worldRender) rootNP.setSz(heightRange) offset = xdim / 2.0 - 0.5 rootNP.setPos(-offset, -offset, -heightRange / 2.0) terrain.generate() # Apply texture diffuse = self.loader.loadTexture(Filename(self.basePath + terrainData["texture"])) diffuse.setWrapU(Texture.WMRepeat) diffuse.setWrapV(Texture.WMRepeat) rootNP.setTexture(diffuse) textureSize = 6.0 ts = TextureStage.getDefault() rootNP.setTexScale(ts, xdim / textureSize, ydim / textureSize) # Create planes around area to prevent player flying off the edge # Levels can define barriers around them but it's probably a good # idea to leave this here just in case sides = ( (Vec3(1, 0, 0), -xdim / 2.0), (Vec3(-1, 0, 0), -xdim / 2.0), (Vec3(0, 1, 0), -ydim / 2.0), (Vec3(0, -1, 0), -ydim / 2.0), ) for sideNum, side in enumerate(sides): normal, offset = side sideShape = BulletPlaneShape(normal, offset) sideNode = BulletRigidBodyNode("side%d" % sideNum) sideNode.addShape(sideShape) self.physicsWorld.attachRigidBody(sideNode)
def create_colliders(root, pose_rig, joints_config): for node, parent in pose_rig.exposed_joints: if node.getName() not in joints_config: continue joint_config = joints_config[node.getName()] if "joints" not in joint_config: continue joints = joint_config["joints"] if len(joints) == 0: continue mass = joint_config["mass"] if "mass" in joint_config else 1 box_rb = BulletRigidBodyNode(node.getName()) box_rb.setMass(1.0) # box_rb.setLinearDamping(0.2) # box_rb.setAngularDamping(0.9) # box_rb.setFriction(1.0) # box_rb.setAnisotropicFriction(1.0) # box_rb.setRestitution(0.0) for joint in joints: child_node, child_parent = next( (child_node, child_parent) for child_node, child_parent in pose_rig.exposed_joints if child_node.getName() == joint ) pos = child_node.getPos(child_parent) width = pos.length() / 2.0 scale = Vec3(3, width, 3) shape = BulletBoxShape(scale) quat = Quat() lookAt(quat, child_node.getPos(child_parent), Vec3.up()) if len(joints) > 1: transform = TransformState.makePosHpr(child_node.getPos(child_parent) / 2.0, quat.getHpr()) else: transform = TransformState.makeHpr(quat.getHpr()) box_rb.addShape(shape, transform) box_np = root.attachNewNode(box_rb) if len(joints) > 1: pos = node.getPos(pose_rig.actor) hpr = node.getHpr(pose_rig.actor) box_np.setPosHpr(root, pos, hpr) else: box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0) box_np.lookAt(child_parent, child_node.getPos(child_parent)) yield box_np
def __init__(self, player_tag): ShowBase.__init__(self) self.__player_tag = player_tag 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"] # Turn off the debugging system which allows the camera to be adjusted directly by the mouse. self.disableMouse() # 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) # Load the 3dWarehouse model. cathedral = self.loader.loadModel("3dWarehouse_Reykjavik_Cathedral.egg") cathedral.reparentTo(self.render) cathedral.setScale(0.5) # Load the Blender model. self.humanoid = Actor("player.egg") self.humanoid.setScale(0.5) self.humanoid.reparentTo(self.render) self.humanoid.loop("Walk") humanoidPosInterval1 = self.humanoid.posInterval(58, Point3(13, -10, 0), startPos=Point3(13, 10, 0)) humanoidPosInterval2 = self.humanoid.posInterval(58, Point3(13, 10, 0), startPos=Point3(13, -10, 0)) humanoidHprInterval1 = self.humanoid.hprInterval(3, Point3(180, 0, 0), startHpr=Point3(0, 0, 0)) humanoidHprInterval2 = self.humanoid.hprInterval(3, Point3(0, 0, 0), startHpr=Point3(180, 0, 0)) # Make the Blender model walk up and down. self.humanoidPace = Sequence(humanoidPosInterval1, humanoidHprInterval1, humanoidPosInterval2, humanoidHprInterval2, name="humanoidPace") self.humanoidPace.loop() # Create a light so we can see the scene. dlight = DirectionalLight('dlight') dlight.setColor(VBase4(2, 2, 2, 0)) dlnp = self.render.attachNewNode(dlight) dlnp.setHpr(0, -60, 0) self.render.setLight(dlnp) # Create a task to update the scene regularly. self.taskMgr.add(self.update, "UpdateTask")
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 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)
class DynamicBox(DynamicObject): def __init__(self, name, game, pos): self.name = name self.game = game self.shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.node = BulletRigidBodyNode(name) self.node.setMass(10.0) self.node.addShape(self.shape) self.setFriction(20) self.np = self.game.render.attachNewNode(self.node) self.np.setPos(pos) self.game.world.attachRigidBody(self.node) self.model = self.game.loader.loadModel("models/crate.egg") self.model.reparentTo(self.np) self.node.setCcdMotionThreshold(1e-7) self.node.setCcdSweptSphereRadius(0.5) self.debugOff() self.slice_able = True def update(self, dt): #self.activate() #if self.node.isActive(): # return contact = self.checkFeet() contacts = self.getContacts() if contact in self.game.objects and contact in contacts: obj = self.game.objects[contact] if type(obj) is KinematicPlatform: self.activate() self.setAngularVelocity(self.getAngularVelocity()*0.9) self.setFriction(0.1) #print "%s is a box sliding on %s" % (self.name, obj.name) #self.addSpeedVec(self.game.objects[contact].getSpeedVec()) #self.setForce(obj.getSpeedVec()*self.node.getMass() * 100) platform_speed = obj.getSpeedVec() force = platform_speed * self.node.getMass() * 50 #self.setSpeedXY(platform_speed[0], platform_speed[1]) self.setSpeedVec(platform_speed) #self.setAngularVelocity(0) #self.node.addLin(obj.getSpeedVec()*self.node.getMass() * 100) #self.node.applyCentralForce(force) #self.setForce(force) #self.setFriction(20) #self.setPos(self.getPos() + obj.getSpeedVec()) #self.node.setActive(False) else: self.setFriction(20)
def buildConeShape(self, _height, _radius, _pos, _hpr): """Build a basic cone shape for the _obj""" shape = BulletConeShape(_radius, _height, ZUp) body = BulletRigidBodyNode("flashLight") body.addShape(shape) np = self.engine.BulletObjects["player"].attachNewNode(body) np.setPos(_pos) np.setHpr(_hpr) np.setCollideMask(BitMask32.allOff()) self.engine.bulletWorld.attachRigidBody(np.node()) return np
def createPlane(self, pos): rb = BulletRigidBodyNode("plane") rb.addShape(BulletPlaneShape(Vec3(0, 0, 1), 1)) rb.setFriction(1.0) rb.setAnisotropicFriction(1.0) rb.setRestitution(1.0) np = self.render.attachNewNode(rb) np.setPos(pos) np.setCollideMask(BitMask32.bit(0)) self.world.attachRigidBody(rb) return np
def setupFloaters2(self): size = Vec3(3.5, 5.5, 0.3) randNum = random.sample(range(10, 1500, 500), 3) for i in range(3): randX = random.randrange(-2, 3, 10) randY = float(randNum[i]) # randY = random.randint(1000, 1500) shape = BulletBoxShape(size * 0.55) node = BulletRigidBodyNode('Floater') node.setMass(0) node.addShape(shape) np = self.render.attachNewNode(node) # np.setPos(9, 30, 3) np.setPos(randX, randY, 6) np.setR(0) self.world2.attachRigidBody(node) dummyNp = self.render.attachNewNode('milkyway') dummyNp.setPos(randX, randY, 6) modelNP = loader.loadModel('models/box.egg') modelNP_tex = loader.loadTexture("models/sky/moon_tex.jpg") modelNP.setTexture(modelNP_tex, 1) modelNP.reparentTo(dummyNp) modelNP.setPos(-1, 0, -1) modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0) modelNP.setScale(size) dummyNp.hprInterval(2.5, Vec3(360, 0, 0)).loop() # Put A Coin On the Floater shape = BulletSphereShape(0.75) coinNode = BulletGhostNode('FloaterCoin-' + str(i)) coinNode.addShape(shape) np = self.render.attachNewNode(coinNode) np.setCollideMask(BitMask32.allOff()) # np.setPos(randX, randY, 2) np.setPos(randX, randY, 7.0) # Adding sphere model sphereNp = loader.loadModel('models/smiley.egg') sphereNp_tex = loader.loadTexture("models/sky/coin_2_tex.jpg") sphereNp.setTexture(sphereNp_tex, 1) sphereNp.reparentTo(np) sphereNp.setScale(0.85) sphereNp.hprInterval(1.5, Vec3(360, 0, 0)).loop() self.world2.attachGhost(coinNode) self.coins2.append(coinNode) print "node name:" + str(coinNode.getName())
def renderObject(self,scale,hpr,collisionOn=False): (x_scale,y_scale,z_scale) = scale (h,p,r) = hpr if collisionOn is True: if self.name is 'wide_ramp': (x_c,y_c,z_c) = (x_scale + .2,y_scale+2.5,z_scale+1.75) if self.name is 'tree1': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) if self.name is 'tree2': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) if self.name is 'rock1': (x_c,y_c,z_c) = (x_scale * 2,y_scale * 2,z_scale*2) if self.name is 'rock2': (x_c,y_c,z_c) = (x_scale*100,y_scale*100,z_scale*100) if self.name is 'gate': (x_c,y_c,z_c) = (x_scale * 10,y_scale,z_scale*3.5) if self.name is 'statue': (x_c,y_c,z_c) = (x_scale,y_scale,z_scale) mesh = BulletTriangleMesh() for geomNP in self.model.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.model) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode(self.name) node.setMass(0) node.addShape(shape) np = self.__game.render.attachNewNode(node) np.setPos(self.x,self.y,self.z) np.setHpr(h,p,r) np.setScale(x_c,y_c,z_c) self.__game.world.attachRigidBody(node) self.model.setPos(self.x,self.y,self.z) self.model.setHpr(h,p,r) self.model.setScale(x_scale,y_scale,z_scale) self.model.reparentTo(self.__game.render) if self.name is 'statue': plat_texture = loader.loadTexture('models/textures/rocky.jpg') self.model.setTexture(plat_texture,1) ts = TextureStage.getDefault() texture = self.model.getTexture() self.model.setTexScale(ts, 1, 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)
class MagicBox(Item): def createItem(self): self.collisionShape = BulletBoxShape(Vec3(0.5, 0.6, 0.5)) self.actor = BulletRigidBodyNode('MagicBox') self.actor.addShape(self.collisionShape) self.np = self.render.attachNewNode(self.actor) self.np.setCollideMask(BitMask32.allOff()) self.np.setPos(self.x, self.y, self.z) self.world.attachRigidBody(self.actor) self.actorModelNP = self.loader.loadModel('models/magicbox/ToyBox.egg') self.actorModelNP.reparentTo(self.np) self.actorModelNP.setScale(0.35) self.actorModelNP.setH(180) self.actorModelNP.setPos(0, 0, -0.5)
def makeCameraCollision(self): #nodes node = BulletRigidBodyNode('Box') #node.setMass(0) self.ccnp = render.attachNewNode(node) self.ccnp.reparentTo(base.camera) #shapes shape = BulletSphereShape(.5) #nodes node.addShape(shape) #bullet world self.world.attachRigidBody(node)