Beispiel #1
0
class Obstacle:
    def __init__(self, x, y, z):

        self.model = loader.loadModel("models/cube")
        self.model.reparentTo(render)
        self.model.setPos(x, y, z)
        self.model.setHpr(0, 0, 0)
        self.model.setColor(0.9, 0.9, 0.9, 1)
        self.model.setTexture(loader.loadTexture("textures/texture.png"))

    def enable_physics(self, physics):

        self.body = OdeBody(physics.world)
        self.initial_position = self.model.getPos(render)
        self.initial_quaternion = self.model.getQuat(render)
        self.reset()

        mass = OdeMass()
        mass.setBox(0.2, 1, 1, 1)
        self.body.setMass(mass)

        self.geom = OdeBoxGeom(physics.space, 1, 1, 1)
        self.geom.setBody(self.body)

        physics.bodymodels[self.body] = self.model

    def reset(self):
        self.body.setPosition(self.initial_position)
        self.body.setQuaternion(self.initial_quaternion)
        self.body.setLinearVel(0, 0, 0)
        self.body.setAngularVel(0, 0, 0)
Beispiel #2
0
class BigWall(StaticObject):

    def __init__(self, game, width=200.0, thickness=4.0, height=10):
        self.game = game
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, width, thickness, height)

        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        
        model = loader.loadModel('BigWall.egg')
        model.setScale(width/50.0, thickness/4.0, height)
        model.reparentTo(self.visualNode)
        model.setZ(266)
#        tex = loader.loadTexture('seina.jpg')
#        model.setTexture(tex, 1)
        
        
    def osuminen(self, ship1):
         if OdeUtil.collide(ship1.collGeom, self.collGeom):
 
            print "sdfgfdhgdfhxfhdhghcfh"
            print "ship1 xdfhgxdgxdgfbcdll!!"
Beispiel #3
0
class bigWall(StaticObject):


    
    def __init__(self, game):
        self.game = game
        
        
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, 50, 15, 15)
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        #remember to make wall model with "50" length... no idea 50 what, though
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('BigWall.egg')
        model.reparentTo(self.visualNode) 
        
        
   
        
        
    def osuminen(self, ship1):
         if OdeUtil.collide(ship1.collGeom, self.collGeom):
 
            print "sdfgfdhgdfhxfhdhghcfh"
            print "ship1 xdfhgxdgxdgfbcdll!!"
Beispiel #4
0
    def __init__(self, space, pos, dim, surface=SurfaceType.FLOOR):
        '''
		kirjoita numerot float muodossa 1.0
		@param space: fysiikka-avaruus?
		'''
        MovingPlane.id += 1
        self.id = id
        self.dim = dim  # dimension
        self.pos = pos  # position
        self.h = (dim[0] / 2, dim[1] / 2, dim[2] / 2)  # center
        self.t = 0

        self.geom = OdeBoxGeom(space, dim[0], dim[1], dim[2])
        space.setSurfaceType(self.geom, surface)

        self.model = loader.loadModel(self.MODEL)
        self.model.setScale(dim[0], dim[1], dim[2])
        # http://www.panda3d.org/wiki/index.php/Creating_a_New_Node_Class
        self.model.flattenLight()
        self.model.reparentTo(render)

        self.rotate = False

        if surface == SurfaceType.SAND:
            self.model.setColor(1, 0, 0)
        self.updateModelNode()
Beispiel #5
0
class smallWall(StaticObject):
    
    def __init__(self, game):
        
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, 10, 2, 30)
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('testipalikka.egg')
        model.reparentTo(self.visualNode)
Beispiel #6
0
	def __init__(self, world):
		GameObject.__init__(self, world)

		# Set the speed parameters
		self.vel = Vec3(0, 0, 0)
		self.strafespeed = 20.0
		self.forwardspeed = 32.0
		self.backspeed = 24.0
		self.jumpspeed = 20
		self.wasJumping = False

		# Set character dimensions
		self.size = (4.0, 3.0, 10.0)
		self.eyeHeight = 9.0
		self.offset = Point3(0, 0, self.eyeHeight - (self.size[2]/2))

		# Create character node
		self.node = base.render.attachNewNode("character")
		self.node.setPos(0, 0, self.eyeHeight)
		self.node.lookAt(0, 1, self.eyeHeight)

		# Create physics representation
		self.mass = OdeMass()
		self.mass.setBox(50, *self.size)
		self.body = OdeBody(world.world)
		self.body.setMass(self.mass)
		self.updatePhysicsFromPos()
		self.body.setData(self)
		self.geom = OdeBoxGeom(world.space, Vec3(*self.size))
		self.geom.setBody(self.body)
		world.space.setSurfaceType(self.geom, world.surfaces["box"])

		# Adjust collision bitmasks.
		self.geom.setCategoryBits(GameObject.bitmaskCharacter)
		self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskBullet)

		# Setup event handling
		self.keys = [0, 0, 0, 0, 0]
		self.setupKeys()
		base.taskMgr.add(self.moveTask, "character-move")

		# Create footsteps sound
		self.footstepsSound = base.loader.loadSfx("media/footsteps.wav")
		self.footstepsSound.setLoop(1)
		self.footsteps = SoundWrapper(self.footstepsSound)

		# Create other sounds.
		self.jumpSound = base.loader.loadSfx("media/jump_start.wav")
		self.landSound = base.loader.loadSfx("media/jump_fall.wav")
Beispiel #7
0
	def __init__(self, world, parent, color, pos, dir, size, density, unglueThreshold=None, shatterLimit=None, shatterThreshold=None):
		GameObject.__init__(self, world)

		if unglueThreshold == None: unglueThreshold = 20
		if shatterLimit == None: shatterLimit = 0
		if shatterThreshold == None: shatterThreshold = 30

		self.size = size
		self.density = density
		self.dir = dir
		self.parent = parent
		self.color = color = makeVec4Color(color)
		
		self.node = parent.attachNewNode("")
		self.node.setPos(*pos)
		self.node.setColorScale(color)
		self.node.setScale(*size)
		self.node.lookAt(self.node, *dir)

		self.model = loader.loadModel("models/box.egg")
		self.model.reparentTo(self.node)
		self.model.setScale(2.0)
		self.model.setPos(-1.0, -1.0, -1.0)

		self.applyTexture()

		self.mass = OdeMass()
		self.mass.setBox(density, Vec3(*size) * 2)
		self.body = OdeBody(world.world)
		self.body.setMass(self.mass)
		self.body.setPosition(self.node.getPos())
		self.body.setQuaternion(self.node.getQuat())
		self.body.setData(self)
		self.geom = OdeBoxGeom(world.space, Vec3(*size) * 2.0)
		self.geom.setBody(self.body)
		world.space.setSurfaceType(self.geom, world.surfaces["box"])

		# Adjust collision bitmasks.
		self.geom.setCategoryBits(GameObject.bitmaskBox)
		self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskTileGlued)

		# Tile, cement and shatter variables.
		self.tiles = []
		self.cements = []
		self.disableCount = 0
		self.unglueThreshold = unglueThreshold
		self.shatterLimit = shatterLimit
		self.shatterThreshold = shatterThreshold
Beispiel #8
0
class AntiGravityPlate(StaticObject):

    def __init__(self, game, x=100, y=100):
    
        self.game = game
    
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, x, y, 2)
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('agplate.egg')
        model.setScale(20)
        model.reparentTo(self.visualNode)
Beispiel #9
0
    def __init__(self, game):
        self.game = game
        
        #poista se fysiikka-avaruus ja vaan tee se alue... justiinsa
        self.collGeom = OdeBoxGeom( 24,8,2 )

        
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(1) )
        self.collGeom.setCollideBits( BitMask32(1) )
        

