def createPlayer(self, render, world): h = 3.38 w = 0.4 shape = BulletCapsuleShape(w + 0.3, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Robot') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(2, 0, 18) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character) self.actorNP = Actor( '../models/robot/lack.egg', { 'walk': '../models/robot/lack-run.egg', 'idle': '../models/robot/lack-idle.egg', 'jump': '../models/robot/lack-jump.egg', 'land': '../models/robot/lack-land.egg', 'damage': '../models/robot/lack-damage.egg' }) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.15) self.actorNP.setH(180) self.actorNP.setPos(0, 0, -0.06)
def __init__(self, name, scene, visualMesh, physicsMesh=None, physicsType="character", shapeMargin=0.02, stepHeight=0.5, x=0, y=0, z=0, mass=0, convex=True, directRender=True, parent=None): global physicsTypes self.name = name self.scene = scene NodePath.__init__(self, self.scene.loadEgg(visualMesh)) if physicsMesh != None: if physicsType == "rigid": self.body = BulletRigidBodyNode(self.name + "_RigidBody") self.attachNewNode(self.body) m = self.scene.Base.loader.loadModel(physicsMesh) if convex: sTuple = modelToConvex(m) else: sTuple = modelToShape(m) sTuple[0].setMargin(shapeMargin) self.body.addShape(sTuple[0], sTuple[1]) self.body.setMass(mass) self.body.setPythonTag("name", self.name + "_RigidBody") self.scene.world.attachRigidBody(self.body) elif physicsType=="character": m = self.scene.Base.loader.loadModel(physicsMesh) sTuple = modelToConvex(m) sTuple[0].setMargin(shapeMargin) self.body = BulletCharacterControllerNode(sTuple[0], stepHeight, self.name + "_Character") self.attachNewNode(self.body) self.body.setPythonTag("name", self.name + "_Character") self.scene.world.attachCharacter(self.body) self.setPos(x, y, z) if directRender: self.reparentTo(self.scene.Base.render) elif parent != None: self.reparentTo(parent)
def __init__(self, world, render, name, animator, position, pose): # Create a box shape shape = BulletBoxShape(Vec3(0.3, 0.2, 0.7)) # Create a Controller Node with the shape self.controllerNode = BulletCharacterControllerNode(shape, 0.4, name) self.controllerNode.setIntoCollideMask(BitMask32.allOn()) # Attach the Controller Node to the world world.attachCharacter(self.controllerNode) # Attach Controller Node to the render and get a NodePath self.nodePath = render.attachNewNode(self.controllerNode) # Setup the nodePath self.nodePath.setCollideMask(BitMask32.allOn()) self.nodePath.setH(DEFAULT_NODEPATH_HEIGHT) self.nodePath.setPos(position) # Set the actor of the Character self.animator = animator # Add animator to NodePath so it can be rendered self.animator.reparentTo(self.nodePath) # Configure the animator self.animator.setScale(DEFAULT_ANIMATOR_SCALE) self.animator.setH(DEFAULT_ANIMATOR_HEIGHT) self.animator.setPos(DEFAULT_ANIMATOR_OFFSET) # Set Current Character Pose self.pose = pose # Save home position self.home = position
def createCharacter(self): charColl = BulletCapsuleShape(0.4, 1.75 - 2 * 0.4, ZUp) self.diamondChar = BulletCharacterControllerNode( charColl, 0.4, 'Player') self.diamondCharNP = self.worldNP.attachNewNode(self.diamondChar) self.diamondCharNP.setPos(0, 0, 0) self.diamondCharNP.setH(-90) self.diamondCharNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.diamondChar) # Summon the lord Diamondback self.diamondbackChar = Actor( "Resources/models/CHAR/CHRIS", { "walk": "Resources/models/CHAR/CHRIS-Walk2", "idle": "Resources/models/CHAR/CHRIS-Idle2", "jump": "Resources/models/CHAR/CHRIS-Jump" }) self.diamondbackChar.reparentTo(self.diamondCharNP) self.diamondbackChar.setPos(0, 0, -.83) self.diamondbackChar.setScale(1) self.diamondbackChar.setBlend(animBlend=True, frameBlend=True) # Set the camera position tracker self.camPos = NodePath(PandaNode("camTracker")) self.camPos.reparentTo(self.diamondbackChar) # Set the camera to track the lord base.camera.reparentTo(self.camPos) base.camera.setPosHpr(0, 6, 2.5, 180, -5, 0) base.camLens.setFov(90)
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), 0) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) 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 shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(10.0) np.node().addShape(shape) np.setPos(3, 0, 4) np.setH(20.0) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Character self.crouching = False h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.character.setMass(1.0) self.characterNP = self.worldNP.attachNewNode(self.character) self.characterNP.setPos(-2, 0, 14) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.actorNP = Actor('models/ralph/ralph.egg', { 'run' : 'models/ralph/ralph-run.egg', 'walk' : 'models/ralph/ralph-walk.egg', 'jump' : 'models/ralph/ralph-jump.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3048) # 1ft = 0.3048m self.actorNP.setH(180) self.actorNP.setPos(0, 0, -1)
def setUp(self): self.itemNumber = 0 self.incBar() # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(0, 0, 130) self.characterNP.setH(180) self.characterNP.setCollideMask(BitMask32.allOn()) self.models.world.attachCharacter(self.character) self.actorNP = Actor( 'models/Bricker/Bricker3.egg', { 'run': 'models/Bricker/Bricker-run.egg', 'walk': 'models/Bricker/Bricker-walk.egg', 'jump': 'models/Bricker/Bricker-jump.egg', 'fallbackGetup': 'models/Bricker/FallbackGetup.egg', 'fallforwardGetup': 'models/Bricker/Bricker-FallforwardGetup.egg', 'fireball': 'models/Bricker/Bricker-fireball.egg', 'punching': 'models/Bricker/Bricker-punching.egg', 'superpunch': 'models/Bricker/Bricker-superpunch.egg' }) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3) self.actorNP.setH(180) self.actorNP.setPos(0, 0, 0.2) #enemies #self.setUpEnemies() #debug self.debugNode = BulletDebugNode('Debug') self.debugNode.showWireframe(True) self.debugNode.showConstraints(True) self.debugNode.showBoundingBoxes(False) self.debugNode.showNormals(False) self.debugNP = render.attachNewNode(self.debugNode) self.debugNP.hide() self.models.world.setDebugNode(self.debugNP.node())
class Player: def __init__(self, x, y, z, id): self.health = 100 radius = .15 height = 1 shape = BulletCylinderShape(radius, height, ZUp) self.playerNode = BulletCharacterControllerNode(shape, 0.4, str(id)) self.playerNode.setMaxJumpHeight(2.0) self.playerNode.setJumpSpeed(4.0) self.playerNP = base.render.attachNewNode(self.playerNode) self.playerNP.setPos(x, y, z) self.playerModel = Actor('models/soldier.egg', {"idle": "models/soldier_ani_idle.egg", "walk": "models/soldier_ani_walk.egg", "pistol": "models/soldier_ani_pistol.egg", "death": "models/soldier_ani_death.egg",}) self.playerModel.makeSubpart("legs", ["mixamorig:LeftUpLeg", "mixamorig:RightUpLeg"]) self.playerModel.makeSubpart("hips", ["mixamorig:Hips"], ["mixamorig:LeftUpLeg", "mixamorig:RightUpLeg", "mixamorig:Spine"]) self.playerModel.makeSubpart("upperBody", ["mixamorig:Spine"]) self.playerModel.pose("idle", 0, partName="hips") self.playerModel.setH(90) self.playerModel.setScale(.06) self.playerModel.setZ(-.45) self.playerModel.flattenLight() # self.playerModel.setLightOff()self.playerSpine self.playerModel.reparentTo(self.playerNP) self.playerSpine = self.playerModel.controlJoint(None, 'modelRoot', 'mixamorig:Spine') self.hand = self.playerModel.exposeJoint(None, 'modelRoot', 'mixamorig:RightHand') self.spineExpose = self.playerModel.exposeJoint(None, 'modelRoot', 'mixamorig:Spine') self.playerSpine.setH(-7) # player weapon self.weapon = Ak47(self.hand) # player animation self.xSpeed = 0 self.ySpeed = 0 self.animation = Animation(self) self.model = NodePath("MySpineNode") def bendBody(self): self.model.setPos(self.spineExpose, 0, 0, 0) obj = RayCollider.getObjectHit() self.model.lookAt(obj) self.playerSpine.setP(self.model.getP())
def __init__(self, render, world, x, y, z, type): self.type = type h = 1.5 w = 0.4 shape = BulletCapsuleShape(w + 0.3, h - 2 * w, ZUp) self.badCharacter = BulletCharacterControllerNode(shape, 0.4, 'Lego') self.badCharacterNP = render.attachNewNode(self.badCharacter) self.badCharacterNP.setPos(x, y, z) self.startPositionX = self.badCharacterNP.getX() self.startPositionY = self.badCharacterNP.getY() self.startPositionZ = self.badCharacterNP.getZ() # self.badCharacterNP.setH(45) self.badCharacterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.badCharacter) # self.world.attachRigidBody(self.badCharacter.node()) self.badActorNP = Actor( '../models/lego/' + self.type + '/' + self.type + '.egg', { 'walk': '../models/lego/' + self.type + '/' + self.type + '-walk.egg', 'attack': '../models/lego/' + self.type + '/' + self.type + '-attack.egg', }) self.badActorNP.reparentTo(self.badCharacterNP) self.badActorNP.setScale(0.3) self.badActorNP.setH(180) self.badActorNP.setPos(0, 0, 0.5) # Associates badActorNP with badCharacterNP self.badCharacterNP.setPythonTag("badActorNP", self.badActorNP)
def server_created_object(self, tag, height, radius): # This shape is used for collision detection, preventing the player falling through the ground for # example. shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) # A character controller is a physical body which responds instantly to keyboard controls. (Bodies # which respond to forces are difficult to control in a satisfactory way using typical video game # controls. Players expect them to move instantly when a button is pressed, but physics dictates that # they should take a short time to accelerate.) node = BulletCharacterControllerNode(shape, 0.4, tag) node_path = self.render.attachNewNode(node) Thing.add(tag, node, node_path) self.world.attachCharacter(node) # Does this object represent the player who is using this client? if tag == self.__player_tag: # If yes, attach the camera to the object, so the player's view follows the object. self.camera.reparentTo(node_path) else: # If no, create a new Actor to represent the player or NPC. humanoid = Actor("player.bam") humanoid.setH(180) humanoid.reparentTo(node_path) # Scale the Actor so it is the same height as the bounding volume requested by the server. point1 = Point3() point2 = Point3() humanoid.calcTightBounds(point1, point2) humanoid.setScale(height / (point2.z - point1.z)) # If the 3D model has the origin point at floor level, we need to move it down by half the height # of the bounding volume. Otherwise it will hang in mid air, with its feet in the middle of the # bounding volume. humanoid.setZ(-height / 2)
def attackMode(self,location,heading): self.state['normal'] = False self.state['rolling'] = True (self.init_x,self.init_y,self.init_z) = location self.__cylinder_shape = BulletCylinderShape(Eve.WIDTH + 2, Eve.HEIGHT - 4, XUp) # Create bullet character controller self.character2= BulletCharacterControllerNode(self.__cylinder_shape,0.4,self.name) self.characterNP2 = self.__render.attachNewNode(self.character2) self.characterNP2.setPos(self.init_x,self.init_y,self.init_z-2) self.characterNP2.setH(heading) self.characterNP2.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character2) self.character2.setGravity(70) self.actorNP2.reparentTo(self.characterNP2) self.actorNP2.setScale(4.0) self.actorNP2.setH(180) self.actorNP2.setPos(0,0,0) self.currentNode = self.actorNP2 self.currentNP = self.characterNP2 self.currentControllerNode = self.character2 # Set play rate of the rolling animation self.currentNode.setPlayRate(15,'roll')
def __init__(self, name, scene, visualMesh, collisionMesh, animations, step=0.2, margin=0.01): """ :type collisionMesh: String :type visualMesh: String :type name: String :type margin: Float :param name: Name :param scene: Scene :param visualMesh: Egg to use as visual mesh :param collisionMesh: Egg to use as convex shape for physics :param animations: Animation dict :param step: Character step height :param margin: Physics shape margin """ self.name = name self.scene = scene m = self.scene.Base.loader.loadModel(collisionMesh) sTuple = modelToConvex(m) sTuple[0].setMargin(margin) self.body = Character(sTuple[0], step, self.name + "_Character") #self.attachNewNode(self.body) self.body.setPythonTag("name", self.name + "_Character") self.scene.world.attachCharacter(self.body) NodePath.__init__(self, self.body) self.actor = Actor(self.scene.loadEgg(visualMesh), animations) self.actor.reparentTo(self)
def setup(self): self.worldNP = render.attach_new_node('World') # World self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Ground shape = BulletPlaneShape(LVector3(0, 0, 1), 0) #img = PNMImage(Filename('models/elevation.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground')) np.node().add_shape(shape) np.set_pos(0, 0, -1) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Box shape = BulletBoxShape(LVector3(1.0, 3.0, 0.3)) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box')) np.node().set_mass(10.0) np.node().add_shape(shape) np.set_pos(3, 0, 4) np.setH(20.0) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Character self.crouching = False h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = self.worldNP.attach_new_node(self.character) self.characterNP.set_pos(-2, 0, 14) self.characterNP.set_h(45) self.characterNP.set_collide_mask(BitMask32.all_on()) self.world.attach(self.character) self.actorNP = Actor( 'samples/roaming-ralph/models/ralph.egg.pz', { 'run': 'samples/roaming-ralph/models/ralph-run.egg.pz', 'walk': 'samples/roaming-ralph/models/ralph-walk.egg.pz' }) self.actorNP.reparent_to(self.characterNP) self.actorNP.set_scale(0.3048) # 1ft = 0.3048m self.actorNP.setH(180) self.actorNP.set_pos(0, 0, -1)
def setPhysics(self, collisionMesh, step, margin): m = self.scene.Base.loader.loadModel(collisionMesh) sTuple = modelToConvex(m) sTuple[0].setMargin(margin) self.body = Character(sTuple[0], step, self.name + "_Character") self.attachNewNode(self.body) self.body.setPythonTag("name", self.name + "_Character") self.scene.world.attachCharacter(self.body) self.actor.reparentTo(self)
def __init__(self, game_state, height, radius, name): Thing.__init__(self, game_state) self.height = height self.radius = radius shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.node = BulletCharacterControllerNode(shape, 0.4, self.get_unique_name(name)) self.node_path = self.game_state.render.attachNewNode(self.node) self.game_state.world.attachCharacter(self.node)
def bulletInit(self,world,pos): oldpath = self.instance.find("**/body_coll") self.radius = oldpath.node().getSolid(0).getRadius() shape = BulletSphereShape(self.radius) self.character = BulletCharacterControllerNode(shape, 0.4, 'AI'+str(Player.counter)) self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(pos[0],pos[1],pos[2]) self.character.setGravity(0) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character)
def buildCharacterController(self, _height, _radius, _pos, _head): """Build a basic BulletCharacter Controller""" shape = BulletCapsuleShape(_radius, _height - 2 * _radius, ZUp) charNode = BulletCharacterControllerNode(shape, _radius, "Player") np = self.engine.BulletObjects["player"].attachNewNode(charNode) np.setPos(_pos) np.setH(_head) np.setCollideMask(BitMask32.allOn()) self.engine.bulletWorld.attachCharacter(np.node()) return np
def __init__(self): super().__init__() self.master = window.Window.get_instance() self.keyMap = { self.master.bind[Bind.FWD.value]: False, self.master.bind[Bind.BWD.value]: False, self.master.bind[Bind.RIGHT.value]: False, self.master.bind[Bind.LEFT.value]: False, self.master.bind[Bind.UP.value]: False, self.master.bind[Bind.DOWN.value]: False, self.master.bind[Bind.SPACE.value]: False } self.equipment = Equipment(self) self.rotation = [-70, 140] height = 2.5 radius = 0.4 character_shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.player_node = BulletCharacterControllerNode( character_shape, 0.4, 'Player') self.player_node_path = self.master.world_node.attachNewNode( self.player_node) self.player_node_path.setPos(90, 31, 395) self.player_node_path.setCollideMask(BitMask32.allOn()) self.master.camera.reparentTo(self.player_node_path) self.master.camera.setY(self.master.camera, -5) self.camera_model = self.master.loader.loadModel( "mesh/models/person/person") self.camera_model.reparentTo(self.player_node_path) self.bind() self.master.taskMgr.add(self.camera_control, "Camera Control") self.master.world.attachCharacter(self.player_node_path.node())
def searchMode(self,location,heading): self.state['normal'] = True self.state['rolling'] = False (self.init_x,self.init_y,self.init_z) = location self.__capsule_shape = BulletCapsuleShape(Eve.WIDTH, Eve.HEIGHT - 2 * Eve.WIDTH, ZUp) # Create bullet character controller self.character1= BulletCharacterControllerNode(self.__capsule_shape,0.4,self.name) #self.character1.setMaxJumpHeight(Eve.MAX_JUMP_HEIGHT) self.character1.setJumpSpeed(Eve.JUMP_SPEED) self.character1.setGravity(70) self.characterNP1 = self.__render.attachNewNode(self.character1) self.characterNP1.setPos(self.init_x,self.init_y,self.init_z) self.characterNP1.setH(heading) self.characterNP1.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character1) self.actorNP1.reparentTo(self.characterNP1) self.actorNP1.setScale(4.0) self.actorNP1.setH(180) self.actorNP1.setPos(0,0,-9) self.currentNode = self.actorNP1 self.currentNP = self.characterNP1 self.currentControllerNode = self.character1 # Create a cylindrical collision shape collisionShape = BulletCylinderShape(6.5,3,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode('Weapon') self.ghostNode.addShape(collisionShape) self.weaponNP = self.__game.render.attachNewNode(self.ghostNode) self.weaponNP.setCollideMask(BitMask32.allOff()) self.weaponNP.setPos(self.init_x, self.init_y, self.init_z) self.__game.world.attachGhost(self.ghostNode) self.weapon = self.__game.loader.loadModel('models/environ/tire/tire.egg') self.weapon.setScale(4,4,4) self.weapon.setPos(-.5,0,0) self.weapon.reparentTo(self.weaponNP) self.weapon.hide() self.__game.taskMgr.add(self.update_weapon_pos,"weapon")
def setupPhysics(self, **kwargs): self.worldNp = kwargs['worldnp'] self.world = kwargs['world'] h = .2 w = .1 shape = BulletCapsuleShape(w, h, ZUp) self.character = BulletCharacterControllerNode( shape, .5, 'Player_{}'.format(self.name)) self.characterNP = self.worldNp.attachNewNode(self.character) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.floater = NodePath(PandaNode('floater')) self.floater.reparentTo(self.characterNP) self.floater.setZ(self.characterNP, .52) self.floater.setY(self.characterNP.getY() + .25)
def setupCharacter2(self): # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character2 = BulletCharacterControllerNode(shape, 0.4, 'Player') self.character2.setGravity(35) self.characterNP2 = self.render.attachNewNode(self.character2) self.characterNP2.setPos(0, 10, 5) self.characterNP2.setCollideMask(BitMask32.allOn()) self.world2.attachCharacter(self.character2) self.ecco2 = Actor('ralph-models/ralph.egg.pz', { 'run': 'ralph-models/ralph-run.egg', 'jump': 'ralph/ralph-run.egg', 'damage': 'models/lack-damage.egg'}) self.ecco2.reparentTo(self.characterNP2) self.ecco2.setScale(0.7048) self.ecco2.setH(180)
def createPlayer(self): h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') # self.character.setMass(1.0) self.characterNP = self.render.attachNewNode(self.character) self.characterNP.setPos(self.x, self.y, self.z) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.actorNP = Actor('models/Bricker/Bricker3.egg', { 'run': 'models/Bricker/Bricker-run.egg', 'jump': 'models/Bricker/Bricker-jump.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3048) self.actorNP.setH(180) self.actorNP.setPos(0, 0, 0.27)
def set_physics(self, phys_mgr): """Set the locomotive physics. Args: phys_mgr (panda3d.bullet.BulletWorld): Physical world. """ self._phys_shape = BulletCharacterControllerNode( BulletBoxShape(Vec3(0.095, 0.55, 0.1)), 10, "train_shape") self._phys_node = self.model.attachNewNode(self._phys_shape) self._phys_node.setZ(0.1) phys_mgr.attachCharacter(self._phys_shape) taskMgr.doMethodLater( # noqa: F821 0.1, self._check_contacts, "check_train_contacts", extraArgs=[phys_mgr, self._phys_node.node()], appendTask=True, )
def createPlayer(self, render, world): h = 3.38 w = 0.4 shape = BulletCapsuleShape(w + 0.3, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Robot') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(2, 0, 18) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character) self.actorNP = Actor('../models/robot/lack.egg', { 'walk': '../models/robot/lack-run.egg', 'idle': '../models/robot/lack-idle.egg', 'jump': '../models/robot/lack-jump.egg', 'land': '../models/robot/lack-land.egg', 'damage': '../models/robot/lack-damage.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.15) self.actorNP.setH(180) self.actorNP.setPos(0, 0, -0.06)
def bulletInit(self,world,pos): """bulletInit parameters: self task: the tskMgr structure returns: none Description: The rest of init requires bullet things """ oldpath = self.human.find("**/body_coll") self.shape = BulletSphereShape(10)#oldpath.node().getSolid(0).getRadius()) self.character = BulletCharacterControllerNode(self.shape, 0.4, 'Human') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(pos[0],pos[1],pos[2]) self.character.setGravity(0) #self.human.setPos(pos) self.human.reparentTo(self.characterNP) self.human.hide() #self.player.setPos(pos) self.player.reparentTo(self.characterNP) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character)
class character(Actor, FSM, GravityWalker): RUNSPEED = 2 def __init__(self, **kwargs): animes = {} for a, b, c in os.walk('models/char/animes'): for d in c: animes[d] = 'models/char/animes/%s' % (d) super(character, self).__init__(kwargs['char'], anims=animes) self.name = kwargs['name'] FSM.__init__(self, self.name) self.setH(180) self.setupAnimes() self.interval_setup() self.setPos(0, 0, -.2) self.setScale(.2) self.lockedOnTarget = True self.targets = [] self.anim_playList = [] self.isAction = { 'run': False, 'jump': False, 'hit_distance': False, 'idle': False, 'jumpPunch': False, 'punch': False, 'kick': False, 'strifeLeft': False, 'strifeRight': False, 'runLeft': False, 'runRight': False } self.animes = { 'jump': self.jumpping, 'run': self.running, 'jumpPunch': self.jumpPunch } inputState.watch('run', 'player1axis1', None) def setupPhysics(self, **kwargs): self.worldNp = kwargs['worldnp'] self.world = kwargs['world'] h = .2 w = .1 shape = BulletCapsuleShape(w, h, ZUp) self.character = BulletCharacterControllerNode( shape, .5, 'Player_{}'.format(self.name)) self.characterNP = self.worldNp.attachNewNode(self.character) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.floater = NodePath(PandaNode('floater')) self.floater.reparentTo(self.characterNP) self.floater.setZ(self.characterNP, .52) self.floater.setY(self.characterNP.getY() + .25) def setupAnimes(self): self.running = self.getAnimControl('run.egg') self.jumpping = self.getAnimControl('jump.egg') self.jumpPunch = self.getAnimControl('jumppunch.egg') self.rightPunch = self.getAnimControl('rightpunch.egg') self.leftKick = self.getAnimControl('leftkick.egg') self.leftKick.setPlayRate(2) self.rightPunch.setPlayRate(3) self.actionAnim = [self.rightPunch, self.leftKick] self.actionList = [] def setupController(self, joy, player, handler): self.game = handler if type(joy) != tuple: if handler.numofjoy >= 1: self.joy = joy['player{}'.format(player + 1)] handler.numofjoy -= 1 taskMgr.add(self.use_joy, 'player{}joyUpdate'.format(player + 1)) self.useKeyboard = False else: self.joy = 'keyboard{}'.format(player + 1) self.useKeyboard = True self.use_Keyboard() else: self.joy = 'keyboard{}'.format(player + 1) self.useKeyboard = True self.use_Keyboard() def setup_collision(self): self.player_results = self.world.contactTest(self.character) dt = globalClock.getDt() for contact in self.player_results.getContacts(): print( str(contact.getNode0()) + ' bumps ' + str(contact.getNode1())) mpoint = contact.getManifoldPoint() #print(mpoint.getDistance()) #print(mpoint.getLocalPointA()) def getModel(self): self.reparentTo(self.characterNP) def use_Keyboard(self): print(self.joy) def use_joy(self, task): self.button1 = self.joy.get_button(0) self.button2 = self.joy.get_button(1) self.button3 = self.joy.get_button(2) self.button4 = self.joy.get_button(3) self.button5 = self.joy.get_button(4) self.button6 = self.joy.get_button(5) self.button7 = self.joy.get_button(6) self.button8 = self.joy.get_button(7) self.button9 = self.joy.get_button(8) self.button10 = self.joy.get_button(9) self.button11 = self.joy.get_button(10) self.button12 = self.joy.get_button(11) self.axis1 = self.joy.get_axis(0) self.axis2 = self.joy.get_axis(1) self.axis3 = self.joy.get_axis(2) self.axis4 = self.joy.get_axis(3) self.dpad = self.joy.get_hat(0) for x in self.actionAnim: if x.isPlaying(): if not x in self.actionList: self.actionList.append(x) print('action') break else: if len(self.actionList) > 0: self.actionList.pop(0) self.enemy_setup() self.joy_controls() return task.cont def toggleLockOn(self): if self.lockedOnTarget: self.lockedOnTarget = False else: self.lockedOnTarget = True def joy_controls(self): self.speed = Vec3(0, 0, 0) omega = globalClock.getDt() if not self.lockedOnTarget: if self.axis2 > .4: self.characterNP.setH(base.camera.getH() + 180) self.speed.setY(self.RUNSPEED) elif self.axis2 < -.4: self.characterNP.setH(base.camera.getH()) self.speed.setY(self.RUNSPEED) elif self.axis1 > .4: self.characterNP.setH(base.camera.getH() - 90) self.speed.setY(self.RUNSPEED) elif self.axis1 < -.4: self.characterNP.setH(base.camera.getH() + 90) self.speed.setY(self.RUNSPEED) if self.axis1 > .4 and self.axis2 < -.4: self.characterNP.setH(base.camera.getH() - 45) elif self.axis1 > .4 and self.axis2 > .4: self.characterNP.setH(base.camera.getH() - 135) elif self.axis1 < -.4 and self.axis2 < -.4: self.characterNP.setH(base.camera.getH() + 45) elif self.axis1 < -.4 and self.axis2 > .4: self.characterNP.setH(base.camera.getH() + 135) if self.axis3 > .4: base.camera.setX(base.camera, +20 * omega) elif self.axis3 < -.4: base.camera.setX(base.camera, -20 * omega) else: if self.axis2 > .4: self.speed.setY(-6) if self.axis2 < -.4: self.speed.setY(6) if self.axis1 > .4: self.speed.setX(5) if self.axis1 < -.4: self.speed.setX(-5) self.characterNP.lookAt(self.targets[0]) if (self.axis1 < -.4 and self.axis2 < -.4): if self.character.isOnGround(): if not self.isAction['runLeft']: self.runLeft() for action in self.isAction: self.isAction[action] = False self.isAction['runLeft'] = True elif (self.axis1 > .4 and self.axis2 < -.4): if self.character.isOnGround(): if not self.isAction['runRight']: self.runRight() for action in self.isAction: self.isAction[action] = False self.isAction['runRight'] = True elif self.axis2 > .4: if self.button2: if self.character.isOnGround(): if not self.isAction['jump']: self.jump() for action in self.isAction: self.isAction[action] = False self.isAction['jump'] = True else: if not len(self.actionList): if self.character.isOnGround(): if not self.isAction['idle']: self.idle() for a in self.isAction: self.isAction[a] = False self.isAction['idle'] = True elif self.button1: if self.character.isOnGround(): if not len(self.actionList): if not self.isAction['punch']: self.punch() for action in self.isAction: self.isAction[action] = False self.isAction['punch'] = True elif not self.character.isOnGround(): if not self.isAction['jumpPunch']: self.jump_punch() for action in self.isAction: self.isAction[action] = False self.isAction['jumpPunch'] = True else: if self.character.isOnGround(): if self.isAction['run'] != True: self.run() for action in self.isAction: self.isAction[action] = False self.isAction['run'] = True elif self.axis2 < -.4: if self.button2: if self.character.isOnGround(): if not self.isAction['jump']: self.jump() for action in self.isAction: self.isAction[action] = False self.isAction['jump'] = True else: if not len(self.actionList): if self.character.isOnGround(): if not self.isAction['idle']: self.idle() for a in self.isAction: self.isAction[a] = False self.isAction['idle'] = True elif self.button1: if self.character.isOnGround(): if not len(self.actionList): if not self.isAction['punch']: self.punch() for action in self.isAction: self.isAction[action] = False self.isAction['punch'] = True elif not self.character.isOnGround(): if not self.isAction['jumpPunch']: self.jump_punch() for action in self.isAction: self.isAction[action] = False self.isAction['jumpPunch'] = True else: if self.character.isOnGround(): if self.isAction['run'] != True: self.run() for action in self.isAction: self.isAction[action] = False self.isAction['run'] = True elif self.axis1 > .4: if self.lockedOnTarget: if self.character.isOnGround(): if self.isAction['strifeRight'] != True: self.strifeRight() for action in self.isAction: self.isAction[action] = False self.isAction['strifeRight'] = True else: if self.character.isOnGround(): if self.isAction['run'] != True: self.run() for action in self.isAction: self.isAction[action] = False self.isAction['run'] = True elif self.axis1 < -.4: if self.lockedOnTarget: if self.character.isOnGround(): if self.isAction['strifeLeft'] != True: self.strifeLeft() for action in self.isAction: self.isAction[action] = False self.isAction['strifeLeft'] = True else: if self.character.isOnGround(): if self.isAction['run'] != True: self.run() for action in self.isAction: self.isAction[action] = False self.isAction['run'] = True elif self.button2: if self.character.isOnGround(): if not self.isAction['jump']: self.jump() for action in self.isAction: self.isAction[action] = False self.isAction['jump'] = True else: if not len(self.actionList): if self.character.isOnGround(): if not self.isAction['idle']: self.idle() for a in self.isAction: self.isAction[a] = False self.isAction['idle'] = True elif self.button1: if self.character.isOnGround(): if not len(self.actionList): if not self.isAction['punch']: self.punch() for action in self.isAction: self.isAction[action] = False self.isAction['punch'] = True elif not self.character.isOnGround(): if not self.isAction['jumpPunch']: self.jump_punch() for action in self.isAction: self.isAction[action] = False self.isAction['jumpPunch'] = True elif self.button3: if self.character.isOnGround(): if not len(self.actionList): if not self.isAction['kick']: self.kick() for action in self.isAction: self.isAction[action] = False self.isAction['kick'] = True else: if not len(self.actionList): if self.character.isOnGround(): if not self.isAction['idle']: self.idle() for a in self.isAction: self.isAction[a] = False self.isAction['idle'] = True else: if not len(self.actionList): if self.character.isOnGround(): if not self.isAction['idle']: self.idle() for a in self.isAction: self.isAction[a] = False self.isAction['idle'] = True if self.button5: self.toggleLockOn() self.character.setLinearMovement(self.speed, True) def enemy_setup(self): for enemy in self.game.listOfPlayers: if enemy.character.name != self.character.name: if not enemy in self.targets: self.targets.append(enemy) def interval_setup(self): self.jumpInterval = self.actorInterval('jump.egg', loop=0, startFrame=1, endFrame=10) self.jumpPunchInterval = self.actorInterval( 'jumppunch.egg', playRate=2, loop=0, startFrame=self.jumpPunch.getNumFrames() / 2, endFrame=self.jumpPunch.getNumFrames()) def lockON(self, player): self.characterNP.lookAt(player) def punch(self): self.request('Punch') def kick(self): self.request('Kick') def jump_punch(self): self.request('JumpPunch') def jump(self): self.request('Jump') def run(self): self.request('Run') def runLeft(self): self.request('RunLeft') def runRight(self): self.request('RunRight') def strifeLeft(self): self.request('StrifeLeft') def strifeRight(self): self.request('StrifeRight') def idle(self): self.request('Idle') #Finite State Rquests def enterJumpPunch(self): self.jumpPunchInterval.start() def enterPunch(self): self.rightPunch.play() def enterKick(self): self.leftKick.play() def enterJump(self): self.character.setMaxJumpHeight(5.0) self.character.setJumpSpeed(2.0) self.jumpInterval.start() self.character.doJump() def enterIdle(self): self.loop('idle.egg') def enterRun(self): self.loop('run.egg') def enterRunLeft(self): self.loop('runleft.egg') def enterRunRight(self): self.loop('runright.egg') def enterStrifeLeft(self): self.loop('leftstrife.egg') def enterStrifeRight(self): self.loop('rightstrife.egg') def exitJumpPunch(self): self.jumpPunchInterval.finish() def exitRun(self): self.stop() def exitRunLeft(self): self.stop() def exitRunRight(self): self.stop() def exitStrifeLeft(self): self.stop() def exitStrifeRight(self): self.stop() def exitPunch(self): self.stop() def exitKick(self): self.stop() def exitJump(self): self.stop() def exitIdle(self): self.stop() def debug_mode(self): pass
class CreatePlayer: def __init__(self, world, worldNP): self.diamondbackChar = None self.world = world self.worldNP = worldNP # Store which keys are being pressed self.keyPressed = {"fwd": 0, "back": 0, "left": 0, "right": 0} # Setup everything self.createCharacter() self.setupKeys() self.isMoving = False taskMgr.add(self.move, "moveTask") self.pos = OnscreenText(text="POS", style=3, fg=(1, 1, 1, 1), pos=(-0.02, 0.1), scale=.07, parent=base.a2dBottomRight, align=TextNode.ARight) self.lerpAnimation(self.diamondbackChar, "idle") def createCharacter(self): charColl = BulletCapsuleShape(0.4, 1.75 - 2 * 0.4, ZUp) self.diamondChar = BulletCharacterControllerNode( charColl, 0.4, 'Player') self.diamondCharNP = self.worldNP.attachNewNode(self.diamondChar) self.diamondCharNP.setPos(0, 0, 0) self.diamondCharNP.setH(-90) self.diamondCharNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.diamondChar) # Summon the lord Diamondback self.diamondbackChar = Actor( "Resources/models/CHAR/CHRIS", { "walk": "Resources/models/CHAR/CHRIS-Walk2", "idle": "Resources/models/CHAR/CHRIS-Idle2", "jump": "Resources/models/CHAR/CHRIS-Jump" }) self.diamondbackChar.reparentTo(self.diamondCharNP) self.diamondbackChar.setPos(0, 0, -.83) self.diamondbackChar.setScale(1) self.diamondbackChar.setBlend(animBlend=True, frameBlend=True) # Set the camera position tracker self.camPos = NodePath(PandaNode("camTracker")) self.camPos.reparentTo(self.diamondbackChar) # Set the camera to track the lord base.camera.reparentTo(self.camPos) base.camera.setPosHpr(0, 6, 2.5, 180, -5, 0) base.camLens.setFov(90) def doJump(self): self.diamondChar.setMaxJumpHeight(1) self.diamondChar.setJumpSpeed(4) self.diamondChar.doJump() self.JUMPSEQ = Sequence( Func(self.lerpAnimation, self.diamondbackChar, "jump", doLoop=False), Wait(2), Func(self.doAnimation)).start() def setupKeys(self): base.accept("w", self.keypress, ["fwd", True]) base.accept("s", self.keypress, ["back", True]) base.accept("a", self.keypress, ["left", True]) base.accept("d", self.keypress, ["right", True]) base.accept('space', self.doJump) base.accept("w-up", self.keypress, ["fwd", False]) base.accept("s-up", self.keypress, ["back", False]) base.accept("a-up", self.keypress, ["left", False]) base.accept("d-up", self.keypress, ["right", False]) def disableKeys(self): base.ignore("w") base.ignore("s") base.ignore("a") base.ignore("d") base.ignore('space') base.ignore("w-up") base.ignore("s-up") base.ignore("a-up") base.ignore("d-up") def keypress(self, key, value): self.keyPressed[key] = value def move(self, task): dt = globalClock.getDt() if (self.keyPressed["fwd"] != 0): self.diamondCharNP.setY(self.diamondCharNP, -5 * dt) if (self.keyPressed["left"] != 0): self.diamondCharNP.setH(self.diamondCharNP.getH() + 150 * dt) if (self.keyPressed["right"] != 0): self.diamondCharNP.setH(self.diamondCharNP.getH() - 150 * dt) if (self.keyPressed["back"] != 0): self.diamondCharNP.setY(self.diamondCharNP, +5 * dt) if self.keyPressed["fwd"] or self.keyPressed[ "back"] or self.keyPressed["left"] or self.keyPressed["right"]: if self.isMoving is False: self.lerpAnimation(self.diamondbackChar, "walk") self.isMoving = True else: if self.isMoving: self.lerpAnimation(self.diamondbackChar, "idle") self.isMoving = False self.pos["text"] = str(self.diamondCharNP.getPos()) return task.cont def doAnimation(self): if self.isMoving: self.lerpAnimation(self.diamondbackChar, "walk") else: self.lerpAnimation(self.diamondbackChar, "idle") if self.JUMPSEQ: self.JUMPSEQ.finish() def lerpAnimation(self, actor, nextAnim, doLoop=True): LerpAnimInterval(actor, 0.4, self.diamondbackChar.getCurrentAnim(), nextAnim).start() actor.stop(actor.getCurrentAnim()) if doLoop: actor.loop(nextAnim) else: actor.play(nextAnim) def moveTo(self, x, y, z, h): self.diamondCharNP.setPosHpr(x, y, z, h, 0, 0)
def characterController(self, name, height, mass, radius, step_height): shape = BulletCapsuleShape(radius, height - 2*radius, ZUp) body = BulletRigidBodyNode(name) body.setMass(mass) body.addShape(shape) return BulletCharacterControllerNode(shape, step_height, name)
class Game(DirectObject): def __init__(self): #ShowBase.__init__(self) base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) #self.accept('space', self.doJump) #self.accept('c', self.doCrouch) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup() # _____HANDLER_____ def doExit(self): self.cleanup() sys.exit(1) def doReset(self): self.cleanup() self.setup() def toggleWireframe(self): base.toggleWireframe() def toggleTexture(self): base.toggleTexture() def toggleDebug(self): if self.debugNP.isHidden(): self.debugNP.show() else: self.debugNP.hide() def doScreenshot(self): base.screenshot('Bullet') #def doJump(self): # self.player.setMaxJumpHeight(5.0) # self.player.setJumpSpeed(8.0) # self.player.doJump() #def doCrouch(self): # self.crouching = not self.crouching # sz = self.crouching and 0.6 or 1.0 # self.playerNP2.setScale(Vec3(1, 1, sz)) # ____TASK___ def processInput(self, dt): speed = Vec3(0, 0, 0) omega = 0.0 if inputState.isSet('forward'): speed.setY(2.0 * dt * 60.0) if inputState.isSet('reverse'): speed.setY(-2.0) if inputState.isSet('left'): speed.setX(-2.0) if inputState.isSet('right'): speed.setX(2.0) if inputState.isSet('turnLeft'): omega = 120.0 if inputState.isSet('turnRight'): omega = -120.0 self.player.setAngularMovement(omega) self.player.setLinearMovement(speed, True) def update(self, task): dt = globalClock.getDt() self.processInput(dt) self.world.doPhysics(dt, 4, 1. / 240.) self.updateCamera() return task.cont def cleanup(self): self.world = None self.worldNP.removeNode() def updateCamera(self): camvec = self.playerNP.getPos() - self.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if camdist > 10.0: self.camera.setPos(self.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if camdist < 5.0: self.camera.setPos(self.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 self.camera.setZ(self.playerNP.getZ() + 2) self.camera.lookAt(self.playerNP) ################################### ############## SETUP ############## ################################### def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() ####### MV self.environ = loader.loadModel("world/world") self.environ.reparentTo(render) self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 0) #actor = Actor('world/world') mesh = BulletTriangleMesh() ###### create terrein colligion shape geomNodeCollection = self.environ.findAllMatches('**/+GeomNode') for nodePath in geomNodeCollection: #.asList(): geomNode = nodePath.node() print("here1") for i in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(i) print("here2") print(geom) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) shape.set_margin(0.0) #print(geomNodeCollection) # for geom in actor.getGeomNode().get_geoms(): # mesh.addGeom(geom) # shape = BulletTriangleMeshShape(mesh, dynamic=False) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, 0) #-1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(50.0) np.node().addShape(shape) np.setPos(3, 0, 7) np.setH(0) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.player = BulletCharacterControllerNode( shape, 0.4, 'Player') #MV was: BulletCharacterNode(shape, 0.4, 'Player') #self.player.setMass(20.0) self.player.setMaxSlope(70.0) self.player.setGravity(9.81) #self.player.setFrictionSlip(100.0) self.playerNP = self.worldNP.attachNewNode(self.player) #self.playerNP.setMass(20.0) self.playerNP.setPos(-2, 0, 10) self.playerNP.setH(-90) self.playerNP.setCollideMask(BitMask32.allOn()) #self.playerNP.flattenLight() self.world.attachCharacter(self.player) self.ralph = Actor("ralph/ralph", { "run": "ralph/ralph-run", "walk": "ralph/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3048) self.ralph.setPos(0, 0, -1) self.ralph.setH(180) self.ralph.reparentTo(self.playerNP) ## Camera self.camera = base.cam base.disableMouse() self.camera.setPos(self.playerNP.getX(), self.playerNP.getY() + 10, 2) self.camera.lookAt(self.playerNP)
class Player(DirectObject): def __init__(self): # Input self.accept('space', self.doJump) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('turnLeft', 'a') inputState.watchWithModifiers('turnRight', 'd') health = 100 self.isNotWalking = False self.isJumping = False def processInput(self, dt): speed = Vec3(0, 0, 0) omega = 0.0 # Change speed of robot if inputState.isSet('forward'): speed.setY(24.0) if inputState.isSet('reverse'): speed.setY(-4.0) if inputState.isSet('left'): speed.setX(-3.0) if inputState.isSet('right'): speed.setX(3.0) if inputState.isSet('turnLeft'): omega = 120.0 if inputState.isSet('turnRight'): omega = -120.0 if inputState.isSet('forward') or inputState.isSet('reverse') or inputState.isSet('left') or \ inputState.isSet('right'): if self.isNotWalking is False: self.actorNP.loop("walk") self.isNotWalking = True else: if self.isNotWalking: self.actorNP.stop() self.actorNP.loop("idle") self.isNotWalking = False if self.character.isOnGround() and self.isJumping: if self.isNotWalking: self.actorNP.stop("jump") self.actorNP.loop("walk") self.isJumping = False self.character.setAngularMovement(omega) self.character.setLinearMovement(speed, True) def createPlayer(self, render, world): h = 3.38 w = 0.4 shape = BulletCapsuleShape(w + 0.3, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Robot') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(2, 0, 18) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character) self.actorNP = Actor('../models/robot/lack.egg', { 'walk': '../models/robot/lack-run.egg', 'idle': '../models/robot/lack-idle.egg', 'jump': '../models/robot/lack-jump.egg', 'land': '../models/robot/lack-land.egg', 'damage': '../models/robot/lack-damage.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.15) self.actorNP.setH(180) self.actorNP.setPos(0, 0, -0.06) def doJump(self): self.isJumping = True # self.jump = loader.loadSfx("../sounds/jump.mp3") # self.jump.setVolume(0.8) self.character.setMaxJumpHeight(18.0) self.character.setJumpSpeed(8.0) self.character.doJump() self.actorNP.play("jump") self.actorNP.setPlayRate(0.8, "jump") # self.actorNP.play("land") # self.actorNP.setPlayRate(0.8, "land") def startPosLevel1(self): self.characterNP.setPos(2, 0, 5) def startPosLevel2(self): self.characterNP.setPos(-218, 496, 5) def cameraFollow(self, floater): base.disableMouse() desiredPos = self.characterNP.getPos() + self.characterNP.getQuat().xform(Vec3(3, -20, 6.5)) base.camera.setPos(desiredPos) # If the camera is too far from robot, move it closer. # If the camera is too close to robot, move it farther. camvec = self.characterNP.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 20.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 20)) camdist = 20.0 if (camdist < 10.0): base.camera.setPos(base.camera.getPos() - camvec * (10 - camdist)) camdist = 10.0 # Camera follows floater that's slightly above player floater.setPos(self.characterNP.getPos()) floater.setZ(self.characterNP.getZ() + 2.5) base.camera.lookAt(floater)
class Character2(object): def __init__(self): self.models = Models2() self.health = 100.0 self.lost = 0 self.won = 0 self.debug = False self.ev = False self.re = False self.isMoving = False self.nextLevel = False self.b3 = 0 self.setUp() self.setUpEnemies() taskMgr.add(self.update, 'update') taskMgr.add(self.updateItems, 'updateItems') taskMgr.add(self.updateEnemies, 'updateEnemies') taskMgr.add(self.updateEndPoint, 'updateEndPoint') self.mySoundRing = base.loader.loadSfx("sound/ring.mp3") self.mySoundPunch = base.loader.loadSfx("sound/punch_or_whack.mp3") self.mySoundEvil = base.loader.loadSfx("sound/Evil_Laugh_Male.mp3") self.mySoundEndFx = base.loader.loadSfx("sound/End_Fx.mp3") self.mySoundEnd = base.loader.loadSfx("sound/Fireworks.mp3") self.mySoundRunning = base.loader.loadSfx("sound/running.mp3") self.mySoundJump = base.loader.loadSfx("sound/jump.mp3") def setUpEnemies(self): h2 = 3.75 w2 = 1.1 shape2 = BulletCapsuleShape(w2, h2 - 2 * w2, ZUp) self.e1 = BulletRigidBodyNode("E1") self.e1.setMass(0) self.e1.addShape(shape2) self.e1NP = render.attachNewNode(self.e1) self.e1NP.setPos(self.models.box6.getX(), self.models.box6.getY(), self.models.box6.getZ() + 3) self.e1NP.setCollideMask(BitMask32.allOn()) self.models.world.attachRigidBody(self.e1) self.actorNPe1 = loader.loadModel('models/mummy/mummy.egg') self.actorNPe1.reparentTo(self.e1NP) self.actorNPe1.setScale(0.05) self.actorNPe1.setPos(0, 0, -1.0) self.e1Hited = 0 h3 = 3.75 w3 = 1.1 shape3 = BulletCapsuleShape(w3, h3 - 2 * w3, ZUp) self.e2 = BulletRigidBodyNode("E2") self.e2.setMass(0) self.e2.addShape(shape3) self.e2NP = render.attachNewNode(self.e2) self.e2NP.setPos(self.models.Cylinder1.getX(), self.models.Cylinder1.getY(), self.models.Cylinder1.getZ() + 3) self.e2NP.setCollideMask(BitMask32.allOn()) self.models.world.attachRigidBody(self.e2) self.actorNPe2 = loader.loadModel('models/mummy/mummy.egg') self.actorNPe2.reparentTo(self.e2NP) self.actorNPe2.setScale(0.05) self.actorNPe2.setPos(0, 0, -1.0) self.e2Hited = 0 h4 = 3.75 w4 = 1.1 shape4 = BulletCapsuleShape(w4, h4 - 2 * w4, ZUp) self.e3 = BulletRigidBodyNode("E3") self.e3.setMass(0) self.e3.addShape(shape4) self.e3NP = render.attachNewNode(self.e3) self.e3NP.setPos(self.models.Cylinder2.getX(), self.models.Cylinder2.getY(), self.models.Cylinder2.getZ() + 3) self.e3NP.setCollideMask(BitMask32.allOn()) self.models.world.attachRigidBody(self.e3) self.actorNPe3 = loader.loadModel('models/mummy/mummy.egg') self.actorNPe3.reparentTo(self.e3NP) self.actorNPe3.setScale(0.05) self.actorNPe3.setPos(0, 0, -1.0) self.e3Hited = 0 h5 = 3.75 w5 = 1.1 shape5 = BulletCapsuleShape(w5, h5 - 2 * w5, ZUp) self.e4 = BulletRigidBodyNode("E4") self.e4.setMass(0) self.e4.addShape(shape5) self.e4NP = render.attachNewNode(self.e4) self.e4NP.setPos(self.models.Cylinder3.getX(), self.models.Cylinder3.getY(), self.models.Cylinder3.getZ() + 3) self.e4NP.setCollideMask(BitMask32.allOn()) self.models.world.attachRigidBody(self.e4) self.actorNPe4 = loader.loadModel('models/mummy/mummy.egg') self.actorNPe4.reparentTo(self.e4NP) self.actorNPe4.setScale(0.05) self.actorNPe4.setPos(0, 0, -1.0) self.e4Hited = 0 def setUp(self): self.itemNumber = 0 self.incBar() # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(0, 0, 130) self.characterNP.setH(180) self.characterNP.setCollideMask(BitMask32.allOn()) self.models.world.attachCharacter(self.character) self.actorNP = Actor( 'models/Bricker/Bricker3.egg', { 'run': 'models/Bricker/Bricker-run.egg', 'walk': 'models/Bricker/Bricker-walk.egg', 'jump': 'models/Bricker/Bricker-jump.egg', 'fallbackGetup': 'models/Bricker/FallbackGetup.egg', 'fallforwardGetup': 'models/Bricker/Bricker-FallforwardGetup.egg', 'fireball': 'models/Bricker/Bricker-fireball.egg', 'punching': 'models/Bricker/Bricker-punching.egg', 'superpunch': 'models/Bricker/Bricker-superpunch.egg' }) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3) self.actorNP.setH(180) self.actorNP.setPos(0, 0, 0.2) #enemies #self.setUpEnemies() #debug self.debugNode = BulletDebugNode('Debug') self.debugNode.showWireframe(True) self.debugNode.showConstraints(True) self.debugNode.showBoundingBoxes(False) self.debugNode.showNormals(False) self.debugNP = render.attachNewNode(self.debugNode) self.debugNP.hide() self.models.world.setDebugNode(self.debugNP.node()) def doJump(self): self.character.setMaxJumpHeight(15.0) self.character.setJumpSpeed(8.0) self.character.doJump() def processInput(self, dt): speed = Vec3(0, 0, 0) omega = 0.0 if inputState.isSet('forward') and self.won == 0 and self.lost == 0: if inputState.isSet('speedUp'): speed.setY(20.0) else: speed.setY(10.0) if inputState.isSet('reverse') and self.won == 0 and self.lost == 0: if inputState.isSet('speedUp'): speed.setY(-20.0) else: speed.setY(-10.0) if inputState.isSet('turnLeft') and self.won == 0 and self.lost == 0: omega = 60.0 if inputState.isSet('turnRight') and self.won == 0 and self.lost == 0: omega = -60.0 if inputState.isSet('jump') and self.won == 0 and self.lost == 0: self.actorNP.loop("jump") self.mySoundRunning.stop() self.mySoundJump.play() self.mySoundJump.setVolume(0.6) self.doJump() if inputState.isSet('hit') and self.won == 0 and self.lost == 0: self.actorNP.loop("punching") speed.setY(30.0) if inputState.isSet('debug') and self.won == 0 and self.lost == 0: if self.debug == True: self.debug = False else: self.debug = True if inputState.isSet('forward') or inputState.isSet( 'reverse') or inputState.isSet('turnLeft') or inputState.isSet( 'turnRight'): if self.isMoving is False and self.won == 0 and self.lost == 0: self.actorNP.loop("run") self.isMoving = True self.mySoundRunning.play() self.mySoundRunning.setVolume(0.4) else: if self.isMoving: self.actorNP.stop() self.actorNP.pose("walk", 0) self.isMoving = False self.mySoundRunning.stop() if inputState.isSet( 'rotateCamLeft') and self.won == 0 and self.lost == 0: base.camera.setX(base.camera, -20 * globalClock.getDt()) if inputState.isSet( 'rotateCamRight') and self.won == 0 and self.lost == 0: base.camera.setX(base.camera, +20 * globalClock.getDt()) self.character.setAngularMovement(omega) self.character.setLinearMovement(speed, True) def update(self, task): if self.debug == True: self.debugNP.show() else: self.debugNP.hide() angleDegrees = task.time * 1000.0 angleRadians = angleDegrees * (pi / 180.0) self.models.Cylinder1.setHpr(angleRadians, 0, 0) self.models.np16.setHpr(angleRadians, 0, 0) self.models.Cylinder2.setHpr(-angleRadians, 0, 0) self.models.np17.setHpr(-angleRadians, 0, 0) self.models.Cylinder3.setHpr(angleRadians, 0, 0) self.models.np18.setHpr(angleRadians, 0, 0) self.models.Cylinder4.setHpr(-angleRadians, 0, 0) self.models.np19.setHpr(-angleRadians, 0, 0) if self.models.np19.is_empty( ) == False and self.models.Cylinder4.is_empty() == False: if self.testWithSingleBody( self.models.node19) == True and inputState.isSet( 'forward') == False and inputState.isSet( 'reverse') == False and inputState.isSet( 'turnLeft') == False and inputState.isSet( 'turnRight') == False and inputState.isSet( 'jump') == False: self.characterNP.setPos(0, -5, 220) self.mySoundEndFx.play() return task.cont def updateItems(self, task): angleDegrees = task.time * 1000.0 angleRadians = angleDegrees * (pi / 180.0) for i in range(self.models.index): if self.models.iteamsNpsList[i].is_empty( ) == False and self.models.iteamsModelsList[i].is_empty() == False: self.models.iteamsModelsList[i].setHpr(angleRadians * 10, 90, 0) self.models.iteamsNpsList[i].setHpr(angleRadians * 10, 90, 0) if self.testWithSingleBody( self.models.iteamsNodesList[i]) == True: self.models.iteamsModelsList[i].setZ(2000) self.models.iteamsNpsList[i].setZ(2000) self.models.iteamsModelsList[i].remove_node() self.models.iteamsNpsList[i].remove_node() self.mySoundRing.play() self.itemNumber += 1 self.item.destroy() self.item = DirectFrame(text=str(self.itemNumber), scale=0.07, pos=(0.9, 0.5, 0.8), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 0.9)) return task.cont def youLost(self): if (self.health < 1 or self.characterNP.getZ() < 90) and self.lost == 0: taskMgr.remove('updateEnemies') self.lost = DirectFrame(text="You Lost", scale=0.2, pos=(0, 0, 0), frameColor=(0, 0, 0, 0), text_fg=(1, 0, 0, 1), text_shadow=(0, 0, 0, 0.9)) p = float( float(self.itemNumber) / float(self.models.index) * 100.0) d = int(p) self.lost2 = DirectFrame(text="You Collected " + str(d) + "% of the Items", scale=0.1, pos=(0, 0, -0.15), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 0.9)) self.b = DirectButton(text="Exit", scale=.07, command=sys.exit, pos=(-0.3, 0, -0.3), text_shadow=(0, 0, 0, 0.9), text_bg=(0, 0, 0, 1), text_fg=(1, 1, 1, 1)) self.b2 = DirectButton(text="Restart", scale=.07, command=self.setRestart, pos=(0.3, 0, -0.3), text_shadow=(0, 0, 0, 0.9), text_bg=(0, 0, 0, 1), text_fg=(1, 1, 1, 1)) def updateEnemies(self, task): self.youLost() if self.testWithSingleBody(self.models.node6) == True: if self.actorNPe1.is_empty() == False and self.e1NP.is_empty( ) == False: if self.ev == False: self.mySoundEvil.play() self.ev = True vecE1 = self.characterNP.getPos() - self.e1NP.getPos() vecE1.setZ(0) vecE1.normalize() self.e1NP.setPos(self.e1NP.getPos() + vecE1 * (1.0 / 10.0)) self.actorNPe1.setH(self.actorNPe1.getH() - 1000 * globalClock.getDt()) if self.testWithSingleBody(self.models.node16) == True: if self.actorNPe2.is_empty() == False and self.e2NP.is_empty( ) == False: if self.ev == False: self.mySoundEvil.play() self.ev = True vecE2 = self.characterNP.getPos() - self.e2NP.getPos() vecE2.setZ(0) vecE2.normalize() self.e2NP.setPos(self.e2NP.getPos() + vecE2 * (1.0 / 10.0)) self.actorNPe2.setH(self.actorNPe2.getH() - 1000 * globalClock.getDt()) if self.testWithSingleBody(self.models.node17) == True: if self.actorNPe3.is_empty() == False and self.e3NP.is_empty( ) == False: if self.ev == False: self.mySoundEvil.play() self.ev = True vecE3 = self.characterNP.getPos() - self.e3NP.getPos() vecE3.setZ(0) vecE3.normalize() self.e3NP.setPos(self.e3NP.getPos() + vecE3 * (1.0 / 10.0)) self.actorNPe3.setH(self.actorNPe3.getH() - 1000 * globalClock.getDt()) if self.testWithSingleBody(self.models.node18) == True: if self.actorNPe4.is_empty() == False and self.e4NP.is_empty( ) == False: if self.ev == False: self.mySoundEvil.play() self.ev = True vecE4 = self.characterNP.getPos() - self.e4NP.getPos() vecE4.setZ(0) vecE4.normalize() self.e4NP.setPos(self.e4NP.getPos() + vecE4 * (1.0 / 10.0)) self.actorNPe4.setH(self.actorNPe4.getH() - 1000 * globalClock.getDt()) if self.testWithSingleBody(self.e1) == True: self.pain() if inputState.isSet('hit'): self.e1Hited += 1.0 self.mySoundPunch.play() self.mySoundPunch.setVolume(0.5) if self.actorNPe1.is_empty() == False and self.e1NP.is_empty( ) == False and self.e1Hited > 3: self.actorNPe1.setZ(2000) self.e1NP.setZ(2000) self.actorNPe1.remove_node() self.e1NP.remove_node() if self.testWithSingleBody(self.e2) == True: self.pain() if inputState.isSet('hit'): self.e2Hited += 1.0 self.mySoundPunch.play() self.mySoundPunch.setVolume(0.5) if self.actorNPe2.is_empty() == False and self.e2NP.is_empty( ) == False and self.e2Hited > 3: self.actorNPe2.setZ(2000) self.e2NP.setZ(2000) self.actorNPe2.remove_node() self.e2NP.remove_node() if self.testWithSingleBody(self.e3) == True: self.pain() if inputState.isSet('hit'): self.e3Hited += 1.0 self.mySoundPunch.play() self.mySoundPunch.setVolume(0.5) if self.actorNPe3.is_empty() == False and self.e3NP.is_empty( ) == False and self.e3Hited > 3: self.actorNPe3.setZ(2000) self.e3NP.setZ(2000) self.actorNPe3.remove_node() self.e3NP.remove_node() if self.testWithSingleBody(self.e4) == True: self.pain() if inputState.isSet('hit'): self.e4Hited += 1.0 self.mySoundPunch.play() self.mySoundPunch.setVolume(0.5) if self.actorNPe4.is_empty() == False and self.e4NP.is_empty( ) == False and self.e4Hited > 3: self.actorNPe4.setZ(2000) self.e4NP.setZ(2000) self.actorNPe4.remove_node() self.e4NP.remove_node() return task.cont def incBar(self): # Create a frame # Add button self.bar = DirectWaitBar(text="HEALTH", value=self.health, range=100, pos=(0.8, 0.5, 0.9), scale=0.5, barColor=(0, 0.9, 0, 1), text_fg=(0, 0.5, 0, 1), text_shadow=(0, 0, 0, 0.5)) self.frame = DirectFrame(text=" Items #", scale=0.07, pos=(0.7, 0.5, 0.8), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 0.9)) self.item = DirectFrame(text=str(self.itemNumber), scale=0.07, pos=(0.9, 0.5, 0.8), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 0.9)) def pain(self): self.bar.destroy() self.health -= 0.3 if self.health < 101 and self.health > 70: self.bar = DirectWaitBar(text="HEALTH", value=self.health, range=100, pos=(0.8, 0.5, 0.9), scale=0.5, barColor=(0, 0.9, 0, 1), text_fg=(0, 0.5, 0, 1), text_shadow=(0, 0, 0, 0.5)) elif self.health < 71 and self.health > 40: self.bar = DirectWaitBar(text="HEALTH", value=self.health, range=100, pos=(0.8, 0.5, 0.9), scale=0.5, barColor=(0.9, 0.9, 0, 1), text_fg=(0.5, 0.5, 0, 1), text_shadow=(0, 0, 0, 0.5)) else: self.bar = DirectWaitBar(text="HEALTH", value=self.health, range=100, pos=(0.8, 0.5, 0.9), scale=0.5, barColor=(0.9, 0, 0, 1), text_fg=(0.5, 0, 0, 1), text_shadow=(0, 0, 0, 0.5)) def updateEndPoint(self, task): angleDegrees = task.time * 5000.0 angleRadians = angleDegrees * (pi / 180.0) if self.models.npEnd.is_empty( ) == False and self.models.endpoint.is_empty( ) == False and self.won == 0: self.models.endpoint.setHpr(angleRadians, 0, 0) self.models.npEnd.setHpr(angleRadians, 0, 0) if self.testWithSingleBody(self.models.nodeEnd) == True: self.mySoundEnd.play() self.models.endpoint.remove_node() self.models.npEnd.remove_node() self.won = DirectFrame(text="You Won", scale=0.2, pos=(0, 0, 0), frameColor=(0, 0, 0, 0), text_fg=(0.5, 1, 0.5, 1), text_shadow=(0, 0, 0, 0.9)) p = float( float(self.itemNumber) / float(self.models.index) * 100.0) d = int(p) self.won2 = DirectFrame(text="You Collected " + str(d) + "% of the Items", scale=0.1, pos=(0, 0, -0.15), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 0.9)) self.b = DirectButton(text="Exit", scale=.07, command=sys.exit, pos=(-0.3, 0, -0.3), text_shadow=(0, 0, 0, 0.9), text_bg=(0, 0, 0, 1), text_fg=(1, 1, 1, 1)) self.b2 = DirectButton(text="Restart", scale=.07, command=self.setRestart, pos=(0.3, 0, -0.3), text_shadow=(0, 0, 0, 0.9), text_bg=(0, 0, 0, 1), text_fg=(1, 1, 1, 1)) self.b3 = DirectButton(text="Go To Level 1", scale=.07, command=self.nextLevel1, pos=(0, 0, -0.5), text_shadow=(0, 0, 0, 0.9), text_bg=(0, 0, 0, 1), text_fg=(1, 1, 1, 1)) return task.cont def testWithSingleBody(self, secondNode): contactResult = self.models.world.contactTestPair( self.character, secondNode) # returns a BulletContactResult object if len(contactResult.getContacts()) > 0: return True def setRestart(self): self.re = True taskMgr.remove('update') taskMgr.remove('updateItems') taskMgr.remove('updateEnemies') taskMgr.remove('updateEndPoint') self.itemNumber = 0 self.item.destroy() self.item = DirectFrame(text=str(self.itemNumber), scale=0.07, pos=(0.9, 0.5, 0.8), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 0.9)) for i in range(self.models.index): if self.models.iteamsNpsList[i].is_empty( ) == False and self.models.iteamsModelsList[i].is_empty() == False: self.models.iteamsModelsList[i].setZ(2000) self.models.iteamsNpsList[i].setZ(2000) self.models.iteamsModelsList[i].remove_node() self.models.iteamsNpsList[i].remove_node() self.models.iteamsModelsList = 0 self.models.iteamsNodesList = 0 self.models.iteamsNpsList = 0 self.models.setupItems() if (self.won != 0): self.won.destroy() self.won2.destroy() self.models.setupEndPoint() if (self.lost != 0): self.lost.destroy() self.lost2.destroy() self.b.destroy() self.b2.destroy() if (self.b3 != 0): self.b3.destroy() self.bar.destroy() self.health = 100 self.bar = DirectWaitBar(text="HEALTH", value=self.health, range=100, pos=(0.8, 0.5, 0.9), scale=0.5, barColor=(0, 0.9, 0, 1), text_fg=(0, 0.5, 0, 1), text_shadow=(0, 0, 0, 0.5)) self.won = 0 self.characterNP.setPos(0, 0, 130) self.characterNP.setH(180) if self.actorNPe1.is_empty() == False and self.e1NP.is_empty( ) == False: self.actorNPe1.setZ(2000) self.e1NP.setZ(2000) self.actorNPe1.remove_node() self.e1NP.remove_node() if self.actorNPe2.is_empty() == False and self.e2NP.is_empty( ) == False: self.actorNPe2.setZ(2000) self.e2NP.setZ(2000) self.actorNPe2.remove_node() self.e2NP.remove_node() if self.actorNPe3.is_empty() == False and self.e3NP.is_empty( ) == False: self.actorNPe3.setZ(2000) self.e3NP.setZ(2000) self.actorNPe3.remove_node() self.e3NP.remove_node() if self.actorNPe4.is_empty() == False and self.e4NP.is_empty( ) == False: self.actorNPe4.setZ(2000) self.e4NP.setZ(2000) self.actorNPe4.remove_node() self.e4NP.remove_node() self.setUpEnemies() base.camera.setPos(self.characterNP.getX(), self.characterNP.getY() + 10, 5) base.camera.setHpr(self.characterNP.getHpr()) base.camera.lookAt(self.characterNP) self.lost = 0 taskMgr.add(self.update, 'update') taskMgr.add(self.updateItems, 'updateItems') taskMgr.add(self.updateEnemies, 'updateEnemies') taskMgr.add(self.updateEndPoint, 'updateEndPoint') def removeAll(self): self.re = True taskMgr.remove('update') taskMgr.remove('updateItems') taskMgr.remove('updateEnemies') taskMgr.remove('updateEndPoint') self.itemNumber = 0 self.item.destroy() for i in range(self.models.index): if self.models.iteamsNpsList[i].is_empty( ) == False and self.models.iteamsModelsList[i].is_empty() == False: self.models.iteamsModelsList[i].setZ(2000) self.models.iteamsNpsList[i].setZ(2000) self.models.iteamsModelsList[i].remove_node() self.models.iteamsNpsList[i].remove_node() self.models.iteamsModelsList = 0 self.models.iteamsNodesList = 0 self.models.iteamsNpsList = 0 if (self.won != 0): self.won.destroy() self.won2.destroy() self.b.destroy() self.b2.destroy() self.b3.destroy() if (self.lost != 0): self.lost.destroy() self.lost2.destroy() self.b.destroy() self.b2.destroy() self.b3.destroy() self.bar.destroy() self.health = 100 self.won = 0 self.lost = 0 self.actorNP.remove_node() self.characterNP.remove_node() self.models.sky.remove_node() self.models.groundNp.remove_node() self.models.endpoint.remove_node() self.models.npEnd.remove_node() self.models.np1.remove_node() self.models.box1.remove_node() self.models.np2.remove_node() self.models.box2.remove_node() self.models.np3.remove_node() self.models.box3.remove_node() self.models.np4.remove_node() self.models.box4.remove_node() self.models.np5.remove_node() self.models.box5.remove_node() self.models.box6.remove_node() self.models.np6.remove_node() self.models.Cylinder1.remove_node() self.models.np16.remove_node() self.models.Cylinder2.remove_node() self.models.np17.remove_node() self.models.Cylinder3.remove_node() self.models.np18.remove_node() self.models.Cylinder4.remove_node() self.models.np19.remove_node() self.models.fire.remove_node() self.models.np7.remove_node() self.models.box7.remove_node() if self.actorNPe1.is_empty() == False and self.e1NP.is_empty( ) == False: self.actorNPe1.setZ(2000) self.e1NP.setZ(2000) self.actorNPe1.remove_node() self.e1NP.remove_node() if self.actorNPe2.is_empty() == False and self.e2NP.is_empty( ) == False: self.actorNPe2.setZ(2000) self.e2NP.setZ(2000) self.actorNPe2.remove_node() self.e2NP.remove_node() if self.actorNPe3.is_empty() == False and self.e3NP.is_empty( ) == False: self.actorNPe3.setZ(2000) self.e3NP.setZ(2000) self.actorNPe3.remove_node() self.e3NP.remove_node() if self.actorNPe4.is_empty() == False and self.e4NP.is_empty( ) == False: self.actorNPe4.setZ(2000) self.e4NP.setZ(2000) self.actorNPe4.remove_node() self.e4NP.remove_node() def nextLevel1(self): self.nextLevel = True
class Game(DirectObject): def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) self.accept('space', self.doJump) self.accept('c', self.doCrouch) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup() # _____HANDLER_____ def doExit(self): self.cleanup() sys.exit(1) def doReset(self): self.cleanup() self.setup() def toggleWireframe(self): base.toggleWireframe() def toggleTexture(self): base.toggleTexture() def toggleDebug(self): if self.debugNP.isHidden(): self.debugNP.show() else: self.debugNP.hide() def doScreenshot(self): base.screenshot('Bullet') def doJump(self): self.character.setMaxJumpHeight(5.0) self.character.setJumpSpeed(8.0) self.character.doJump() def doCrouch(self): self.crouching = not self.crouching sz = self.crouching and 0.6 or 1.0 self.characterNP.setScale(Vec3(1, 1, sz)) #self.character.getShape().setLocalScale(Vec3(1, 1, sz)) #self.characterNP.setScale(Vec3(1, 1, sz) * 0.3048) #self.characterNP.setPos(0, 0, -1 * sz) # ____TASK___ def processInput(self, dt): speed = Vec3(0, 0, 0) omega = 0.0 if inputState.isSet('forward'): speed.setY( 2.0) if inputState.isSet('reverse'): speed.setY(-2.0) if inputState.isSet('left'): speed.setX(-2.0) if inputState.isSet('right'): speed.setX( 2.0) if inputState.isSet('turnLeft'): omega = 120.0 if inputState.isSet('turnRight'): omega = -120.0 self.character.setAngularMovement(omega) self.character.setLinearMovement(speed, True) def update(self, task): dt = globalClock.getDt() self.processInput(dt) self.world.doPhysics(dt, 4, 1./240.) 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), 0) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) 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 shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3)) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) np.node().setMass(10.0) np.node().addShape(shape) np.setPos(3, 0, 4) np.setH(20.0) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Character self.crouching = False h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.character.setMass(1.0) self.characterNP = self.worldNP.attachNewNode(self.character) self.characterNP.setPos(-2, 0, 14) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.actorNP = Actor('models/ralph/ralph.egg', { 'run' : 'models/ralph/ralph-run.egg', 'walk' : 'models/ralph/ralph-walk.egg', 'jump' : 'models/ralph/ralph-jump.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3048) # 1ft = 0.3048m self.actorNP.setH(180) self.actorNP.setPos(0, 0, -1)
def install_upgrade(self, upgrade): """Install the given upgrade on to the locomotive. Args: upgrade (dict): The upgrade description. """ self._upgrades.append(upgrade["name"]) if upgrade["name"] in ("Armor Plate", "Пластина Брони"): self._armor_plate = ArmorPlate(self.model) return if upgrade["name"] in ("Grenade Launcher", "Гранатомёт"): self._grenade_launcher = GrenadeLauncher(self.model) self._gui.activate_weapon( "Grenade Launcher", base.train.load_grenade_launcher # noqa: F821 ) return if upgrade["name"] in ("Cluster Howitzer", "Ракетомёт"): self._cluster_howitzer = ClusterHowitzer(self.model) self._gui.activate_weapon( "Cluster Howitzer", base.train.load_cluster_howitzer # noqa: F821 ) return if upgrade["name"] in ("Machine Gun", "Пулемёт"): self._machine_gun = MachineGun(self.model) self._gui.activate_weapon( "Machine Gun", base.train.load_machine_gun # noqa: F821 ) return up_model = loader.loadModel(address(upgrade["model"])) # noqa: F821 up_model.reparentTo(self.model) if upgrade["name"] in ("Ram", "Таран"): taskMgr.remove("update_physics") # noqa: F821 taskMgr.remove("check_train_contacts") # noqa: F821 base.world.phys_mgr.removeCharacter(self._phys_shape) # noqa: F821 self._phys_node.removeNode() self._phys_shape = self._phys_shape = BulletCharacterControllerNode( BulletBoxShape(Vec3(0.095, 0.58, 0.1)), 10, "train_shape") self._phys_node = self.model.attachNewNode(self._phys_shape) self._phys_node.setPos(0, 0.03, 0.1) base.world.phys_mgr.attachCharacter(self._phys_shape) # noqa: F821 taskMgr.add( # noqa: F821 base.world.update_physics, # noqa: F821 "update_physics", extraArgs=[0.03], appendTask=True, ) taskMgr.doMethodLater( # noqa: F821 0.1, self._check_contacts, "check_train_contacts", extraArgs=[base.world.phys_mgr, self._phys_node.node()], # noqa: F821 appendTask=True, ) return if upgrade["name"] in ("Floodlights", "Прожекторы"): self._floodlights_mat = up_model.findMaterial("lamp_glass") self._lights[0].node().setColor((1, 1, 1, 1)) for light in self._lights[1:]: light.node().setAttenuation(1.7) return if upgrade["name"] in ("Fire Extinguishers", "Огнетушители"): taskMgr.doMethodLater(30, self._repair, "train_repair") # noqa: F821 return if upgrade["name"] in ("Sleeper", "Место"): self.cells += 1 self.parts["part_rest"].cells += 1 base.res_gui.update_chars() # noqa: F821 return if upgrade["name"] in ("Protectors", "Протекторы"): self._max_durability = 1500 self.durability += 500 SHOT_COORS[0][0] += 0.02 self._gui.increase_max_duration()
class App(ShowBase): def moveForward(self, catch): print('w key pressed') self.cy = 3.0 print(self.current_pos) def moveBackward(self, catch): print('w key pressed') self.cy = -3.0 print(self.current_pos) def moveLeft(self, catch): print('w key pressed') self.cx = 3.0 print(self.current_pos) def moveRight(self, catch): print('w key pressed') self.cx = -3.0 print(self.current_pos) def lookLeft(self, catch): self.current_omega = 120 def lookRight(self, catch): self.current_omega = -120 def lookUp(self, catch): self.current_hpr = (self.current_hpr[0], self.current_hpr[1] - 1, self.current_hpr[2]) def moveUp(self, catch): self.current_pos = (self.current_pos[0], self.current_pos[1], self.current_pos[2] + 1) def lookUp(self, catch): self.current_hpr = (self.current_hpr[0], self.current_hpr[1] + 1, self.current_hpr[2]) def lookDown(self, catch): self.current_hpr = (self.current_hpr[0], self.current_hpr[1] - 1, self.current_hpr[2]) def fire(self, catch): print("Fire!") if self.pandaPos[0] == self.current_pos[0] and self.pandaPos[ 2] + 0.5 == self.current_pos[2] and not self.pandaPos[ 1] == self.current_pos[1] and not self.pandaPos[ 1] - 1 == self.current_pos[1] and not self.current_pos[ 1] - 1 == self.pandaPos[1] and not self.current_pos[ 1] > self.pandaPos[1]: print('Oof') def jump(self, catch): self.player.setMaxJumpHeight(5.0) self.player.setJumpSpeed(8.0) self.player.doJump() def __init__(self): ShowBase.__init__(self) #self.word = BulletWorld() self.cx = 0.0 self.cy = 0.0 self.current_omega = 0 s = self.loader.loadSfx('Doom Soundtrack - Level 1 (Extended).mp3') s.play() self.current_pos = (10, 5, 1) self.current_hpr = (0, 0, 0) #self.fxboy = self.loader.loadModel("cubearm.egg") self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -12.0)) #self.physicsMgr.attachPhysicalNode(self.camera) keyboard.on_press_key('w', self.moveForward) keyboard.on_press_key('s', self.moveBackward) keyboard.on_press_key('j', self.lookLeft) keyboard.on_press_key('y', self.lookUp) keyboard.on_press_key('h', self.lookDown) keyboard.on_press_key('g', self.lookRight) keyboard.on_press_key('d', self.moveLeft) #self.fxboy.reparentTo(self.render) #self.camera.reparentTo(self.render) #self.camera.reparentTo(self.fxboy) keyboard.on_press_key('a', self.moveRight) keyboard.on_press_key('space', self.fire) keyboard.on_press_key('2', self.jump) #keyboard.on_press_key('y',self.lookUp) keyboard.on_press_key('1', self.moveUp) self.cam = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.player = BulletCharacterControllerNode(self.cam, 0.4, 'Player') self.playernp = self.render.attachNewNode(self.player) self.world.attachCharacter(self.playernp.node()) self.camera.reparentTo(self.playernp) self.playernp.setPos(self.current_pos) self.playernp.setHpr(self.current_hpr) self.playernp.setH(45) #self.player.setMass(10.0) # self.playernp.setCollideMask(BitMask32.allOn()) self.disableMouse() self.scenes = BulletBoxShape(Vec3(0.25, 0.25, 0.25)) self.scenenode = BulletRigidBodyNode('Scene') self.scenenode.setMass(12.0) self.scenenode.addShape(self.scenes) self.scenenp = render.attachNewNode(self.scenenode) self.scenenp.setPos(-8, 40, 0) self.world.attachRigidBody(self.scenenode) self.scene = self.loader.loadModel("models/environment.egg.pz") self.scene.reparentTo(self.render) self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 40, 0) self.scene.reparentTo(self.scenenp) self.scenenode.setGravity(Vec3(0, 0, 0)) #self.taskMgr.add(self.spinCameraTask,"SpinCameraTask") self.taskMgr.add(self.moveChar, "MoveChar") self.taskMgr.add(self.moveCBod, "MoveCBod") self.pandaActor = Actor("cubearm.egg", {"walk": "cubearm4-ArmatureAction.egg"}) self.pandaActor.setScale(0.12, 0.12, 0.12) self.pandaActor.setPos((10, 10, 0.5)) self.pandaPos = (10, 10, 0.5) self.pandaActor.reparentTo(self.render) self.pandaActor.loop('walk') ''' posInterval1 = self.pandaActor.posInterval(13,Point3(0,-10,0),startPos=Point3(0,10,0)) posInterval2 = self.pandaActor.posInterval(13,Point3(0,10,0),startPos=Point3(0,-10,0)) hprInterval1 = self.pandaActor.hprInterval(3,Point3(180,0,0),startHpr=Point3(0,0,0)) hprInterval2 = self.pandaActor.hprInterval(3,Point3(0,0,0),startHpr=Point3(180,0,0)) self.pandaPace = Sequence(posInterval1,hprInterval1,posInterval2,hprInterval2,name="pandaPace") self.pandaPace.loop() ''' def spinCameraTask(self, task): print(task.time * 6.0) angleDegrees = task.time * 6.0 angleRadians = angleDegrees * (pi / 180.0) self.camera.setPos(20 * sin(angleRadians), -20 * cos(angleRadians), 3) self.camera.setHpr(angleDegrees, 0, 0) return Task.cont def moveChar(self, task): speed = Vec3(0, 0, 0) omega = self.current_omega speed.setX(self.cx) speed.setY(self.cy) #self.scenenp.setPos(-8,40,0) print('[Scene]: ' + str(self.scenenp.getPos())) print('[Cam]: ' + str(self.playernp.getPos())) self.player.setAngularMovement(omega) #self.player.setLinearMovement(speed,True) #self.playernp.setPos(self.current_pos) self.playernp.setHpr(self.current_hpr) return task.cont def moveCBod(self, task): self.world.doPhysics(globalClock.getDt()) return task.cont
class Player(DirectObject): def __init__(self): super().__init__() self.master = window.Window.get_instance() self.keyMap = { self.master.bind[Bind.FWD.value]: False, self.master.bind[Bind.BWD.value]: False, self.master.bind[Bind.RIGHT.value]: False, self.master.bind[Bind.LEFT.value]: False, self.master.bind[Bind.UP.value]: False, self.master.bind[Bind.DOWN.value]: False, self.master.bind[Bind.SPACE.value]: False } self.equipment = Equipment(self) self.rotation = [-70, 140] height = 2.5 radius = 0.4 character_shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.player_node = BulletCharacterControllerNode( character_shape, 0.4, 'Player') self.player_node_path = self.master.world_node.attachNewNode( self.player_node) self.player_node_path.setPos(90, 31, 395) self.player_node_path.setCollideMask(BitMask32.allOn()) self.master.camera.reparentTo(self.player_node_path) self.master.camera.setY(self.master.camera, -5) self.camera_model = self.master.loader.loadModel( "mesh/models/person/person") self.camera_model.reparentTo(self.player_node_path) self.bind() self.master.taskMgr.add(self.camera_control, "Camera Control") self.master.world.attachCharacter(self.player_node_path.node()) def set_key(self, key, value): self.keyMap[key] = value def jump(self): self.player_node.setMaxJumpHeight(5.0) self.player_node.setJumpSpeed(8.0) self.player_node.doJump() def camera_control(self, task): dt = globalClock.getDt() if dt > .20: return task.cont if self.master.mouseWatcherNode.hasMouse(): mouse_position = self.master.mouseWatcherNode.getMouse() self.rotation[0] += mouse_position.getY() * 30 self.rotation[1] += mouse_position.getX() * -50 self.master.camera.setP(self.rotation[0]) self.master.camera.setH(self.rotation[1]) self.player_node_path.setH(self.player_node_path.getH() + mouse_position.getX() * -1) self.master.win.movePointer(0, int(self.master.win.getXSize() / 2), int(self.master.win.getYSize() / 2)) if self.keyMap["w"]: self.player_node_path.setY(self.player_node_path, SPEED * dt) if self.keyMap["s"]: self.player_node_path.setY(self.player_node_path, -SPEED * dt) if self.keyMap["a"]: self.player_node_path.setX(self.player_node_path, -SPEED * dt) if self.keyMap["d"]: self.player_node_path.setX(self.player_node_path, SPEED * dt) if self.keyMap["shift"]: self.player_node_path.setZ(self.player_node_path, SPEED * dt) if self.keyMap["control"]: self.player_node_path.setZ(self.player_node_path, -SPEED * dt) if self.keyMap["space"]: self.jump() return task.cont def bind(self): self.accept("w", self.set_key, ["w", True]) self.accept("s", self.set_key, ["s", True]) self.accept("a", self.set_key, ["a", True]) self.accept("d", self.set_key, ["d", True]) self.accept("shift", self.set_key, ["shift", True]) self.accept("control", self.set_key, ["control", True]) self.accept("space", self.set_key, ["space", True]) self.accept("e", self.show_hide_equipment) self.accept("f1", self.master.toggle_debug) self.accept("w-up", self.set_key, ["w", False]) self.accept("s-up", self.set_key, ["s", False]) self.accept("a-up", self.set_key, ["a", False]) self.accept("d-up", self.set_key, ["d", False]) self.accept("shift-up", self.set_key, ["shift", False]) self.accept("control-up", self.set_key, ["control", False]) self.accept("space-up", self.set_key, ["space", False]) def show_hide_equipment(self): self.equipment.equipment_change_visibility(self)
def __init__(self): # Notice that you must not call ShowBase.__init__ (or super), the # render pipeline does that for you. If this is unconvenient for you, # have a look at the other initialization possibilities. # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes. In case you placed the render # pipeline in a subfolder of your project, you have to adjust this. sys.path.insert(0, "../../") sys.path.insert(0, "../../RenderPipeline") # Import the main render pipeline class from rpcore import RenderPipeline, SpotLight world = BulletWorld() # Construct and create the pipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) from rpcore.util.movement_controller import MovementController self.render_pipeline.daytime_mgr.time = 0.769 self.controller = MovementController(self) self.controller.set_initial_position(Vec3(6.6, -18.8, 4.5), Vec3(4.7, -16.7, 3.4)) self.controller.setup() # Done! You can start setting up your application stuff as regular now. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0 } self.speed = 1.0 base.win.setClearColor(Vec4(0, 0, 0, 1)) # # vertex_format = GeomVertexFormat.get_v3n3() # vertex_data = GeomVertexData("triangle_data", vertex_format, Geom.UH_static) # # pos_writer = GeomVertexWriter(vertex_data,"vertex") # normal_writer = GeomVertexWriter(vertex_data,"normal") # normal = Vec3(0., -1., 0.) # # pos_writer.add_data3(-1., 0., -1.) # pos_writer.add_data3(1., 0., -1.) # pos_writer.add_data3(0., 0., 1.) # # for _ in range(3): # normal_writer.add_data3(normal) # # prim = GeomTriangles(Geom.UH_static) # prim.add_vertices(0, 1, 2) # # geom = Geom(vertex_data) # geom.add_primitive(prim) # node = GeomNode("my_triangle") # node.add_geom(geom) # triangle = NodePath(node) # triangle.reparent_to(some_other_nodepath) # square1 = create_colored_rect(0, 0, 200, 200) # square2 = create_colored_rect(350, 100, 200, 200, (0, 0, 1, 1)) # square3 = create_colored_rect(-640, -360, 200, 200, (0, 1, 0, 1)) self.tr1 = create_triangle(0, 0, 0, 0, 200, 0, 0, 0, 200, (0, 1, 0, 1)) self.tr2 = create_triangle(-500, 0, 0, -300, 200, 0, -300, 0, 200, (0, 1, 0, 1)) radius = 60 height = 40 shape1 = BulletCylinderShape(radius, height, ZUp) shape2 = BulletCylinderShape(Vec3(radius, 0, 0.5 * height), ZUp) self.gnode = GeomNode('square') # gnode.addGeom(square1) # gnode.addGeom(square2) # gnode.addGeom(square3) height = 1.75 radius = 0.4 shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.gnode.addGeom(self.tr1) self.gnode.addGeom(self.tr2) playerNode = BulletCharacterControllerNode(shape, 0.4, 'Player') playerNP = self.render.attachNewNode(playerNode) playerNP.setPos(0, 0, 14) playerNP.setH(45) playerNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(playerNP.node()) # self.tr1.setPos(400,400, 0) # self.render.attachNewNode(self.gnode) gnode2 = GeomNode('square2') textured_rect = create_textured_rect(-320, 0, 200, 280) gnode2.addGeom(textured_rect) texture = self.loader.loadTexture("assets/playte.png") ship = self.render.attachNewNode(gnode2) ship.setTransparency(TransparencyAttrib.MAlpha) ship.setTexture(texture) # self.ralph = Actor(tr1) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) self.accept("escape", sys.exit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("p", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("=", self.adjustSpeed, [0.25]) self.accept("+", self.adjustSpeed, [0.25]) self.accept("-", self.adjustSpeed, [-0.25]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(5, 5, 0) base.camLens.setFov(80)
class Player(): model = 0 counter = 0 def __init__(self,ppos, world, worldNP): self.traptime = 0 self.world = world self.worldNP = worldNP if not Player.model: Player.model = Model("../assets/3d/Actors/robot rig 10 coll.egg")#NPC_robot_mesh.egg") #Player.model.modelRoot.find("**/body_coll").show() self.instance = Player.model.createInstance(pos=ppos) self.velocity = (0,0,0) self.prevTime = 0 taskMgr.add(self.fpMove,"moveTask") self.projectiles = list() self.projTime = 0.0 pnode = ModelRoot("player") self.player = render.attachNewNode(pnode) pc = self.player.attachNewNode(CollisionNode("playerCollision")) pc.node().addSolid(CollisionRay(0,0,-1,0,0,1)) self.playerCnode = pc self.id = Player.counter Player.counter = Player.counter + 1 def fpMove(self,task): #CONSTANTS ACCELERATION = 0.6 MINDISTANCE = 150 MAXSPEED = 100 THROWPERIOD = 5.0 #Function dt = task.time-self.prevTime self.instance.setZ(self.instance.getZ()) self.prevTime = task.time target = camera targetPos = target.getPos() pos = self.characterNP.getPos() vector2Target = self.normalize(targetPos - pos) #notarget = 0 #if notarget == 1: # return task.cont #gogo trigonometry angle = 90 + ( atan2(vector2Target[1],vector2Target[0])*180 / math.pi ) angle2 = ( atan2(-vector2Target[2],sqrt(pow(vector2Target[1], 2) + pow(vector2Target[0], 2)))*180 / math.pi ) self.instance.setH(angle) self.instance.setP(angle2) #curSpeed = sqrt(pow(self.velocity[0],2)+pow(self.velocity[1],2)+pow(self.velocity[2],2)) #Use Distance formula, if further than MINDISTANCE, keep moving, otherwise stop distance = sqrt(pow(target.getX()-self.instance.getX(),2)+pow(target.getY()-self.instance.getY(),2)+pow(target.getZ()-self.instance.getZ(),2)) if(distance<MINDISTANCE): ACCELERATION = 0.0 #get the velocity self.velocity = (self.velocity[0] + ACCELERATION * vector2Target[0], self.velocity[1] + ACCELERATION * vector2Target[1], self.velocity[2] + ACCELERATION * vector2Target[2]) self.velocity = (min(MAXSPEED,self.velocity[0]),min(MAXSPEED,self.velocity[1]),min(MAXSPEED,self.velocity[2])) #get displacement dis = (self.velocity[0]*dt,self.velocity[1]*dt,self.velocity[2]*dt) #update position #self.player.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2]) #self.instance.setPos(self.player.getX(),self.player.getY(),self.player.getZ()) self.character.setAngularMovement(0) self.character.setLinearMovement(self.velocity, True) self.instance.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2]-self.radius*.7) #if self.id == 0: # print pos[0]+dis[0] # print pos[1]+dis[1] # print pos[2]+dis[2] # print str(self.id) + " Z Displacement:" + str(dis[2]) + " distance:" + str(distance) self.projTime += dt if self.projTime >= THROWPERIOD: self.projTime -= THROWPERIOD self.projectiles.append(Projectile(self.instance.getPos(),deg2Rad(180+angle),deg2Rad(angle2),self,self.velocity, self.world, self.worldNP)) return task.cont def bulletInit(self,world,pos): oldpath = self.instance.find("**/body_coll") self.radius = oldpath.node().getSolid(0).getRadius() shape = BulletSphereShape(self.radius) self.character = BulletCharacterControllerNode(shape, 0.4, 'AI'+str(Player.counter)) self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(pos[0],pos[1],pos[2]) self.character.setGravity(0) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character) def normalize(self, vector): return vector / sqrt(pow(vector[0],2) + pow(vector[1], 2) + pow(vector[2], 2)) def die(self,event): base.cTrav.removeCollider(self.wheelsphere) self.instance.node().getChild(0).removeChild(0) print "Computer player eliminated!" def trap1(self): self.velocity = map(lambda x: x*.25, self.vel) self.traptime = self.traptime + 20 return def trap2(self): self.velocity = (0,0,0) self.traptime = self.traptime + 20 return def impact(self,vel): diff = map(lambda i: self.velocity[i]-vel[i], range(3)) self.velocity = map(lambda i: self.velocity[i]-diff[i], range(3))
class EccoGame(ShowBase): def __init__(self): ShowBase.__init__(self) base.setBackgroundColor(0, 0, 0) game_title = "ECCO" titleN = TextNode('game-title') font = loader.loadFont("font/Caveman.ttf") titleN.setFont(font) titleN.setText(game_title) titleN.setTextColor(1, 1, 1, 1) titleN.setSlant(0.1) titleN.setShadow(0.05) titleN.setShadowColor(0, 0, 200, 1) titleN.setFrameColor(0, 0, 255, 1) titleN.setFrameLineWidth(5.0) textNodePath = self.aspect2d.attachNewNode(titleN) textNodePath.setPos(-0.4, 1.5, 0.5) textNodePath.setScale(0.2) self.level1Button = DirectButton(text=("Level 1"), scale=.1, pos=(0, 0, 0.2), command=self.level1) self.level2Button = DirectButton(text=("Level 2"), scale=.1, pos=(0, 0, 0), command=self.level2) def level1(self): titleNp = self.aspect2d.find('game-title') titleNp.removeNode() self.level1Button.destroy() self.level2Button.destroy() self.sizescale = 0.6 self.setupWorld() self.setupSky() self.setupFloor() self.setupCharacter() self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left key]: Turn Ecco Left") self.inst3 = addInstructions(0.85, "[Right key]: Turn Ecco Right") self.inst4 = addInstructions(0.80, "[Up key]: Jump Ecco") inputState.watchWithModifiers('esc', 'escape') inputState.watchWithModifiers('w', 'w') inputState.watchWithModifiers('arrow_left', 'arrow_left') inputState.watchWithModifiers('arrow_right', 'arrow_right') inputState.watchWithModifiers('pause', 'p') inputState.watchWithModifiers('space', 'space') inputState.watchWithModifiers('arrow_up', 'arrow_up') inputState.watchWithModifiers('cam-left', 'z') inputState.watchWithModifiers('cam-right', 'x') inputState.watchWithModifiers('cam-forward', 'c') inputState.watchWithModifiers('cam-backward', 'v') taskMgr.add(self.update, "update") # Game state variables self.isMoving = False # display framerate self.setFrameRateMeter(True) # Set up the camera self.disableMouse() self.camera.setPos(self.characterNP.getX(), self.characterNP.getY() - 30, 4) self.setupSound() # coins variables self.coinsCollected = 0 self.dictOfCoins = {} self.coins = [] # Set up Coins as Collectables self.setupCoins() # Set up Obstacles self.setupObstacles() # Setup Level Display self.setupLevelDisplay() self.counter = 0 def setupLevelDisplay(self): LEVEL_1 = "Level 1" levelDisplay(LEVEL_1) levelN = TextNode('level-display') levelN.setText(LEVEL_1) font = loader.loadFont("font/Caveman.ttf") levelN.setFont(font) levelN.setTextColor(1, 1, 1, 1) levelN.setSlant(0.1) levelN.setShadow(0.05) levelN.setShadowColor(255, 0, 0, 1) textNodePath = self.aspect2d.attachNewNode(levelN) textNodePath.setPos(-0.45, 0, 0) textNodePath.setScale(0.2) def update(self, task): dt = globalClock.getDt() self.pos = self.characterNP.getPos() self.counter = self.counter + 1 if self.counter == 150: levelNp = self.aspect2d.find('level-display') levelNp.removeNode() self.setUpCamera() self.processInput(dt) self.processContacts() self.coinScoreDisplay() self.checkIfEccoDied() self.world.doPhysics(dt, 10, 1 / 230.0) return task.cont def setupWorld(self): # create bullet world self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug')) #self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) def setupSky(self): self.milkyWayNp = render.attachNewNode('milkyway') self.milkyWay_2Np = render.attachNewNode('milkyway_2') self.marsNp = render.attachNewNode('mars') self.sunNp = render.attachNewNode('sun') # Load the model for the sky # self.sky = loader.loadModel("models/sky/solar_sky_sphere") self.sky = loader.loadModel("models/sky/solar_sky_sphere") # Load the texture for the sky. self.sky_tex = loader.loadTexture("models/sky/stars_1k_tex.jpg") # Set the sky texture to the sky model self.sky.setTexture(self.sky_tex, 1) # Parent the sky model to the render node so that the sky is rendered self.sky.reparentTo(self.render) # Scale the size of the sky. self.sky.setScale(15000) x = 0.005 y = 1700.0 z = 0.0 self.sky.setPos(x, y, 0) # #milkyway 1 self.milkyWay = loader.loadModel("models/sky/planet_sphere") self.milkWay_tex = loader.loadTexture("models/sky/milkyway_tex.jpg") self.milkyWay.setTexture(self.milkWay_tex, 1) self.milkyWay.reparentTo(self.milkyWayNp) self.milkyWay.setScale(200) self.milkyWay.setPos(x + 2000, y + 10000, z - 500) # milkyway 2 self.milkyWay_2 = loader.loadModel("models/sky/planet_sphere") self.milkWay_2_tex = loader.loadTexture("models/sky/milkyway_2_tex.jpg") self.milkyWay_2.setTexture(self.milkWay_2_tex, 1) self.milkyWay_2.reparentTo(self.milkyWay_2Np) self.milkyWay_2.setScale(400) self.milkyWay_2.setPos(x - 3000, y + 10000, z + 500) # sun self.sun = loader.loadModel("models/sky/planet_sphere") self.sun_tex = loader.loadTexture("models/sky/sun_2_tex.jpg") self.sun.setTexture(self.sun_tex, 1) self.sun.reparentTo(self.sunNp) self.sun.setScale(600) self.sun.setPos(x + 1000, y + 10000, z + 1000) # # Load Mars self.mars = loader.loadModel("models/sky/planet_sphere") self.mars_tex = loader.loadTexture("models/sky/mars_1k_tex.jpg") self.mars.setTexture(self.mars_tex, 1) self.mars.reparentTo(self.marsNp) self.mars.setScale(200) self.mars.setPos(x + 3000, y + 10000, z + 500) def setupSound(self): # Set up sound mySound = base.loader.loadSfx("sounds/Farm Morning.ogg") mySound.play() mySound.setVolume(3.0) mySound.setLoop(True) footsteps = base.loader.loadSfx("sounds/Footsteps_on_Cement-Tim_Fryer.wav") footsteps.play() footsteps.setVolume(0.8) footsteps.setLoop(True) self.jumpSound = base.loader.loadSfx("sounds/Jump-SoundBible.com-1007297584.wav") self.jumpSound.setVolume(0.2) self.collectSound = base.loader.loadSfx("sounds/pin_dropping-Brian_Rocca-2084700791.wav") self.gameOverSound = base.loader.loadSfx("sounds/Bike Horn-SoundBible.com-602544869.wav") self.levelCompleteSound = base.loader.loadSfx("sounds/Ta Da-SoundBible.com-1884170640.wav") def setupFloor(self): size = Vec3(7.5, 3000, 1.81818) shape = BulletBoxShape(size * 0.55) # shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Box-Floor') node.addShape(shape) node.setMass(0) stairNP = self.render.attachNewNode(node) stairNP.setPos(0, 0, 0) stairNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(stairNP.node()) modelNP = loader.loadModel('models/box.egg') modelNP.reparentTo(stairNP) modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0) modelNP.setScale(size) def setupCharacter(self): # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.character.setGravity(35) self.characterNP = self.render.attachNewNode(self.character) self.characterNP.setPos(0, 10, 5) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.ecco = Actor('ralph-models/ralph.egg.pz', { 'run': 'ralph-models/ralph-run.egg', 'jump': 'ralph/ralph-run.egg', 'damage': 'models/lack-damage.egg'}) self.ecco.reparentTo(self.characterNP) self.ecco.setScale(0.7048) self.ecco.setH(180) def setUpCamera(self): # If the camera is too far from ecco, move it closer. # If the camera is too close to ecco, move it farther. camvec = self.characterNP.getPos() - self.camera.getPos() camvec.setZ(0.0) camdist = camvec.length() camvec.normalize() if camdist > 10.0: self.camera.setPos(self.camera.getPos() + camvec * (camdist - 40)) camdist = 10.0 if camdist < 5.0: self.camera.setPos(self.camera.getPos() - camvec * (35 - camdist)) camdist = 5.0 def processInput(self, dt): speed = Vec3(0, 0, 0) if inputState.isSet('esc'): sys.exit() if inputState.isSet('w'): speed.setY(35.0) if inputState.isSet('arrow_left'): speed.setX(-35.0) if inputState.isSet('arrow_right'): speed.setX(35.0) if inputState.isSet('space'): self.jump() self.jumpSound.play() if inputState.isSet('arrow_up'): self.jump() self.jumpSound.play() if inputState.isSet('cam-left'): self.camera.setX(self.camera, -20 * dt) if inputState.isSet('cam-right'): self.camera.setX(self.camera, +20 * dt) if inputState.isSet('cam-forward'): self.camera.setY(self.camera, -200 * dt) if inputState.isSet('cam-backward'): self.camera.setY(self.camera, +200 * dt) # Make Ecco run if self.isMoving is False: self.ecco.loop("run") self.isMoving = True if self.pos.getY() > 1450.0: speed.setY(0.0) else: speed.setY(40.0) self.character.setLinearMovement(speed, True) def jump(self): self.character.setMaxJumpHeight(3.0) self.character.setJumpSpeed(25.0) self.character.doJump() def setupCoins(self): # display coins = 0 textN = TextNode('coin-score') textN.setText(str("Coins: " + str(self.coinsCollected))) textN.setSlant(0.1) textNodePath = self.aspect2d.attachNewNode(textN) textNodePath.setPos(0, 0.95, 0.9) textNodePath.setScale(0.08) randNum = random.sample(range(0, 1500, 200), 6) # coins for i in range(6): randX = random.uniform(-3.0, 3.2) randY = float(randNum[i]) shape = BulletSphereShape(0.3) coinNode = BulletGhostNode('Coin-' + str(i)) coinNode.addShape(shape) np = self.render.attachNewNode(coinNode) np.setCollideMask(BitMask32.allOff()) np.setPos(randX, randY, 2) # 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.45) sphereNp.hprInterval(2.5, Vec3(360, 0, 0)).loop() self.world.attachGhost(coinNode) self.coins.append(coinNode) print "node name:" + str(coinNode.getName()) def processContacts(self): for coin in self.coins: self.testWithSingleBody(coin) self.coinsCollected = len(self.dictOfCoins) def testWithSingleBody(self, secondNode): contactResult = self.world.contactTestPair(self.character, secondNode) if contactResult.getNumContacts() > 0: self.collectSound.play() for contact in contactResult.getContacts(): cp = contact.getManifoldPoint() node0 = contact.getNode0() node1 = contact.getNode1() self.dictOfCoins[node1.getName()] = 1 np = self.render.find(node1.getName()) np.node().removeAllChildren() self.world.removeGhost(np.node()) def setupObstacles(self): # Obstacle origin = Point3(2, 0, 0) size = Vec3(2, 2.75, 1.5) shape = BulletBoxShape(size * 0.55) randNum1 = random.sample(range(0, 1500, 300), 3) randNum2 = random.sample(range(0, 1500, 500), 3) for i in range(2): randX = random.uniform(-3.5, 3.5) randY = float(randNum1[i]) pos = origin + size * i ObstacleNP = self.render.attachNewNode(BulletRigidBodyNode('Obstacle%i' % i)) ObstacleNP.node().addShape(shape) ObstacleNP.node().setMass(1.0) ObstacleNP.setPos(randX, randY, 3) ObstacleNP.setCollideMask(BitMask32.allOn()) modelNP = loader.loadModel('models/box.egg') modelNP_tex = loader.loadTexture("models/sky/milkyway_tex.jpg") modelNP.setTexture(modelNP_tex, 1) modelNP.reparentTo(ObstacleNP) # modelNP.setPos(0, 0, 0) modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0) modelNP.setScale(size) self.world.attachRigidBody(ObstacleNP.node()) size_2 = Vec3(3, 2.75, 1.5) shape2 = BulletBoxShape(size_2 * 0.55) for i in range(2): randX = random.uniform(-3.5, 3.5) randY = float(randNum2[i]) pos = origin + size_2 * i pos.setY(0) ObstacleNP = self.render.attachNewNode(BulletRigidBodyNode('ObstacleSmall%i' % i)) ObstacleNP.node().addShape(shape2) ObstacleNP.node().setMass(1.0) ObstacleNP.setPos(randX, randY, 2) ObstacleNP.setCollideMask(BitMask32.allOn()) modelNP = loader.loadModel('models/box.egg') modelNP_tex = loader.loadTexture("models/sky/moon_1k_tex.jpg") modelNP.setTexture(modelNP_tex, 1) modelNP.reparentTo(ObstacleNP) # modelNP.setPos(0, 0, 0) modelNP.setPos(-size_2.x / 2.0, -size_2.y / 2.0, -size_2.z / 2.0) modelNP.setScale(size_2) self.world.attachRigidBody(ObstacleNP.node()) def checkIfEccoDied(self): print "position" + str(self.pos.getY()) if self.pos.getZ() > -50.0 and self.pos.getZ() < 0.0: title = "Game Over" levelCompleteN = TextNode('ecco-died') font = loader.loadFont("font/Caveman.ttf") levelCompleteN.setFont(font) levelCompleteN.setText(title) levelCompleteN.setTextColor(1, 1, 1, 1) levelCompleteN.setSlant(0.1) levelCompleteN.setShadow(0.03) levelCompleteN.setShadowColor(0, 0, 200, 1) # levelN.setFrameAsMargin(0, 0, 0, 0) levelCompleteN.setFrameColor(200, 0, 0, 1) levelCompleteN.setFrameLineWidth(5.0) # textNp.node().setGlyphShift(1.0) textNodePath = self.aspect2d.attachNewNode(levelCompleteN) textNodePath.setPos(-0.9, 1.5, 0.5) textNodePath.setScale(0.2) if self.pos.getZ() < -49.0: self.gameOverSound.play() elif self.pos.getZ() < -50.0: if self.gameOverSound.status() != self.gameOverSound.PLAYING: sys.exit(1) elif self.pos.getY() > 1300.0: title = "Level 1 \n Complete" levelCompleteN = TextNode('level-complete') font = loader.loadFont("font/Caveman.ttf") levelCompleteN.setFont(font) levelCompleteN.setText(title) levelCompleteN.setTextColor(1, 1, 1, 1) levelCompleteN.setSlant(0.1) levelCompleteN.setShadow(0.03) levelCompleteN.setShadowColor(0, 0, 200, 1) # levelN.setFrameAsMargin(0, 0, 0, 0) levelCompleteN.setFrameColor(200, 0, 0, 1) levelCompleteN.setFrameLineWidth(5.0) # textNp.node().setGlyphShift(1.0) textNodePath = self.aspect2d.attachNewNode(levelCompleteN) textNodePath.setPos(-0.6, 1.5, 0.5) textNodePath.setScale(0.2) if self.levelCompleteSound.status() != self.levelCompleteSound.PLAYING: self.levelCompleteSound.play() else: pass def coinScoreDisplay(self): textNp = self.aspect2d.find('coin-score') textNp.node().clearText() textNp.node().setText(str("Coins: " + str(self.coinsCollected))) #Level 2 def level2(self): titleNp2 = self.aspect2d.find('game-title') titleNp2.removeNode() self.level1Button.destroy() self.level2Button.destroy() self.sizescale2 = 0.6 self.setupWorld2() self.setupSky2() self.setupFloor2() self.setupCharacter2() # self.title = addTitle(" ") self.inst12 = addInstructions(0.95, "[ESC]: Quit") self.inst22 = addInstructions(0.90, "[Left key]: Turn Ecco Left") self.inst32 = addInstructions(0.85, "[Right key]: Turn Ecco Right") self.inst42 = addInstructions(0.80, "[Up key]: Jump Ecco") inputState.watchWithModifiers('esc', 'escape') inputState.watchWithModifiers('w', 'w') inputState.watchWithModifiers('arrow_left', 'arrow_left') inputState.watchWithModifiers('arrow_right', 'arrow_right') inputState.watchWithModifiers('pause', 'p') inputState.watchWithModifiers('space', 'space') inputState.watchWithModifiers('arrow_up', 'arrow_up') inputState.watchWithModifiers('cam-left', 'z') inputState.watchWithModifiers('cam-right', 'x') inputState.watchWithModifiers('cam-forward', 'c') inputState.watchWithModifiers('cam-backward', 'v') taskMgr.add(self.update2, "update") # Game state variables self.isMoving2 = False # display framerate self.setFrameRateMeter(True) # Set up the camera self.disableMouse() self.camera.setPos(self.characterNP2.getX(), self.characterNP2.getY() - 30, 4) self.setupSound2() # coins variables self.coinsCollected2 = 0 self.dictOfCoins2 = {} self.coins2 = [] # Set up Coins as Collectables self.setupCoins2() # Set up Floaters with coins self.setupFloaters2() # Set up Obstacles self.setupObstacles2() # Setup Level Display self.setupLevelDisplay2() self.counter2 = 0 def setupLevelDisplay2(self): LEVEL_2 = "Level 2" levelDisplay(LEVEL_2) levelN = TextNode('level-display') levelN.setText(LEVEL_2) # www.webpagepublicity.com font = loader.loadFont("font/Caveman.ttf") levelN.setFont(font) levelN.setTextColor(1, 1, 1, 1) levelN.setSlant(0.1) levelN.setShadow(0.05) levelN.setShadowColor(255, 0, 0, 1) # levelN.setFrameAsMargin(0, 0, 0, 0) # levelN.setFrameColor(0, 0, 255, 1) # levelN.setFrameLineWidth(5.0) # # textNp.node().setGlyphShift(1.0) textNodePath = self.aspect2d.attachNewNode(levelN) textNodePath.setPos(-0.45, 0, 0) textNodePath.setScale(0.2) def update2(self, task): dt = globalClock.getDt() self.pos2 = self.characterNP2.getPos() self.counter2 = self.counter2 + 1 if self.counter2 == 150: levelNp = self.aspect2d.find('level-display') levelNp.removeNode() self.setUpCamera2() self.processInput2(dt) self.processContacts2() self.coinScoreDisplay2() self.checkIfEccoDied2() self.world2.doPhysics(dt, 10, 1 / 230.0) return task.cont def setupWorld2(self): # create bullet world self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug')) #self.debugNP.show() self.world2 = BulletWorld() self.world2.setGravity(Vec3(0, 0, -9.81)) self.world2.setDebugNode(self.debugNP.node()) def setupSky2(self): self.milkyWayNp = render.attachNewNode('milkyway') self.milkyWay_2Np = render.attachNewNode('milkyway_2') self.marsNp = render.attachNewNode('mars') self.sunNp = render.attachNewNode('sun') # Load the model for the sky # self.sky = loader.loadModel("models/sky/solar_sky_sphere") self.sky = loader.loadModel("models/sky/solar_sky_sphere") # Load the texture for the sky. self.sky_tex = loader.loadTexture("models/sky/stars_1k_tex.jpg") # Set the sky texture to the sky model self.sky.setTexture(self.sky_tex, 1) # Parent the sky model to the render node so that the sky is rendered self.sky.reparentTo(self.render) # Scale the size of the sky. self.sky.setScale(15000) x = 0.005 y = 1700.0 z = 0.0 self.sky.setPos(x, y, 0) # #milkyway 1 self.milkyWay = loader.loadModel("models/sky/planet_sphere") self.milkWay_tex = loader.loadTexture("models/sky/milkyway_tex.jpg") self.milkyWay.setTexture(self.milkWay_tex, 1) self.milkyWay.reparentTo(self.milkyWayNp) self.milkyWay.setScale(200) self.milkyWay.setPos(x + 2000, y + 10000, z - 500) # milkyway 2 self.milkyWay_2 = loader.loadModel("models/sky/planet_sphere") self.milkWay_2_tex = loader.loadTexture("models/sky/milkyway_2_tex.jpg") self.milkyWay_2.setTexture(self.milkWay_2_tex, 1) self.milkyWay_2.reparentTo(self.milkyWay_2Np) self.milkyWay_2.setScale(400) self.milkyWay_2.setPos(x - 3000, y + 10000, z + 500) # sun self.sun = loader.loadModel("models/sky/planet_sphere") self.sun_tex = loader.loadTexture("models/sky/sun_2_tex.jpg") self.sun.setTexture(self.sun_tex, 1) self.sun.reparentTo(self.sunNp) self.sun.setScale(600) self.sun.setPos(x + 1000, y + 10000, z + 1000) # # Load Mars self.mars = loader.loadModel("models/sky/planet_sphere") self.mars_tex = loader.loadTexture("models/sky/mars_1k_tex.jpg") self.mars.setTexture(self.mars_tex, 1) self.mars.reparentTo(self.marsNp) self.mars.setScale(200) self.mars.setPos(x + 3000, y + 10000, z + 500) def setUpCamera2(self): # If the camera is too far from ecco, move it closer. # If the camera is too close to ecco, move it farther. camvec = self.characterNP2.getPos() - self.camera.getPos() camvec.setZ(0.0) camdist = camvec.length() camvec.normalize() if camdist > 10.0: self.camera.setPos(self.camera.getPos() + camvec * (camdist - 40)) camdist = 10.0 if camdist < 5.0: self.camera.setPos(self.camera.getPos() - camvec * (35 - camdist)) camdist = 5.0 def setupSound2(self): # Set up sound mySound = base.loader.loadSfx("sounds/Farm Morning.ogg") mySound.play() mySound.setVolume(3.0) mySound.setLoop(True) footsteps = base.loader.loadSfx("sounds/Footsteps_on_Cement-Tim_Fryer.wav") footsteps.play() footsteps.setVolume(0.8) footsteps.setLoop(True) self.jumpSound2 = base.loader.loadSfx("sounds/Jump-SoundBible.com-1007297584.wav") self.jumpSound2.setVolume(0.2) self.collectSound2 = base.loader.loadSfx("sounds/pin_dropping-Brian_Rocca-2084700791.wav") self.gameOverSound2 = base.loader.loadSfx("sounds/Bike Horn-SoundBible.com-602544869.wav") self.levelCompleteSound2 = base.loader.loadSfx("sounds/Ta Da-SoundBible.com-1884170640.wav") def setupFloor2(self): size = Vec3(7.5, 3000, 1.81818) shape = BulletBoxShape(size * 0.55) # shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Box-Floor') node.addShape(shape) node.setMass(0) stairNP = self.render.attachNewNode(node) stairNP.setPos(0, 0, 0) stairNP.setCollideMask(BitMask32.allOn()) self.world2.attachRigidBody(stairNP.node()) modelNP = loader.loadModel('models/box.egg') modelNP.reparentTo(stairNP) modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0) modelNP.setScale(size) def setupCharacter2(self): # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character2 = BulletCharacterControllerNode(shape, 0.4, 'Player') self.character2.setGravity(35) self.characterNP2 = self.render.attachNewNode(self.character2) self.characterNP2.setPos(0, 10, 5) self.characterNP2.setCollideMask(BitMask32.allOn()) self.world2.attachCharacter(self.character2) self.ecco2 = Actor('ralph-models/ralph.egg.pz', { 'run': 'ralph-models/ralph-run.egg', 'jump': 'ralph/ralph-run.egg', 'damage': 'models/lack-damage.egg'}) self.ecco2.reparentTo(self.characterNP2) self.ecco2.setScale(0.7048) self.ecco2.setH(180) def processInput2(self, dt): speed = Vec3(0, 0, 0) if inputState.isSet('esc'): sys.exit() if inputState.isSet('w'): speed.setY(35.0) if inputState.isSet('arrow_left'): speed.setX(-35.0) if inputState.isSet('arrow_right'): speed.setX(35.0) if inputState.isSet('space'): self.jump2() self.jumpSound2.play() if inputState.isSet('arrow_up'): self.jump2() self.jumpSound2.play() if inputState.isSet('cam-left'): self.camera.setX(self.camera, -20 * dt) if inputState.isSet('cam-right'): self.camera.setX(self.camera, +20 * dt) if inputState.isSet('cam-forward'): self.camera.setY(self.camera, -200 * dt) if inputState.isSet('cam-backward'): self.camera.setY(self.camera, +200 * dt) # Make Ecco run if self.isMoving2 is False: self.ecco2.loop("run") self.isMoving2 = True if self.pos2.getY() > 1450.0: speed.setY(0.0) else: speed.setY(40.0) self.character2.setLinearMovement(speed, True) def jump2(self): self.character2.setMaxJumpHeight(3.0) self.character2.setJumpSpeed(25.0) self.character2.doJump() def setupCoins2(self): # display coins = 0 textN = TextNode('coin-score') textN.setText(str("Coins: " + str(self.coinsCollected2))) textN.setSlant(0.1) textNodePath = self.aspect2d.attachNewNode(textN) textNodePath.setPos(0, 0.95, 0.9) textNodePath.setScale(0.08) randNum = random.sample(range(0, 1500, 200), 6) # coins for i in range(6): randX = random.uniform(-3.0, 3.2) randY = float(randNum[i]) shape = BulletSphereShape(0.3) coinNode = BulletGhostNode('Coin-' + str(i)) coinNode.addShape(shape) np = self.render.attachNewNode(coinNode) np.setCollideMask(BitMask32.allOff()) np.setPos(randX, randY, 2) # 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.45) sphereNp.hprInterval(2.5, Vec3(360, 0, 0)).loop() self.world2.attachGhost(coinNode) self.coins2.append(coinNode) print "node name:" + str(coinNode.getName()) def setupObstacles2(self): # Obstacle origin = Point3(2, 0, 0) size = Vec3(2, 2.75, 1.5) shape = BulletBoxShape(size * 0.55) randNum1 = random.sample(range(0, 1500, 300), 3) randNum2 = random.sample(range(0, 1500, 500), 3) for i in range(2): randX = random.uniform(-3.5, 3.5) randY = float(randNum1[i]) pos = origin + size * i ObstacleNP = self.render.attachNewNode(BulletRigidBodyNode('Obstacle%i' % i)) ObstacleNP.node().addShape(shape) ObstacleNP.node().setMass(1.0) ObstacleNP.setPos(randX, randY, 3) ObstacleNP.setCollideMask(BitMask32.allOn()) modelNP = loader.loadModel('models/box.egg') modelNP_tex = loader.loadTexture("models/sky/milkyway_tex.jpg") modelNP.setTexture(modelNP_tex, 1) modelNP.reparentTo(ObstacleNP) # modelNP.setPos(0, 0, 0) modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0) modelNP.setScale(size) self.world2.attachRigidBody(ObstacleNP.node()) size_2 = Vec3(3, 2.75, 1.5) shape2 = BulletBoxShape(size_2 * 0.55) for i in range(2): randX = random.uniform(-3.5, 3.5) randY = float(randNum2[i]) pos = origin + size_2 * i pos.setY(0) ObstacleNP = self.render.attachNewNode(BulletRigidBodyNode('ObstacleSmall%i' % i)) ObstacleNP.node().addShape(shape2) ObstacleNP.node().setMass(1.0) ObstacleNP.setPos(randX, randY, 2) ObstacleNP.setCollideMask(BitMask32.allOn()) modelNP = loader.loadModel('models/box.egg') modelNP_tex = loader.loadTexture("models/sky/moon_1k_tex.jpg") modelNP.setTexture(modelNP_tex, 1) modelNP.reparentTo(ObstacleNP) # modelNP.setPos(0, 0, 0) modelNP.setPos(-size_2.x / 2.0, -size_2.y / 2.0, -size_2.z / 2.0) modelNP.setScale(size_2) self.world2.attachRigidBody(ObstacleNP.node()) 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 processContacts2(self): for coin in self.coins2: self.testWithSingleBody2(coin) self.coinsCollected2 = len(self.dictOfCoins2) def testWithSingleBody2(self, secondNode): contactResult = self.world2.contactTestPair(self.character2, secondNode) if contactResult.getNumContacts() > 0: self.collectSound2.play() for contact in contactResult.getContacts(): cp = contact.getManifoldPoint() node0 = contact.getNode0() node1 = contact.getNode1() self.dictOfCoins2[node1.getName()] = 1 np = self.render.find(node1.getName()) np.node().removeAllChildren() self.world2.removeGhost(np.node()) def checkIfEccoDied2(self): print "position" + str(self.pos2.getY()) if self.pos2.getZ() > -50.0 and self.pos2.getZ() < 0.0: title = "Game Over" levelCompleteN = TextNode('ecco-died') font = loader.loadFont("font/Caveman.ttf") levelCompleteN.setFont(font) levelCompleteN.setText(title) levelCompleteN.setTextColor(1, 1, 1, 1) levelCompleteN.setSlant(0.1) levelCompleteN.setShadow(0.03) levelCompleteN.setShadowColor(0, 0, 200, 1) # levelN.setFrameAsMargin(0, 0, 0, 0) levelCompleteN.setFrameColor(200, 0, 0, 1) levelCompleteN.setFrameLineWidth(5.0) # textNp.node().setGlyphShift(1.0) textNodePath = self.aspect2d.attachNewNode(levelCompleteN) textNodePath.setPos(-0.9, 1.5, 0.5) textNodePath.setScale(0.2) if self.pos2.getZ() < -49.0: self.gameOverSound2.play() elif self.pos2.getZ() < -50.0: if self.gameOverSound2.status() != self.gameOverSound2.PLAYING: sys.exit(1) elif self.pos2.getY() > 1300.0: title = "Level 2 \n Complete" levelCompleteN = TextNode('level-complete') font = loader.loadFont("font/Caveman.ttf") levelCompleteN.setFont(font) levelCompleteN.setText(title) levelCompleteN.setTextColor(1, 1, 1, 1) levelCompleteN.setSlant(0.1) levelCompleteN.setShadow(0.03) levelCompleteN.setShadowColor(0, 0, 200, 1) # levelN.setFrameAsMargin(0, 0, 0, 0) levelCompleteN.setFrameColor(200, 0, 0, 1) levelCompleteN.setFrameLineWidth(5.0) # textNp.node().setGlyphShift(1.0) textNodePath = self.aspect2d.attachNewNode(levelCompleteN) textNodePath.setPos(-0.6, 1.5, 0.5) textNodePath.setScale(0.2) if self.levelCompleteSound2.status() != self.levelCompleteSound2.PLAYING: self.levelCompleteSound2.play() else: pass def coinScoreDisplay2(self): textNp = self.aspect2d.find('coin-score') textNp.node().clearText() textNp.node().setText(str("Coins: " + str(self.coinsCollected2)))
def __init__(self, name, scene, visualMeshEgg, parent, physicsType, physicsShapeEgg=None, shapeMargin=0.04, animable=False, animationsDict=None, stepHeight=0.5, x=0, y=0, z=0, mass=0, perpixelShading=False): """ :type name: str :type scene: HLevel :type visualMeshEgg: str :type parent: panda3d.core.NodePath :type physicsType: int :type physicsShapeEgg: str :type shapeMargin: float :type animable: bool :type animationsDict: dict :type stepHeight: float :type x: float :type y: float :type z: float :type mass: float :type perpixelShading: bool """ self.name = name self.scene = scene if visualMeshEgg is not None: if animable: if animationsDict is not None: self.vMesh = Actor(visualMeshEgg, animationsDict) self.vMesh.setBlend(frameBlend=True) else: self.vMesh = Actor(visualMeshEgg) self.vMesh.setBlend(frameBlend=True) else: self.vMesh = scene.Base.loader.loadModel(visualMeshEgg) else: self.vMesh = None if physicsType == physicsTypes["character"]: print name + " is a character" self.shapeModel = self.scene.loadEgg(physicsShapeEgg) self.shape = modelToConvex(self.shapeModel)[0] self.shape.setMargin(shapeMargin) self.body = BulletCharacterControllerNode(self.shape, stepHeight, name) self.bodyNP = parent.attachNewNode(self.body) if visualMeshEgg is not None: self.vMesh.reparentTo(self.bodyNP) self.scene.world.attachCharacter(self.body) self.bodyNP.setPos(x, y, z) self.body.setPythonTag("name", name) elif physicsType == physicsTypes["dynamic"]: self.shapeModel = self.scene.loadEgg(physicsShapeEgg) self.shape = modelToConvex(self.shapeModel)[0] self.shape.setMargin(shapeMargin) self.body = BulletRigidBodyNode(name) self.body.setMass(mass) self.body.addShape(self.shape) self.bodyNP = parent.attachNewNode(self.body) if visualMeshEgg is not None: self.vMesh.reparentTo(self.bodyNP) self.scene.world.attachRigidBody(self.body) self.bodyNP.setPos(x, y, z) self.body.setPythonTag("name", name) elif physicsType == physicsTypes["ghost"]: self.shapeModel = self.scene.loadEgg(physicsShapeEgg) self.shape = modelToConvex(self.shapeModel)[0] self.shape.setMargin(shapeMargin) self.body = BulletGhostNode(name) # self.body.setMass(mass) self.body.addShape(self.shape) self.bodyNP = parent.attachNewNode(self.body) if visualMeshEgg is not None: self.vMesh.reparentTo(self.bodyNP) self.scene.world.attachGhost(self.body) self.bodyNP.setPos(x, y, z) self.body.setPythonTag("name", name) else: pass # ###3Events # self.scene.Base.taskMgr.add(self.onFrame,"onFrame") self.shaders = perpixelShading if self.vMesh is not None and not self.shaders: self.scene.Base.taskMgr.add(self.clearShaderTask, name + "_clearShader") # self.scene.Base.taskMgr.add(self._calcVel,self.name+"_calcVelTask") self._lastPos = Point3() self.velocity = Vec3()
class Character(): def __init__(self, world, render, name, animator, position, pose): # Create a box shape shape = BulletBoxShape(Vec3(0.3, 0.2, 0.7)) # Create a Controller Node with the shape self.controllerNode = BulletCharacterControllerNode(shape, 0.4, name) self.controllerNode.setIntoCollideMask(BitMask32.allOn()) # Attach the Controller Node to the world world.attachCharacter(self.controllerNode) # Attach Controller Node to the render and get a NodePath self.nodePath = render.attachNewNode(self.controllerNode) # Setup the nodePath self.nodePath.setCollideMask(BitMask32.allOn()) self.nodePath.setH(DEFAULT_NODEPATH_HEIGHT) self.nodePath.setPos(position) # Set the actor of the Character self.animator = animator # Add animator to NodePath so it can be rendered self.animator.reparentTo(self.nodePath) # Configure the animator self.animator.setScale(DEFAULT_ANIMATOR_SCALE) self.animator.setH(DEFAULT_ANIMATOR_HEIGHT) self.animator.setPos(DEFAULT_ANIMATOR_OFFSET) # Set Current Character Pose self.pose = pose # Save home position self.home = position # ========== Character Controls def lookAt(self, position): position.setZ(self.getPosition().getZ()) self.nodePath.lookAt(position) def movement(self, vector): self.controllerNode.setLinearMovement(vector, True) # ========== Getters def getNodePath(self): return self.nodePath def getHeight(self): return self.nodePath.getZ() def getPosition(self): return self.nodePath.getPos() def getPose(self): return self.pose def getControllerNode(self): return self.controllerNode def getCurrentPoseName(self): return self.getCurrentAnim() def getHomePosition(self): return self.home # ========== Setters def setPosition(self, position): self.nodePath.setPos(position) def setPose(self, pose): if self.animator.getCurrentAnim() != 'jump': if pose == JUMPING: self.animator.stop() self.animator.play('jump') self.pose = JUMPING else: if self.pose != pose: self.pose = pose self.animator.stop() if (self.pose == RUNNING): self.animator.loop('run') elif (self.pose == WALKING): self.animator.loop('run') elif (self.pose == STANDING): self.animator.pose('walk', 0) elif (self.pose == ATTACKING): self.animator.loop('attack') self.pose == STANDING # ========== Boolean Functions def isWalking(self): animate = self.animator.getCurrentAnim() return animate == 'walk' or animate == 'run' def isAttacking(self): animate = self.animator.getCurrentAnim() return animate == 'attack' def goBackHome(self): return
class Eve(Character): #----- CLASS VARIABLES -----# HEIGHT = 21.00 WIDTH = 5.0 INITIAL_HEADING = 90 MAX_JUMP_HEIGHT = 200.0 JUMP_SPEED = 70 RUNNING_SPEED = 40.0 INITIAL_ROLL_SPEED = 200.0 ROLL_ANIM_RATE = 15 OMEGA = 60.0 #----- CONSTRUCTOR -----# def __init__(self,game,render,world,accept,health=100,damage=0): super(Eve,self).__init__('Eve',health,damage) #----- INSTANCE VARIABLES -----# self.state = {'normal': True, 'jumping' : False, 'rolling' : False} self.speed = Vec3(0, 0, 0) self.omega = 0.0 self.tiresCollected = 0 self.accept = accept self.ready = True #----- PRIVATE INSTANCE VARIABLES -----# self.__render = render self.__world = world self.__game = game #----- ACTOR SETUP -----# self.actorNP1 = Actor('models/eve/eve.egg', { 'run' : 'models/eve/eve-run.egg', 'walk' : 'models/eve/eve-walk.egg', 'jump' : 'models/eve/eve-jump.egg'}) self.actorNP2 = Actor('models/eve/eve-tireroll.egg', {'roll' : 'models/eve/eve-tireroll.egg'}) self.actorNP1.setPlayRate(2,'walk') #----- PREPARE SFX -----# self.jump = base.loader.loadSfx("sfx/jump.wav") self.jump.setVolume(.1) self.running = base.loader.loadSfx("sfx/walking.wav") self.running.setLoop(True) self.running.setPlayRate(1.55) self.running.setVolume(.08) self.land = base.loader.loadSfx("sfx/land.flac") self.land.setLoop(False) self.land.setVolume(.05) self.roll = base.loader.loadSfx("sfx/rolling.wav") self.roll.setLoop(True) self.roll.setVolume(.09) self.ouch = base.loader.loadSfx("sfx/ouch.wav") self.ouch.setLoop(False) self.ouch.setVolume(.75) self.ouch.setPlayRate(1.25) self.throw = base.loader.loadSfx("sfx/throw.wav") self.throw.setLoop(False) self.throw.setVolume(.75) self.blocked = base.loader.loadSfx("sfx/blocked.wav") self.blocked.setVolume(.05) #----- SETUP CONTROL FOR EVE -----# inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('turnLeft', 'a') inputState.watchWithModifiers('turnRight', 'd') inputState.watchWithModifiers('backwards', 's') def render_eve(self,pos): self.searchMode(pos,Eve.INITIAL_HEADING) # Changing jump animation play rate self.currentNode.setPlayRate(1,'jump') self.__game.taskMgr.add(self.process_contacts,'attacks') def disable_character_controls(self): self.accept('m', self.do_nothing) self.accept('space', self.do_nothing) self.accept('enter',self.do_nothing) def enable_character_controls(self): self.accept('m', self.toggle_modes) self.accept('space', self.doJump) self.accept('enter',self.attack) def do_nothing(self): pass #------ METHODS USED TO MODIFY JUMP ANIMATION ------# def firstPart(self): self.currentNode.play('jump', fromFrame=0) def stopInJump(self): self.currentNode.stop() def finishJump(self): self.currentNode.play('jump', fromFrame=11) self.land.play() #self.currentNode.play('jump', fromFrame=self.currentNode.getCurrentFrame('jump')) def doJump(self): if self.currentControllerNode.isOnGround() is True: if self.currentState() is 'normal': if self.speed.getY() > 0: self.running.stop() self.state['jumping'] = True self.jump.play() self.currentControllerNode.doJump() #sequence = Sequence(Func(self.firstPart),Wait(.3),Func(self.stopInJump),Wait(2.95),Func(self.finishJump)) sequence = Sequence(Func(self.firstPart),Wait(.3),Func(self.stopInJump),Wait(2.95)) sequence.start() def searchMode(self,location,heading): self.state['normal'] = True self.state['rolling'] = False (self.init_x,self.init_y,self.init_z) = location self.__capsule_shape = BulletCapsuleShape(Eve.WIDTH, Eve.HEIGHT - 2 * Eve.WIDTH, ZUp) # Create bullet character controller self.character1= BulletCharacterControllerNode(self.__capsule_shape,0.4,self.name) #self.character1.setMaxJumpHeight(Eve.MAX_JUMP_HEIGHT) self.character1.setJumpSpeed(Eve.JUMP_SPEED) self.character1.setGravity(70) self.characterNP1 = self.__render.attachNewNode(self.character1) self.characterNP1.setPos(self.init_x,self.init_y,self.init_z) self.characterNP1.setH(heading) self.characterNP1.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character1) self.actorNP1.reparentTo(self.characterNP1) self.actorNP1.setScale(4.0) self.actorNP1.setH(180) self.actorNP1.setPos(0,0,-9) self.currentNode = self.actorNP1 self.currentNP = self.characterNP1 self.currentControllerNode = self.character1 # Create a cylindrical collision shape collisionShape = BulletCylinderShape(6.5,3,XUp) # Create a ghost node and attach to render self.ghostNode = BulletGhostNode('Weapon') self.ghostNode.addShape(collisionShape) self.weaponNP = self.__game.render.attachNewNode(self.ghostNode) self.weaponNP.setCollideMask(BitMask32.allOff()) self.weaponNP.setPos(self.init_x, self.init_y, self.init_z) self.__game.world.attachGhost(self.ghostNode) self.weapon = self.__game.loader.loadModel('models/environ/tire/tire.egg') self.weapon.setScale(4,4,4) self.weapon.setPos(-.5,0,0) self.weapon.reparentTo(self.weaponNP) self.weapon.hide() self.__game.taskMgr.add(self.update_weapon_pos,"weapon") def reset(self): self.characterNP1.setPos(self.init_x,self.init_y,self.init_z) def update_weapon_pos(self,task): self.weaponNP.setPos(self.characterNP1.getX(),self.characterNP1.getY(), self.characterNP1.getZ() + 5) self.weaponNP.setH(self.characterNP1.getH()) return task.cont def attack(self): if self.tiresCollected > 0 and self.ready is True: self.throw.play() self.weapon.show() xpos = 100 * cos((90 - self.characterNP1.getH()) * (pi / 180.0)) ypos = -100 * sin((90 - self.characterNP1.getH()) * (pi / 180.0)) trajectory = ProjectileInterval(self.weaponNP, startPos = self.weaponNP.getPos(), endPos = Point3(self.weaponNP.getX() - xpos,self.weaponNP.getY() - ypos, self.weaponNP.getZ()-10), duration = .5, gravityMult = 15) Sequence(Func(self.set_weapon_busy),trajectory,Func(self.weapon.hide),Func(self.set_weapon_ready)).start() self.tiresCollected -= 1 else: self.blocked.play() def set_weapon_ready(self): self.ready = True def set_weapon_busy(self): self.ready = False def process_contacts(self,task): for enemy in self.__game.e.enemies: self.check_impact(enemy) return task.cont def check_impact(self,enemy): result = self.__game.world.contactTestPair(self.ghostNode,enemy.np.node()) if len(result.getContacts()) > 0: if self.weapon.isHidden() is False: self.weapon.hide() if self.ready is False: enemy.take_damage(self.damage) def attackMode(self,location,heading): self.state['normal'] = False self.state['rolling'] = True (self.init_x,self.init_y,self.init_z) = location self.__cylinder_shape = BulletCylinderShape(Eve.WIDTH + 2, Eve.HEIGHT - 4, XUp) # Create bullet character controller self.character2= BulletCharacterControllerNode(self.__cylinder_shape,0.4,self.name) self.characterNP2 = self.__render.attachNewNode(self.character2) self.characterNP2.setPos(self.init_x,self.init_y,self.init_z-2) self.characterNP2.setH(heading) self.characterNP2.setCollideMask(BitMask32.allOn()) self.__world.attachCharacter(self.character2) self.character2.setGravity(70) self.actorNP2.reparentTo(self.characterNP2) self.actorNP2.setScale(4.0) self.actorNP2.setH(180) self.actorNP2.setPos(0,0,0) self.currentNode = self.actorNP2 self.currentNP = self.characterNP2 self.currentControllerNode = self.character2 # Set play rate of the rolling animation self.currentNode.setPlayRate(15,'roll') def is_attack_mode(self): return self.state['rolling'] def toggle_modes(self): if self.is_attack_mode() is False: loc = (self.characterNP1.getX(),self.characterNP1.getY(),self.characterNP1.getZ()) heading = self.characterNP1.getH() self.__world.removeCharacter(self.character1) self.character1.removeChild(0) self.attackMode(loc,heading) else: loc = (self.characterNP2.getX(),self.characterNP2.getY(),self.characterNP2.getZ()) heading = self.characterNP2.getH() self.__world.removeCharacter(self.character2) self.character2.removeChild(0) self.searchMode(loc,heading) def processEveInput(self): if self.currentControllerNode.isOnGround() is True: self.speed = Vec3(0, 0, 0) self.omega = 0.0 if inputState.isSet('forward'): if self.state['rolling'] == True: self.speed.setY( Eve.INITIAL_ROLL_SPEED) else: self.speed.setY( Eve.RUNNING_SPEED) self.currentNode.setP(15) if inputState.isSet('backwards'): if self.state['rolling'] == True: self.speed.setY( Eve.INITIAL_ROLL_SPEED - 300) else: self.speed.setY(-1 * Eve.RUNNING_SPEED - 10) if inputState.isSet('turnLeft'): self.omega = Eve.OMEGA if self.speed.getY() == 0: self.currentNode.setR(0) else: self.currentNode.setR(15) if inputState.isSet('turnRight'): self.omega = Eve.OMEGA * -1 if self.speed.getY() == 0: self.currentNode.setR(0) else: self.currentNode.setR(-15) self.currentControllerNode.setAngularMovement(self.omega) if self.currentControllerNode.isOnGround() is False: self.currentControllerNode.setAngularMovement(0.0) self.currentControllerNode.setLinearMovement(self.speed, True) self.currentNode.setR(0) if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() == 'jump': self.currentNode.setR(0) self.currentControllerNode.setAngularMovement(0.0) self.currentControllerNode.setLinearMovement(0.0, True) if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump': self.currentControllerNode.setAngularMovement(self.omega) self.currentControllerNode.setLinearMovement(self.speed, True) def currentState(self): if self.state['rolling'] is True: return 'rolling' else: return 'normal' def updateEveAnim(self): self.processEveInput() if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump': if self.speed.getY() > 0: if self.omega == 0.0: self.currentNode.setR(0) if self.currentState() is 'rolling': if self.running.status() == self.running.PLAYING: self.running.stop() if self.roll.status() != self.roll.PLAYING: self.roll.play() if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll') elif self.currentState() is 'normal': if self.roll.status() == self.roll.PLAYING: self.roll.stop() if self.running.status() != self.running.PLAYING: self.running.play() if self.currentNode.getCurrentAnim() != 'run': self.currentNode.loop('run') elif self.speed.getY() < 0: if self.currentState() is 'rolling': if self.running.status() == self.running.PLAYING: self.running.stop() if self.roll.status() != self.roll.PLAYING: self.roll.play() if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll') elif self.currentState() is 'normal': if self.roll.status() == self.roll.PLAYING: self.roll.stop() if self.running.status() != self.running.PLAYING: self.running.play() if self.currentNode.getCurrentAnim() != 'walk': self.currentNode.loop('walk') else: if self.omega != 0: if self.currentState() is 'rolling': if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll') elif self.currentState() is 'normal': if self.currentNode.getCurrentAnim() != 'walk': self.actorNP1.setPlayRate(1,'walk') self.currentNode.loop('walk') else: self.currentNode.stop(self.currentNode.getCurrentAnim()) self.actorNP1.setPlayRate(2,'walk') self.currentNode.setP(0) self.currentNode.setR(0) if self.running.status() == self.running.PLAYING: self.running.stop() if self.roll.status() == self.roll.PLAYING: self.roll.stop() if self.state['rolling'] is True: frame = self.currentNode.getCurrentFrame('roll') if frame is None: frame = 0 else: frame = self.currentNode.getCurrentFrame('roll') self.currentNode.pose('roll',frame) elif self.state['normal'] is True: self.currentNode.pose('walk',5) elif self.currentControllerNode.isOnGround() is False and self.state['jumping'] is False: self.currentNode.pose('jump',7) def take_damage(self,damage): self.ouch.play() color_scale_interval1 = LerpColorScaleInterval(self.currentNode, .5, (1,0,0,.1), (1,0,0,0)) Sequence(color_scale_interval1,Wait(.005),Func(self.currentNode.clearColorScale)).start() self.health -= damage
class Player(object): def __init__(self, render, world, x, y, z): self.render = render self.world = world self.x = x self.y = y self.z = z # Game state variables self.isMoving = False self.isJumping = False # This is used to store which keys are currently pressed. self.keyMap = {"left": 0, "right": 0, "forward": 0, "reverse": 0} # Defining sound effects self.jumpSound = base.loader.loadSfx("sounds/jumping.wav") self.runSound = base.loader.loadSfx("sounds/running.ogg") self.createPlayer() def createPlayer(self): h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') # self.character.setMass(1.0) self.characterNP = self.render.attachNewNode(self.character) self.characterNP.setPos(self.x, self.y, self.z) self.characterNP.setH(45) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) self.actorNP = Actor('models/Bricker/Bricker3.egg', { 'run': 'models/Bricker/Bricker-run.egg', 'jump': 'models/Bricker/Bricker-jump.egg'}) self.actorNP.reparentTo(self.characterNP) self.actorNP.setScale(0.3048) self.actorNP.setH(180) self.actorNP.setPos(0, 0, 0.27) def setKey(self, key, value): self.keyMap[key] = value def doJump(self): self.character.setMaxJumpHeight(5.0) self.character.setJumpSpeed(8.5) self.character.doJump() self.actorNP.play("jump") self.jumpSound.play() def move(self): speed = Vec3(0, 0, 0) omega = 0.0 if self.keyMap["left"]: omega = 120.0 if self.keyMap["right"]: omega = -120.0 if self.keyMap["forward"]: speed.setY(4.0) if self.keyMap["reverse"]: speed.setY(-4.0) self.character.setAngularMovement(omega) self.character.setLinearMovement(speed, True) if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["reverse"]: if self.isMoving is False: self.actorNP.loop("run") self.runSound.play() self.isMoving = True else: if self.isMoving: self.actorNP.stop() self.runSound.stop() self.isMoving = False def getCharacterNP(self): return self.characterNP def getCharacter(self): return self.character def getActrorNP(self): return self.actorNP def resetCharacter(self): if (Data.currentLevel == 1): self.characterNP.setPos(0, 0, 0) else: self.characterNP.setPos(100, 100, 0)
def __init__(self): ShowBase.__init__(self) #self.word = BulletWorld() self.cx = 0.0 self.cy = 0.0 self.current_omega = 0 s = self.loader.loadSfx('Doom Soundtrack - Level 1 (Extended).mp3') s.play() self.current_pos = (10, 5, 1) self.current_hpr = (0, 0, 0) #self.fxboy = self.loader.loadModel("cubearm.egg") self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -12.0)) #self.physicsMgr.attachPhysicalNode(self.camera) keyboard.on_press_key('w', self.moveForward) keyboard.on_press_key('s', self.moveBackward) keyboard.on_press_key('j', self.lookLeft) keyboard.on_press_key('y', self.lookUp) keyboard.on_press_key('h', self.lookDown) keyboard.on_press_key('g', self.lookRight) keyboard.on_press_key('d', self.moveLeft) #self.fxboy.reparentTo(self.render) #self.camera.reparentTo(self.render) #self.camera.reparentTo(self.fxboy) keyboard.on_press_key('a', self.moveRight) keyboard.on_press_key('space', self.fire) keyboard.on_press_key('2', self.jump) #keyboard.on_press_key('y',self.lookUp) keyboard.on_press_key('1', self.moveUp) self.cam = BulletCapsuleShape(radius, height - 2 * radius, ZUp) self.player = BulletCharacterControllerNode(self.cam, 0.4, 'Player') self.playernp = self.render.attachNewNode(self.player) self.world.attachCharacter(self.playernp.node()) self.camera.reparentTo(self.playernp) self.playernp.setPos(self.current_pos) self.playernp.setHpr(self.current_hpr) self.playernp.setH(45) #self.player.setMass(10.0) # self.playernp.setCollideMask(BitMask32.allOn()) self.disableMouse() self.scenes = BulletBoxShape(Vec3(0.25, 0.25, 0.25)) self.scenenode = BulletRigidBodyNode('Scene') self.scenenode.setMass(12.0) self.scenenode.addShape(self.scenes) self.scenenp = render.attachNewNode(self.scenenode) self.scenenp.setPos(-8, 40, 0) self.world.attachRigidBody(self.scenenode) self.scene = self.loader.loadModel("models/environment.egg.pz") self.scene.reparentTo(self.render) self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 40, 0) self.scene.reparentTo(self.scenenp) self.scenenode.setGravity(Vec3(0, 0, 0)) #self.taskMgr.add(self.spinCameraTask,"SpinCameraTask") self.taskMgr.add(self.moveChar, "MoveChar") self.taskMgr.add(self.moveCBod, "MoveCBod") self.pandaActor = Actor("cubearm.egg", {"walk": "cubearm4-ArmatureAction.egg"}) self.pandaActor.setScale(0.12, 0.12, 0.12) self.pandaActor.setPos((10, 10, 0.5)) self.pandaPos = (10, 10, 0.5) self.pandaActor.reparentTo(self.render) self.pandaActor.loop('walk') '''
class Human(): def __init__(self,parent, world, worldNP): """__init__ parameters: self parent: the World object world: bullet world worldNP: where in the world to put it returns: none Description: Create the human player """ self.traptime = 0 self.world = world self.worldNP = worldNP self.projectiles = list() self.floatTraps = list() self.keymap = {"left": 0, "right":0, "up":0,"down":0, "m1":0} self.prevTime = 0 # panda walk parent.accept("w",self.setKey,["up",1]) parent.accept("w-up",self.setKey,["up",0]) parent.accept("s",self.setKey,["down",1]) parent.accept("s-up",self.setKey,["down",0]) parent.accept("a",self.setKey,["left",1]) parent.accept("a-up",self.setKey,["left",0]) parent.accept("d",self.setKey,["right",1]) parent.accept("d-up",self.setKey,["right",0]) parent.accept("mouse1", self.setKey, ["m1",1]) self.velocity = 0 self.dir = (0,0,0) self.vel = (0,0,0) taskMgr.add(self.fpMove,"moveTask",sort=50) taskMgr.add(self.mouseTask, 'mouseTask') self.parent = parent #self.human = self.parent.human #self.human = collision.loadAndPositionModelFromFile("../assets/3d/Actors/robot rig 10 coll.egg",scale=.07,show=0) self.human = Actor('../assets/3d/Actors/robot_idle_final_actor.egg', { 'idle':'../assets/3d/Actors/robot_idle_final_anim.egg', # 'throw':'../assets/3d/Actors/animation eggs/robot_throw_final.egg', # 'place':'../assets/3d/Actors/animation eggs/robot_place_final.egg', # 'death':'../assets/3d/Actors/animation eggs/robot_death_final.egg', }) #print self.human.find("**/eyes_sphere").getPos() #self.human.flattenLight() print self.human.ls() #self.human.node().getChild(0).removeChild(0) self.human.setH(camera.getH()+180) campos = self.human.getPos() campos[2] = campos[2]-5 camera.lookAt(campos) pnode = ModelRoot("player") self.player = render.attachNewNode(pnode) pc = self.player.attachNewNode(CollisionNode("playerCollision")) pc.node().addSolid(CollisionRay(0,0,-1,0,0,1)) self.playerCnode = pc self.player.setPos(0,0,1) #self.human.play('idle') self.human.loop('idle') def bulletInit(self,world,pos): """bulletInit parameters: self task: the tskMgr structure returns: none Description: The rest of init requires bullet things """ oldpath = self.human.find("**/body_coll") self.shape = BulletSphereShape(10)#oldpath.node().getSolid(0).getRadius()) self.character = BulletCharacterControllerNode(self.shape, 0.4, 'Human') self.characterNP = render.attachNewNode(self.character) self.characterNP.setPos(pos[0],pos[1],pos[2]) self.character.setGravity(0) #self.human.setPos(pos) self.human.reparentTo(self.characterNP) self.human.hide() #self.player.setPos(pos) self.player.reparentTo(self.characterNP) self.characterNP.setCollideMask(BitMask32.allOn()) world.attachCharacter(self.character) def fpMove(self,task): """fpMove parameters: self task: the taskMgr structure returns: none Description: player movement """ dt = task.time-self.prevTime camera.setPos(self.player.getPos()+(0,0,1)) damp = (1.-(.2*dt)) self.vel = map(lambda x: damp*x, self.vel) if self.traptime>0: self.traptime = self.traptime-dt #self.human.setZ(self.player.getZ()-.5) #if not self.parent.editMode: #camera.setPos(self.player.getPos()-(0.0264076, 4.60993, -10.0715)) self.prevTime = task.time pos = self.player.getParent().getPos() delta = 10*dt h = deg2Rad(camera.getH()) p = deg2Rad(camera.getP()) # player control if self.keymap["up"] and self.traptime<=0: dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) self.vel = map(lambda i: self.vel[i]+dir[i]*delta, range(3)) if self.keymap["down"] and self.traptime<=0: dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) self.vel = map(lambda i: self.vel[i]-dir[i]*delta, range(3)) if self.keymap["m1"] and self.traptime<=0: weapon = self.parent.overlay.wepCounter if self.parent.overlay.wepAmmo[weapon] > 0: self.parent.overlay.changeAmmo(weapon, -1) if weapon == 0: self.launch() dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p)) self.vel = map(lambda i: self.vel[i]-dir[i]*100, range(3)) elif weapon == 1: self.placeFloatTrap() elif weapon == 2: self.placeClawTrap() self.keymap["m1"] = 0 self.character.setAngularMovement(0) self.character.setLinearMovement(LVector3(self.vel[0],self.vel[1],self.vel[2]),True) #get displacement dis = (self.vel[0]*dt,self.vel[1]*dt,self.vel[2]*dt) #set the new position self.player.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2]) self.human.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2]) #self.human.setX(self.player.getX()+sin(deg2Rad(camera.getH())+math.pi)) #self.human.setY(self.player.getY()-cos(deg2Rad(camera.getH())+math.pi)) return task.cont def launch(self): """launch parameters: self returns: none Description: Fire a projectile """ self.projectiles.append(Projectile(self.player.getPos(),deg2Rad(camera.getH()),deg2Rad(camera.getP()),self,self.vel, self.world, self.worldNP)) def placeFloatTrap(self): """placeFloatTrap parameters: self returns: none Description: Place a float trap """ self.floatTraps.append(floatTrap(self.player.getPos(),self.world,self.worldNP)) def placeClawTrap(self): """placeClawTrap parameters: self returns: none Description: Place a claw trap """ trap = clawTrap(self.world,self.worldNP) weapon = self.parent.overlay.wepCounter self.parent.overlay.changeAmmo(weapon, trap.failed) def setKey(self,key,value): self.keymap[key] = value def mouseTask(self,task): """mouseTask parameters: self task: the tskMgr structure returns: none Description: Keep track of the mouse and record its movement """ global mousePos, mousePrevPos if (not base.mouseWatcherNode.hasMouse() ): return Task.cont # Get mouse coordinates from mouse watcher x=base.mouseWatcherNode.getMouseX() y=base.mouseWatcherNode.getMouseY() mousePos = [x,y] # Calculate mouse movement from last frame and output (print) move = [mousePos[0],mousePos[1]] if move==[0,0]: return Task.cont #print "Moved:\t %f right, \t %f up." %(move[0], move[1]) base.win.movePointer(0, base.win.getXSize() / 2, base.win.getYSize() / 2) # Save current position for next calculation mousePrevPos = mousePos camera.setP(camera.getP()+75*move[1]) camera.setH(camera.getH()-75*move[0]) self.human.setH(camera.getH()+180) self.human.setX(self.player.getX()+sin(deg2Rad(camera.getH()+180))) self.human.setY(self.player.getY()-cos(deg2Rad(camera.getH()+180))) contacts = self.world.contactTest(self.character).getContacts() for c in contacts: contactObject = c.getNode0() if c.getNode0().getName()=="Human": contactObject = c.getNode1() if contactObject.getName()=="env": self.vel = map(lambda x: x*.9, self.vel) return Task.cont def die(self,event): """die parameters: self task: the tskMgr structure returns: none Description: Kill the player """ #base.cTrav.removeCollider(self.wheelsphere) self.human.node().getChild(0).removeChild(0) self.filters.setInverted() print "You Died!" def trap1(self): """trap1 parameters: self returns: none Description: Inflict the floating trap penalty """ self.vel = map(lambda x: x*.25, self.vel) self.traptime = self.traptime + 20 return def trap2(self): """trap2 parameters: self returns: none Description: Inflict the claw trap penalty """ self.vel = (0,0,0) self.traptime = self.traptime + 30 return def impact(self,vel): diff = map(lambda i: self.vel[i]-vel[i], range(3)) self.vel = map(lambda i: self.vel[i]-diff[i], range(3))