def getPhysBody(self): bsph = BulletSphereShape(0.6) bcy = BulletCylinderShape(0.25, 0.35, ZUp) body = BulletRigidBodyNode('tntBody') body.addShape( bsph, TransformState.makePosHpr((0.05, 0, 0.43), (86.597, 24.5539, 98.1435))) body.addShape( bcy, TransformState.makePosHpr((0.05, 0.655, 0.35), (86.597, 24.5539, 98.1435))) body.setKinematic(True) body.setCcdMotionThreshold(1e-7) body.setCcdSweptSphereRadius(0.6) return body
def _initPhysics(self, world): rad = 1 shape = BulletSphereShape(rad) self._rb_node = BulletRigidBodyNode('Box') self._rb_node.setMass(80.0) self._rb_node.setFriction(1.8) self._rb_node.addShape(shape) self._rb_node.setAngularFactor(Vec3(0,0,0)) self._rb_node.setDeactivationEnabled(False, True) self.playerNode = render.attachNewNode(self._rb_node) self.playerNode.setPos(0, 0, 4) self.playerNode.setHpr(0,0,0) world.attachRigidBody(self._rb_node) self.camNode = self.playerNode.attachNewNode("cam node") base.camera.reparentTo(self.camNode) self.camNode.setPos(self.camNode, 0, 0, 1.75-rad)
def npc_testAttackLOS(self, startPos, endPos): # Makes sure the NPC has a line-of-sight to endPos for this attack # If not, tries to find a new position either directly to the left # or right of startPos that has a line-of-sight to endPos. losChecks = 5 losStep = 1.0 stepRight = self.avatar.getQuat().getRight() * losStep stepRight[2] = 0 testLeft = Vec3(startPos) testRight = Vec3(startPos) sphere = BulletSphereShape(1.0) # Test center result = self.avatar.battleZone.physicsWorld.sweepTestClosest( sphere, TransformState.makePos(startPos), TransformState.makePos(endPos), CIGlobals.WorldGroup) if not result.hasHit(): # We have a line-of-sight from start to end return [True, Vec3()] for i in range(losChecks): testLeft -= stepRight testRight += stepRight # Test to the left result = self.avatar.battleZone.physicsWorld.sweepTestClosest( sphere, TransformState.makePos(testLeft), TransformState.makePos(endPos), CIGlobals.WorldGroup) if not result.hasHit(): # We now have a line-of-sight, move to the new position vecMove = testLeft - startPos return [False, vecMove] # Test to the right result = self.avatar.battleZone.physicsWorld.sweepTestClosest( sphere, TransformState.makePos(testRight), TransformState.makePos(endPos), CIGlobals.WorldGroup) if not result.hasHit(): # We now have a line-of-sight, move to the new position vecMove = testRight - startPos return [False, vecMove] # Couldn't get a line-of-sight, randomly choose left or right and try again return [False, random.choice([testLeft, testRight]) - startPos]
def __addElements(self): # Walk Capsule self.__walkCapsule = BulletCapsuleShape(self.__walkCapsuleR, self.__walkCapsuleH) self.__walkCapsuleNP = self.movementParent.attachNewNode( BulletRigidBodyNode('Capsule')) self.__walkCapsuleNP.node().addShape(self.__walkCapsule) self.__walkCapsuleNP.node().setKinematic(True) self.__walkCapsuleNP.node().setCcdMotionThreshold(1e-7) self.__walkCapsuleNP.node().setCcdSweptSphereRadius( self.__walkCapsuleR) self.__walkCapsuleNP.setCollideMask(BitMask32.allOn()) self.__world.attachRigidBody(self.__walkCapsuleNP.node()) # Crouch Capsule self.__crouchCapsule = BulletCapsuleShape(self.__crouchCapsuleR, self.__crouchCapsuleH) self.__crouchCapsuleNP = self.movementParent.attachNewNode( BulletRigidBodyNode('crouchCapsule')) self.__crouchCapsuleNP.node().addShape(self.__crouchCapsule) self.__crouchCapsuleNP.node().setKinematic(True) self.__crouchCapsuleNP.node().setCcdMotionThreshold(1e-7) self.__crouchCapsuleNP.node().setCcdSweptSphereRadius( self.__crouchCapsuleR) self.__crouchCapsuleNP.setCollideMask(BitMask32.allOn()) # Set default self.capsule = self.__walkCapsule self.capsuleNP = self.__walkCapsuleNP # Make the event sphere a tiny bit bigger than the capsule # so our capsule doesn't block the event sphere from entering triggers. eventSphere = BulletSphereShape(self.__walkCapsuleR * 1.5) self.eventSphereNP = self.movementParent.attachNewNode( BulletGhostNode('eventSphere')) self.eventSphereNP.node().addShape( eventSphere, TransformState.makePos(Point3(0, 0, self.__walkCapsuleR * 1.5))) self.eventSphereNP.node().setKinematic(True) self.eventSphereNP.setCollideMask(CIGlobals.EventGroup) self.__world.attach(self.eventSphereNP.node()) # Init self.__updateCapsule()
def setupEndPoint(self): blocks_tex8 = loader.loadTexture("models/blocks_tex8.jpg") self.endpoint= loader.loadModel("models/Sphere_HighPoly/Sphere_HighPoly") self.endpoint.reparentTo(render) self.endpoint.setScale(.8) self.endpoint.setPos(0,-200,2) self.endpoint.setTexture(blocks_tex8, 1) radius = 2.65 self.shapeEnd = BulletSphereShape(radius) self.nodeEnd = BulletGhostNode('EndPoint') self.nodeEnd.addShape(self.shapeEnd) self.npEnd = render.attachNewNode(self.nodeEnd) self.npEnd.setPos(0, -200, 2) self.npEnd.setCollideMask(BitMask32.allOn()) self.world.attachGhost(self.nodeEnd)
def add_ball(task): bullet_body = BulletRigidBodyNode() bullet_body.set_linear_sleep_threshold(0) bullet_body.set_angular_sleep_threshold(0) bullet_body.set_mass(1.0) bullet_body.add_shape(BulletSphereShape(ball_size)) func = random.choice([ add_smiley, add_panda, add_mr_man_static, add_mr_man_dynamic, ]) func(world, bullet_body) return task.again
def do_explosion(self, node, radius, force): center = node.get_pos(self.scene) expl_body = BulletGhostNode("expl") expl_shape = BulletSphereShape(radius) expl_body.add_shape(expl_shape) expl_bodyNP = self.scene.attach_new_node(expl_body) expl_bodyNP.set_pos(center) self.physics.attach_ghost(expl_body) result = self.physics.contact_test(expl_body) for contact in result.getContacts(): n0_name = contact.getNode0().get_name() n1_name = contact.getNode1().get_name() obj = None try: obj = self.objects[n1_name] except: break if n0_name == "expl" and n1_name not in EXPLOSIONS_DONT_PUSH and not n1_name.startswith( 'Walker'): # repeat contact test with just this pair of objects # otherwise all manifold point values will be the same # for all objects in original result real_c = self.physics.contact_test_pair(expl_body, obj.solid) mpoint = real_c.getContacts()[0].getManifoldPoint() distance = mpoint.getDistance() if distance < 0: if hasattr(obj, 'decompose'): obj.decompose() else: expl_vec = Vec3(mpoint.getPositionWorldOnA() - mpoint.getPositionWorldOnB()) expl_vec.normalize() magnitude = force * 1.0 / math.sqrt( abs(radius - abs(distance))) obj.solid.set_active(True) obj.solid.apply_impulse(expl_vec * magnitude, mpoint.getLocalPointB()) if hasattr(obj, 'damage'): obj.damage(magnitude / 5) self.physics.remove_ghost(expl_body) expl_bodyNP.detach_node() del (expl_body, expl_bodyNP)
def __init__(self, parent_node_np: NodePath, num_lasers: int = 16, distance: float = 50, enable_show=False): # properties assert num_lasers > 0 show = enable_show and (AssetLoader.loader is not None) self.dim = num_lasers self.num_lasers = num_lasers self.perceive_distance = distance self.height = self.DEFAULT_HEIGHT self.radian_unit = 2 * np.pi / num_lasers self.start_phase_offset = 0 self.node_path = parent_node_np.attachNewNode("Could_points") self._lidar_range = np.arange( 0, self.num_lasers) * self.radian_unit + self.start_phase_offset # detection result self.cloud_points = np.ones((self.num_lasers, ), dtype=float) self.detected_objects = [] # override these properties to decide which elements to detect and show self.node_path.hide(CamMask.RgbCam | CamMask.Shadow | CamMask.Shadow | CamMask.DepthCam) self.mask = BitMask32.bit(CollisionGroup.BrokenLaneLine) self.cloud_points_vis = [] if show else None logging.debug("Load Vehicle Module: {}".format( self.__class__.__name__)) if show: for laser_debug in range(self.num_lasers): ball = AssetLoader.loader.loadModel( AssetLoader.file_path("models", "box.bam")) ball.setScale(0.001) ball.setColor(0., 0.5, 0.5, 1) shape = BulletSphereShape(0.1) ghost = BulletGhostNode('Lidar Point') ghost.setIntoCollideMask(BitMask32.allOff()) ghost.addShape(shape) laser_np = self.node_path.attachNewNode(ghost) self.cloud_points_vis.append(laser_np) ball.getChildren().reparentTo(laser_np)
def makeNodePath(self): self.nodePath = NodePath('treasure') if self.billboard: self.nodePath.setBillboardPointEye() self.nodePath.setScale(0.9 * self.scale) self.treasure = self.nodePath.attachNewNode('treasure') if self.shadow: if not self.dropShadow: self.dropShadow = loader.loadModel( 'phase_3/models/props/drop_shadow.bam') self.dropShadow.setColor(0, 0, 0, 0.5) self.dropShadow.setPos(0, 0, 0.025) self.dropShadow.setScale(0.4 * self.scale) self.dropShadow.flattenLight() self.dropShadow.reparentTo(self.nodePath) sphere = BulletSphereShape(self.sphereRadius) ghost = BulletGhostNode(self.uniqueName('treasureSphere')) ghost.addShape(sphere) ghost.setIntoCollideMask(CIGlobals.EventGroup) self.collNodePath = self.nodePath.attachNewNode(ghost) self.collNodePath.stash()
def announceGenerate(self): DistributedEntity.announceGenerate(self) self.addSound("pickup", "sound/items/jellybean_pickup.ogg") import random color = random.choice(self.Colors) self.getModelNP().setColorScale(color, 1) from direct.interval.IntervalGlobal import LerpHprInterval self.rot = LerpHprInterval(self.getModelNP(), 1.0, (360, 0, 0), (0, 0, 0)) self.rot.loop() from src.coginvasion.globals import CIGlobals from panda3d.bullet import BulletSphereShape, BulletGhostNode sph = BulletSphereShape(0.5) body = BulletGhostNode(self.uniqueName('jellybean-trigger')) body.addShape(sph) body.setIntoCollideMask(CIGlobals.EventGroup) self.setupPhysics(body, True) self.acceptOnce('enter' + self.uniqueName('jellybean-trigger'), self.__enterJellybeanTrigger)
def do_shoot(self): # Get from/to points from mouse click pMouse = base.mouseWatcherNode.get_mouse() pFrom = LPoint3() pTo = LPoint3() base.camLens.extrude(pMouse, pFrom, pTo) pFrom = render.get_relative_point(base.cam, pFrom) pTo = render.get_relative_point(base.cam, pTo) # Calculate initial velocity v = pTo - pFrom v.normalize() v *= 100.0 # Create bullet shape = BulletSphereShape(0.3) body = BulletRigidBodyNode('Bullet') bodyNP = self.worldNP.attach_new_node(body) bodyNP.node().add_shape(shape) bodyNP.node().set_mass(1.0) bodyNP.node().set_linear_velocity(v) bodyNP.node().set_ccd_motion_threshold(1e-7) bodyNP.node().set_ccd_swept_sphere_radius(0.50) bodyNP.set_collide_mask(BitMask32.all_on()) bodyNP.set_pos(pFrom) visNP = loader.load_model('models/ball.egg') visNP.set_scale(0.8) visNP.reparent_to(bodyNP) self.world.attach(bodyNP.node()) # Remove the bullet again after 2 seconds taskMgr.do_method_later(2, self.do_remove, 'doRemove', extraArgs=[bodyNP], appendTask=True)
def doShoot(self): # Get from/to points from mouse click pMouse = base.mouseWatcherNode.getMouse() pFrom = Point3() pTo = Point3() base.camLens.extrude(pMouse, pFrom, pTo) pFrom = render.getRelativePoint(base.cam, pFrom) pTo = render.getRelativePoint(base.cam, pTo) # Calculate initial velocity v = pTo - pFrom 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 createBall(self): self.actor.play("launch") # Sphere self.shape = BulletSphereShape(0.15) self.node = BulletRigidBodyNode('Sphere') self.node.setMass(1) self.node.addShape(self.shape) self.np = self.showbase.render.attachNewNode(self.node) self.np.setPos(self.actor.getX(), self.actor.getY(), self.actor.getZ() + 2.5) # Smiley self.model = self.showbase.loader.loadModel("./models/smiley") self.model.setTexture( self.showbase.loader.loadTexture(imagePath + 'metal1.jpg'), 1) self.model.flattenLight() self.model.setScale(0.15, 0.15, 0.15) self.model.reparentTo(self.np) # Set speed h = self.actor.getH() if (h == 0): x = 0 y = 8 if (h == 90): x = -7 y = 0 if (h == 180): x = 0 y = -8 if (h == -90): x = 8 y = 0 self.node.setLinearVelocity(Vec3(x, y, 6.2)) #self.actor.getX()/3, 11, 6.2) self.showbase.world.attachRigidBody(self.node)
def __init__(self, parent_node_np: NodePath, laser_num: int = 240, distance: float = 50): show = self.enable_show and (AssetLoader.loader is not None) self.Lidar_point_cloud_obs_dim = laser_num self.laser_num = laser_num self.perceive_distance = distance self.radian_unit = 2 * np.pi / laser_num self.detection_results = [] self.node_path = parent_node_np.attachNewNode("cloudPoints") self.node_path.hide(CamMask.RgbCam | CamMask.Shadow) self.cloud_points = [] if show else None logging.debug("Load Vehicle Module: {}".format(self.__class__.__name__)) if show: for laser_debug in range(self.laser_num): ball = AssetLoader.loader.loadModel(AssetLoader.file_path("models", "box.egg")) ball.setScale(0.001) ball.setColor(0., 0.5, 0.5, 1) shape = BulletSphereShape(0.1) ghost = BulletGhostNode('Lidar Point') ghost.setIntoCollideMask(BitMask32.allOff()) ghost.addShape(shape) laser_np = self.node_path.attachNewNode(ghost) self.cloud_points.append(laser_np) ball.getChildren().reparentTo(laser_np)
def load_scene(self): # ground sandbox = loader.loadModel('maps/practice/sandbox') np = self.root_node.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(bullet_shape_from(sandbox)) np.setPos(0, 0, 0) np.setCollideMask(BitMask32.allOn()) self.physics.world.attachRigidBody(np.node()) sandbox.reparentTo(np) moon = DirectionalLight('moon') moon.setColor(hex_to_rgb('ffffff')) moon.setShadowCaster(True, 2048, 2048) moon_np = self.root_node.attachNewNode(moon) moon_np.setPos(-5, -5, 10) moon_np.lookAt(0, 0, 0) self.root_node.setLight(moon_np) moon = DirectionalLight('sun') moon.setColor(hex_to_rgb('666666')) moon.setShadowCaster(True, 2048, 2048) moon_np = self.root_node.attachNewNode(moon) moon_np.setPos(5, 5, 10) moon_np.lookAt(0, 0, 0) self.root_node.setLight(moon_np) # dynamic sphere np = self.root_node.attachNewNode(BulletRigidBodyNode('Sphere')) np.node().addShape(BulletSphereShape(1)) np.node().setMass(3.0) np.setPos(5, 5, 2) self.physics.world.attachRigidBody(np.node()) ball = loader.loadModel('geometry/ball') ball.reparentTo(np) self.char_marks.add('ball', ball, OnscreenText(text='sphere', scale=0.07), 1) # dynamic box np = self.root_node.attachNewNode(BulletRigidBodyNode('Box')) np.node().addShape(BulletBoxShape(Vec3(0.5, 0.5, 0.5))) np.node().setMass(1.0) np.setPos(-1, -2, 2) self.physics.world.attachRigidBody(np.node()) np.node().applyCentralImpulse((0, 2, 7)) box = loader.loadModel('geometry/box') box.reparentTo(np) self.char_marks.add('box', box, OnscreenText(text='cube', scale=0.06), 0.5) # static np = self.root_node.attachNewNode(BulletRigidBodyNode('Static')) np.node().addShape(BulletBoxShape(Vec3(0.5, 0.5, 0.5))) np.setPos(1, 2, 0.8) self.physics.world.attachRigidBody(np.node()) box = loader.loadModel('geometry/box') box.reparentTo(np) def move_box(task): angle_degrees = task.time * 12.0 if angle_degrees > 360: angle_degrees -= 360 angle_radians = angle_degrees * (pi / 180) np.setPos(5 * sin(angle_radians), -5 * cos(angle_radians), .5) np.setHpr(angle_degrees, 4, 0) return task.cont base.taskMgr.add(move_box, 'move_box') self.char_marks.add('static', box, OnscreenText(text='static', scale=0.08), 0.5)
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()) # Plane (static) shape = BulletPlaneShape(Vec3(0, 0, 1), 0) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, -1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box (dynamic) shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(0, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) self.boxNP = np # For applying force & torque #np.node().notifyCollisions(True) #self.accept('bullet-contact-added', self.doAdded) #self.accept('bullet-contact-destroyed', self.doRemoved) # Sphere (dynamic) shape = BulletSphereShape(0.6) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(-4, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Cone (dynamic) shape = BulletConeShape(0.6, 1.2, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(4, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Capsule (dynamic) shape = BulletCapsuleShape(0.5, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Capsule')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(0, 4, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Cyliner (dynamic) shape = BulletCylinderShape(0.7, 1.5, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cylinder')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(4, 4, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Convex (dynamic) shape = BulletConvexHullShape() shape.addPoint(Point3(1, 1, 2)) shape.addPoint(Point3(0, 0, 0)) shape.addPoint(Point3(2, 0, 0)) shape.addPoint(Point3(0, 2, 0)) shape.addPoint(Point3(2, 2, 0)) # Another way to create the convex hull shape: #shape = BulletConvexHullShape() #shape.addArray([ # Point3(1, 1, 2), # Point3(0, 0, 0), # Point3(2, 0, 0), # Point3(0, 2, 0), # Point3(2, 2, 0), #]) # Yet another way to create the convex hull shape: #geom = loader.loadModel('models/box.egg')\ # .findAllMatches('**/+GeomNode')\ # .getPath(0)\ # .node()\ # .getGeom(0) #shape = BulletConvexHullShape() #shape.addGeom(geom) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Convex')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(-4, 4, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Mesh (static) p0 = Point3(-10, -10, 0) p1 = Point3(-10, 10, 0) p2 = Point3(10, -10, 0) p3 = Point3(10, 10, 0) mesh = BulletTriangleMesh() mesh.addTriangle(p0, p1, p2) mesh.addTriangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) # Another way to create the triangle mesh shape: #geom = loader.loadModel('models/box.egg')\ # .findAllMatches('**/+GeomNode')\ # .getPath(0)\ # .node()\ # .getGeom(0) #mesh = BulletTriangleMesh() #mesh.addGeom(geom) #shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(shape) np.setPos(0, 0, 0.1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # MutiSphere points = [Point3(-1, 0, 0), Point3(0, 0, 0), Point3(1, 0, 0)] radii = [.4, .8, .6] shape = BulletMultiSphereShape(points, radii) np = self.worldNP.attachNewNode(BulletRigidBodyNode('MultiSphere')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(8, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node())
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_.node().showWireframe(True) self.debug_node_.node().showConstraints(True) self.debug_node_.node().showBoundingBoxes(True) self.debug_node_.node().showNormals(True) self.physics_world_.setDebugNode(self.debug_node_.node()) self.debug_node_.hide() # setting up collision groups self.physics_world_.setGroupCollisionFlag(GAME_OBJECT_BITMASK.getLowestOnBit(),GAME_OBJECT_BITMASK.getLowestOnBit(),True) self.physics_world_.setGroupCollisionFlag(SECTOR_ENTERED_BITMASK.getLowestOnBit(),SECTOR_ENTERED_BITMASK.getLowestOnBit(),True) self.physics_world_.setGroupCollisionFlag(GAME_OBJECT_BITMASK.getLowestOnBit(),SECTOR_ENTERED_BITMASK.getLowestOnBit(),False) # 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(GAME_OBJECT_BITMASK) self.physics_world_.attachRigidBody(self.ground_.node()) # creating level objects self.setupLevelSectors() # creating controlled objects diameter = 0.4 sphere_visual = loader.loadModel('models/ball.egg') bounds = sphere_visual.getTightBounds() # start of model scaling extents = Vec3(bounds[1] - bounds[0]) scale_factor = diameter/max([extents.getX(),extents.getY(),extents.getZ()]) sphere_visual.clearModelNodes() sphere_visual.setScale(scale_factor,scale_factor,scale_factor) # end of model scaling sphere_visual.setTexture(loader.loadTexture('models/bowl.jpg'),1) sphere = NodePath(BulletRigidBodyNode('Sphere')) sphere.node().addShape(BulletSphereShape(0.5*diameter)) sphere.node().setMass(1.0) #sphere.node().setLinearFactor((1,0,1)) #sphere.node().setAngularFactor((0,1,0)) sphere.setCollideMask(GAME_OBJECT_BITMASK) sphere_visual.instanceTo(sphere) self.physics_world_.attachRigidBody(sphere.node()) self.controlled_objects_.append(sphere) sphere.reparentTo(self.world_node_) sphere.setPos(self.level_sectors_[0],Vec3(0,0,diameter+10)) sphere.setHpr(self.level_sectors_[0],Vec3(0,0,0)) # creating bullet ghost for detecting entry into other sectors player_ghost = sphere.attachNewNode(BulletGhostNode('player-ghost-node')) ghost_box_shape = BulletSphereShape(PLAYER_GHOST_DIAMETER/2) ghost_box_shape.setMargin(SECTOR_COLLISION_MARGIN) ghost_sphere_shape = BulletSphereShape(PLAYER_GHOST_DIAMETER*0.5) ghost_sphere_shape.setMargin(SECTOR_COLLISION_MARGIN) player_ghost.node().addShape(ghost_box_shape) player_ghost.setPos(sphere,Vec3(0,0,0)) player_ghost.node().setIntoCollideMask(SECTOR_ENTERED_BITMASK) self.physics_world_.attach(player_ghost.node()) # creating mobile box size = Vec3(0.2,0.2,0.4) mbox_visual = loader.loadModel('models/box.egg') bounds = mbox_visual.getTightBounds() extents = Vec3(bounds[1] - bounds[0]) scale_factor = 1/max([extents.getX(),extents.getY(),extents.getZ()]) mbox_visual.setScale(size.getX()*scale_factor,size.getY()*scale_factor,size.getZ()*scale_factor) mbox = NodePath(BulletRigidBodyNode('MobileBox')) mbox.node().addShape(BulletBoxShape(size/2)) mbox.node().setMass(1.0) #mbox.node().setLinearFactor((1,0,1)) #mbox.node().setAngularFactor((0,1,0)) mbox.setCollideMask(GAME_OBJECT_BITMASK) mbox_visual.instanceTo(mbox) self.physics_world_.attachRigidBody(mbox.node()) self.controlled_objects_.append(mbox) mbox.reparentTo(self.level_sectors_[0]) mbox.setPos(Vec3(1,0,size.getZ()+1)) # switching to sector 1 self.switchToSector(self.level_sectors_[0])
# Debug visualization debug_node = BulletDebugNode('Debug') debug_node.showWireframe(True) debug_node.showConstraints(True) debug_node.showBoundingBoxes(False) debug_node.showNormals(False) debug_np = s.render.attach_new_node(debug_node) bullet_world.set_debug_node(debug_node) debug_np.show() # The object in question mass = BulletRigidBodyNode() mass.set_mass(1) mass.setLinearSleepThreshold(0) mass.setAngularSleepThreshold(0) shape = BulletSphereShape(1) mass.add_shape(shape) mass_node = s.render.attach_new_node(mass) mass_node.set_hpr(1, 1, 1) bullet_world.attach_rigid_body(mass) model = s.loader.load_model('models/smiley') model.reparent_to(mass_node) model_axis = loader.load_model('models/zup-axis') model_axis.reparent_to(model) model_axis.set_pos(0, 0, 0) model_axis.set_scale(0.2) # The orientation to reach target_node = s.loader.load_model('models/smiley') target_node.reparent_to(s.render) target_node.set_hpr(0, 0, 0)
def __addSphere(self, body, model, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1) ): size = self.getSize(model) shape = BulletSphereShape( max(size)/2 ) body.addShape(shape, TransformState.makePosHprScale(pos,hpr,scale) )
def insert(self, world, render, i, pos): # Important numbers head_radius = 0.5 head_elevation = 1.5 torso_x = 0.3 torso_y = 0.5 torso_z = 0.75 arm_radius = 0.15 shoulder_space = 0.05 shoulder_elevation = head_elevation - head_radius - 0.1 - arm_radius torso_elevation = head_elevation - head_radius - torso_z x, y = pos # measurements below are in degrees neck_yaw_limit = 90 neck_pitch_limit = 45 shoulder_twist_limit = 90 # limit for twisting arm along the bicep axis shoulder_in_limit = 175 # maximum declination from T-pose towards torso shoulder_out_limit = 90 # maximum elevation from T-pose away from torso shoulder_forward_limit = 175 # maximum angle from down by side to pointing forward shoulder_backward_limit = 90 # maximum angle from down by side to pointing backward # Create a head head_node = BulletRigidBodyNode('Head') head_node.addShape(BulletSphereShape(head_radius)) head_node.setMass(1.0) head_pointer = render.attachNewNode(head_node) head_pointer.setPos(x, y, head_elevation) world.attachRigidBody(head_node) # Create a torso torso_node = BulletRigidBodyNode('Torso') torso_node.addShape(BulletBoxShape(Vec3(torso_x, torso_y, torso_z))) torso_node.setMass(0.0) # remain in place torso_pointer = render.attachNewNode(torso_node) torso_pointer.setPos(x, y, torso_elevation) world.attachRigidBody(torso_node) # Attach the head to the torso head_frame = TransformState.makePosHpr(Point3(0, 0, -head_radius), Vec3(0, 0, -90)) torso_frame = TransformState.makePosHpr(Point3(0, 0, torso_z), Vec3(0, 0, -90)) neck = BulletConeTwistConstraint(head_node, torso_node, head_frame, torso_frame) neck.setDebugDrawSize(0.5) neck.setLimit(neck_pitch_limit, neck_pitch_limit, neck_yaw_limit) world.attachConstraint(neck) # Create arms shoulder_pos_l = Point3( x, y - i * (torso_y + shoulder_space + arm_radius), shoulder_elevation) shoulder_pos_r = Point3( x, y + i * (torso_y + shoulder_space + arm_radius), shoulder_elevation) limits = (shoulder_in_limit, shoulder_out_limit, shoulder_forward_limit, shoulder_backward_limit, shoulder_twist_limit) arm_l = Arm(world, render, shoulder_pos_l, -i, LEFT, torso_pointer, limits) arm_r = Arm(world, render, shoulder_pos_r, i, RIGHT, torso_pointer, limits) self.head = head_pointer self.torso = torso_pointer self.arm_l, self.arm_r = arm_l, arm_r
def __init__(self, manager, position: Vec3, uri="-1", printDebugInfo=False): self.base = manager.base self.manager = manager # The position of the real drone this virtual drone is connected to. # If a connection is active, this value is updated each frame. self.realDronePosition = Vec3(0, 0, 0) self.canConnect = False # true if the virtual drone has a uri to connect to a real drone self.isConnected = False # true if the connection to a real drone is currently active self.uri = uri if self.uri != "-1": self.canConnect = True self.id = int(uri[-1]) self.randVec = Vec3(random.uniform(-1, 1), random.uniform(-1, 1), random.uniform(-1, 1)) # add the rigidbody to the drone, which has a mass and linear damping self.rigidBody = BulletRigidBodyNode( "RigidSphere") # derived from PandaNode self.rigidBody.setMass(self.RIGIDBODYMASS) # body is now dynamic self.rigidBody.addShape(BulletSphereShape(self.RIGIDBODYRADIUS)) self.rigidBody.setLinearSleepThreshold(0) self.rigidBody.setFriction(0) self.rigidBody.setLinearDamping(self.LINEARDAMPING) self.rigidBodyNP = self.base.render.attachNewNode(self.rigidBody) self.rigidBodyNP.setPos(position) # self.rigidBodyNP.setCollideMask(BitMask32.bit(1)) self.base.world.attach(self.rigidBody) # add a 3d model to the drone to be able to see it in the 3d scene model = self.base.loader.loadModel(self.base.modelDir + "/drones/drone1.egg") model.setScale(0.2) model.reparentTo(self.rigidBodyNP) self.target = position # the long term target that the virtual drones tries to reach self.setpoint = position # the immediate target (setpoint) that the real drone tries to reach, usually updated each frame self.waitingPosition = Vec3(position[0], position[1], 0.7) self.lastSentPosition = self.waitingPosition # the position that this drone last sent around self.printDebugInfo = printDebugInfo if self.printDebugInfo: # put a second drone model on top of drone that outputs debug stuff model = self.base.loader.loadModel(self.base.modelDir + "/drones/drone1.egg") model.setScale(0.4) model.setPos(0, 0, .2) model.reparentTo(self.rigidBodyNP) # initialize line renderers self.targetLineNP = self.base.render.attachNewNode(LineSegs().create()) self.velocityLineNP = self.base.render.attachNewNode( LineSegs().create()) self.forceLineNP = self.base.render.attachNewNode(LineSegs().create()) self.actualDroneLineNP = self.base.render.attachNewNode( LineSegs().create()) self.setpointNP = self.base.render.attachNewNode(LineSegs().create())
def init_player(self): # Stop the default mouse behaviour base.disableMouse() # Character has a capsule shape shape = BulletCapsuleShape(0.2, 1, ZUp) self.player = BulletRigidBodyNode('Player') self.player.setMass(80.0) self.player.addShape(shape) self.playernp = render.attachNewNode(self.player) self.playernp.setPos(0, 0, 1) self.world.attachRigidBody(self.player) self.player.setLinearSleepThreshold(0.0) self.player.setAngularFactor(0.0) self.player_speed = 3 self.player_is_grabbing = False # self.head = BulletRigidBodyNode('Player Head') # self.head.addShape(BulletSphereShape(0.2)) # self.head.setMass(10) # self.head.setInertia(Vec3(1,1,1)) # self.head.setAngularFactor(1.0) # self.head.setLinearFactor(0.0) # self.headnp = self.playernp.attachNewNode(self.head) # self.headnp.setPos(0,0,0) # self.headnp.setCollideMask(BitMask32.allOff()) # self.world.attachRigidBody(self.head) # Attach the camera to the player's head base.camera.reparentTo(self.playernp) # base.camera.setPos(0,0,.5) base.camLens.setFov(80) base.camLens.setNear(0.01) # Make the torch and attach it to our character torch = Spotlight('torch') torch.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() lens.setFov(80) lens.setNearFar(20, 100) torch.setLens(lens) self.torchnp = base.camera.attachNewNode(torch) self.torchnp.setPos(0, 0, 0) # Allow the world to be illuminated by our torch render.setLight(self.torchnp) self.cs = None # Player's "hand" in the world hand_model = loader.loadModel('../data/mod/hand.egg') hand_model.setScale(1) hand_model.setBillboardPointEye() self.hand = BulletRigidBodyNode('Hand') self.hand.addShape(BulletSphereShape(0.1)) self.hand.setLinearSleepThreshold(0.0) self.hand.setLinearDamping(0.9999999) self.hand.setAngularFactor(0.0) self.hand.setMass(1.0) self.world.attachRigidBody(self.hand) self.handnp = render.attachNewNode(self.hand) self.handnp.setCollideMask(BitMask32.allOff()) # hand_model.reparentTo(self.handnp) # Create a text node to display object identification information and attach it to the player's "hand" self.hand_text = TextNode('Hand Text') self.hand_text.setText("Ch-ch-chek yoself befo yo rek yoself, bro.") self.hand_text.setAlign(TextNode.ACenter) self.hand_text.setTextColor(1, 1, 1, 1) self.hand_text.setShadow(0.05, 0.05) self.hand_text.setShadowColor(0, 0, 0, 1) self.hand_text_np = render.attachNewNode(self.hand_text) self.hand_text_np.setScale(0.03) self.hand_text_np.setBillboardPointEye() self.hand_text_np.hide() # Disable the depth testing for the hand and the text - we always want these things on top, with no clipping self.handnp.setDepthTest(False) self.hand_text_np.setDepthTest(False) # Add the player update task taskMgr.add(self.update, 'update_player_task')
def spawnShip(self, shipName, shipClass, spawnPoint=LPoint3d(0, 0, 0), playerShip=False, entityid=-1, turrets=None): if shipName == '' or shipClass == '': return if entityid == -1: ship = sandbox.createEntity() else: ship = sandbox.addEntity(entityid) if playerShip: component = shipComponents.PlayerComponent() ship.addComponent(component) else: component = shipComponents.AIPilotComponent() ship.addComponent(component) shape = BulletSphereShape(1) velocity = Vec3(0, 0, 0) truex = spawnPoint.getX() truey = spawnPoint.getY() component = physics.addNewBody(shipName, shape, shipClasses[shipClass]['mass'], truex, truey, velocity) ship.addComponent(component) component = shipComponents.ThrustComponent() for engine in shipClasses[shipClass]['engines']: component.forward += engine['thrust'] / CONVERT component.heading = shipClasses[shipClass]['torque'] / CONVERT ship.addComponent(component) component = shipComponents.InfoComponent() component.shipClass = shipClass component.name = shipName ship.addComponent(component) component = graphicsComponents.RenderComponent() #component.mesh = sandbox.base.loader.loadModel('ships/' + shipClasses[shipClass]['path']) component.mesh = Actor('ships/' + shipClasses[shipClass]['path']) component.mesh.reparentTo(sandbox.ships) component.mesh.getPart('modelRoot').setPythonTag('entityID', ship.id) component.mesh.setScale(1 / CONVERT) if universals.runClient and not playerShip: sandbox.send('makePickable', [component.mesh]) ship.addComponent(component) # Load turret info here. Also check if gun is actually on ship! def containsAny(string, check): return 1 in [c in string for c in check] turretsComponent = shipComponents.TurretsComponent() if not turrets: for weapon in shipClasses[shipClass]['weapons']: turretEntity = sandbox.createEntity() turret = shipComponents.TurretComponent() if not containsAny( shipClasses[shipClass]['weapons'][weapon]['decay'], 'abcdefghijklmnopqrstuvwyz'): turret.decay = lambda x: eval(shipClasses[shipClass][ 'weapons'][weapon]['decay']) turret.name = weapon turret.damage = shipClasses[shipClass]['weapons'][weapon][ 'damage'] if 'traverser' in shipClasses[shipClass]['weapons'][weapon][ 'joints']: turret.traverser = shipClasses[shipClass]['weapons'][ weapon]['joints']['traverser']['axes'] if 'elevator' in shipClasses[shipClass]['weapons'][weapon][ 'joints']: turret.elevator = shipClasses[shipClass]['weapons'][ weapon]['joints']['elevator']['axes'] turret.parentID = ship.id turretEntity.addComponent(turret) turretsComponent.turretIDs.append(turretEntity.id) if turrets: for t in turrets: turretEntity = sandbox.addEntity(t.turretid) turret = shipComponents.TurretComponent() weapon = t.turretName if not containsAny( shipClasses[shipClass]['weapons'][weapon]['decay'], 'abcdefghijklmnopqrstuvwyz'): turret.decay = lambda x: eval(shipClasses[shipClass][ 'weapons'][weapon]['decay']) turret.name = weapon turret.damage = shipClasses[shipClass]['weapons'][weapon][ 'damage'] if 'traverser' in shipClasses[shipClass]['weapons'][weapon][ 'joints']: turret.traverser = shipClasses[shipClass]['weapons'][ weapon]['joints']['traverser']['axes'] if 'elevator' in shipClasses[shipClass]['weapons'][weapon][ 'joints']: turret.elevator = shipClasses[shipClass]['weapons'][ weapon]['joints']['elevator']['axes'] turret.parentID = ship.id turretEntity.addComponent(turret) turretsComponent.turretIDs.append(turretEntity.id) ship.addComponent(turretsComponent) #sandbox.send("shipGenerated", [ship, playerShip]) log.info("Ship spawned: " + shipName + " " + shipClass)
physics = BulletWorld() physics.setGravity(Vec3(0, 0, 0)) 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)) physics.attachRigidBody(node) # Attaching the physical object in the scene graph and adding # a visible model to it np = s.render.attachNewNode(node) np.setPos(0, 0, 0) m = loader.loadModel("models/smiley") m.reparentTo(np) # 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
def create_solid(self): node = BulletGhostNode(self.name) node_shape = BulletSphereShape(.05) node.add_shape(node_shape) node.set_kinematic(True) return node