#        self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2)
#        #self.collGeom.setBody(self.body)
#        self.collGeomOuter.setCategoryBits( BitMask32(1) )
#        self.collGeomOuter.setCollideBits( BitMask32(1) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('Base.egg')
        model.reparentTo(self.visualNode)
        
        plight = PointLight('baselight')
        plight.setPoint( Point3(0, 0, 12) )
        plight.setColor( Vec4(1,1,1,1) )
        plight.setAttenuation( Vec3(0.1, 0.1, 0.005) )
        self.visualNode.setLight(model.attachNewNode(plight))
Beispiel #10
0
 def __init__(self, game):
     self.game = game
     
     self.collGeomInner = OdeBoxGeom( self.game.physicsSpace, 24,8,2)
     #self.collGeom.setBody(self.body)
     self.collGeomInner.setCategoryBits( BitMask32(1) )
     self.collGeomInner.setCollideBits( BitMask32(1) )
     
     self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2)
     #self.collGeom.setBody(self.body)
     self.collGeomOuter.setCategoryBits( BitMask32(1) )
     self.collGeomOuter.setCollideBits( BitMask32(1) )
     
     self.visualNode = NodePath('Visual node')
     self.visualNode.reparentTo(render)
     model = loader.loadModel('Base.egg')
     model.reparentTo(self.visualNode)
Beispiel #11
0
class AntiGravityPlate(StaticObject):

    def __init__(self, game, x=100, y=100):
    
        self.game = game
    
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, x, y, 2)
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        self.visualNode = NodePath('Visual node')
        model = loader.loadModel('agplate.egg')
#        ts = TextureStage('ts')
#        ts.setMode(TextureStage.MReplace)
        tex = loader.loadTexture('agplatetex.jpg')
        model.setTexture(tex, 1)
        model.setScale(30)
        model.reparentTo(self.visualNode)
        self.visualNode.reparentTo(render)
 def createCubicObstacle(self, pos, obstacleIndex):
     self.notify.debug('create obstacleindex %s' % obstacleIndex)
     sideLength = IceGameGlobals.TireRadius * 2
     geom = OdeBoxGeom(self.space, sideLength, sideLength, sideLength)
     geom.setCollideBits(self.allTiresMask)
     geom.setCategoryBits(self.obstacleMask)
     self.space.setCollideId(geom, self.obstacleCollideId)
     tireModel = loader.loadModel('phase_4/models/minigames/ice_game_crate')
     tireModel.setPos(pos)
     tireModel.reparentTo(render)
     geom.setPosition(tireModel.getPos())
     tireModel.setZ(0)
     return tireModel
Beispiel #13
0
class Base(StaticObject):
    #17.12.2009: collGeomInner -> collGeom, dropBall(x, y ,z, linX, linY), collectible.setPos() ja setVelocity()
    def __init__(self, game):
        self.game = game
        
        #poista se fysiikka-avaruus ja vaan tee se alue... justiinsa
        self.collGeom = OdeBoxGeom( 24,8,2 )

        
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(1) )
        self.collGeom.setCollideBits( BitMask32(1) )
        

#        self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2)
#        #self.collGeom.setBody(self.body)
#        self.collGeomOuter.setCategoryBits( BitMask32(1) )
#        self.collGeomOuter.setCollideBits( BitMask32(1) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('Base.egg')
        model.reparentTo(self.visualNode)
        
        plight = PointLight('baselight')
        plight.setPoint( Point3(0, 0, 12) )
        plight.setColor( Vec4(1,1,1,1) )
        plight.setAttenuation( Vec3(0.1, 0.1, 0.005) )
        self.visualNode.setLight(model.attachNewNode(plight))
 
    def checkCollision( self, ship, collectiblelist ):
        if OdeUtil.collide(ship.collGeom, self.collGeom) and ship.hasBall():
            #if ship.hasBall():
            ship.addPoints( (ship.Ball.getValue()*2) )
            pos = self.getPos()
            ship.dropBall( x = pos[0], y = pos[1], z = 50, linX = random.randrange(-10,10), linY = (0-pos[1]) / 4 )
            print ship.SHIP_TYPE + " " +  str(ship.getPoints()) + " Points! "
            
            if (self.game.goalSfx.status() == 1):
                self.game.goalSfx.play()
            self.game.updateHUD()
            #print " Base One! "
        for collectible in collectiblelist:
            if OdeUtil.collide(collectible.collGeom, self.collGeom):
                pos = self.getPos()
                ship.addPoints(collectible.getValue())
                collectible.setPos( Vec3(pos[0], pos[1], 50))
                collectible.setVelocity(x = random.randrange(-10,10), y = (0-pos[1]) / 4)
                self.game.goalSfx.play()
                self.game.updateHUD()
                print ship.SHIP_TYPE + " " + str(ship.getPoints()) + " Points! by throwing the ball"

    def addToBaseList(self, baseList):
        baseList.append(self)
        
    def setPos(self, pos, pos2):
        self.visualNode.setPos( pos )
        self.collGeom.setPosition( pos2 )
Beispiel #14
0
class Plate:

    def __init__(self, x, y, z, width, height):

        self.model = loader.loadModel("models/cube")
        self.model.reparentTo(render)
        self.model.setScale(width, height, 0.2)
        self.model.setPos(x, y, z)
        self.model.setHpr(0, 0, 0)
        self.model.setColor(0.7, 0.3, 0.1, 1)
        self.model.setTexture(loader.loadTexture('textures/texture.png'))

        self.width = width
        self.height = height


    def enable_physics(self, physics):
        self.geom = OdeBoxGeom(physics.space, self.width, self.height, 0.2)
        self.geom.setPosition(self.model.getPos())
        self.geom.setQuaternion(self.model.getQuat())

    def reset(self):
        pass
Beispiel #15
0
 def __init__(self, game):
     self.game = game
     
     
     self.collGeom = OdeBoxGeom( self.game.physicsSpace, 50, 15, 15)
     #self.collGeom.setBody(self.body)
     self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
     self.collGeom.setCollideBits( BitMask32(0x000000ff) )
     
     #remember to make wall model with "50" length... no idea 50 what, though
     self.visualNode = NodePath('Visual node')
     self.visualNode.reparentTo(render)
     model = loader.loadModel('BigWall.egg')
     model.reparentTo(self.visualNode) 
 def createCubicObstacle(self, pos, obstacleIndex):
     self.notify.debug('create obstacleindex %s' % obstacleIndex)
     sideLength = IceGameGlobals.TireRadius * 2
     geom = OdeBoxGeom(self.space, sideLength, sideLength, sideLength)
     geom.setCollideBits(self.allTiresMask)
     geom.setCategoryBits(self.obstacleMask)
     self.space.setCollideId(geom, self.obstacleCollideId)
     tireModel = loader.loadModel('phase_4/models/minigames/ice_game_crate')
     tireModel.setPos(pos)
     tireModel.reparentTo(render)
     geom.setPosition(tireModel.getPos())
     tireModel.setZ(0)
     return tireModel
    def __init__(self, world):
        GameObject.__init__(self, world)

        # Set the speed parameters
        self.vel = Vec3(0, 0, 0)
        self.strafespeed = 20.0
        self.forwardspeed = 32.0
        self.backspeed = 24.0
        self.jumpspeed = 20
        self.wasJumping = False

        # Set character dimensions
        self.size = (4.0, 3.0, 10.0)
        self.eyeHeight = 9.0
        self.offset = Point3(0, 0, self.eyeHeight - (self.size[2] / 2))

        # Create character node
        self.node = base.render.attachNewNode("character")
        self.node.setPos(0, 0, self.eyeHeight)
        self.node.lookAt(0, 1, self.eyeHeight)

        # Create physics representation
        self.mass = OdeMass()
        self.mass.setBox(50, *self.size)
        self.body = OdeBody(world.world)
        self.body.setMass(self.mass)
        self.updatePhysicsFromPos()
        self.body.setData(self)
        self.geom = OdeBoxGeom(world.space, Vec3(*self.size))
        self.geom.setBody(self.body)
        world.space.setSurfaceType(self.geom, world.surfaces["box"])

        # Adjust collision bitmasks.
        self.geom.setCategoryBits(GameObject.bitmaskCharacter)
        self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskBullet)

        # Setup event handling
        self.keys = [0, 0, 0, 0, 0]
        self.setupKeys()
        base.taskMgr.add(self.moveTask, "character-move")

        # Create footsteps sound
        self.footstepsSound = base.loader.loadSfx("media/footsteps.wav")
        self.footstepsSound.setLoop(1)
        self.footsteps = SoundWrapper(self.footstepsSound)

        # Create other sounds.
        self.jumpSound = base.loader.loadSfx("media/jump_start.wav")
        self.landSound = base.loader.loadSfx("media/jump_fall.wav")
Beispiel #18
0
    def enable_physics(self, physics):

        self.body = OdeBody(physics.world)
        self.initial_position = self.model.getPos(render)
        self.initial_quaternion = self.model.getQuat(render)
        self.reset()

        mass = OdeMass()
        mass.setBox(0.2, 1, 1, 1)
        self.body.setMass(mass)

        self.geom = OdeBoxGeom(physics.space, 1, 1, 1)
        self.geom.setBody(self.body)

        physics.bodymodels[self.body] = self.model
Beispiel #19
0
    def __init__(self, game, width=200.0, thickness=4.0, height=10):
        self.game = game
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, width, thickness, height)

        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        
        model = loader.loadModel('BigWall.egg')
        model.setScale(width/50.0, thickness/4.0, height)
        model.reparentTo(self.visualNode)
        model.setZ(266)
Beispiel #20
0
    def createCubicObstacle(self, pos, obstacleIndex):
        """Create one physics obstacle. Returns a nodePath"""
        self.notify.debug("create obstacleindex %s" % (obstacleIndex))
        sideLength = IceGameGlobals.TireRadius * 2
        geom = OdeBoxGeom(self.space, sideLength, sideLength, sideLength)
        geom.setCollideBits(self.allTiresMask)  # we only collide against tires
        geom.setCategoryBits(self.obstacleMask)
        self.space.setCollideId(geom, self.obstacleCollideId)

        #tireModel = render.attachNewNode('cubicObstacle-%d'% obstacleIndex)
        #BuildGeometry.addBoxGeom(tireModel, sideLength, sideLength, sideLength)
        #tireModel.setPos(pos)
        #tireModel.setColor(0.5,0.5,0.5)

        tireModel = loader.loadModel("phase_4/models/minigames/ice_game_crate")
        tireModel.setPos(pos)
        tireModel.reparentTo(render)

        geom.setPosition(tireModel.getPos())

        # the real assets are set at Z zero
        tireModel.setZ(0)
        return tireModel
Beispiel #21
0
class MovingPlane:
    ''' moving plane '''
    id = 0

    MODEL = "../egg/box.egg"

    def __init__(self, space, pos, dim, surface=SurfaceType.FLOOR):
        '''
		kirjoita numerot float muodossa 1.0
		@param space: fysiikka-avaruus?
		'''
        MovingPlane.id += 1
        self.id = id
        self.dim = dim  # dimension
        self.pos = pos  # position
        self.h = (dim[0] / 2, dim[1] / 2, dim[2] / 2)  # center
        self.t = 0

        self.geom = OdeBoxGeom(space, dim[0], dim[1], dim[2])
        space.setSurfaceType(self.geom, surface)

        self.model = loader.loadModel(self.MODEL)
        self.model.setScale(dim[0], dim[1], dim[2])
        # http://www.panda3d.org/wiki/index.php/Creating_a_New_Node_Class
        self.model.flattenLight()
        self.model.reparentTo(render)

        self.rotate = False

        if surface == SurfaceType.SAND:
            self.model.setColor(1, 0, 0)
        self.updateModelNode()

    def updateModelNode(self):
        pos = self.pos
        h = self.h
        if (self.rotate):
            self.t = self.t + 0.03
            rot = pos[2] + 2 * sin(self.t)
            self.geom.setPosition(pos[0], pos[1], rot)
            self.model.setPos(pos[0] - h[0], pos[1] - h[1], rot - h[2])
        else:
            self.geom.setPosition(pos[0], pos[1], pos[2])
            self.model.setPos(pos[0] - h[0], pos[1] - h[1], pos[2] - h[2])

    def getId(self):
        return id

    def getGeom(self):
        return self.geom

    def removeNode(self):
        self.model.removeNode()
        self.geom = None

    def setPosition(self, pos):
        self.pos = pos

    def setInterval(pos1, pos2):
        pass

    def setSpeed(self, speed):
        pass
Beispiel #22
0
class Vehicle(object):
    '''
    '''
    def __init__(self, ode_world, ode_space, name="standard"):
        '''
        '''
        self._notify = DirectNotify().newCategory("Vehicle")
        self._notify.info("New Vehicle-Object created: %s" % (self))
        self._ode_world = ode_world
        self._ode_space = ode_space
        self._model = None
        self._physics_model = None
        self._physics_mass = None
        self._collision_model = None
        self._speed = 0.0  # the actual speed of the vehicle (forward direction)
        self._direction = Vec3(0, 0, 0)  # the direction the car is heading
        self._boost_direction = Vec3(0, 0, 0)
        self._boost_strength = 10.0  # the boost propertys of the vehicle
        self._control_strength = 1.5  # impact on the steering behaviour
        self._grip_strength = 0.5  # impact on the steering behaviour
        self._track_grip = 0.8  # impact on the steering behaviour
        self._energy = 100.0
        self._armor = 100.0
        self._max_energy = 100.0
        self._max_armor = 100.0
        self._weight = 10.0
        self._description = "The best vehicle ever"
        self._name = "The flying egg"
        self._brake_strength = 10.0
        self._hit_ground = True
        self._model_loading = False
        self._blowout = []
        self._blowout_on = False
        self._streetnormal = Vec3(0, 0, 1)

        # set up the propertys of the vehicle that schould be loaded
        # the methods get called because the data is immutable and
        # wouldnt get updated when calling the objects directly
        # the last entry is the function to convert the string
        self._tags = [["name", self.setName, str],
                      ["description", self.setDescription, str],
                      ["control_strength", self.setControlStrength, float],
                      ["grip_strength", self.setGripStrength, float],
                      ["track_grip", self.setTrackGrip, float],
                      ["max_energy", self.setMaxEnergy, float],
                      ["max_armor", self.setMaxArmor, float],
                      ["weight", self.setWeight, float],
                      ["brake_strength", self.setBrakeStrength, float],
                      ["boost_strength", self.setBoostStrength, float]]

    # ---------------------------------------------------------

    def setVehicle(self, model):
        '''
        Choose what vehicle the player has chosen. This method initializes all data of this vehicle
        '''
        self.cleanResources()

        self._notify.debug("Set new vehicle: %s" % model)

        # Load the attributes of the vehicle
        attributes = model.find("**/Attributes")
        if attributes.isEmpty():
            self._notify.warning("No Attribute-Node found")
        for tag in self._tags:
            value = attributes.getNetTag(tag[0])
            if value:
                self._notify.debug("%s: %s" % (tag[0], value))
                # translate the value if its a string
                if type(tag[2](value)) == str:
                    tag[1](_(tag[2](value)))
                else:
                    tag[1](tag[2](value))
            else:
                self._notify.warning("No value defined for tag: %s" % (tag[0]))

        self._weight = 10  # for testing purposes

        blowout = model.find("**/Blowout")
        if not blowout.isEmpty():
            self._notify.debug("Loading Blowout-Particles")
            for node in blowout.getChildren():
                particle = ParticleEffect()
                self._blowout.append(particle)
                particle.loadConfig('./data/particles/blowout_test.ptf')

                try:  # try to read out the particle scale
                    scale = float(node.getTag("scale"))
                except Exception:  # default is 0.5
                    scale = .5

                renderer = particle.getParticlesList()[0].getRenderer()
                renderer.setInitialXScale(scale)
                renderer.setInitialYScale(scale)

                particle.setLightOff()
                particle.start(node)
                particle.softStop()
        else:
            self._notify.warning("No Blowout-Node found")

        if self._model is not None:
            heading = self._model.getH()
            self._model.removeNode()
        else:
            heading = 160

        # display the attributes
        text = model.getParent().find("AttributeNode")
        if not text.isEmpty():
            node = text.find("name")
            if not node.isEmpty():
                node = node.node()
                node.setText(self._name)
                node.update()
                text.show()

            node = text.find("description")
            if not node.isEmpty():
                node = node.node()
                node.setText(self._name)
                node.update()
                text.show()

        self._model = model
        self._model.setPos(0, 0, 2)
        self._model.setHpr(heading, 0, 0)

        #        #Test
        #        plightCenter = NodePath( 'plightCenter' )
        #        plightCenter.reparentTo( render )
        #        self.interval = plightCenter.hprInterval(12, Vec3(360, 0, 0))
        #        self.interval.loop()
        #
        #        plight = PointLight('plight')
        #        plight.setColor(VBase4(0.8, 0.8, 0.8, 1))
        #        plight.setAttenuation(Vec3(1,0,0))
        #        plnp = plightCenter.attachNewNode(plight)
        #        plnp.setPos(5, 5, 10)
        #        render.setLight(plnp)
        #
        #        alight = AmbientLight('alight')
        #        alight.setColor(VBase4(0,0,0, 1))
        #        alnp = render.attachNewNode(alight)
        #        render.setLight(alnp)

        #        GlowTextur
        #        self.glowSize=10
        #        self.filters = CommonFilters(base.win, self._model)
        #        self.filters.setBloom(blend=(0,self.glowSize,0,0) ,desat=1, intensity=1, size='medium')
        #        tex = loader.loadTexture( 'data/textures/glowmap.png' )
        #        ts = TextureStage('ts')
        #        ts.setMode(TextureStage.MGlow)
        #        self._model.setTexture(ts, tex)

        # Initialize the physics-simulation for the vehicle
        self._physics_model = OdeBody(self._ode_world)
        self._physics_model.setPosition(self._model.getPos(render))
        self._physics_model.setQuaternion(self._model.getQuat(render))

        # Initialize the mass of the vehicle
        physics_mass = OdeMass()
        physics_mass.setBoxTotal(self._weight, 1, 1, 1)
        self._physics_model.setMass(physics_mass)

        # Initialize the collision-model of the vehicle
        # for use with blender models
        # try:
        # col_model = loader.loadModel("data/models/vehicles/%s.collision" %(self._model.getName()))
        # self.collision_model = OdeTriMeshGeom(self._ode_space, OdeTriMeshData(col_model, True))
        # self._notify.info("Loading collision-file: %s" %("data/models/vehicles/%s.collision" %(self._model.getName())))
        # for fast collisions
        # except:
        # self._notify.warning("Could not load collision-file. Using standard collision-box")
        # self.collision_model = OdeTriMeshGeom(self._ode_space, OdeTriMeshData(model, False))
        # self._collision_model = OdeBoxGeom(self._ode_space, 3,3,2)
        self._collision_model = OdeBoxGeom(self._ode_space, 3, 3, 2)
        self._collision_model.setBody(self._physics_model)
        self._collision_model.setCollideBits(7)
        self._collision_model.setCategoryBits(2)

        # Add collision-rays for the floating effect
        self._ray = CollisionRay(Vec3(5, 0, 0),
                                 Vec3(0, 0, -1),
                                 self._ode_space,
                                 parent=self._collision_model,
                                 collide_bits=0,
                                 length=20.0)
        # This one is used for the floating effect but also for slipstream
        self._frontray = CollisionRay(Vec3(0, 0, 0),
                                      Vec3(1, 0, 0),
                                      self._ode_space,
                                      parent=self._collision_model,
                                      collide_bits=0,
                                      length=15.0)
        # Overwrite variables for testing purposes
        self._grip_strength = 0.9
        self._track_grip = 0.2
        self._boost_strength = 1400
        self._control_strength = 2.5

        # Loading finished
        self._model_loading = False

    def toggleGlow(self):
        self.glowSize += .1
        print((self.glowSize))
        if (self.glowSize == 4):
            self.glowSize = 0
        self.filters.setBloom(blend=(0, self.glowSize, 0, 0),
                              desat=-2,
                              intensity=3,
                              size='medium')

    def boggleGlow(self):
        self.glowSize -= .1
        print((self.glowSize))
        if (self.glowSize == 4):
            self.glowSize = 0
        self.filters.setBloom(blend=(0, self.glowSize, 0, 0),
                              desat=-2,
                              intensity=3.0,
                              size='medium')

    # ---------------------------------------------------------

    def setPos(self, x, y, z):
        '''
        '''
        self._model.setPos(x, y, z)

    def getPos(self):
        '''
        '''
        return self._model.getPos()

    position = property(fget=getPos, fset=setPos)

    # ---------------------------------------------------------

    def startBlowout(self):
        '''
        '''
        if not self._blowout_on:
            self._blowout_on = True
            for particle in self._blowout:
                particle.softStart()

    def stopBlowout(self):
        '''
        '''
        if self._blowout_on:
            self._blowout_on = False
            for particle in self._blowout:
                particle.softStop()

    # ---------------------------------------------------------

    def setModel(self, model):
        '''
        '''
        self._model = model

    def getModel(self):
        '''
        '''
        return self._model

    model = property(fget=getModel, fset=setModel)

    # ---------------------------------------------------------

    def setCollisionModel(self, model):
        '''
        '''
        self._collision_model = model

    def getCollisionModel(self):
        '''
        '''
        return self._collision_model

    collision_model = property(fget=getCollisionModel, fset=setCollisionModel)

    # ---------------------------------------------------------

    def setPhysicsModel(self, model):
        '''
        '''
        self._physics_model = model

    def getPhysicsModel(self):
        '''
        '''
        return self._physics_model

    physics_model = property(fget=getPhysicsModel, fset=setPhysicsModel)

    # ---------------------------------------------------------
    def setBoost(self, strength=1):
        '''
        Boosts the vehicle by indicated strength
        '''
        self.startBlowout()
        if self._hit_ground:
            direction = self._streetnormal.cross(
                self._collision_model.getQuaternion().xform(Vec3(1, 0, 0)))
            self._physics_model.addForce(
                direction *
                ((self._boost_strength *
                  self.physics_model.getMass().getMagnitude() * strength)))
            self._hit_ground = False
            self._collision_model.setCollideBits(7)
        else:
            direction = self._streetnormal.cross(
                self._collision_model.getQuaternion().xform(Vec3(1, 0, 0)))
            self._physics_model.addForce(
                direction * self._boost_strength * 0.5 *
                self.physics_model.getMass().getMagnitude() * strength)

    # ---------------------------------------------------------

    def setDirection(self, dir):
        '''
        Steers the vehicle into the target-direction
        '''
        rel_direction = self._collision_model.getQuaternion().xform(
            Vec3(dir[1], 0, dir[0]))
        # rel_position = self._collision_model.getQuaternion().xform(Vec3(5,0,0))
        # force = Vec3(rel_direction[0]*self.direction[0]*self._control_strength*self.speed,rel_direction[1]*self.direction[1]*self._control_strength*self.speed,rel_direction[2]*self.direction[2]*self._control_strength*self.speed)
        self._physics_model.addTorque(
            -rel_direction * self._control_strength *
            self.physics_model.getMass().getMagnitude())

    def getDirection(self):
        return self._direction

    direction = property(fget=getDirection, fset=setDirection)

    # ---------------------------------------------------------

    def getBoostDirection(self):
        return self._boost_direction

    boost_direction = property(fget=getBoostDirection)

    # ---------------------------------------------------------

    def getSpeed(self):
        return self._speed

    speed = property(fget=getSpeed)

    # ---------------------------------------------------------

    def setEnergy(self, energy):
        '''
        Boosts the vehicle by indicated strength
        '''
        self._energy = energy

    def getEnergy(self):
        return self._energy

    energy = property(fget=getEnergy, fset=setEnergy)

    # ---------------------------------------------------------
    def setModelLoading(self, bool):
        '''
        '''
        self._model_loading = bool

    def getModelLoading(self):
        return self._model_loading

    model_loading = property(fget=getModelLoading, fset=setModelLoading)

    # ---------------------------------------------------------

    def doStep(self):
        '''
        Needs to get executed every Ode-Step
        '''
        # refresh variables
        linear_velocity = self._physics_model.getLinearVel()
        direction = self._streetnormal.cross(
            self._collision_model.getQuaternion().xform(Vec3(1, 0, 0)))
        self._boost_direction[0], self._boost_direction[
            1], self._boost_direction[2] = self.physics_model.getLinearVel(
            )[0], self.physics_model.getLinearVel(
            )[1], self.physics_model.getLinearVel()[2]

        # This needs to be done, so we dont create a new object but only change the existing one. else the camera wont update
        self._direction[0], self._direction[1], self._direction[2] = direction[
            0], direction[1], direction[2]

        xy_direction = self.collision_model.getQuaternion().xform(Vec3(
            1, 1, 0))
        self._speed = Vec3(linear_velocity[0] * xy_direction[0],
                           linear_velocity[1] * xy_direction[1],
                           linear_velocity[2] * xy_direction[2]).length()

        # calculate air resistance
        self._physics_model.addForce(
            -linear_velocity * linear_velocity.length() /
            10)  # *((self._speed/2)*(self._speed/2)))#+linear_velocity)

        # calculate delayed velocity changes
        linear_velocity.normalize()
        self._direction.normalize()
        self._physics_model.addForce(
            self._direction *
            (self._speed * self._grip_strength *
             self.physics_model.getMass().getMagnitude()))  # +linear_velocity)
        self._physics_model.addForce(
            -linear_velocity *
            (self._speed * self._grip_strength *
             self.physics_model.getMass().getMagnitude()))  # +linear_velocity)

        # calculate the grip
        self._physics_model.addTorque(
            self._physics_model.getAngularVel() * -self._track_grip *
            self.physics_model.getMass().getMagnitude())

        # refresh the positions of the collisionrays
        self._ray.doStep()
        self._frontray.doStep()
        self._physics_model.setGravityMode(1)

    # ---------------------------------------------------------

    def getRay(self):
        return self._ray

    ray = property(fget=getRay)

    # ---------------------------------------------------------

    def getFrontRay(self):
        return self._frontray

    frontray = property(fget=getFrontRay)

    # -----------------------------------------------------------------

    def getHitGround(self):
        return self._hit_ground

    def setHitGround(self, value):
        if type(value) != bool:
            raise TypeError("Type should be %s not %s" % (bool, type(value)))
        self._hit_ground = value

    hit_ground = property(fget=getHitGround, fset=setHitGround)

    # -----------------------------------------------------------------

    def getControlStrength(self):
        return self._control_strength

    def setControlStrength(self, value):
        self._control_strength = value

    control_strength = property(fget=getControlStrength,
                                fset=setControlStrength)

    # -----------------------------------------------------------------

    def getBoostStrength(self):
        return self._boost_strength

    def setBoostStrength(self, value):
        self._boost_strength = value

    boost_strength = property(fget=getBoostStrength, fset=setBoostStrength)

    # -----------------------------------------------------------------

    def getGripStrength(self):
        return self._grip_strength

    def setGripStrength(self, value):
        self._grip_strength = value

    grip_strength = property(fget=getGripStrength, fset=setGripStrength)

    # -----------------------------------------------------------------

    def getTrackGrip(self):
        return self._track_grip

    def setTrackGrip(self, value):
        self._track_grip = value

    track_grip = property(fget=getTrackGrip, fset=setTrackGrip)

    # -----------------------------------------------------------------

    def getMaxEnergy(self):
        return self._max_energy

    def setMaxEnergy(self, value):
        self._max_energy = value

    max_energy = property(fget=getMaxEnergy, fset=setMaxEnergy)

    # -----------------------------------------------------------------

    def getMaxArmor(self):
        return self._max_armor

    def setMaxArmor(self, value):
        self._max_armor = value

    max_armor = property(fget=getMaxArmor, fset=setMaxArmor)

    # -----------------------------------------------------------------

    def getWeight(self):
        return self._weight

    def setWeight(self, value):
        self._weight = value

    weight = property(fget=getWeight, fset=setWeight)

    # -----------------------------------------------------------------

    def getDescription(self):
        return self._description

    def setDescription(self, value):
        self._description = value

    description = property(fget=getDescription, fset=setDescription)

    # -----------------------------------------------------------------

    def getBrakeStrength(self):
        return self._brake_strength

    def setBrakeStrength(self, value):
        self._brake_strength = value

    brake_strength = property(fget=getBrakeStrength, fset=setBrakeStrength)

    # -----------------------------------------------------------------

    def getName(self):
        return self._name

    def setName(self, value):
        self._name = value

    name = property(fget=getName, fset=setName)

    # -----------------------------------------------------------------

    def getStreetNormal(self):
        return self._streetnormal

    def setStreetNormal(self, value):
        self._streetnormal = value

    streetnormal = property(fget=getStreetNormal, fset=setStreetNormal)

    # -----------------------------------------------------------------

    def cleanResources(self):
        '''
        Removes old nodes, gets called when a new vehcile loads
        '''
        for node in self._blowout:
            node.removeNode()
            self._blowout = []

        if self._model is not None:
            for node in self._model.getChildren():
                node.removeNode()
            self._model.removeNode()
            self._model = None
            # self._physics_model.destroy()
            # self._collision_model.destroy()
            # temporary fix because destroy() doesnt work
            self._physics_model.disable()
            self._collision_model.disable()

        self._notify.info("Vehicle-Object cleaned: %s" % (self))

    def __del__(self):
        '''
        Destroy unused nodes
        '''
        for node in self._blowout:
            node.removeNode()

        if self._model is not None:
            for node in self._model.getChildren():
                node.removeNode()
            self._model.removeNode()
            self._model = None
            self._physics_model.destroy()
            self._collision_model.destroy()
            # temporary fix because destroy() doesnt work
            self._physics_model.disable()
            self._collision_model.disable()

        self._notify.info("Vehicle-Object deleted: %s" % (self))
Beispiel #23
0
class Box(GameObject):
	disableGracePeriod = 20
	
	def __init__(self, world, parent, color, pos, dir, size, density, unglueThreshold=None, shatterLimit=None, shatterThreshold=None):
		GameObject.__init__(self, world)

		if unglueThreshold == None: unglueThreshold = 20
		if shatterLimit == None: shatterLimit = 0
		if shatterThreshold == None: shatterThreshold = 30

		self.size = size
		self.density = density
		self.dir = dir
		self.parent = parent
		self.color = color = makeVec4Color(color)
		
		self.node = parent.attachNewNode("")
		self.node.setPos(*pos)
		self.node.setColorScale(color)
		self.node.setScale(*size)
		self.node.lookAt(self.node, *dir)

		self.model = loader.loadModel("models/box.egg")
		self.model.reparentTo(self.node)
		self.model.setScale(2.0)
		self.model.setPos(-1.0, -1.0, -1.0)

		self.applyTexture()

		self.mass = OdeMass()
		self.mass.setBox(density, Vec3(*size) * 2)
		self.body = OdeBody(world.world)
		self.body.setMass(self.mass)
		self.body.setPosition(self.node.getPos())
		self.body.setQuaternion(self.node.getQuat())
		self.body.setData(self)
		self.geom = OdeBoxGeom(world.space, Vec3(*size) * 2.0)
		self.geom.setBody(self.body)
		world.space.setSurfaceType(self.geom, world.surfaces["box"])

		# Adjust collision bitmasks.
		self.geom.setCategoryBits(GameObject.bitmaskBox)
		self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskTileGlued)

		# Tile, cement and shatter variables.
		self.tiles = []
		self.cements = []
		self.disableCount = 0
		self.unglueThreshold = unglueThreshold
		self.shatterLimit = shatterLimit
		self.shatterThreshold = shatterThreshold

	def applyTexture(self):
		self.texture = loader.loadTexture("media/brick_wall.tga")
		self.texture.setWrapU(Texture.WMRepeat)
		self.texture.setWrapV(Texture.WMRepeat)
		self.model.setTexture(self.texture, 1)
		self.model.setTexScale(TextureStage.getDefault(), max(self.size[0], self.size[1]), self.size[2])

	def addTile(self, tile):
		if tile not in self.tiles:
			self.tiles.append(tile)

	def removeTile(self, tile):
		if tile in self.tiles:
			self.tiles.remove(tile)

	def addCement(self, cement):
		if cement not in self.cements:
			self.cements.append(cement)

	def removeCement(self, cement):
		if cement in self.cements:
			self.cements.remove(cement)

	def destroy(self):
		for tile in self.tiles:
			tile.unglue()
		for cement in self.cements:
			cement.destroy()
		GameObject.destroy(self)

	def makeTiles(self, xNeg=False, xPos=False, yNeg=False, yPos=False, zNeg=False, zPos=False, thickness=0.1, unglueThreshold=None, shatterLimit=None, shatterThreshold=None):
		if xNeg: Tile(self, self.color, (-1,0,0), thickness, self.density, unglueThreshold, shatterLimit, shatterThreshold)
		if xPos: Tile(self, self.color, ( 1,0,0), thickness, self.density, unglueThreshold, shatterLimit, shatterThreshold)
		if yNeg: Tile(self, self.color, (0,-1,0), thickness, self.density, unglueThreshold, shatterLimit, shatterThreshold)
		if yPos: Tile(self, self.color, (0, 1,0), thickness, self.density, unglueThreshold, shatterLimit, shatterThreshold)
		if zNeg: Tile(self, self.color, (0,0,-1), thickness, self.density, unglueThreshold, shatterLimit, shatterThreshold)
		if zPos: Tile(self, self.color, (0,0, 1), thickness, self.density, unglueThreshold, shatterLimit, shatterThreshold)

	def onCollision(self, otherBody, entry):
		if otherBody.isEmpty():
			return
		self.disableCount = 0
		speed = otherBody.getData().body.getLinearVel()
		#if otherBody.getData().__class__ == Bullet: print speed.length(), self.shatterThreshold, self.shatterLimit #######
		if self.active and speed.length() >= self.shatterThreshold and self.shatterLimit > 0:
			adj = otherBody.getData().body.getMass().getMagnitude() / self.body.getMass().getMagnitude()
			speedMag = speed.length() * adj
			speedBase = ((speed * adj) + (self.body.getLinearVel() * 2) / 3)
			self.shatter(speedMag, speedBase)

	def shatter(self, speedMag, speedBase):
		#print 'box shatter' #########
		self.destroy()
		taskMgr.add(self.spawnTask, "box-spawn", extraArgs=[speedMag, speedBase])

		# Graphic (camera shake) and sound effects
		self.world.game.cameraHandler.shake((0,0,2), 0.1)
		sound = base.loader.loadSfx("media/shatter.wav")
		sound.setVolume(1.5)
		sound.play()

	def spawnTask(self, speedMag, speedBase):
		pos = self.node.getPos()
		size = Vec3(self.size) / 2
		w = 1
		for i in [-w, w]:
			for j in [-w, w]:
				for k in [-w, w]:
					box = Box(self.world, self.parent, self.color,
						(pos[0] + (i * size[0]), pos[1] + (j * size[1]), pos[2] + (k * size[2])),
						self.dir, size, self.density, self.unglueThreshold, self.shatterLimit - 1, self.shatterThreshold * 1)
					speed = (speedBase * (1.5 + random())) + (Vec3(i,j,k) * speedMag * (1 + random()))
					speed = speed / 2.0
					box.body.setLinearVel(speed)
					box.body.setAngularVel(speedMag * random(), speedMag * random(), speedMag * random())
					taskMgr.add(box.disableOnStopTask, "box-disableOnStop")

	def disableOnStopTask(self, task):
		if self.body.getLinearVel().length() > 0.1 or self.body.getAngularVel().length() > 0.1:
			self.disableCount = 0
			return task.cont
		elif self.disableCount < Box.disableGracePeriod:
			self.disableCount += 1
			return task.cont
		else:
			self.visibleAfterDestroy = True
			if DEBUG: self.node.setColorScale(1.0, 2.0, 1.0, 0.5)
			self.destroy()
			return task.done
Beispiel #24
0
class Character(GameObject):	
	def __init__(self, world):
		GameObject.__init__(self, world)

		# Set the speed parameters
		self.vel = Vec3(0, 0, 0)
		self.strafespeed = 20.0
		self.forwardspeed = 32.0
		self.backspeed = 24.0
		self.jumpspeed = 20
		self.wasJumping = False

		# Set character dimensions
		self.size = (4.0, 3.0, 10.0)
		self.eyeHeight = 9.0
		self.offset = Point3(0, 0, self.eyeHeight - (self.size[2]/2))

		# Create character node
		self.node = base.render.attachNewNode("character")
		self.node.setPos(0, 0, self.eyeHeight)
		self.node.lookAt(0, 1, self.eyeHeight)

		# Create physics representation
		self.mass = OdeMass()
		self.mass.setBox(50, *self.size)
		self.body = OdeBody(world.world)
		self.body.setMass(self.mass)
		self.updatePhysicsFromPos()
		self.body.setData(self)
		self.geom = OdeBoxGeom(world.space, Vec3(*self.size))
		self.geom.setBody(self.body)
		world.space.setSurfaceType(self.geom, world.surfaces["box"])

		# Adjust collision bitmasks.
		self.geom.setCategoryBits(GameObject.bitmaskCharacter)
		self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskBullet)

		# Setup event handling
		self.keys = [0, 0, 0, 0, 0]
		self.setupKeys()
		base.taskMgr.add(self.moveTask, "character-move")

		# Create footsteps sound
		self.footstepsSound = base.loader.loadSfx("media/footsteps.wav")
		self.footstepsSound.setLoop(1)
		self.footsteps = SoundWrapper(self.footstepsSound)

		# Create other sounds.
		self.jumpSound = base.loader.loadSfx("media/jump_start.wav")
		self.landSound = base.loader.loadSfx("media/jump_fall.wav")

	def updatePosFromPhysics(self):
		self.node.setPos(render, self.body.getPosition() + self.offset)
		self.body.setAngularVel(0, 0, 0)

	def updatePhysicsFromPos(self):
		self.body.setPosition(self.node.getPos() - self.offset)
		self.body.setQuaternion(self.node.getQuat())

	def getDir(self):
		return base.render.getRelativeVector(self.node, (0, 1, 0))

	def moveTo(self, pos):
		self.node.setPos(pos)
		self.updatePhysicsFromPos()

	def recoil(self, mag):
		vel = self.body.getLinearVel()
		diff = self.getDir() * mag
		
		# Limit recoil
		if sign(vel[0]) != sign(diff[0]) and abs(vel[0]) > 15: diff[0] = 0
		if sign(vel[1]) != sign(diff[1]) and abs(vel[1]) > 15: diff[1] = 0
		diff[2] = 0

		self.body.setLinearVel(vel - diff)

	def jump(self):
		vel = self.body.getLinearVel()
		self.body.setLinearVel(vel[0], vel[1], vel[2] + self.jumpspeed)
		self.jumpSound.play()

	def isJumping(self):
		return abs(self.body.getLinearVel()[2]) > 0.05

	def setKey(self, button, value):
		self.keys[button] = value

	def setupKeys(self):
		base.accept("w", self.setKey, [0, 1]) #forward
		base.accept("s", self.setKey, [1, 1]) #back
		base.accept("a", self.setKey, [2, 1]) #strafe left
		base.accept("d", self.setKey, [3, 1]) #strafe right
		base.accept("space", self.setKey, [4, 1]) #jump
		base.accept("w-up", self.setKey, [0, 0])
		base.accept("s-up", self.setKey, [1, 0])
		base.accept("a-up", self.setKey, [2, 0])
		base.accept("d-up", self.setKey, [3, 0])
		base.accept("space-up", self.setKey, [4, 0])

	def moveTask(self, task):
		# Initialize variables
		elapsed = globalClock.getDt()
		x = 0.0
		y = 0.0
		jumping = self.isJumping()

		# Calculate movement vector.
		if self.keys[0] != 0:
			y = self.forwardspeed
		if self.keys[1] != 0:
			y = -self.backspeed
		if self.keys[2] != 0:
			x = -self.strafespeed
		if self.keys[3] != 0:
			x = self.strafespeed
		self.vel = Vec3(x, y, 0)
		self.vel *= elapsed

		# Move the character along the ground.
		hpr = self.node.getHpr()
		self.node.setP(0)
		self.node.setR(0)
		self.node.setPos(self.node, self.vel)
		self.updatePhysicsFromPos()
		self.node.setHpr(hpr)

		# Play landing sound (if applicable).
		if self.wasJumping and not jumping:
			pass #Landing detection not working.
			#self.landSound.play()

		# Jump (if applicable).
		if self.keys[4] and not jumping:
			self.jump()
		self.wasJumping = jumping

		# Play footsteps if walking.
		if not jumping and (self.keys[0] != 0 or self.keys[1] != 0 or self.keys[2] != 0 or self.keys[3] != 0):
			self.footsteps.resume()
		else:
			self.footsteps.pause()

		return task.cont
Beispiel #25
0
class Base(StaticObject):
    
    def __init__(self, game):
        self.game = game
        
        self.collGeomInner = OdeBoxGeom( self.game.physicsSpace, 24,8,2)
        #self.collGeom.setBody(self.body)
        self.collGeomInner.setCategoryBits( BitMask32(1) )
        self.collGeomInner.setCollideBits( BitMask32(1) )
        
        self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2)
        #self.collGeom.setBody(self.body)
        self.collGeomOuter.setCategoryBits( BitMask32(1) )
        self.collGeomOuter.setCollideBits( BitMask32(1) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('Base.egg')
        model.reparentTo(self.visualNode)

    
    def checkCollision(self, ship):
         if OdeUtil.collide(ship.collGeom, self.collGeomInner) and ship.hasBall():
            #if ship.hasBall():
            ship.addPoints(ship.Ball.getValue())
            ship.dropBall( z = 300 )
            print ship.SHIP_TYPE + " " +  str(ship.getPoints()) + " Points! "
            #print " Base One! "
            
    def addToBaseList(self, baseList):
        baseList.append(self)
        
    def setPos(self, pos):
        self.visualNode.setPos( pos )
        self.collGeomInner.setPosition( pos )
        self.collGeomOuter.setPosition( pos )
Beispiel #26
0
    def setVehicle(self, model):
        '''
        Choose what vehicle the player has chosen. This method initializes all data of this vehicle
        '''
        self.cleanResources()

        self._notify.debug("Set new vehicle: %s" % model)

        # Load the attributes of the vehicle
        attributes = model.find("**/Attributes")
        if attributes.isEmpty():
            self._notify.warning("No Attribute-Node found")
        for tag in self._tags:
            value = attributes.getNetTag(tag[0])
            if value:
                self._notify.debug("%s: %s" % (tag[0], value))
                # translate the value if its a string
                if type(tag[2](value)) == str:
                    tag[1](_(tag[2](value)))
                else:
                    tag[1](tag[2](value))
            else:
                self._notify.warning("No value defined for tag: %s" % (tag[0]))

        self._weight = 10  # for testing purposes

        blowout = model.find("**/Blowout")
        if not blowout.isEmpty():
            self._notify.debug("Loading Blowout-Particles")
            for node in blowout.getChildren():
                particle = ParticleEffect()
                self._blowout.append(particle)
                particle.loadConfig('./data/particles/blowout_test.ptf')

                try:  # try to read out the particle scale
                    scale = float(node.getTag("scale"))
                except Exception:  # default is 0.5
                    scale = .5

                renderer = particle.getParticlesList()[0].getRenderer()
                renderer.setInitialXScale(scale)
                renderer.setInitialYScale(scale)

                particle.setLightOff()
                particle.start(node)
                particle.softStop()
        else:
            self._notify.warning("No Blowout-Node found")

        if self._model is not None:
            heading = self._model.getH()
            self._model.removeNode()
        else:
            heading = 160

        # display the attributes
        text = model.getParent().find("AttributeNode")
        if not text.isEmpty():
            node = text.find("name")
            if not node.isEmpty():
                node = node.node()
                node.setText(self._name)
                node.update()
                text.show()

            node = text.find("description")
            if not node.isEmpty():
                node = node.node()
                node.setText(self._name)
                node.update()
                text.show()

        self._model = model
        self._model.setPos(0, 0, 2)
        self._model.setHpr(heading, 0, 0)

        #        #Test
        #        plightCenter = NodePath( 'plightCenter' )
        #        plightCenter.reparentTo( render )
        #        self.interval = plightCenter.hprInterval(12, Vec3(360, 0, 0))
        #        self.interval.loop()
        #
        #        plight = PointLight('plight')
        #        plight.setColor(VBase4(0.8, 0.8, 0.8, 1))
        #        plight.setAttenuation(Vec3(1,0,0))
        #        plnp = plightCenter.attachNewNode(plight)
        #        plnp.setPos(5, 5, 10)
        #        render.setLight(plnp)
        #
        #        alight = AmbientLight('alight')
        #        alight.setColor(VBase4(0,0,0, 1))
        #        alnp = render.attachNewNode(alight)
        #        render.setLight(alnp)

        #        GlowTextur
        #        self.glowSize=10
        #        self.filters = CommonFilters(base.win, self._model)
        #        self.filters.setBloom(blend=(0,self.glowSize,0,0) ,desat=1, intensity=1, size='medium')
        #        tex = loader.loadTexture( 'data/textures/glowmap.png' )
        #        ts = TextureStage('ts')
        #        ts.setMode(TextureStage.MGlow)
        #        self._model.setTexture(ts, tex)

        # Initialize the physics-simulation for the vehicle
        self._physics_model = OdeBody(self._ode_world)
        self._physics_model.setPosition(self._model.getPos(render))
        self._physics_model.setQuaternion(self._model.getQuat(render))

        # Initialize the mass of the vehicle
        physics_mass = OdeMass()
        physics_mass.setBoxTotal(self._weight, 1, 1, 1)
        self._physics_model.setMass(physics_mass)

        # Initialize the collision-model of the vehicle
        # for use with blender models
        # try:
        # col_model = loader.loadModel("data/models/vehicles/%s.collision" %(self._model.getName()))
        # self.collision_model = OdeTriMeshGeom(self._ode_space, OdeTriMeshData(col_model, True))
        # self._notify.info("Loading collision-file: %s" %("data/models/vehicles/%s.collision" %(self._model.getName())))
        # for fast collisions
        # except:
        # self._notify.warning("Could not load collision-file. Using standard collision-box")
        # self.collision_model = OdeTriMeshGeom(self._ode_space, OdeTriMeshData(model, False))
        # self._collision_model = OdeBoxGeom(self._ode_space, 3,3,2)
        self._collision_model = OdeBoxGeom(self._ode_space, 3, 3, 2)
        self._collision_model.setBody(self._physics_model)
        self._collision_model.setCollideBits(7)
        self._collision_model.setCategoryBits(2)

        # Add collision-rays for the floating effect
        self._ray = CollisionRay(Vec3(5, 0, 0),
                                 Vec3(0, 0, -1),
                                 self._ode_space,
                                 parent=self._collision_model,
                                 collide_bits=0,
                                 length=20.0)
        # This one is used for the floating effect but also for slipstream
        self._frontray = CollisionRay(Vec3(0, 0, 0),
                                      Vec3(1, 0, 0),
                                      self._ode_space,
                                      parent=self._collision_model,
                                      collide_bits=0,
                                      length=15.0)
        # Overwrite variables for testing purposes
        self._grip_strength = 0.9
        self._track_grip = 0.2
        self._boost_strength = 1400
        self._control_strength = 2.5

        # Loading finished
        self._model_loading = False
class Character(GameObject):
    def __init__(self, world):
        GameObject.__init__(self, world)

        # Set the speed parameters
        self.vel = Vec3(0, 0, 0)
        self.strafespeed = 20.0
        self.forwardspeed = 32.0
        self.backspeed = 24.0
        self.jumpspeed = 20
        self.wasJumping = False

        # Set character dimensions
        self.size = (4.0, 3.0, 10.0)
        self.eyeHeight = 9.0
        self.offset = Point3(0, 0, self.eyeHeight - (self.size[2] / 2))

        # Create character node
        self.node = base.render.attachNewNode("character")
        self.node.setPos(0, 0, self.eyeHeight)
        self.node.lookAt(0, 1, self.eyeHeight)

        # Create physics representation
        self.mass = OdeMass()
        self.mass.setBox(50, *self.size)
        self.body = OdeBody(world.world)
        self.body.setMass(self.mass)
        self.updatePhysicsFromPos()
        self.body.setData(self)
        self.geom = OdeBoxGeom(world.space, Vec3(*self.size))
        self.geom.setBody(self.body)
        world.space.setSurfaceType(self.geom, world.surfaces["box"])

        # Adjust collision bitmasks.
        self.geom.setCategoryBits(GameObject.bitmaskCharacter)
        self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskBullet)

        # Setup event handling
        self.keys = [0, 0, 0, 0, 0]
        self.setupKeys()
        base.taskMgr.add(self.moveTask, "character-move")

        # Create footsteps sound
        self.footstepsSound = base.loader.loadSfx("media/footsteps.wav")
        self.footstepsSound.setLoop(1)
        self.footsteps = SoundWrapper(self.footstepsSound)

        # Create other sounds.
        self.jumpSound = base.loader.loadSfx("media/jump_start.wav")
        self.landSound = base.loader.loadSfx("media/jump_fall.wav")

    def updatePosFromPhysics(self):
        self.node.setPos(render, self.body.getPosition() + self.offset)
        self.body.setAngularVel(0, 0, 0)

    def updatePhysicsFromPos(self):
        self.body.setPosition(self.node.getPos() - self.offset)
        self.body.setQuaternion(self.node.getQuat())

    def getDir(self):
        return base.render.getRelativeVector(self.node, (0, 1, 0))

    def moveTo(self, pos):
        self.node.setPos(pos)
        self.updatePhysicsFromPos()

    def recoil(self, mag):
        vel = self.body.getLinearVel()
        diff = self.getDir() * mag

        # Limit recoil
        if sign(vel[0]) != sign(diff[0]) and abs(vel[0]) > 15:
            diff[0] = 0
        if sign(vel[1]) != sign(diff[1]) and abs(vel[1]) > 15:
            diff[1] = 0
        diff[2] = 0

        self.body.setLinearVel(vel - diff)

    def jump(self):
        vel = self.body.getLinearVel()
        self.body.setLinearVel(vel[0], vel[1], vel[2] + self.jumpspeed)
        self.jumpSound.play()

    def isJumping(self):
        return abs(self.body.getLinearVel()[2]) > 0.05

    def setKey(self, button, value):
        self.keys[button] = value

    def setupKeys(self):
        base.accept("w", self.setKey, [0, 1])  # forward
        base.accept("s", self.setKey, [1, 1])  # back
        base.accept("a", self.setKey, [2, 1])  # strafe left
        base.accept("d", self.setKey, [3, 1])  # strafe right
        base.accept("space", self.setKey, [4, 1])  # jump
        base.accept("w-up", self.setKey, [0, 0])
        base.accept("s-up", self.setKey, [1, 0])
        base.accept("a-up", self.setKey, [2, 0])
        base.accept("d-up", self.setKey, [3, 0])
        base.accept("space-up", self.setKey, [4, 0])

    def moveTask(self, task):
        # Initialize variables
        elapsed = globalClock.getDt()
        x = 0.0
        y = 0.0
        jumping = self.isJumping()

        # Calculate movement vector.
        if self.keys[0] != 0:
            y = self.forwardspeed
        if self.keys[1] != 0:
            y = -self.backspeed
        if self.keys[2] != 0:
            x = -self.strafespeed
        if self.keys[3] != 0:
            x = self.strafespeed
        self.vel = Vec3(x, y, 0)
        self.vel *= elapsed

        # Move the character along the ground.
        hpr = self.node.getHpr()
        self.node.setP(0)
        self.node.setR(0)
        self.node.setPos(self.node, self.vel)
        self.updatePhysicsFromPos()
        self.node.setHpr(hpr)

        # Play landing sound (if applicable).
        if self.wasJumping and not jumping:
            pass  # Landing detection not working.
            # self.landSound.play()

            # Jump (if applicable).
        if self.keys[4] and not jumping:
            self.jump()
        self.wasJumping = jumping

        # Play footsteps if walking.
        if not jumping and (self.keys[0] != 0 or self.keys[1] != 0 or self.keys[2] != 0 or self.keys[3] != 0):
            self.footsteps.resume()
        else:
            self.footsteps.pause()

        return task.cont
Beispiel #28
0
 def enable_physics(self, physics):
     self.geom = OdeBoxGeom(physics.space, self.width, self.height, 0.2)
     self.geom.setPosition(self.model.getPos())
     self.geom.setQuaternion(self.model.getQuat())