Exemple #1
0
def SmokeRing(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename(MYDIRPART+'smokering.ptf'))        
    p1.start(model)
    p1.setPos(0, 0.000, 0)
Exemple #2
0
def Water(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename(MYDIRPART+'fountain.ptf'))        
    p1.start(model)
    p1.setPos(3.000, 0.000, 2.250)
Exemple #3
0
def Smoke(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename(MYDIRPART+'smoke.ptf'))        
    p1.start(model)
    p1.setPos(3.000, 0.000, 2.250)
class BlockDestroyedEffect(object):
    __base = None
    __pos = None
    def __init__(self, base, pos):
        self.__base = base
        self.__pos = pos
        self.particleEffect()

    def particleEffect(self):
        self.p = ParticleEffect()
        self.loadParticleConfig('particleEffect.ptf')
        self.__base.taskMgr.doMethodLater(0.5, self.stopParticles, "stop")
        self.__base.taskMgr.doMethodLater(2.0, self.cleanUpParticles, "cleanup")


    def cleanUpParticles(self, task):
         self.p.cleanup()

    def stopParticles(self, task):
         self.p.softStop()

    def loadParticleConfig(self, file):
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))
        self.p.setPos(self.__pos.x, self.__pos.y, 2)
        self.p.start(parent = self.__base.render, renderParent = self.__base.render)
class ParticleDemo(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)

        # Standard title and instruction text
        self.title = OnscreenText(
            text="Panda3D: Tutorial - Particles",
            parent=base.a2dBottomCenter,
            style=1, fg=(1, 1, 1, 1), pos=(0, 0.1), scale=.08)
        self.escapeEvent = OnscreenText(
            text=HELP_TEXT, parent=base.a2dTopLeft,
            style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.06),
            align=TextNode.ALeft, scale=.05)

        # More standard initialization
        self.accept('escape', sys.exit)
        self.accept('1', self.loadParticleConfig, ['steam.ptf'])
        self.accept('2', self.loadParticleConfig, ['dust.ptf'])
        self.accept('3', self.loadParticleConfig, ['fountain.ptf'])
        self.accept('4', self.loadParticleConfig, ['smoke.ptf'])
        self.accept('5', self.loadParticleConfig, ['smokering.ptf'])
        self.accept('6', self.loadParticleConfig, ['fireish.ptf'])

        self.accept('escape', sys.exit)
        base.disableMouse()
        base.camera.setPos(0, -20, 2)
        base.camLens.setFov(25)
        base.setBackgroundColor(0, 0, 0)

        # This command is required for Panda to render particles
        base.enableParticles()
        self.t = loader.loadModel("teapot")
        self.t.setPos(0, 10, 0)
        self.t.reparentTo(render)
        self.setupLights()
        self.p = ParticleEffect()
        self.loadParticleConfig('steam.ptf')

    def loadParticleConfig(self, filename):
        # Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(filename))
        # Sets particles to birth relative to the teapot, but to render at
        # toplevel
        self.p.start(self.t)
        self.p.setPos(3.000, 0.000, 2.250)

    # Setup lighting
    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 8, -2.5))
        directionalLight.setColor((0.9, 0.8, 0.9, 1))
        # Set lighting on teapot so steam doesn't get affected
        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))
Exemple #6
0
def Flame(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename('ee.ptf'))#'fireish.ptf'))        
    p1.start(model)
    p1.setPos(3.000, 0.000, 2.250)
    setupLights(self,model)
class World(DirectObject):
    def __init__(self):
        #Standard title and instruction text
        self.title = OnscreenText(
            text="Panda3D: Tutorial - Particles",
            style=1, fg=(1,1,1,1), pos=(0.8,-0.95), scale = .07)
        self.escapeEvent = OnscreenText(
            text=HELPTEXT,
            style=1, fg=(1,1,1,1), pos=(-1.3, 0.95),
            align=TextNode.ALeft, scale = .05)

        #More standard initialization
        self.accept('escape', sys.exit)
        self.accept('1', self.loadParticleConfig , ['steam.ptf'])
        self.accept('2', self.loadParticleConfig , ['dust.ptf'])
        self.accept('3', self.loadParticleConfig , ['fountain.ptf'])
        self.accept('4', self.loadParticleConfig , ['smoke.ptf'])
        self.accept('5', self.loadParticleConfig , ['smokering.ptf'])
        self.accept('6', self.loadParticleConfig , ['fireish.ptf'])
        
        self.accept('escape', sys.exit)
        base.disableMouse()
        camera.setPos(0,-20,2)
        base.setBackgroundColor( 0, 0, 0 )

        #This command is required for Panda to render particles
        base.enableParticles()
        self.t = loader.loadModel("models/teapot")
        self.t.setPos(0,10,0)
        self.t.reparentTo(render)
        self.setupLights()
        self.p = ParticleEffect()
        self.loadParticleConfig('steam.ptf')

    def loadParticleConfig(self, file):
        #Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))        
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.p.start(self.t)
        self.p.setPos(3.000, 0.000, 2.250)
    
    #Setup lighting
    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3( 0, 8, -2.5 ) )
        directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) )
        #Set lighting on teapot so steam doesn't get affected
        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))
class Effects:
    def __init__(self):

        #Initialisierung
        base.enableParticles()
        self.__space = ParticleEffect()
        self.__particlepath = ""

        #Dropvariablen
        self.__nDrop = None
        self.__dropitem = ""
        self.__chance = 0

        #Explosionen Attribute
        self.__nExplosion = None

        #Dropattribute
        self.__heal = 0

    def createSpaceStars(self, particlefile):
        self.__particlepath = particlefile
        self.__space.loadConfig(Filename(self.__particlepath))

        self.__space.setPos(0, 10000, -20)
        self.__space.setScale(250, 200, 250)

    def removeSpaceStars(self):
        self.__space.cleanup()

    def getDrop(self, drop, chnc, pos):
        self.__dropitem = drop
        self.__chance = chnc
        generate = choice(range(0, 100) + range(0, 100))
        if generate < self.__chance:
            self.__nDrop = loader.loadModel(self.__dropitem)
            self.__nDrop.setScale(1, 1, 1)
            self.__nDrop.reparentTo(render)
            self.__nDrop.setPos(pos)
            return self.__nDrop
        else:
            self.__nDrop = None

    def getExplosion(self, pos):
        self.__nExplosion = loader.loadModel("models/box")
        self.__nExplosion.reparentTo(render)
        self.__nExplosion.setScale(1, 1, 1)
        self.__nExplosion.setPos(pos)
        return self.__nExplosion
Exemple #9
0
 def particle(path, parent, render_parent, pos, timeout):
     par = ParticleEffect()
     par.loadConfig(path)
     par.start(parent=parent, renderParent=render_parent)
     par.set_pos(pos)
     args = timeout, lambda par: par.cleanup(), [par]
     eng.do_later(*args)
Exemple #10
0
class smoke_emitter():
    def __init__(self, parent, _x, _y, _z):
        self.x = _x
        self.y = _y
        self.z = _z
        self.parent = parent
        self.p = ParticleEffect()
        self.load_config('steam.ptf')
        self.p.setScale(200)

    def load_config(self, file_name):
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(file_name)
        self.p.start(render)
        self.p.setPos(self.x, self.y, self.z)
        self.p.reparentTo(self.parent)
Exemple #11
0
class SmokeTrail(object):
    def __init__(self, warsim):
        self.warsim = warsim
        self.initialize()

    def initialize(self):
        smokeEffect = self.warsim.path + "smoke.ptf"
        self.particle = ParticleEffect()
        self.particle.loadConfig(Filename(smokeEffect))
        self.litterMin = 1.0
        # rough estimate based on masses that are around 50000->120000.  gets the max litter down to 25 -> 60
        self.litterMax = self.warsim.myShip.mass / 2500.0
        self.litterSize = self.litterMin
        self.particleStarted = False

    def update(self, facing):

        if self.warsim.myShip.strength >= 99.0:
            return

        if not self.particleStarted:
            self.particle.start(parent=self.warsim.sim,
                                renderParent=render)  #, renderParent=self.sim)
            self.particleStarted = True

        p0 = self.particle.particlesDict['particles']

        # 90 degree offset from what you waht expect
        radians = math.radians(self.warsim.myShip.facing - 90)
        xvec = math.cos(radians)
        yvec = math.sin(radians)

        p0.emitter.setOffsetForce(Vec3(0.0, xvec, yvec))

        futureLitterSize = self.warsim.myShip.strength * self.litterMax / 100.0
        futureLitterSize = abs(self.litterMax - futureLitterSize)
        if self.litterSize != futureLitterSize:
            # want the inverse
            self.litterSize = futureLitterSize
            p0.setLitterSize(int(self.litterSize))

    def cleanup(self):
        self.particle.cleanup()
Exemple #12
0
class World(DirectObject):
    def __init__(self):
        

        #More standard initialization
        self.accept('escape', sys.exit)
        self.accept('1', self.loadParticleConfig , ['spark.ptf'])
        
        
        self.accept('escape', sys.exit)
        base.disableMouse()
        camera.setPos(0,-20,2)
        base.setBackgroundColor( 0, 0, 0 )

        #This command is required for Panda to render particles
        base.enableParticles()
        self.t = loader.loadModel("models/stepipe")
        self.t.setPos(0,0,0)
        self.t.reparentTo(render)
        self.setupLights()
        self.p = ParticleEffect()
        self.loadParticleConfig('spark.ptf')
        self.p.setScale(3)

    def loadParticleConfig(self, file):
        #Start of the code from spark.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))        
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.p.start(self.t)
        self.p.setPos(-2.00, 0.000, 3.150)
    
    #Setup lighting
    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3( 0, 8, -2.5 ) )
        directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) )
        #Set lighting on teapot so spark doesn't get affected
        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))
Exemple #13
0
class BurnSmoke:
    """Smoke from a burning object effect.

    Args:
        parent (object): Object to parent the effect to.
    """

    def __init__(self, parent):
        self._parent = parent
        self._smoke = ParticleEffect()
        self._smoke.loadConfig("effects/after_explode_smoke1.ptf")

    def _clear_smoke(self, task):
        """Clear the smoke effect."""
        self._smoke.softStop()
        self._smoke.cleanup()
        return task.done

    def play(self):
        """Start playing the particle effect."""
        self._smoke.start(self._parent.model, render)  # noqa: F821
        taskMgr.doMethodLater(  # noqa: F821
            11, self._clear_smoke, self._parent.id + "_stop_smoke"
        )
Exemple #14
0
class Projectile(DirectObject.DirectObject):
    '''
    __init__
    Will initialize the rocket.
    @param start: starting position.
    @param dir: flight direction, the higher the norm of this vector, the faster the missile
    @param rot: a Hpr value the specify where the tip of the missile is supposed to point at
    @param orign: name if the node which starts this projectile, if this is set wrong, you will
                  get hit by your own missile!
    '''
    def __init__(self, start, dir, rot, orign):
        self.node = NodePath('projectile')
        self.node.setTag("orign",orign)
        self.start = start
        self.dir = dir
        self.rotation = rot
        self.collisionHandler = 0
        self.particleEffect = 0
        self.loadModel()
        self.addSound()
        self.createCollisions()
        self.setUpEvents()
        
        # setup the projectile interval, fly for 3 sec        
        self.trajectory = ProjectileInterval(self.node,
                                     startPos = self.start,
                                     duration = 3, startVel = self.dir,
                                     gravityMult=0.000000001)
        # this event will be called if the ProjectileInterval has finished.
        # we also pass the unique ID of this object, else other missiles will catch
        # this event as well!
        self.trajectory.setDoneEvent("projectileDie"+str(id(self)))
        self.trajectory.start()
        
    '''
    createCollisions
    This will add all the collision stuff
    ''' 
    def createCollisions(self):
        self.cNode = CollisionNode('projectile')
        self.cNode.addSolid(CollisionSphere(0,0,0,0.2))
        # there is a list of all bitmasks in game.py
        self.cNode.setIntoCollideMask(BitMask32(0x10))
        self.cNode.setFromCollideMask(BitMask32(0x1E))
        
        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        
        self.collisionHandler = CollisionHandlerEvent()
        self.collisionHandler.addInPattern('projectileHit'+str(id(self)))
       
        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)        

    '''
    deleteTask
    task which calls the destructor after a given time (after the explosion animation)
    '''
    def deleteTask(self, task):
        self.__del__()
        return task.done

    '''
    explode
    this will cause the missile to explode with a nice particle effect.
    '''
    def explode(self):
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        self.nodeModel.hide()
        self.particleEffect.cleanup()
        self.particleEffect = ParticleEffect()
        self.particleEffect.setTransparency(TransparencyAttrib.MDual)
        self.particleEffect.loadConfig('media/explosion.ptf')
        self.particleEffect.start(self.node)
        self.particleEffect.setLightOff()
        
        self.Sound.stop()
        self.audio3d.detachSound(self.Sound)
        self.Sound = self.audio3d.loadSfx('explosion.mp3')
        self.audio3d.attachSoundToObject( self.Sound, self.node )
        self.Sound.play()
        
        # call deleteTask after 1 sec
        self.deleteTask = taskMgr.doMethodLater(1, self.deleteTask, 'delete task')

    '''
    evtHit
    This event will be called if the missile hits an other element.
    If the other element is not the "orign" of this missile, the event will 
    cause the missile to explode.
    @bug: this sometimes crashes and I don't know why...
    '''    
    def evtHit(self, entry):
        
        #if entry.getFromNodePath() == self.cNodePath and entry.getIntoNodePath().getName() != self.node.getTag("orign"):
        if entry:
            if entry.getIntoNodePath().getParent().getName() != self.node.getTag("orign"):
                if entry.getIntoNodePath().getParent().getTag('targetID') != "":
                    messenger.send( entry.getIntoNodePath().getParent().getTag('targetID')+'-evtGotHit')
                self.trajectory.pause()
                self.explode()
        else:
            print "warning entry not defined"
    
    '''
    loadModel
    This will load all the visible stuff
    '''   
    def loadModel(self):
        self.node.reparentTo(render)
        self.node.setPos(self.start)
        self.node.setHpr(self.rotation)
        self.nodeModel = loader.loadModel('rocket')
        self.nodeModel.reparentTo(self.node)
        
        self.particleEffect = ParticleEffect()
        self.particleEffect.setTransparency(TransparencyAttrib.MDual)
        self.particleEffect.loadConfig('media/rocket_contrail.ptf')
        self.particleEffect.start(self.node, render)
    
    '''
    addSound
    adds sound effect
    '''
    def addSound(self):
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('missile.mp3')
        self.audio3d.attachSoundToObject( self.Sound, self.node )
        self.Sound.play()
        
    '''
    setUpEvents
    This will set up the events the missile will accept
    '''
    def setUpEvents(self):
        self.accept('projectileHit'+str(id(self)), self.evtHit)
        self.accept('projectileDie'+str(id(self)), self.explode)
    
    '''
    __del__
    destructor will remove particle effect and the whole node
    '''
    def __del__(self):
        self.particleEffect.cleanup()
        self.Sound.stop()
        self.audio3d.detachSound(self.Sound)
        self.node.removeNode()
Exemple #15
0
class Arena:
    def __init__(self, arenaNr):
        arenaPath = "levels/arena{}/".format(arenaNr)
        self.arena = loader.loadModel(arenaPath + "arena")
        self.arena.setScale(2)
        self.arena.reparentTo(render)
        self.arena.hide()

        ambientLight = AmbientLight("ambient_light")
        ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.alnp = render.attachNewNode(ambientLight)

        sunLens = PerspectiveLens()
        sunLens.setFilmSize(50)
        sun = DirectionalLight("sun")
        sun.setColor((1, 1, 1, 1))
        sun.setShadowCaster(True, 2048, 2048)
        sun.setScene(render)
        #sun.showFrustum()

        self.ambientSound = None
        self.levelParticles = None
        if arenaNr == 1:
            sunLens.setNearFar(25, 45)
            sun.setLens(sunLens)
            self.sunNp = render.attachNewNode(sun)
            self.sunNp.setPos(-10, -10, 30)
            self.sunNp.lookAt(0, 0, 0)

            self.ambientSound = loader.loadSfx(
                "assets/audio/ambientLevel1.ogg")
            self.ambientSound.setLoop(True)

            self.fog = Fog("Outside Fog")
            self.fog.setColor(0.3, 0.3, 0.5)
            self.fog.setExpDensity(0.025)

            self.levelParticles = ParticleEffect()
            self.levelParticles.loadConfig("assets/fx/Leafs.ptf")
            self.levelParticles.start(parent=render2d, renderParent=render2d)
        elif arenaNr == 2:
            sunLens.setFov(120, 40)
            sunLens.setNearFar(2, 10)
            sun.setLens(sunLens)
            self.sunNp = render.attachNewNode(sun)
            self.sunNp.setPos(0, 0, 5)
            self.sunNp.lookAt(0, 0, 0)

            self.fog = Fog("Temple Fog")
            self.fog.setColor(0, 0, 0)
            self.fog.setExpDensity(0.065)

    def start(self):
        self.arena.show()
        render.setLight(self.alnp)
        render.setLight(self.sunNp)
        if self.ambientSound != None:
            self.ambientSound.play()
        render.setFog(self.fog)

    def stop(self):
        self.arena.hide()
        render.clearLight()
        if self.ambientSound != None:
            self.ambientSound.stop()
        render.clearFog()
        if self.levelParticles != None:
            self.levelParticles.cleanup()

    def getStartPos(self, charNr):
        if charNr == 1:
            return self.arena.find("**/StartPosA").getPos() * 2
        elif charNr == 2:
            return self.arena.find("**/StartPosB").getPos() * 2
        else:
            return (0, 0, 0)
Exemple #16
0
class Rock:

    p_pos_x = 0
    p_pos_z = 0
    max_particles = 5
    life = 0
    p_life = 0
    particle_count = 0
    p = 0

    def __init__(self, game, start_posX, start_posY):

        self.game = game

        self.model = Actor(os.path.join("data", "rock"))
        self.model.setPos(start_posX, 0, start_posY)
        self.model.setScale(1)

        self.life = 5
        self.p_life = 30

        self.rock_collision = EntityCollision(self)

        self.model.reparentTo(render)

        self.game.taskMgr.add(self.update, "update_rock")

    def spawn_particles(self, pos_x, pos_z):

        if self.particle_count < self.max_particles:
            self.particle_count += 1
            self.p_pos_x = pos_x
            self.p_pos_z = pos_z

            self.p_life = 30

            self.p = ParticleEffect()
            self.p.loadConfig(Filename('data/particles/dust.ptf'))

            self.p.start(self.model)

            self.p.setPos(self.p_pos_x, 0.000, self.p_pos_z)

    def update(self, task):

        dt = globalClock.getDt()

        if self.model:

            if self.p:
                if self.p_life:

                    self.p_life -= 1

                    if self.p_life <= 0:
                        self.p.cleanup()

            self.model.setR(self.model, 10 * dt)
            self.model.setZ(self.model.getZ() - dt)

            if self.life <= 0:
                self.model.remove_node()

        return task.cont
Exemple #17
0
class Labryn(DirectObject):

    def setCamera(self, spin):
        self.spin = spin
    
    def spinCamera(self, task):
        if self.spin == 1: # spin counter-clockwise
            self.cameraSpinCount += 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R) 
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 2: # spin clockwise
            self.cameraSpinCount  -= 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 3: # ZOOM IN not spin
            self.cameraZoomCount += 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*new_R)
        elif self.spin == 4: # ZOOM OUT
            self.cameraZoomCount -= 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
                          
        return Task.cont

    def checkMouse(self, task):
        if base.mouseWatcherNode.hasMouse():
            self.mouseX=base.mouseWatcherNode.getMouseX()
            self.mouseY=base.mouseWatcherNode.getMouseY()
        return Task.cont

    def dropRock(self):
        if self.pokeMoveChoice == 1: # selected Geodude
            result = MAZE.canDropRock(self.rockX, self.rockY)
            if result != False: # can place rock here
                MAZE.dropRock(result[0],result[1])
                self.rock.setPos(self.rockX, self.rockY, 1)
                self.rockOnMaze = True
                self.pokeMoveChoice = None
                self.myPokeName.hide()
                self.myPokeName = None
                self.updateTwoD()
                self.playerCandyCount -= 1

    def useFlame(self):
        self.onFire = True # on fire
        self.playerCandyCount -= 1
        self.pokeStatus = 1
        self.flame = ParticleEffect()
        self.flame.loadConfig("fireish.ptf")
        self.flame.setPos(self.pikachu.getPos())
        self.flame.start(parent=render, renderParent=render)
        self.updateTwoD()

    def useStringShot(self):
        self.pokeStatus = 2
        self.updateTwoD()

    def placeRock(self, task):
        if self.pokeMoveChoice == 1: # selected Geodude
            dX,dY = ((self.mouseX-self.rockRefX),
                     (self.mouseY-self.rockRefY))
            self.rockX, self.rockY = MAZE.translateRockPosition(self.rockRefX,
                                                      self.rockRefY,
                                                      dX, dY)
            self.rock.show()
            self.rock.setPos(self.rockX, self.rockY, 1)
        self.updateTwoD()
        return Task.cont
    
    def placeRareCandy(self, task):
        if int(task.time) % 4 == 9 and self.candyOnBoard:
            self.candy.hide()
            self.candyOnBoard = False
        if int(task.time) % 10 ==  0 and (self.candyOnBoard == False):
            # every 10 seconds
            self.candy.setPos(MAZE.generateCandyPos())
            self.candy.show()
            self.candyOnBoard = True
        return Task.cont

    def updateTwoD(self):
        # update player candy count
        self.playerCandyStatus.destroy()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        # update pikachu candy count
        # TODO
        # update my pokes color     
        if self.playerCandyCount == 0 :
            groupHide(self.myPokesBright)
            groupShow(self.myPokesDark)
            # update name
            if self.myPokeName != None:
                self.myPokeName.destroy()

    def clearRock(self):
        self.rock.hide()
        self.rockOnMaze = False
        MAZE.clearRock() # clear it in 2D

    def clearFlame(self):
        self.onFire = False
        self.flame.cleanup()
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

    def clearString(self):
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

        
    def timer(self, task): # deals with moves' lasting effects
        ##############################################################
        if self.rockOnMaze: # rock on maze
            self.rockCounter += 1
        elif self.rockCounter != 1: # rock not on maze, counter not cleared
            self.rockCounter = 0

        if self.onFire:
            self.fireCounter += 1
        elif self.fireCounter != 1:
            self.fireCounter = 0

        if self.pokeStatus == 2: # string shot
            self.stringCounter += 1
        elif self.stringCounter != 1:
            self.stringCounter = 0

        ##################################################################
        if self.rockCounter == 500:
            self.clearRock()

        if self.fireCounter == 80:
            self.clearFlame()

        if self.stringCounter == 120:
            self.clearString()
            
        return Task.cont
    
    def usePokeMove(self, number):
        if self.playerCandyCount > 0: # have more than one candy
            if number == 1 and self.rockOnMaze == False:
                if self.pokeMoveChoice != 1: # NONE or other
                    # set to center position
                    centerx =  base.win.getProperties().getXSize()/2
                    centery =  base.win.getProperties().getYSize()/2
                    base.win.movePointer(0,centerx,centery)
                    self.pokeMoveChoice = 1 # placeRock called here
                    self.rockRefX, self.rockRefY = 0,0
                    self.rock.show()
                    self.rock.setPos(0,0,1)
                else: # already 1
                    self.pokeMoveChoice = None
                    self.clearRock() # clear rock
            elif number == 2:
                if self.pokeMoveChoice != 2:
                    self.pokeMoveChoice = 2
                    self.useFlame()
                else:
                    self.pokeMoveChoice = None
            elif number == 3:
                if self.pokeMoveChoice != 3:
                    self.pokeMoveChoice = 3
                    self.useStringShot()
                else:
                    self.pokeMoveChoice = None
            if self.pokeMoveChoice == None: # no choice
                if self.myPokeName != None: # there is a name on board
                    self.myPokeName.destroy() # kill it
                else: # no name
                    pass
            else: # there is a choice
                if self.myPokeName != None:
                    self.myPokeName.destroy()
                self.myPokeName = Two_D.writePokeName(self.pokeMoveChoice)
  
    def loadRareCandy(self):
        self.candy = Model_Load.loadRareCandy()
        self.candy.reparentTo(render)
        self.candy.setScale(0.1)
        self.candy.hide()
        
    def eatRareCandy(self, task):
        if self.candyOnBoard: # candy on board
            if checkEat(self.ballRoot.getX(), self.ballRoot.getY(),
                        self.candy.getX(), self.candy.getY()): # ball eats
                self.candy.hide() # eaten
                self.candyOnBoard = False
                self.playerCandyCount += 1
                # self.playerCandyStatus.destroy()
                # self.playerCandyStatus = candyStatus(0,
                                       # self.playerCandyCount) # update
                print "BALL EATS CANDY"
                groupShow(self.myPokesBright)

            elif checkEat(self.pikachu.getX(), self.pikachu.getY(),
                          self.candy.getX(), self.candy.getY()):
                self.candy.hide()
                self.candyOnBoard = False
                self.pokemonCandyCount += 1
        return Task.cont

    def setFocus(self, changing):
        self.changingFocus = changing
        if changing == True: # Just Pressed
            self.referenceX, self.referenceY = self.mouseX, self.mouseY
        else: # cursor moves up
            self.referenceX, self.referenceY = None, None

    def resetView(self):
        self.CAM_R, self.CAM_RAD = 12, 0
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        # _FOCUS = [0,0,0] does not work WHY???
        _FOCUS[0], _FOCUS[1], _FOCUS[2] = 0,0,0
        self.changingFocus = False
        self.referenceX, self.referenceY = None, None
        camera.setPos(_FOCUS[0], _FOCUS[1]-self.CAM_R, 25)
        camera.setHpr(0, -65, 0)
        
    def changeFocus(self, task):
        if (self.changingFocus == True and self.mouseX != None and
            self.mouseY != None ):
            dX, dY = ((self.mouseX - self.referenceX)*0.1,
                      (self.mouseY - self.referenceY)*0.1)
            _FOCUS[0] += dX
            _FOCUS[1] += dY
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
        return Task.cont

    def initialize(self):
        #bgmusic = load_bgmusic("palette.mp3")
        #bgmusic.play()

        self.background = Two_D.loadBackground()
        base.cam2dp.node().getDisplayRegion(0).setSort(-20)
        self.candyOnBoard = False
        self.playerCandyCount, self.pokemonCandyCount = 2, 0
        ######################Rare Candy###############################
        pokes=['caterpie', 'charmander', 'geodude']
        self.myPokesDark = Two_D.loadMyPokemon_Dark(pokes) # my pokemons
        self.myPokesBright = Two_D.loadMyPokemon_Bright()
        groupHide(self.myPokesBright)
        self.loadRareCandy() # load rare candy
        ######################Camera Initialization####################
        self.CAM_R, self.CAM_RAD = 12, 0
        camera.setPos(_FOCUS[0],_FOCUS[1]-12,_FOCUS[2]+25)
        camera.setHpr(0, -65, 0)
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        self.changingFocus = False
        self.spin = 0
        #######################ICONS###################################
        self.myIcon = Two_D.loadMyIcon()
        self.pokeIcon = Two_D.loadPokeIcon()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        #######################FLAMES##################################
        base.enableParticles()
        self.fireCounter = 0
        self.onFire = False
        #######################STRINGSHOT#############################
        self.stringCounter = 0
        #######################GLOBALS#################################
        self.i = 0
        self.myDirection = ['zx', 'zy']
        self.rockCounter  = 0
        self.rockX, self.rockY = None, None
        self.rockOnMaze = False
        self.pokeMoveChoice = None
        self.myPokeName = None
        self.arrowKeyPressed = False
        self.pokemonDirection = 'd'
        self.mouseX, self.mouseY = None, None
        # direction the ball is going
        self.jerkDirection = None
        base.disableMouse()
        self.jerk = (0,0,0)
        self.MAZE = Model_Load.loadLabyrinth()
        Control.keyControl(self)
        self.loadPokemonLevel1()
        self.light()
        self.loadBall()
        self.pokeStatus = 0 # 0 is normal, 1 is burned, 2 is slow-speed
        ########################################ROCK###################
        self.rock = Model_Load.loadRock()
        self.rock.reparentTo(render)
        self.rock.hide() # Do not show, but load beforehand for performance
        
    def loadPokemonLevel1(self):
        self.pikachu = load_model("pikachu.egg")
        self.pikachu.reparentTo(render)
        self.pikachu.setScale(0.3)
        endPos = self.MAZE.find("**/end").getPos()
        self.pikachu.setPos(endPos) 
        
    def light(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    def loadBall(self):
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = load_model("ball")
        self.ball.reparentTo(self.ballRoot)
        self.ball_tex = load_tex("pokeball.png")
        self.ball.setTexture(self.ball_tex,1)
        self.ball.setScale(0.8)
        # Find the collision sphere for the ball in egg.
        self.ballSphere = self.ball.find("**/ball")
        self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())
        #self.ballSphere.show()
        # Now we create a ray to cast down at the ball.
        self.ballGroundRay = CollisionRay()
        self.ballGroundRay.setOrigin(0,0,10)
        self.ballGroundRay.setDirection(0,0,-1)

        # Collision solids go in CollisionNode
        self.ballGroundCol =  CollisionNode('groundRay')
        self.ballGroundCol.addSolid(self.ballGroundRay)
        self.ballGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
        
        # light
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0,0,-1))
        directionalLight.setColor(Vec4(0.375,0.375,0.375,1))
        directionalLight.setSpecularColor(Vec4(1,1,1,1))
        self.ballRoot.setLight(render.attachNewNode(ambientLight))
        self.ballRoot.setLight(render.attachNewNode(directionalLight))
        # material to the ball
        m = Material()
        m.setSpecular(Vec4(1,1,1,1))
        m.setShininess(96)
        self.ball.setMaterial(m,1)

    def __init__(self):
        self.initialize()
        self.WALLS = self.MAZE.find("**/Wall.004")
        self.WALLS.node().setIntoCollideMask(BitMask32.bit(0))
        # collision with the ground. different bit mask
        #self.mazeGround = self.maze.find("**/ground_collide")
        #self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
        self.MAZEGROUND = self.MAZE.find("**/Cube.004")
        self.MAZEGROUND.node().setIntoCollideMask(BitMask32.bit(1))
        # add collision to the rock
        cs = CollisionSphere(0, 0, 0, 0.5)
        self.cnodePath = self.rock.attachNewNode(CollisionNode('cnode'))
        self.cnodePath.node().addSolid(cs)
        self.cnodePath.show()
        self.cnodePath.node().setIntoCollideMask(BitMask32.bit(0))
        # load the ball and attach it to the scene.
        # it is on a dummy node so that we can rotate the ball
        # without rotating the ray that will be attached to it

        # CollisionTraversers calculate collisions
        self.cTrav = CollisionTraverser()
        #self.cTrav.showCollisions(render)
        #self.cTrav.showCollisions(render)
        # A list collision handler queue
        self.cHandler = CollisionHandlerQueue()
        # add collision nodes to the traverse.
        # maximum nodes per traverser: 32
        self.cTrav.addCollider(self.ballSphere,self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp,self.cHandler)
        self.cTrav.addCollider(self.cnodePath, self.cHandler)
        # collision traversers have a built-in tool to visualize collisons
        #self.cTrav.showCollisions(render)
        self.start()

    def pokemonTurn(self, pokemon, direction):
        if direction  == 'l' and self.pokemonDirection != 'l':
            self.pokemonDirection = 'l'
            pokemon.setH(-90)
        if direction  == 'r' and self.pokemonDirection != 'r':
            self.pokemonDirection = 'r'
            pokemon.setH(90)
        if direction  == 'd' and self.pokemonDirection != 'd':
            self.pokemonDirection = 'd'
            pokemon.setH(0)
        if direction  == 'u' and self.pokemonDirection != 'u':
            self.pokemonDirection = 'u'
            pokemon.setH(180)
                        
    def pokemonMove(self, pokemon, direction):
        self.pokemonTurn(pokemon, direction)
        if self.pokeStatus == 0: speed = _SPEED
        elif self.pokeStatus == 1: speed = 0
        else: # self.pokeStatus == 2
            speed = _SPEED/2.0
        if direction == 'l':
            newX = pokemon.getX() - speed
            pokemon.setX(newX)
        elif direction == 'r':
            newX = pokemon.getX() + speed
            pokemon.setX(newX)
        elif direction == 'u':
            newY = pokemon.getY() + speed
            pokemon.setY(newY)
        elif direction == 'd':
            newY = pokemon.getY() - speed
            pokemon.setY(newY)
        elif direction == "s": # stop
            pass
        
    def whereToGo(self, task):
        # this returns the direction pokemon should go
        # tell MAZE pokemon and ball's board position
        print self.myDirection
        MAZE.setPokeCoord(self.pikachu.getX(), self.pikachu.getY(),
                          self.pokemonDirection)
        MAZE.setBallCoord(self.ballRoot.getX(), self.ballRoot.getY())
        # find out which direction to go
        direction = MAZE.getDecision()
        self.pokemonMove(self.pikachu,direction)
        return Task.cont

    def getInformation(self, task):
        # get information on the board
        # TODO
        self.i += 1 # sample every other call to avoid 
        if self.i % 2 == 0:
            dX = self.ballRoot.getX() - self.oldPos[0]
            dY = self.ballRoot.getY() - self.oldPos[1]
            if dX < 0 :
                # print "going left"
                self.myDirection[0] = 'l'
            elif abs(dX) < _EPSILON:
                # print "not moving horiz"
                self.myDirection[0] = 'zx'
            else:
                # print "going right"
                self.myDirection[0] = 'r'

            if dY < 0 :
                # print "going down"
                self.myDirection[1] = 'd'
            elif abs(dY) < _EPSILON:
                # print "not moving verti"
                self.myDirection[1] = 'zy'
            else:
                # print "going up"
                self.myDirection[1] = 'u'
            self.oldPos = self.ballRoot.getPos()
        return Task.cont
    
    def start(self):
        # maze model has a locator in it
        # self.ballRoot.show()
        self.startPos = self.MAZE.find("**/start").getPos()
        self.oldPos = self.MAZE.find("**/start").getPos()
        self.ballRoot.setPos(self.startPos) # set the ball in the pos
        self.ballV = Vec3(0,0,0) # initial velocity
        self.accelV = Vec3(0,0,0) # initial acceleration

        # for a traverser to work, need to call traverser.traverse()
        # base has a task that does this once a frame
        base.cTrav = self.cTrav

        # create the movement task, make sure its not already running
        taskMgr.remove("rollTask")
        taskMgr.add(self.placeRock, "placeRock")
        taskMgr.add(self.timer, "timer")
        taskMgr.add(self.getInformation, "getInformation")
        taskMgr.add(self.eatRareCandy, "eatRareCandy")
        taskMgr.add(self.placeRareCandy, "placeRareCandy")
        taskMgr.add(self.checkMouse, "checkMouse")
        taskMgr.add(self.spinCamera, "spinCamera")
        taskMgr.add(self.changeFocus, "changeFocus")
        taskMgr.add(self.whereToGo, "whereToGo")
        # taskMgr.add(lambda task: self.moveBall(task, self.jerkDirection),
                    # "moveBall")
        taskMgr.add(self.moveBall, "moveBall")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
        self.mainLoop.last = 0

    def moveBallWrapper(self, direction):
        if direction == False:
            self.arrowKeyPressed = False
        else:
            self.arrowKeyPressed = True
            self.jerkDirection = direction
    
    def moveBall(self, task):
        direction = self.jerkDirection
        if self.arrowKeyPressed == True:
            if direction == "u":
                self.jerk = Vec3(0,_JERK,0)
            elif direction == "d":
                self.jerk = Vec3(0,-_JERK,0)
            elif direction == "l":
                self.jerk = Vec3(-_JERK,0,0)
            elif direction == "r":
                self.jerk = Vec3(_JERK,0,0)
        return Task.cont        
    """      
    def moveBall(self, task, direction):
        if self.arrowKeyPressed == True:
            if direction == "u":
                self.jerk = Vec3(0,_JERK,0)
            elif direction == "d":
                self.jerk = Vec3(0,-_JERK,0)
            elif direction == "l":
                self.jerk = Vec3(-_JERK,0,0)
            elif direction == "r":
                self.jerk = Vec3(_JERK,0,0)
        return Task.cont
    """       
    # collision between ray and ground
    # info about the interaction is passed in colEntry
    
    def groundCollideHandler(self,colEntry):
        # set the ball to the appropriate Z for it to be on the ground
        newZ = colEntry.getSurfacePoint(render).getZ()
        self.ballRoot.setZ(newZ+.4)

        # up vector X normal vector
        norm = colEntry.getSurfaceNormal(render)
        accelSide = norm.cross(UP)
        self.accelV = norm.cross(accelSide)

    # collision between the ball and a wall
    def wallCollideHandler(self,colEntry):
        # some vectors needed to do the calculation
        norm = colEntry.getSurfaceNormal(render) * -1
        norm.normalize()
        curSpeed = self.ballV.length()
        inVec = self.ballV/curSpeed
        velAngle = norm.dot(inVec) # angle of incidance
        hitDir = colEntry.getSurfacePoint(render) - self.ballRoot.getPos()
        hitDir.normalize()
        hitAngle = norm.dot(hitDir)
    # deal with collision cases

        if velAngle > 0 and hitAngle >.995:
            # standard reflection equation
            reflectVec = (norm * norm.dot(inVec*-1)*2) + inVec

            # makes velocity half of hitting dead-on
            self.ballV = reflectVec * (curSpeed * (((1-velAngle)*.5)+.5))

            # a collision means the ball is already a little bit buried in
            # move it so exactly touching the wall
            disp = (colEntry.getSurfacePoint(render) -
                    colEntry.getInteriorPoint(render))
            newPos = self.ballRoot.getPos() + disp
            self.ballRoot.setPos(newPos)
            
    def rollTask(self,task):
        # standard technique for finding the amount of time
        # since the last frame
        dt = task.time - task.last
        task.last = task.time

        # If dt is large, then there is a HICCUP
        # ignore the frame
        if dt > .2: return Task.cont

        # dispatch which function to handle the collision based on name
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()
       
            if name == "Wall.004":
                self.wallCollideHandler(entry)
            elif name=="Cube.004":
                self.groundCollideHandler(entry)
            else: 
                if self.rockOnMaze == True:
                    self.wallCollideHandler(entry)
        self.accelV += self.jerk
        # move the ball, update the velocity based on accel
        self.ballV += self.accelV * dt * ACCELERATION
        # clamp the velocity to the max speed
        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED
        # update the position
        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV*dt))

        # uses quaternion to rotate the ball
        prevRot = LRotationf(self.ball.getQuat())
        axis = UP.cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)
        return Task.cont # continue the task
Exemple #18
0
class World(DirectObject):
	def __init__(self):
		#sys.path.append('../game')
		#Standard title and instruction text
		self.title = OnscreenText(
			text="PSG: Test - Explosion",
			style=1, fg=(1,1,1,1), pos=(0.9,-0.95), scale = .07)
		self.escapeEvent = OnscreenText(
			text=HELPTEXT,
			style=1, fg=(1,1,1,1), pos=(-1.3, 0.95),
			align=TextNode.ALeft, scale = .05)

		#More standard initialization
		self.accept('escape', sys.exit)
		self.accept('1', self.loadParticleConfig , ['explosion1.ptf'])
		self.accept('2', self.loadParticleConfig , ['explosion2.ptf'])
		self.accept('3', self.loadParticleConfig , ['explosion3.ptf'])
		self.accept('4', self.loadParticleConfig , ['explosion4.ptf'])
		self.accept('5', self.loadParticleConfig , ['explosion5.ptf'])
		self.accept('6', self.loadParticleConfig , ['explosion6.ptf'])
		
		self.accept('escape', sys.exit)
		base.disableMouse()
		camera.setPos(0,-20,2)
		base.setBackgroundColor( 0, 0, 0 )

		#This command is required for Panda to render particles
		base.enableParticles()
		self.t = loader.loadModel("../data/models/ship_03.egg")
		self.t.setScale(0.5)
		self.t.setHpr(180, 0, 0)
		self.t.setPos(0,10,0)
		self.t.reparentTo(render)
		self.setupLights()
		self.p = ParticleEffect()
		self.loadParticleConfig('explosion1.ptf')

	def loadParticleConfig(self,file):
		#Start of the code from steam.ptf
		self.p.cleanup()
		self.p = ParticleEffect()
		self.p.loadConfig(Filename(file))        
		#Sets particles to birth relative to the teapot, but to render at toplevel
		self.p.start(self.t)
		self.p.setPos(0.000, 0.000, 0.00)
	
	#Setup lighting
	def setupLights(self):
		lAttrib = LightAttrib.makeAllOff()
		ambientLight = AmbientLight( "ambientLight" )
		ambientLight.setColor( Vec4(.6, .6, .55, 1) )
		lAttrib = lAttrib.addLight( ambientLight )
		directionalLight = DirectionalLight( "directionalLight" )
		directionalLight.setDirection( Vec3( 0, 8, -2.5 ) )
		directionalLight.setColor( Vec4( 0.9, 0.8, 0.9, 1 ) )
		lAttrib = lAttrib.addLight( directionalLight )
		#set lighting on teapot so steam doesn't get affected
		#self.t.attachNewNode( directionalLight.upcastToPandaNode() )
		self.t.attachNewNode( directionalLight ) 
		#self.t.attachNewNode( ambientLight.upcastToPandaNode() )
		self.t.attachNewNode( ambientLight) 
		self.t.node().setAttrib( lAttrib )
class Player(object, DirectObject.DirectObject):
    def __init__(self):
        self.node = 0  #the player main node
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 10
        self.speedMax = 100
        self.agility = 3
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        #self

        self.textSpeed = OnscreenText(text='Speed: ' + str(self.speed),
                                      pos=(-1.34, 0.95),
                                      scale=0.07,
                                      fg=(1, 1, 1, 1),
                                      bg=(0.2, 0.2, 0.2, 0.4),
                                      align=TextNode.ALeft)
        self.textHP = OnscreenText(text='Health:    ' + str(self.HP),
                                   pos=(-1.33, 0.85),
                                   scale=0.07,
                                   fg=(1, 1, 1, 1),
                                   bg=(0.2, 0.2, 0.2, 0.4),
                                   align=TextNode.ALeft)
        self.roll = 0
        self.camHeight = 0

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)

        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    '''
    loadModel
    This will load all the visible stuff
    '''

    def loadModel(self):
        """ make the nodepath for player """
        self.node = NodePath('player')
        self.node.setPos(1000, 1000, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('griffin')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #self.contrail.loadConfig('media/contrail.ptf')
        #self.contrail.start(self.node,render)

        #gravity (aceleration 9.82)
        self.gravityFN = ForceNode('world-forces')
        self.gravityFNP = render.attachNewNode(self.gravityFN)
        self.gravityForce = LinearVectorForce(0, 0, -9.82)
        self.gravityFN.addForce(self.gravityForce)

        #add gravity to engine
        #base.physicsMgr.addLinerForce(self.gravityForce)

        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)

        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)

        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)

        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)

    '''
    addCamera
    camera setup
    '''

    def addCamera(self):
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    '''
    addEvents
    This will set up the events the class will accept
    '''

    def addEvents(self):
        self.accept("wheel_up", self.evtSpeedUp)
        self.accept("wheel_down", self.evtSpeedDown)
        self.accept('hit', self.evtHit)
        self.accept('l', self.evtLand)
        self.accept('o', self.evtStart)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        self.accept('mouse3', self.evtBoostOn)
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    '''
    addCollisions
    This will add a collision sphere for the player
    and a segment to check weather the ground is close/flat enough for landing
    '''

    def addCollisions(self):
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNode.setFromCollideMask(BitMask32(0x1A))
        self.cNode.setIntoCollideMask(BitMask32(0x4))

        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        self.collisionHandler.addInPattern('hit')
        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        # landing segment:
        self.landingCNodeSegment = CollisionNode('playerRay')
        self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20))
        self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff())
        self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8))

        self.landingCNodeSegmentPath = self.node.attachNewNode(
            self.landingCNodeSegment)
        #self.landingCNodeSegmentPath.show()
        base.cTrav.addCollider(self.landingCNodeSegmentPath,
                               self.collisionHandlerQueue)

    '''
    addSound
    adds the engine sound
    @TODO add more
    '''

    def addSound(self):
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

    '''
    deleteTask
    task which calls the destructor after a given time (after the explosion animation)
    '''

    def deleteTask(self, task):
        self.__del__()
        return task.done

    '''
    mouseUpdateTask
    This task will handle mouse movement and control the planes rotation.
    If free look is enabled, it will rotate the camera around the player.
    '''

    def mouseUpdateTask(self, task):
        """ this task updates the mouse """
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)
        #base.camera.setY(-30+self.speed/10)
        #base.camera.setX(self.roll*0.5)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    '''
    moveUpdateTask
    Will update players position depending on speed and direction
    '''

    def moveUpdateTask(self, task):
        """ this task makes the player move """
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))

        #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed)
        return task.cont

    def landTask(self, task):
        if self.collisionHandlerQueue.getNumEntries() == 0 and task.frame > 3:
            print 'to faar'
            self.landing = False
            self.evtFreeLookOFF()
            return task.done
        elif self.collisionHandlerQueue.getNumEntries() == 0:
            return task.cont

        self.collisionHandlerQueue.sortEntries()
        entry = self.collisionHandlerQueue.getEntry(0)
        if entry.getInto != self.cNode:
            n = entry.getSurfaceNormal(render)
            n.normalize()
            if n.getZ() < 0.8:
                print 'too steep'
                self.landing = False
                self.evtFreeLookOFF()
                return task.done

            self.cNode.setFromCollideMask(BitMask32(0x0))
            self.cNode.setIntoCollideMask(BitMask32(0x0))
            self.node.setZ(self.node.getZ() - 0.05)
            if entry.getSurfacePoint(self.node).getZ() > -0.5:
                #self.landing = tr
                #self.evtFreeLookOFF()
                return task.done

        return task.cont

    def startTask(self, task):
        self.collisionHandlerQueue.sortEntries()
        entry = self.collisionHandlerQueue.getEntry(0)

        self.node.setZ(self.node.getZ() + 0.05)
        if entry.getSurfacePoint(self.node).getZ() < -10:
            self.landing = False
            self.evtFreeLookOFF()
            self.cNode.setFromCollideMask(BitMask32(0x18))
            self.cNode.setIntoCollideMask(BitMask32(0x4))
            return task.done

        return task.cont

    '''
    explode
    this will cause the plane to explode with a nice particle effect.
    '''

    def explode(self):
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()
        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    '''
    zoomTask
    will adjust camera position according to zoom factor specified in self.zoom
    in a smooth way.
    '''

    def zoomTask(self, task):
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    '''
    evtBoostOn
    Will set most inputs to ignore, add a speed boost and an additional
    particle effect     
    '''

    def evtBoostOn(self):
        taskMgr.remove(self.mouseTask)
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('mouse1')
        self.ignore('l')
        self.ignore('o')
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    '''
    evtBoostOff
    Will reactivate inputs, substract speed boost and stop the additional
    particle effect     
    '''

    def evtBoostOff(self):
        self.speed -= 200
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.ignore('mouse3-up')
        self.addEvents()
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        #self.contrail.loadConfig('../../media/contrail.ptf')
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    '''
    evtHit
    This event will be called if the player gets hit by an object.
    It will reduce the HP by 1 each time we hit a missile.
    If HP reaches 0, the player will explode.
    If we hit an other object like a rock, the player will explode imidiatly
    '''

    def evtHit(self, entry):
        if entry.getIntoNodePath().getParent().getTag(
                "orign") != self.node.getName():

            #if entry.getIntoNodePath().getName() == "projectile":
            #self.HP -= 1
            #self.textHP.setText('HP   : '+str(self.HP))
            if self.HP == 0:
                self.explode()
            else:
                self.explode()

    '''
    evtFreeLookON
    Event that activates free look mode and therefore changes cam position
    '''

    def evtFreeLookON(self):
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    '''
    evtFreeLookOFF
    Event that deactivates free look mode and therefore changes cam position
    back to original
    '''

    def evtFreeLookOFF(self):
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    '''
    __del__
    destructor will remove particle effect, tasks and the whole node
    '''

    def __del__(self):
        self.ignoreAll()
        self.contrail.cleanup()
        base.camera.reparentTo(render)
        base.camera.setPos(2000, 2000, 800)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        messenger.send('player-death')

    '''
    evtSpeedUp
    Will be called if player wants to increase speed.
    - engine sound will become louder
    - camera will zoom out
    - speed display will be updated
    '''

    def evtSpeedUp(self):
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1)
        self.zoom = -5 - (self.speed / 10)
        self.textSpeed.setText('Speed: ' + str(self.speed))

    '''
    evtSpeedDown
    Will be called if player wants to decrease speed.
    - engine sound will become more silent
    - camera will zoom in
    - speed display will be updated
    '''

    def evtSpeedDown(self):
        if self.landing:
            return 0
        self.textSpeed.setText('Speed: ' + str(self.speed))
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            #self.engineSound.setVolume(0)
            self.engineSound.setPlayRate(0)
        self.zoom = -5 - (self.speed / 10)

    def evtLand(self):
        if self.speed != 0 or self.landing:
            return 0
        self.evtFreeLookON()  # landing will enable freelook mode
        self.landing = True
        self.node.setP(0)
        taskMgr.add(self.landTask, 'land-task')

    def evtStart(self):
        if not self.landing:
            return 0
        taskMgr.add(self.startTask, 'start-task')

    def evtMenuOpen(self):
        """event that will be called if main menu is opened (esc)"""
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)

    def evtMenuClose(self):
        """event that will be called if main menu is closed (esc)"""
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
Exemple #20
0
class Pies:
    notify = DirectNotify().newCategory("Pies")

    def __init__(self):
        self.models = {
            1: "phase_3.5/models/props/tart.bam",
            0: "phase_5/models/props/birthday-cake-mod.bam",
            2: "phase_5/models/props/cream-pie-slice.bam"
        }
        self.hitsounds = {
            1: "phase_4/audio/sfx/AA_wholepie_only.mp3",
            0: "phase_4/audio/sfx/AA_wholepie_only.mp3",
            2: "phase_3.5/audio/sfx/AA_tart_only.mp3"
        }
        self.splatcolors = {
            1: VBase4(1, 1, 0, 1),
            0: VBase4(1, 0, 1, 1),
            2: VBase4(1, 1, 0, 1)
        }
        self.playrates = {1: 1.0, 0: 1.0, 2: 1.0, 3: 1.0}
        self.damage = {1: 36, 0: 75, 2: 17, 3: 180}
        self.health = {1: 5, 0: 10, 2: 2}
        self.max_ammo = {1: 7, 0: 3, 2: 15, 3: 2}
        self.current_ammo = {1: 7, 0: 3, 2: 15, 3: 0}
        self.weapon_id_2_weapon = {0: "cake", 1: "tart", 2: "slice", 3: "tnt"}
        self.avatar = None
        self.splat = None
        self.pie = None
        self.tnt = None
        self.tntSparks = None
        self.tntTrajectory = None
        self.tntExplosion = None
        self.woosh = None
        self.dynamiteSfx = None
        self.pie_type = 1  # Default pie is the wholecream pie.
        self.pie_state = "start"
        self.tnt_state = "ready"
        return

    def getPieTypeName(self):
        return self.weapon_id_2_weapon.get(self.pie_type, None)

    def attachTNT(self):
        self.detachTNT()
        self.tnt = Actor("phase_5/models/props/tnt-mod.bam",
                         {"chan": "phase_5/models/props/tnt-chan.bam"})
        self.tnt.reparentTo(self.avatar.find('**/def_joint_right_hold'))
        self.tntSparks = ParticleEffect()
        self.tntSparks.loadConfig("phase_5/etc/tnt.ptf")
        #self.tntSparks.start(parent = self.tnt.find('**/joint_attachEmitter'),
        #	renderParent = self.tnt.find('**/joint_attachEmitter'))

    def detachTNT(self):
        if self.tntTrajectory:
            self.tntTrajectory.pause()
            self.tntTrajectory = None
        if self.tnt is not None:
            self.tnt.cleanup()
            self.tnt = None
        if self.tntSparks is not None:
            self.tntSparks.cleanup()
            self.tntSparks = None

    def delete(self):
        self.avatar = None
        if self.splat is not None:
            self.splat.cleanup()
            self.splat = None
        self.detachTNT()
        self.tnt = None
        self.tnt_state = None
        self.tntSparks = None
        if self.tntExplosion:
            self.tntExplosion.cleanup()
            self.tntExplosion = None
        if self.dynamiteSfx:
            self.dynamiteSfx.stop()
            self.dynamiteSfx = None
        if self.pie is not None:
            self.deletePie()
        self.pie_type = None
        self.pie_state = None
        self.current_ammo = None
        self.max_ammo = None
        self.damage = None
        self.playrates = None
        self.splatcolors = None
        self.hitsounds = None
        self.models = None
        return

    def setAvatar(self, avatar):
        self.avatar = avatar

    def getAvatar(self):
        return self.avatar

    def setPieType(self, pietype):
        self.pie_type = pietype
        weaponType = None
        if pietype in [0, 1, 2]:
            weaponType = "pie"
        elif pietype == 3:
            weaponType = "tnt"
        if hasattr(self.avatar, 'setWeaponType'):
            self.avatar.setWeaponType(weaponType)

    def getPieType(self):
        return self.pie_type

    def setAmmo(self, ammo, pietype=None):
        if pietype is None:
            pietype = self.getPieType()
        self.current_ammo[pietype] = ammo

    def getAmmo(self, pietype=None):
        if pietype is None:
            pietype = self.getPieType()
        return self.current_ammo[pietype]

    def getDamage(self, weapon_id=None):
        if weapon_id is None:
            return self.damage[self.pie_type]
        else:
            return self.damage[weapon_id]

    def getHealth(self, weapon_id=None):
        if weapon_id is None:
            return self.health[self.pie_type]
        else:
            return self.health[weapon_id]

    def deletePie(self):
        try:
            self.trajectory.pause()
        except:
            pass
        if self.pie:
            self.pie.removeNode()
            self.pie = None

    def pieStart(self):
        try:
            audio3d.detachSound(self.woosh)
            self.trajectory.pause()
            self.pie.remove()
            self.pie = None
        except:
            pass
        self.pie_state = 'start'
        self.pie = loader.loadModel(self.models[self.pie_type])
        self.pie.reparentTo(
            self.avatar.getPart('torso').find('**/def_joint_right_hold'))

        self.avatar.setPlayRate(self.playrates[self.pie_type], "pie")
        self.avatar.play("pie", fromFrame=0, toFrame=45)

    def tntStart(self):
        self.avatar.play("toss", fromFrame=22)
        self.tnt_state = "start"

    def tntRelease(self):
        if self.tnt is None:
            return

        tntNp = self.avatar.attachNewNode('tntNp')
        tntNp.setScale(render, 1.0)
        tntNp.setPos(0, 160, -120)
        tntNp.setHpr(0, 90, 0)

        self.tntTrajectory = ProjectileInterval(
            self.tnt,
            startPos=(self.avatar.getPart('torso').find(
                '**/def_joint_right_hold').getPos(render)),
            endPos=tntNp.getPos(render),
            gravityMult=0.9,
            duration=3)
        self.tnt.setHpr(tntNp.getHpr(render))
        self.tntTrajectory.start()
        self.tnt.reparentTo(render)
        self.tnt_state = "released"
        self.setAmmo(self.getAmmo() - 1)

    def handleTntHitGround(self):
        if not self.tnt:
            return

        self.tntSparks.start(
            parent=self.tnt.find('**/joint_attachEmitter'),
            renderParent=self.tnt.find('**/joint_attachEmitter'))

        self.dynamiteSfx = audio3d.loadSfx("phase_5/audio/sfx/TL_dynamite.mp3")
        audio3d.attachSoundToObject(self.dynamiteSfx, self.tnt)
        self.dynamiteSfx.play()

        self.tnt.play("chan")

        if self.tntTrajectory:
            self.tntTrajectory.pause()
            self.tntTrajectory = None

    def tntExplode(self):
        if not self.tnt:
            return

        self.tntExplosion = Actor(
            "phase_5/models/props/kapow-mod.bam",
            {"chan": "phase_5/models/props/kapow-chan.bam"})
        self.tntExplosion.reparentTo(render)
        self.tntExplosion.setBillboardPointEye()
        self.tntExplosion.setPos(self.tnt.getPos(render) + (0, 0, 4))
        self.tntExplosion.setScale(0.5)
        self.tntExplosion.play("chan")
        if self.dynamiteSfx:
            self.dynamiteSfx.stop()
            self.dynamiteSfx = None
        explosionSfx = audio3d.loadSfx(
            "phase_3.5/audio/sfx/ENC_cogfall_apart.mp3")
        audio3d.attachSoundToObject(explosionSfx, self.tntExplosion)
        SoundInterval(explosionSfx).start()
        if self.tntSparks:
            self.tntSparks.cleanup()
            self.tntSparks = None
        if self.tnt:
            self.tnt.cleanup()
            self.tnt = None
        self.tnt_state = "ready"
        if self.getAmmo(3) > 0 and self.getPieType() == 3:
            self.attachTNT()
            if hasattr(self.avatar, "enablePieKeys"):
                # This must be the local avatar
                self.avatar.enablePieKeys()
        taskMgr.doMethodLater(0.5, self.delTntExplosion, "delTntExplosion")

    def delTntExplosion(self, task):
        if self.tntExplosion:
            self.tntExplosion.cleanup()
            self.tntExplosion = None
        return task.done

    def tntCollisions(self):
        if not self.tnt:
            return
        tss = CollisionSphere(0, 0, 0, 1)
        tsNode = CollisionNode('tntSensor')
        tsNode.add_solid(tss)
        self.tsNp = self.tnt.attach_new_node(tsNode)
        self.tsNp.set_scale(0.75, 0.8, 0.75)
        self.tsNp.set_pos(0.0, 0.1, 0.5)
        self.tsNp.set_collide_mask(BitMask32(0))
        self.tsNp.node().set_from_collide_mask(CIGlobals.FloorBitmask)

        event = CollisionHandlerEvent()
        event.set_in_pattern("%fn-into")
        event.set_out_pattern("%fn-out")
        base.cTrav.add_collider(self.tsNp, event)

    def setTntPos(self, pos):
        if self.tnt:
            self.tnt.setPos(pos)

    def pieCollisions(self):
        pss = CollisionSphere(0, 0, 0, 1)
        psnode = CollisionNode('pieSensor')
        psnode.add_solid(pss)
        self.psnp = self.pie.attach_new_node(psnode)
        self.psnp.set_collide_mask(BitMask32(0))
        self.psnp.node().set_from_collide_mask(CIGlobals.WallBitmask
                                               | CIGlobals.FloorBitmask)

        event = CollisionHandlerEvent()
        event.set_in_pattern("%fn-into")
        event.set_out_pattern("%fn-out")
        base.cTrav.add_collider(self.psnp, event)

    def pieThrow(self):
        self.avatar.play("pie", fromFrame=45, toFrame=90)

    def pieRelease(self):
        if self.pie is None:
            return

        self.woosh = audio3d.loadSfx(
            "phase_3.5/audio/sfx/AA_pie_throw_only.mp3")
        audio3d.attachSoundToObject(self.woosh, self.pie)
        self.woosh.play()

        self.pieNp = NodePath("PieNp")
        self.pieNp.reparentTo(self.avatar)
        self.pieNp.setScale(render, 1.0)
        self.pieNp.setPos(0, 160, -90)
        self.pieNp.setHpr(90, -90, 90)

        self.pie.setScale(self.pie.getScale(render))
        self.pie.reparentTo(render)
        self.pie.setHpr(self.pieNp.getHpr(render))

        self.trajectory = ProjectileInterval(
            self.pie,
            startPos=(self.avatar.getPart('torso').find(
                '**/def_joint_right_hold').getPos(render)),
            endPos=self.pieNp.getPos(render),
            gravityMult=0.9,
            duration=3)
        self.trajectory.start()
        self.pie_state = 'released'
        self.setAmmo(self.getAmmo() - 1)

    def handlePieSplat(self):
        if self.splat:
            self.splat.cleanup()
            self.splat = None

        if self.pie_type == 3:
            # Not sure why I get a KeyError: 3 crash, but just for now
            # return if the pie type is tnt (3).
            return

        self.splat = Actor("phase_3.5/models/props/splat-mod.bam",
                           {"chan": "phase_3.5/models/props/splat-chan.bam"})
        self.splat_sfx = audio3d.loadSfx(self.hitsounds[self.pie_type])
        audio3d.attachSoundToObject(self.splat_sfx, self.splat)
        self.splat_sfx.play()
        pietype2splatscale = {0: 0.6, 1: 0.5, 2: 0.35}
        self.splat.setScale(pietype2splatscale[self.pie_type])
        self.splat.reparentTo(render)
        self.splat.setBillboardPointEye()
        self.splat.setColor(self.splatcolors[self.pie_type])
        if self.pie and self.splat:
            self.splat.setPos(self.pie.getPos(render))
            self.splat.play("chan")

        if self.woosh:
            self.woosh.stop()
            self.woosh = None
        try:
            self.trajectory.pause()
        except:
            pass
        if self.pie:
            self.pie.removeNode()
            self.pie = None
        taskMgr.doMethodLater(0.5, self.delSplat, "delSplat")
        del pietype2splatscale

    def delSplat(self, task):
        if self.splat:
            self.splat.cleanup()
            self.splat = None
        return task.done
Exemple #21
0
class Effects(ShowBase):
    def __init__(self):
        #ShowBase.__init__(self)

        #################fulscreen###############
        root = Tkinter.Tk()
        w = root.winfo_screenwidth()
        h = root.winfo_screenheight()
        props = WindowProperties()
        props.setSize(w, h)
        base.win.requestProperties(props)
        #################end####################3

        #camera.setPos(-500,-80,0)
        base.enableParticles()
        self.txt = ""
        self.p = ParticleEffect()

        st_x = 5.0  ####-515,-60,0
        st_y = 8.0
        st_z = 0.0

        self.c2 = Actor(
            'Models/dancer/dancer'
        )  #Actor("Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve",{"run":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-run",	"jump":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-jump",	"offbalance":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-offbalance",	"tireroll":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-tireroll"})
        self.c2.setPos(offset_x + st_x, offset_y + st_y + 7, offset_z + st_z)
        self.c2.reparentTo(render)
        self.c2.loadAnims({'win': 'Models/dancer/dancer'})
        self.c2.loop('win')
        '''self.tex = Texture()
		self.tex.setMinfilter(Texture.FTLinear)
		base.win.addRenderTexture(self.tex, GraphicsOutput.RTMTriggeredCopyTexture)
		
		self.backcam = base.makeCamera2d(base.win, sort=-10)
		self.background = NodePath("background")
		self.backcam.reparentTo(self.background)
		self.background.setDepthTest(0)
		self.background.setDepthWrite(0)
		self.backcam.node().getDisplayRegion(0).setClearDepthActive(0)
		
		#taskMgr.add(self.takeSnapShot, "takeSnapShot")
		
		self.bcard = base.win.getTextureCard()
		self.bcard.reparentTo(self.background)
		self.bcard.setTransparency(1)
		self.fcard = base.win.getTextureCard()
		self.fcard.reparentTo(render2d)
		self.fcard.setTransparency(1)
		
		base.setBackgroundColor(0,0,0,1)
		self.bcard.hide()
		self.fcard.show()
		self.fcard.setColor(1.0,1.0,1.0,0.99)
		self.fcard.setScale(1.00)
		self.fcard.setPos(0,0,0)
		self.fcard.setR(0)
		self.clickrate = 30
		self.nextclick = 0'''

        self.c4 = Actor('Models/dancer/dancer')
        #self.c2.loadModel('Models/dancer/dancer')
        self.c4.setPos(offset_x - st_x, offset_y + st_y + 7, offset_z + st_z)
        self.c4.reparentTo(render)
        self.c4.loadAnims({'win': 'Models/dancer/dancer'})
        self.c4.loop('win')

        #self.c2.setR(-90)

        #self.c2.loop('tireroll')
        #base.setSleep(0.5)
        self.c3 = Actor(
            "Models/cat-humans/bvw-f2004--ralph-egg/bvw-f2004--ralph/ralph")
        self.c3.setScale(2)
        self.c3.setPos(offset_x + 0, offset_y + 20, offset_z + (-1))
        self.c3.reparentTo(render)
        self.c3.listJoints()
        #self.c4.listJoints()
        self.actorRh = self.c3.controlJoint(None, 'modelRoot', 'RightShoulder')
        self.actorLh = self.c3.controlJoint(None, 'modelRoot', 'LeftShoulder')
        self.actorNeck = self.c3.controlJoint(None, 'modelRoot', 'Neck')

        self.actorNeck1 = self.c3.controlJoint(None, 'modelRoot', 'Neck')

        #self.actorNeck.hprInterval(3,Point3(0,90,0)).loop()
        self.actorLh.hprInterval(3, Point3(90, 0, 0)).loop()
        self.actorRh.hprInterval(3, Point3(0, 0, -180)).loop()
        #self.actorRh.hprInterval(3,Point3(0,90,0)).loop()
        self.actorRh.setHpr(180, 180, -60)  # For Both hands upward
        self.actorLh.setHpr(90, -90, 120)

        self.loadchar('', '')
        self.duckPlane = loader.loadModel('Models/plane/plane')
        self.duckPlane.setPos(offset_x - 2, offset_y + 8,
                              offset_z + 10)  #set its position
        self.duckPlane.reparentTo(render)  #reparent to render
        self.duckPlane.setTransparency(1)
        self.duckTexs = self.loadTextureMovie(24,
                                              'duck/duck_fly_left',
                                              'png',
                                              padding=2)
        self.duckTask = taskMgr.add(self.textureMovie, "duckTask")
        self.duckTask.fps = 36
        self.duckTask.obj = self.duckPlane
        self.duckTask.textures = self.duckTexs
        self.duckPlane.node().setEffect(BillboardEffect.makePointEye())

        self.expPlane = loader.loadModel(
            'Models/plane/plane')  #load the object
        self.expPlane.setScale(18, 10, 10)
        self.expPlane.setPos(offset_x + 0, offset_y + 22,
                             offset_z + 4)  #set the position
        self.expPlane.reparentTo(render)  #reparent to render
        self.expPlane.setTransparency(1)  #enable transparency

        self.expTexs = self.loadTextureMovie(50,
                                             'explosion/def',
                                             'png',
                                             padding=4)
        #create the animation task
        self.expTask = taskMgr.add(self.textureMovie, "movieTask")
        self.expTask.fps = 30  #set framerate
        self.expTask.obj = self.expPlane  #set object
        self.expTask.textures = self.expTexs  #set texture list
        #self.expPlane.node().setEffect(BillboardEffect.makePointEye())

        self.c1 = loader.loadModel("Models/Dynamite/Dynamite")
        self.c1.setPos(offset_x - 6, offset_y + 10, offset_z + 2)
        self.c1.reparentTo(render)

        self.expPlane1 = loader.loadModel(
            'Models/plane/plane')  #load the object
        #self.expPlane1.setScale(1,10,10)
        self.expPlane1.setPos(offset_x - 8, offset_y + 10,
                              offset_z + 3)  #set the position
        self.expPlane1.reparentTo(render)  #reparent to render
        self.expPlane1.setTransparency(1)

        self.expTexs1 = self.loadTextureMovie(50,
                                              'explosion1/explosion',
                                              'png',
                                              padding=4)
        #create the animation task
        self.expTask1 = taskMgr.add(self.textureExplosion, "explosionTask")
        self.expTask1.fps = 30  #set framerate
        self.expTask1.obj = self.expPlane1  #set object
        self.expTask1.textures = self.expTexs1  #set texture list
        self.expPlane1.node().setEffect(BillboardEffect.makePointEye())

        self.orientPlane = loader.loadModel(
            'Models/plane/plane')  #Load the object
        #self.orientPlane.setScale(1)
        self.orientTex = loader.loadTexture("Models/plane/textures/carpet.jpg")
        self.orientPlane.setTexture(self.orientTex, 1)  #Set the texture
        self.orientPlane.reparentTo(render)  #Parent to render
        #Set the position, orientation, and scale
        self.orientPlane.setPosHprScale(offset_x + 0, offset_y + 18, offset_z,
                                        0, -90, 0, 20, 20, 20)

    def textureMovie(self, task):
        currentFrame = int(task.time * task.fps)
        task.obj.setTexture(task.textures[currentFrame % len(task.textures)],
                            1)
        return Task.cont

    def textureExplosion(self, task):
        currentFrame = int(task.time * task.fps)
        #print "curr  "
        #print currentFrame%51
        if ((currentFrame % len(task.textures)) > 10):
            self.c1.hide()
        elif ((currentFrame % len(task.textures)) <= 0):
            self.c1.show()
        task.obj.setTexture(task.textures[currentFrame % len(task.textures)],
                            1)
        return Task.cont

    def takeSnapShot(self, task):
        if (task.time > self.nextclick):
            self.nextclick += 1.0 / self.clickrate
            if (self.nextclick < task.time):
                self.nextclick = task.time
            base.win.triggerCopy()
        return Task.cont

    def loadTextureMovie(self, frames, name, suffix, padding=1):
        return [
            loader.loadTexture(
                (name + "%0" + str(padding) + "d." + suffix) % i)
            for i in range(frames)
        ]

    def loadchar(self, main_char, txt):
        self.txt = txt
        if (txt == ''):
            self.t = loader.loadModel("Models/DJTable/DJTable")
            self.t.setPos(offset_x + 0, offset_y + 20, offset_z)
            self.t.setH(180)
            self.t.reparentTo(render)
            self.setupLights()
            self.loadParticleConfig('fountain2.ptf')
        else:
            self.t = main_char  #loader.loadModel("Models/cat-vehicles-road/bvw-f2004--girlscar-egg/bvw-f2004--girlscar/girlcar")#loader.loadModel("Models/cat-vehicles-road/bvw-f2004--carnsx-egg/bvw-f2004--carnsx/carnsx")
            #self.t.setPos(0,20,0)
            #self.t.reparentTo(render)
            self.setupLights()
            self.loadParticleConfig('steam.ptf')

    def loadParticleConfig(self, file):
        #Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        if (self.txt == ''):
            self.txt = ''
            self.p.loadConfig(Filename(file))
            self.p.setPos(0.000, 0, 2.500)
        elif (self.txt == 'blue'):
            self.txt = ''
            self.p.loadConfig(Filename('steam_front.ptf'))
            self.p.setPos(0.000, -1.8, -0.800)

        elif (self.txt == 'red'):
            self.txt = ''
            self.p.loadConfig(Filename(file))
            self.p.setPos(0.000, 1.800, 0.250)
        self.p.start(self.t)

    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0, 8, -2.5))
        directionalLight.setColor(Vec4(0.9, 0.8, 0.9, 1))

        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))


#w = Effects()
#run()
Exemple #22
0
class Lvl03(DirectObject):
    def start(self):
        base.disableMouse() #turn off mouse camera control
        base.enableParticles()
	
	self.music = loader.loadMusic("models/gamedev/DEC.mp3")
	self.music.play()
	
        camera.setPosHpr(Vec3(98,-390,90), Vec3(0,-5,0))
        self.ballNum = 10
	self.setupStage()
        self.loadModels()
        self.setupLighting()
        self.setupCollisions()
        self.setupIntervals()
	
	taskMgr.add(self.ballMovementTask,'ballMoveTask')
        
        self.gameLen = 30
        
	self.player1Weapon = ""
	self.player2Weapon = ""
	
        #hud = OnscreenImage(image = 'models/gamedev/lvl2hud.jpg', pos = (0,1,20),scale=5.0)
        #hud.reparentTo(render)
        
        globalClock.reset()
        
        self.timer = OnscreenText("%d" % (self.gameLen-globalClock.getRealTime(),), pos = (98,145), scale = 18.0)
        self.timer.setColor(1,1,1)
        taskMgr.add(self.clockTask,"clockTask")
        
        self.player1Score = 0
        self.player2Score = 0
        
        self.nodeCount1 = 0
        self.nodeCount2 = 0
	
	self.player1Invincible = 0
        self.player2Invincible = 0
	
	self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2")
	self.jNP2 = self.playerModel2.exposeJoint(None,"modelRoot","ikHandle2")
	
        self.climbing1 = 0
        self.climbing2 = 0
        
        self.speed1 = 3.0
        self.speed2 = 3.0
        
        self.ignoreColl= 0
        
        self.player1IsColliding = 0
        self.player2IsColliding = 0
        
        taskMgr.doMethodLater(self.gameLen, self.endGame,'gameFinished')
        
        #taskMgr.doMethodLater(self.gameLen/2.0,self.changeMusic,'musicSwitch')
        
        
        #setup key controls
        self.accept("escape",sys.exit)
        #self.acceptOnce("space",self.drop)
        # Player 1 movement
        
        self.acceptOnce("a",self.left)
        self.acceptOnce("d",self.right)
        
        self.accept("a-up",self.stopLeft)
        self.accept("d-up",self.stopRight)
        
        self.acceptOnce("w", self.jump)

        
        #Player 2 movement keys
        #self.accept("l",self.fall2)
        
        self.acceptOnce("k",self.left2)
        self.acceptOnce(";",self.right2)
        
        self.accept("k-up",self.stopLeft2)
        self.accept(";-up",self.stopRight2)
        
        self.acceptOnce("o", self.jumpT2)
        
    def setupStage(self):
	self.ball = []
	self.movement = []
	for i in range(self.ballNum+1):
		z=random.randint(1,2)
		if z ==1:
			z=-1
		else:
			z=1
		weapBalls.define(self.ball,i,render)
		self.movement.append(Vec3(random.random()*z,0,random.random()*z))
		#self.movement[i].Vec3(random.randint(1,3),0,random.randint(1,3))
		
	self.background2 = OnscreenImage(image = 'models/gamedev/frozenbg.JPG', pos = (98,10,0),scale=500)
	self.background2.detachNode()
        self.background = OnscreenImage(image = 'models/gamedev/moltenbg.JPG', pos = (98,10,0),scale=500)
        self.background.reparentTo(render)
        
        self.lava = loader.loadModel("models/gamedev/lava")
        self.lava.setPosHpr(Vec3(98,0,-18),Vec3(0,5,0))
        self.lava.setScale(50)
        self.lava.reparentTo(render)
        
        
        x1= 196
        x2 = 0
        m1 = 98
        m2 = 107.8
        len = 9.8
        h = 0
        a = 0
        p = 0
        
        for j in range(4):
            if j > 0:
                x1Old = x1
                x2Old = x2
                x1 = 196-(random.randint(0,3)*9.8)
                x2 = 0+random.randint(0,3)*9.8
                m1=98-(random.randint(0,3)*9.8)
                m2= 107.8+random.randint(0,3)*9.8
            
                for count in range(1):
                    l = random.randint(2,5)
                    r = random.randint(2,5)
                    c1 = random.randint(2,5)
                    c2 = random.randint(2,5)
                    if l+r < 4:
		        count = 0
			
            else:
                l = 4
                r = 4
                c1 = 2
                c2 = 2
            '''
            if j ==1 or j == 3:
                self.ladder = loader.loadModel("models/gamedev/ladder")
                self.ladder.reparentTo(render)
                self.ladder.setScale(1.5)
                self.ladder.setPos(x2+4.9,0,h-20)
                self.ladder2 = loader.loadModel("models/gamedev/ladder")
                self.ladder2.reparentTo(render)
                self.ladder2.setScale(1.5)
                self.ladder2.setPos(x1-4.9,0,h-20)
            
            if j == 2:
                self.ladder = loader.loadModel("models/gamedev/ladder")
                self.ladder.reparentTo(render)
                self.ladder.setScale(1.5)
                self.ladder.setPos(m1-4.9,0,h-20)
                self.ladder2 = loader.loadModel("models/gamedev/ladder")
                self.ladder2.reparentTo(render)
                self.ladder2.setScale(1.5)
                self.ladder2.setPos(m2+4.9,0,h-20)
            '''
            self.first = 1

            for i in range(r):
                '''Right half of stage'''
                self.environment = loader.loadModel("models/gamedev/platform")
                self.environment.reparentTo(render)
                self.environment.setScale(5)
                self.environment.setPos(x1,0,h)
                    
                if self.first == 1:
                    self.first = 0
                    bounds = self.environment.getChild(0).getBounds()
                    center = bounds.getCenter()
                    poly1 = Point3(center.getX()+1, center.getY()-.5, center.getZ()+.2)
                    poly2 = Point3(center.getX()-(2*r-1), center.getY()-.5, center.getZ()+.2)
                    poly3 = Point3(center.getX()+1, center.getY()+.5, center.getZ()+.2)
                    poly4 = Point3(center.getX()-(2*r-1), center.getY()+.5, center.getZ()+.2)
                    cPoly = CollisionPolygon(poly4, poly2, poly1, poly3)
                    cNode = CollisionNode("platform")
                    cNode.addSolid(cPoly)
                    cNodePath = self.environment.attachNewNode(cNode)
                    cNodePath.show()
                    
                x1 = x1 - len

            self.first = 1
            
            for i in range(l):
                '''Left Half of stage'''
                self.environment = loader.loadModel("models/gamedev/platform")
                self.environment.reparentTo(render)
                self.environment.setScale(5)
                self.environment.setPos(x2,0,h)
                
                if self.first == 1:
                    self.first = 0
                    bounds = self.environment.getChild(0).getBounds()
                    center = bounds.getCenter()
                    poly1 = Point3(center.getX()+(2*l-1), center.getY()-.5, center.getZ()+.2)
                    poly2 = Point3(center.getX()-1, center.getY()-.5, center.getZ()+.2)
                    poly3 = Point3(center.getX()+(2*l-1), center.getY()+.5, center.getZ()+.2)
                    poly4 = Point3(center.getX()-1, center.getY()+.5, center.getZ()+.2)
                    cPoly = CollisionPolygon(poly4, poly2, poly1, poly3)
                    cNode = CollisionNode("platform")
                    cNode.addSolid(cPoly)
                    cNodePath = self.environment.attachNewNode(cNode)
                    cNodePath.show()
                
                x2 = x2 + len
                
            self.first = 1
            
            for i in range(c1):
                '''Right half of stage'''
                self.environment = loader.loadModel("models/gamedev/platform")
                self.environment.reparentTo(render)
                self.environment.setScale(5)
                self.environment.setPos(m1,0,h)
                
                if self.first == 1:
                    self.first = 0
                    bounds = self.environment.getChild(0).getBounds()
                    center = bounds.getCenter()
                    poly1 = Point3(center.getX()+1, center.getY()-.5, center.getZ()+.2)
                    poly2 = Point3(center.getX()-(2*c1-1), center.getY()-.5, center.getZ()+.2)
                    poly3 = Point3(center.getX()+1, center.getY()+.5, center.getZ()+.2)
                    poly4 = Point3(center.getX()-(2*c1-1), center.getY()+.5, center.getZ()+.2)
                    cPoly = CollisionPolygon(poly4, poly2, poly1, poly3)
                    cNode = CollisionNode("platform")
                    cNode.addSolid(cPoly)
                    cNodePath = self.environment.attachNewNode(cNode)
                    cNodePath.show()
                
                m1 = m1 - len
                
            self.first = 1
            
            for i in range(c2):
                '''Left Half of stage'''
                self.environment = loader.loadModel("models/gamedev/platform")
                self.environment.reparentTo(render)
                self.environment.setScale(5)
                self.environment.setPos(m2,0,h)
                
                if self.first == 1:
                    self.first = 0
                    bounds = self.environment.getChild(0).getBounds()
                    center = bounds.getCenter()
                    poly1 = Point3(center.getX()+(2*c2-1), center.getY()-.5, center.getZ()+.2)
                    poly2 = Point3(center.getX()-1, center.getY()-.5, center.getZ()+.2)
                    poly3 = Point3(center.getX()+(2*c2-1), center.getY()+.5, center.getZ()+.2)
                    poly4 = Point3(center.getX()-1, center.getY()+.5, center.getZ()+.2)
                    cPoly = CollisionPolygon(poly4, poly2, poly1, poly3)
                    cNode = CollisionNode("platform")
                    cNode.addSolid(cPoly)
                    cNodePath = self.environment.attachNewNode(cNode)
                    cNodePath.show()
                
                m2 = m2 + len
            
            h = h+40
            a = 0

    def loadModels(self):
    
        # ** Load female character that will represent first player** #
        
        
        self.playerModel = Actor("models/gamedev/redguy-model",{"walk":"models/gamedev/redguy-run"})
        self.playerModel.reparentTo(render)
        self.playerModel.setScale(.6)
        self.playerModel.setH(90)
        
        # ** Position player at center of the field with it lying directly above the field. ** #
        
        self.playerModel.setPos(0,0,1.76)
        
        # ** Load female character that will represent second player** #
        
        self.playerModel2 = Actor("models/gamedev/bluegirl-model",{"walk2":"models/gamedev/bluegirl-run"})
        self.playerModel2.reparentTo(render)
        self.playerModel2.setScale(.6)
        self.playerModel2.setH(0)
        
        # ** Position player at center of the field with it lying directly above the field. ** #
        
        self.playerModel2.setPos(196,0,2.0)

    def reset(self):
	self.an1.getPhysicsObject().setVelocity(Vec3(0,0,0))
	self.an2.getPhysicsObject().setVelocity(Vec3(0,0,0))
	self.an1.getPhysicsObject().setPosition(Point3(0,0,11.76))
	self.an2.getPhysicsObject().setPosition(Point3(196,0,22.0))
	
	self.playerModel.setH(90)
	self.playerModel.detachNode()
	self.playerModel.setPos(0,0,1.76)
	self.anp.setFluidPos(Point3(0,0,1.76))
	self.playerModel.reparentTo(self.anp)
	
	self.playerModel2.setH(0)
	self.playerModel2.detachNode()
	self.playerModel2.setPos(196,0,22.0)
	self.anp2.setFluidPos(Point3(196,0,22.0))
	self.playerModel2.reparentTo(self.anp2)

    def setupLighting(self):
        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor(Vec4(0.55,0.55,0.55,1.0))
        ambientLightNP = render.attachNewNode(ambientLight)
        render.setLight(ambientLightNP)
        dirLight = DirectionalLight('dirLight')
        dirLight.setColor(Vec4(0.6,0.6,0.6,1))
        dirLightNP = render.attachNewNode(dirLight)
        dirLightNP.setHpr(Vec3(0.0,-26.0,0.0))
        render.setLight(dirLightNP)
        
    def setupIntervals(self):
        self.charWalk1l = self.playerModel.actorInterval("walk")
        self.charWalk1l.loop( )
        self.charWalk1l.pause( )
        
        self.charWalk1r = self.playerModel.actorInterval("walk")
        self.charWalk1r.loop( )
        self.charWalk1r.pause( )
        
        self.charWalk2l = self.playerModel2.actorInterval("walk2")
        self.charWalk2l.loop( )
        self.charWalk2l.pause( )
        
        self.charWalk2r = self.playerModel2.actorInterval("walk2")
        self.charWalk2r.loop( )
        self.charWalk2r.pause( )
        
        self.jump1 = self.playerModel.actorInterval("jump")
        self.jump1.loop()
        self.jump1.pause()
        
        self.jump2 = self.playerModel2.actorInterval("jump2")
        self.jump2.loop()
        self.jump2.pause()
        
        self.climb1 = self.playerModel.actorInterval("climb")
        self.climb1.loop()
        self.climb1.pause()
        
        self.climb2 = self.playerModel2.actorInterval("climb2")
        self.climb2.loop()
        self.climb2.pause()
        
        # end setupIntervals

        # ############################
        # Actual Working movement code
        # ############################

    def rise(self):
        dist = 40
        self.playerModel.setH(0)
        playerJump = self.playerModel.posInterval(1.0,Vec3(self.playerModel.getX(), self.playerModel.getY(),self.playerModel.getZ()+dist))
        playerJump.start()
        
    def rise2(self):
        dist = 40
        self.playerModel2.setH(90)
        playerJump2 = self.playerModel2.posInterval(1.0,Vec3(self.playerModel2.getX(), self.playerModel2.getY(),self.playerModel2.getZ()+dist))
        playerJump2.start()
        
    # PLAYER ONE #
        
    def left(self):
        taskMgr.add(self.leftTask,'leftTask')
        self.charWalk1l.loop()
        #end left
        
    def leftTask(self,task):
        if self.climbing1 == 0:
            self.playerModel.setH(270)
            self.playerModel.setPos(Vec3(self.playerModel.getX()-self.speed1, self.playerModel.getY(), self.playerModel.getZ()))
        return Task.cont
        
    def right(self):
        taskMgr.add(self.rightTask,'rightTask')
        self.charWalk1r.loop()
        #end right
        
    def rightTask(self,task):
        if self.climbing1 == 0:
            self.playerModel.setH(90)
            self.playerModel.setPos(Vec3(self.playerModel.getX()+self.speed1, self.playerModel.getY(), self.playerModel.getZ()))
        return Task.cont	

	def climbable(self,cEntry):
		self.nodeCount1+=1
		print self.nodeCount1
		self.ignore("w")
		self.ignore("w-up")
		self.ignore("s")
		self.ignore("s-up")
		self.acceptOnce("w",self.climb,[1])
		self.accept("w-up",self.noClimb)
		self.acceptOnce("s",self.climb,[-1])
		self.accept("s-up",self.noClimb)

	def climb(self,dir):
		self.dir1 = dir
		self.climbing1 = 1
		self.climbSpeed1 = 1
		self.ignore("a")
		self.ignore("a-up")
		self.ignore("d")
		self.ignore("d-up")
		taskMgr.add(self.climbTask,'climbTask')
		self.climb1.loop()
		
	def noClimb(self):
		taskMgr.remove('climbTask')
		self.climb1.pause()
		if self.nodeCount1 == 0:
			self.climbing = 0
		self.climbSpeed1 = 0
		self.acceptOnce("w",self.climb,[1])
		self.acceptOnce("s",self.climb,[-1])
		
	def jumpable(self,cEntry):
		self.nodeCount1+=-1
		print self.nodeCount1
		if self.nodeCount1 == 0:
			taskMgr.remove('climbTask')
			self.ignore("w")
			self.ignore("w-up")
			self.ignore("s")
			self.ignore("s-up")
			self.acceptOnce("w",self.jump)
			self.acceptOnce("a",self.left)
			self.acceptOnce("d",self.right)
			self.accept("a-up",self.stopLeft)
			self.accept("d-up",self.stopRight)
			self.climbing1 = 0
			self.climbSpeed1 = 0
			self.climb1.pause()
			
	def walkable(self,cEntry):
		self.ignore("w")
		self.ignore("w-up")
		self.ignore("s")
		self.ignore("s-up")
		self.acceptOnce("w",self.climb,[1])
		self.accept("w-up",self.noClimb)
		self.acceptOnce("s",self.climb,[-1])
		self.accept("s-up",self.noClimb)
		self.acceptOnce("a",self.left)
		self.acceptOnce("d",self.right)
		self.accept("a-up",self.stopLeft)
		self.accept("d-up",self.stopRight)
		self.climbing1 = 0
		self.climbSpeed1 = 0
		self.climb1.pause()
			
	def climbTask(self,task):
		if self.playerModel.getZ() >=0:
			self.playerModel.setH(0)
			self.playerModel.setPos(Vec3(self.playerModel.getX(), self.playerModel.getY(), self.playerModel.getZ()+self.climbSpeed1*self.dir1))
		return Task.cont	

    def jump(self):
        if self.nodeCount1 == 0:
            self.ignore("w")
            self.ignore("w-up")
            z = self.playerModel.getZ()
            j = ProjectileInterval(self.playerModel, startPos = self.playerModel.getPos(), startVel = Point3(5,0,30), duration = 2.0)
            j.start()
            taskMgr.doMethodLater(2,self.jumpTask,"jumpTask")
        else:
            self.acceptOnce("w",self.climb,[1])
        
    def jumpTask(self, task):
        if self.climbing1 == 0:
            self.jump1.pause()
            self.acceptOnce("w",self.jump)
        #return task.cont
    
    def allowRight(self):
        self.acceptOnce("d",self.right)
    
    def noRight(self):
        taskMgr.remove('rightTask')
        self.charWalk1r.pause()
        self.acceptOnce("d",self.right)

    def stopRight(self):
        self.noRight()
        #self.allowRight()

    def rightWall(self,cEntry):
	self.ignore("d")
	self.noRight()
		
    def rightEdge(self,cEntry):
	self.ignore("d")
	self.noRight()

    def rightOK(self,cEntry):
	self.allowRight()	
		
    def allowLeft(self):
	self.acceptOnce("a",self.left)

    def noLeft(self):
        taskMgr.remove('leftTask')
        self.charWalk1l.pause()
        self.acceptOnce("a",self.left)

    def stopLeft(self):
        self.noLeft()
        #self.allowLeft()
        
    def leftWall(self,cEntry):
        self.ignore("a")
        self.noLeft()
        
    def leftEdge(self,cEntry):
        self.ignore("a")
        self.noLeft()
        
    def leftOK(self,cEntry):
        self.allowLeft()

	# PLAYERTWO #

    def left2(self):
        taskMgr.add(self.leftTask2,'leftTask2')
        self.charWalk2l.loop()
    #end left

    def leftTask2(self,task):
        if self.climbing2 == 0:
            self.playerModel2.setH(0)
            self.playerModel2.setPos(Vec3(self.playerModel2.getX()-self.speed2, self.playerModel2.getY(), self.playerModel2.getZ()))
        return Task.cont

    def right2(self):
        taskMgr.add(self.rightTask2,'rightTask2')
        self.charWalk2r.loop()
        #end right

    def rightTask2(self,task):
        if self.climbing2 == 0:
            self.playerModel2.setH(180)
            self.playerModel2.setPos(Vec3(self.playerModel2.getX()+self.speed2, self.playerModel2.getY(), self.playerModel2.getZ()))
        return Task.cont	

	def climbable2(self,cEntry):
		self.nodeCount2+=1
		#print self.nodeCount1
		self.ignore("o")
		self.ignore("o-up")
		self.ignore("l")
		self.ignore("l-up")
		self.acceptOnce("o",self.climbT2,[1])
		self.accept("o-up",self.noClimb2)
		self.acceptOnce("l",self.climbT2,[-1])
		self.accept("l-up",self.noClimb2)

	def climbT2(self,dir):
		self.dir2 = dir
		self.climbing2 = 1
		self.climbSpeed2 = 1
		self.ignore("k")
		self.ignore("k-up")
		self.ignore(";")
		self.ignore(";-up")
		taskMgr.add(self.climbTask2,'climbTask2')
		self.climb2.loop()
		
	def noClimb2(self):
		taskMgr.remove('climbTask2')
		self.climb2.pause()
		if self.nodeCount2 == 0:
			self.climbing2 = 0
		self.climbSpeed2 = 0
		self.acceptOnce("o",self.climbT2,[1])
		self.acceptOnce("l",self.climbT2,[-1])
		
	def jumpable2(self,cEntry):
		self.nodeCount2+=-1
		#print self.nodeCount2
		if self.nodeCount2 == 0:
			taskMgr.remove('climbTask2')
			self.ignore("o")
			self.ignore("o-up")
			self.ignore("l")
			self.ignore("l-up")
			self.acceptOnce("o",self.jumpT2)
			self.acceptOnce("k",self.left2)
			self.acceptOnce(";",self.right2)
			self.accept("k-up",self.stopLeft2)
			self.accept(";-up",self.stopRight2)
			self.climbing2 = 0
			self.climbSpeed2 = 0
			self.climb2.pause()
			
	def walkable2(self,cEntry):
		self.ignore("o")
		self.ignore("o-up")
		self.ignore("l")
		self.ignore("l-up")
		self.acceptOnce("o",self.climbT2,[1])
		self.accept("o-up",self.noClimb2)
		self.acceptOnce("l",self.climbT2,[-1])
		self.accept("l-up",self.noClimb2)
		self.acceptOnce("k",self.left2)
		self.acceptOnce(";",self.right2)
		self.accept("k-up",self.stopLeft)
		self.accept(";-up",self.stopRight)
		self.climbing2 = 0
		self.climbSpeed2 = 0
		self.climb2.pause()
			
	def climbTask2(self,task):
		if self.playerModel2.getZ() >=0:
			self.playerModel2.setH(90)
			self.playerModel2.setPos(Vec3(self.playerModel2.getX(), self.playerModel2.getY(), self.playerModel2.getZ()+self.climbSpeed2*self.dir2))
		return Task.cont	

    def jumpT2(self):
        if self.nodeCount2 == 0:
            self.ignore("o")
            self.ignore("o-up")
            z = self.playerModel2.getZ()
            j = ProjectileInterval(self.playerModel2, startPos = self.playerModel2.getPos(), startVel = Point3(3,0,30), duration = 2.0)
            j.start()
            taskMgr.doMethodLater(3,self.jumpTask2,"jumpTask2")
        else:
            self.acceptOnce("w",self.climb,[1])
        
    def jumpTask2(self, task):
        if self.climbing2 == 0:
            self.jump2.pause()
            self.acceptOnce("o",self.jumpT2)
        #return task.cont

	def allowRight2(self):
		self.acceptOnce(";",self.right2)

    def noRight2(self):
        taskMgr.remove('rightTask2')
        self.charWalk2r.pause()
        self.acceptOnce(";",self.right2)

    def stopRight2(self):
        self.noRight2()
        #self.allowRight()
        
    def rightWall2(self,cEntry):
        self.ignore(";")
        self.noRight2()
        
    def rightEdge2(self,cEntry):
        self.ignore(";")
        self.noRight2()

    def rightOK2(self,cEntry):
        self.allowRight2()	
    
    def allowLeft2(self):
        self.acceptOnce("k",self.left2)

    def noLeft2(self):
        taskMgr.remove('leftTask2')
        self.charWalk2l.pause()
        self.acceptOnce("k",self.left2)

    def stopLeft2(self):
        self.noLeft2()
        #self.allowLeft()
        
    def leftWall2(self,cEntry):
        self.ignore("k")
        self.noLeft2()
        
    def leftEdge2(self,cEntry):
        self.ignore("k")
        self.noLeft2()
        
    def leftOK2(self,cEntry):
        self.allowLeft2()
    
    def setupCollisions(self):
	self.cHandler = PhysicsCollisionHandler()
        #self.cHandler.setInPattern("ate-%in")
        self.cHandler.addInPattern('%fn-into-%in')
	#self.cHandler2.addInPattern('%fn-into-%in')         
        self.cHandler.setAgainPattern('%fn-again-%in')          
        self.cHandler.setOutPattern('%fn-outof-%in')        
        self.cTrav = CollisionTraverser()
	#self.cTrav2 = CollisionTraverser()
        base.cTrav = self.cTrav
	
        #Player 1 collision solid
        bounds = self.playerModel.getChild(0).getBounds()
        center = bounds.getCenter()-Vec3(0,0,12)
        radius = bounds.getRadius()-18
        boundsB = self.playerModel.getChild(0).getBounds()
        centerB = bounds.getCenter()-Vec3(0,0,-4)
        radiusB = bounds.getRadius()-20
        cSphere = CollisionSphere(center,radius)
        cSphereB = CollisionSphere(centerB,radiusB)
        cNode = CollisionNode("player1")
        #print radius, radiusB
        cNode.addSolid(cSphere)
        cNode.addSolid(cSphereB)
        cNodePath = self.playerModel.attachNewNode(cNode)
        cNodePath.show()
        
        Node=NodePath(PandaNode("PhysicsNode"))
        Node.reparentTo(render)
        self.an1=ActorNode("player1-physics")
        self.anp=Node.attachNewNode(self.an1)
        base.physicsMgr.attachPhysicalNode(self.an1)
        self.playerModel.reparentTo(self.anp)
	#self.anp.reparentTo(self.playerModel)
	
        #Player 2 collision solid
        bounds2 = self.playerModel2.getChild(0).getBounds()
        center2 = bounds2.getCenter()-Vec3(0,0,-4)
        radius2 = bounds2.getRadius()-20
        cSphere2 = CollisionSphere(center2,radius2)
        bounds2B = self.playerModel2.getChild(0).getBounds()
        center2B = bounds2B.getCenter()-Vec3(0,0,12)
        radius2B = bounds2B.getRadius()-18
        cSphere2B = CollisionSphere(center2B,radius2B)
        cNode2 = CollisionNode("player2")
        #print radius2, radius2B
        cNode2.addSolid(cSphere2)
        cNode2.addSolid(cSphere2B)
        cNodePath2 = self.playerModel2.attachNewNode(cNode2)
        cNodePath2.show()
        
        Node2=NodePath(PandaNode("PhysicsNode"))
        Node2.reparentTo(render)
        self.an2=ActorNode("player2-physics")
        self.anp2=Node2.attachNewNode(self.an2)
        base.physicsMgr.attachPhysicalNode(self.an2)
        self.playerModel2.reparentTo(self.anp2)
        #self.anp2.reparentTo(self.playerModel2)
	
        gravityFN=ForceNode('world-forces')
        gravityFNP=render.attachNewNode(gravityFN)
        gravityForce=LinearVectorForce(0,0,-9.8) #gravity acceleration
        gravityFN.addForce(gravityForce)
        
        base.physicsMgr.addLinearForce(gravityForce)
	self.an1.getPhysicsObject().setMass(15)
	self.an2.getPhysicsObject().setMass(15)
	gravityForce.setMassDependent(1)
        
        self.cHandler.addCollider(cNodePath, self.anp)
        self.cHandler.addCollider(cNodePath2, self.anp2)
        self.cTrav.addCollider(cNodePath,self.cHandler)
        self.cTrav.addCollider(cNodePath2,self.cHandler)
        self.cTrav.addCollider(cNodePath,self.cHandler)
        self.cTrav.addCollider(cNodePath2,self.cHandler)
	#self.cTrav.addCollider(cNodePath,self.cHandler2)
        #self.cTrav.addCollider(cNodePath2,self.cHandler2)
        #self.cTrav2.addCollider(cNodePath,self.cHandler2)
        #self.cTrav2.addCollider(cNodePath2,self.cHandler2)
	
	#cHandler2 = CollisionHandlerEvent()
	#cHandler2.addInPattern('%fn-into-%in')
	#self.cTrav.addCollider(cNodePath1,cHandler2)
        #self.cTrav.addCollider(cNodePath2,cHandler2)
	
        for i in range(self.ballNum+1):
            boundsB = self.ball[i].getChild(0).getBounds()
            centerB = boundsB.getCenter()
            radiusB = boundsB.getRadius()*0.65
            cSphereB = CollisionSphere(centerB,radiusB)
            cNodeB = CollisionNode("ball")
            cNodeB.addSolid(cSphereB)
            cNodePathB = self.ball[i].attachNewNode(cNodeB)
	    #self.cTrav.addCollider(cNodePathB,self.cHandler)

            #cNodePathB.show()
	
	self.accept("player1-into-ball",self.acquire1)
	#self.accept("ball-into-player1",self.acquire1)
	self.accept("player2-into-ball",self.acquire2)
	#self.accept("ball-into-player2",self.acquire2)
	#self.accept( 'player1-into2-platform', self.wall1)
        #self.accept( 'player2-into2-platform', self.wall2)
        
    def wall1(self,cEntry):
	self.an1.getPhysicsObject().setVelocity(Vec3(0,0,0))
	
    def wall2(self,cEntry):
	self.an2.getPhysicsObject().setVelocity(Vec3(0,0,0))
	
    def player1Wins(self,cEntry):
	if self.player2Invincible == 0:
		self.player1Score+=10
		self.reset()
	
    def player2Wins(self,cEntry):
	if self.player1Invincible == 0:
		self.player2Score+=10
		self.reset()
		
    def acquire1(self,cEntry):
	self.playerModel.setY(0)
	if str(cEntry.getIntoNodePath().getParent()) == "render/sawball":
	    self.player1Weapon = "saw"
	    saw = loader.loadModel("models/gamedev/saw")
	    saw.setScale(2.5)
	    self.jNP.getChildren().detach()
	    saw.reparentTo(self.jNP)
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/moltovball":
	    self.player1Weapon = "molotov"
	    molo = loader.loadModel("models/gamedev/moltov")
	    molo.setScale(2.5)
	    #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2")
	    self.jNP.getChildren().detach()
	    molo.reparentTo(self.jNP)
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/grenadeball":
	    self.player1Weapon = "grenade"
	    gren = loader.loadModel("models/gamedev/grenade")
	    gren.setScale(2.5)
	    #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2")
	    self.jNP.getChildren().detach()
	    gren.reparentTo(self.jNP)
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/pogo": #done
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "jump"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/golden": #done
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "speedUp"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/crystalball":
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "icestage"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/fireball": #done
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "meteo"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/blackball": #done
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "blind"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/translucent":
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "invis"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/superball": #done
	    self.jNP.getChildren().detach()
	    self.player1Weapon = "invincible"
	    self.acceptOnce("e",self.useWeapon1)
	    self.acceptOnce("q",self.useWeapon1)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/death": #done
	    self.jNP.getChildren().detach()
	    if self.player1Invincible == 0:
		self.player2Deaths+= 1
		self.reset()
	
	cEntry.getIntoNodePath().getParent().removeNode()
		
	#Drop a New Ball
	self.ballNum+=1
	z=random.randint(1,2)
	if z ==1:
		z=-1
	else:
		z=1
	self.movement.append(Vec3(random.random()*z,0,random.random()*z))
	weapBalls.define(self.ball,self.ballNum,render)
	
	boundsB = self.ball[self.ballNum].getChild(0).getBounds()
	centerB = boundsB.getCenter()
	radiusB = boundsB.getRadius()*.65
	cSphereB = CollisionSphere(centerB,radiusB)
	cNodeB = CollisionNode("ball")
	cNodeB.addSolid(cSphereB)
	cNodePathB = self.ball[self.ballNum].attachNewNode(cNodeB)
		
    def acquire2(self,cEntry):
	if str(cEntry.getIntoNodePath().getParent()) == "render/sawball":
	    self.player2Weapon = "saw"
	    saw = loader.loadModel("models/gamedev/saw")
	    saw.setScale(2.5)
	    self.jNP2.getChildren().detach()
	    saw.reparentTo(self.jNP2)
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/moltovball":
	    self.player2Weapon = "molotov"
	    molo = loader.loadModel("models/gamedev/moltov")
	    molo.setScale(2.5)
	    #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2")
	    self.jNP.getChildren().detach()
	    molo.reparentTo(self.jNP)
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/grenadeball":
	    self.player2Weapon = "grenade"
	    gren = loader.loadModel("models/gamedev/grenade")
	    gren.setScale(2.5)
	    #self.jNP = self.playerModel.exposeJoint(None,"modelRoot","ikHandle2")
	    self.jNP.getChildren().detach()
	    gren.reparentTo(self.jNP)
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/pogo": #done
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "jump"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/golden": #done
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "speedUp"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/crystalball":
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "icestage"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/fireball": #done
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "meteo"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/blackball": #done
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "blind"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/translucent":
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "invis"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/superball": #done
	    self.jNP.getChildren().detach()
	    self.player2Weapon = "invincible"
	    self.acceptOnce("e",self.useWeapon2)
	    self.acceptOnce("q",self.useWeapon2)
	elif str(cEntry.getIntoNodePath().getParent()) == "render/death": #done
	    self.jNP.getChildren().detach()
	    if self.player2Invincible == 0:
		self.player1Score+=3
		self.reset()
	
	cEntry.getIntoNodePath().getParent().removeNode()
		
	#Drop a New Ball
	self.ballNum+=1
	z=random.randint(1,2)
	if z ==1:
		z=-1
	else:
		z=1
	self.movement.append(Vec3(random.random()*z,0,random.random()*z))
	weapBalls.define(self.ball,self.ballNum,render)
	
	boundsB = self.ball[self.ballNum].getChild(0).getBounds()
	centerB = boundsB.getCenter()
	radiusB = boundsB.getRadius()*.65
	cSphereB = CollisionSphere(centerB,radiusB)
	cNodeB = CollisionNode("ball")
	cNodeB.addSolid(cSphereB)
	cNodePathB = self.ball[self.ballNum].attachNewNode(cNodeB)

    def useWeapon1(self):
	if self.player1Weapon == "meteo":
		fireRain = Sequence(Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), 
		Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain))
		fireRain.start()
	elif self.player1Weapon == "jump":
		self.playerModel.detachNode()
		self.playerModel.reparentTo(render)
		angle = (self.playerModel.getH())*math.pi/180.0
		ProjectileInterval(self.playerModel, startPos = Point3(self.playerModel.getPos()),startVel = Point3(math.sin(angle)*30,0,100), duration= 4.0).start()
	elif self.player1Weapon == "speedUp":
		self.speed1 = 6
		taskMgr.doMethodLater(5,self.restoreSpeedBG,"restoreStuff")
	elif self.player1Weapon == "blind":
		camera.setPos(Vec3(-50,0,0))
		taskMgr.doMethodLater(5,self.restoreCamera,"restoreCamera")
	elif self.player1Weapon == "invincible":
		self.player1Invincible = 1
		taskMgr.doMethodLater(5,self.notInvince1,"mortal1")
	elif self.player1Weapon == "grenade":
		self.jNP.getChildren().detach()
		gren = loader.loadModel("models/gamedev/grenade")
		gren.setScale(2.5)
		gren.reparentTo(render)
		angle = (self.playerModel.getH())*math.pi/180.0
		ProjectileInterval(gren, startPos = Point3(self.playerModel.getPos()),startVel = Point3(math.sin(angle)*30,0,10), endZ = -50).start()
		if gren.getZ() == -50:
			gren.removeNode()
		cHandler = CollisionHandlerEvent()
		cHandler.addInPattern('%fn-into-%in')
		boundsB = gren.getChild(0).getBounds()
		centerB = boundsB.getCenter()
		radiusB = boundsB.getRadius()*0.65
		cSphereB = CollisionSphere(centerB,radiusB)
		cNodeB = CollisionNode("grenade")
		cNodeB.addSolid(cSphereB)
		cNodePathB = gren.attachNewNode(cNodeB)
		self.cTrav.addCollider(cNodePathB,cHandler)
		
		self.acceptOnce("grenade-into-platform",self.explode)
		
	elif self.player1Weapon == "molotov":
		self.jNP.getChildren().detach()
	elif self.player1Weapon == "saw":
		self.jNP.getChildren().detach()
	elif self.player1Weapon == "invis":
		self.jNP.getChildren().detach()
		self.playerModel2.hide()
		taskMgr.doMethodLater(4.0,self.showPlayer,"showPlayer")
	elif self.player1Weapon == "icestage":
		self.jNP.getChildren().detach()
		self.speed1 = 6
		self.speed2 = 6
		self.background.detachNode()
		self.background2.reparentTo(render)
		taskMgr.doMethodLater(5,self.restoreSpeedBG,"restoreStuff")
		
    def restoreSpeedBG(self,task):
	self.speed1 = 3
	self.speed2 = 3
	self.background2.detachNode()
	self.background.reparentTo(render)
	
    def showPlayer(self,task):
	self.playerModel.show()
	self.playerModel2.show()
	
    def useWeapon2(self):
	if self.player2Weapon == "meteo":
		fireRain = Sequence(Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), 
		Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain), Wait(.5), Func(self.rain))
		fireRain.start()
	elif self.player2Weapon == "jump":
		angle = self.playerModel2.getH()/90
		ProjectileInterval(self.playerModel2, startPos = Point3(self.playerModel2.getPos()),startVel = Point3(angle*30,0,100), endZ = self.playerModel2.getZ()).start()
	elif self.player2Weapon == "speedUp":
		self.speed2 = 6
	elif self.player2Weapon == "blind":
		camera.setPos(Vec3(-50,0,0))
		taskMgr.doMethodLater(5,self.restoreCamera,"restoreCamera")
	elif self.player2Weapon == "invincible":
		self.player2Invincible = 1
		taskMgr.doMethodLater(5,self.notInvince2,"mortal2")
	elif self.player2Weapon == "grenade":
		self.jNP2.getChildren().detach()
		gren = loader.loadModel("models/gamedev/grenade")
		gren.setScale(2.5)
		gren.reparentTo(render)
		angle = (self.playerModel2.getH())*math.pi/180.0
		ProjectileInterval(gren, startPos = Point3(self.playerModel2.getPos()),startVel = Point3(math.sin(angle)*30,0,10), endZ = -50).start()
		if gren.getZ() == -50:
			gren.removeNode()
		cHandler = CollisionHandlerEvent()
		cHandler.addInPattern('%fn-into-%in')
		boundsB = gren.getChild(0).getBounds()
		centerB = boundsB.getCenter()
		radiusB = boundsB.getRadius()*0.65
		cSphereB = CollisionSphere(centerB,radiusB)
		cNodeB = CollisionNode("grenade")
		cNodeB.addSolid(cSphereB)
		cNodePathB = gren.attachNewNode(cNodeB)
		self.cTrav.addCollider(cNodePathB,cHandler)
		
		self.acceptOnce("grenade-into-platform",self.explode)
		
	elif self.player2Weapon == "molotov":
		self.jNP.getChildren().detach()
	elif self.player2Weapon == "saw":
		self.jNP.getChildren().detach()
	elif self.player2Weapon == "invis":
		self.jNP.getChildren().detach()
		self.playerModel1.hide()
		taskMgr.doMethodLater(4.0,self.showPlayer,"showPlayer")
	elif self.player2Weapon == "icestage":
		self.jNP2.getChildren().detach()
		self.speed1 = 6
		self.speed2 = 6
		self.background.detachNode()
		self.background2.reparentTo(render)
		taskMgr.doMethodLater(5,self.restoreSpeedBG,"restoreStuff")
		
    def rain(self):
	    meteoBall = Actor("models/gamedev/fireball")
	    meteoBall.reparentTo(render)
	    meteoBall.setScale(2)
	    meteoBall.setH(-15)
	    boundsB = meteoBall.getChild(0).getBounds()
            centerB = boundsB.getCenter()
            radiusB = boundsB.getRadius()*0.65
            cSphereB = CollisionSphere(centerB,radiusB)
            cNodeB = CollisionNode("meteor")
            cNodeB.addSolid(cSphereB)
            cNodePathB = meteoBall.attachNewNode(cNodeB)
	    #cNodePathB.show()
	    
	    ProjectileInterval(meteoBall, startPos = Point3(random.randint(15,211),0,170),startVel = Point3(-12,0,0), endZ = -50).start()
	    
	    cHandler = CollisionHandlerEvent()
	    cHandler.addInPattern('%fn-into-%in')
	    self.cTrav.addCollider(cNodePathB,cHandler)
	    self.accept("meteor-into-player1",self.player2Wins)
	    self.accept("meteor-into-player2",self.player1Wins)
	    
    def showBalls(self,task):
        for i in self.ball:
            i.show()
     
    def notInvince1(self,task):
	self.player1Invincible = 0
	
    def notInvince2(self,task):
        self.player2Invincible = 0

    def restoreCamera(self,task):
        camera.setPosHpr(Vec3(98,-390,90), Vec3(0,-5,0))
        
    def switch(self,task):
        self.environment.setColor(0,1,0.3)
        
    def colliding1( self, collEntry ): # accept a collision entry argument    
        if self.ignoreColl == 0:
            self.player1IsColliding = 1 # we are colliding        
            self.stopWalk( ) # pause all walking animation and movement        
            disp = ( collEntry.getSurfacePoint( render ) - collEntry.getInteriorPoint( render ) )
            newPos = self.playerModel2.getPos( ) + disp # get new position
            self.playerModel2.setPos( newPos ) # and set it to tiny's position
        # end colliding        
        
    def notColliding1( self, collEntry ): 
        self.player1IsColliding = 0    
        
    def colliding2( self, collEntry ): # accept a collision entry argument 
        if self.ignoreColl == 0:
            self.player2IsColliding = 1 # we are colliding        
            self.stopWalk2( ) # pause all walking animation and movement               
            disp = ( collEntry.getSurfacePoint( render ) - collEntry.getInteriorPoint( render ) )
            newPos = self.playerModel2B.getPos( ) + disp # get new position
            self.playerModel2B.setPos( newPos ) # and set it to tiny's position
        # end colliding        
        
    def notColliding2( self, collEntry ): 
        self.player2IsColliding = 0    
        
    def returnSpeeds(self,task):
        self.speed1 = 8.0
        self.speed2 = 8.0
        self.turnSpeed1 = 80.0
        self.turnSpeed2 = 80.0
        
    def returnSpeeds2(self,task):
        self.acceptOnce("w",self.walk)
        self.acceptOnce("o",self.walk2)
        self.speed1 = 8.0
        self.speed2 = 8.0
        self.turnSpeed1 = 80.0
        self.turnSpeed2 = 80.0
        
    def returnSpeeds3(self,task):
        self.speed1 = 8.0
        self.speed2 = 8.0
        self.turnSpeed1 = 80.0
        self.turnSpeed2 = 80.0
        
    def changeMusic(self,task):
        self.music.stop()
        self.music2  = loader.loadMusic("models/gamedev/ADRENALINE.mp3")
        self.music2.play()
        
    def clockTask(self,task):
        self.timer.detachNode()
        self.timer = OnscreenText("%d" % (self.gameLen-globalClock.getRealTime(),), pos = (98,145), scale = 18.0)
        self.timer.setColor(1,1,1)
        self.timer.reparentTo(render)
        return Task.cont
    
    def ballMovementTask(self,task):
	self.anp.setY(0)
	self.anp2.setY(0)
	for i in range(self.ballNum+1):
		if i < len(self.ball):
			if self.ball[i].getX() > 234 or self.ball[i].getX() < -38 or self.ball[i].getZ() < -10 or self.ball[i].getZ() > 132:
				self.ball[i].setPos(self.ball[i].getPos()/1.005)
				z=random.randint(1,2)
				if z ==1:
					z=-1
				else:
					z=1
				self.movement[i]=Vec3(random.random()*z,0,random.random()*z)
			else:
				self.ball[i].setPos(self.ball[i].getPos()+self.movement[i])
	return Task.cont
	
    def fire(self):
        
        self.fire = ParticleEffect()
        
        self.fire.reset()
        self.fire.setPos(0.000, 0.000, 0.000)
        self.fire.setHpr(0.000, 0.000, 0.000)
        self.fire.setScale(10.000, 10.000, 10.000)
        p0 = Particles('particles-1')
        # Particles parameters
        p0.setFactory("PointParticleFactory")
        p0.setRenderer("SpriteParticleRenderer")
        p0.setEmitter("DiscEmitter")
        p0.setPoolSize(1024)
        p0.setBirthRate(0.0200)
        p0.setLitterSize(10)
        p0.setLitterSpread(0)
        p0.setSystemLifespan(1200.0000)
        p0.setLocalVelocityFlag(1)
        p0.setSystemGrowsOlderFlag(0)
        # Factory parameters
        p0.factory.setLifespanBase(2.0000)
        p0.factory.setLifespanSpread(0.0000)
        p0.factory.setMassBase(1.0000)
        p0.factory.setMassSpread(0.0000)
        p0.factory.setTerminalVelocityBase(400.0000)
        p0.factory.setTerminalVelocitySpread(0.0000)
        # Point factory parameters
        # Renderer parameters
        p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAOUT)
        p0.renderer.setUserAlpha(0.22)
        # Sprite parameters
        p0.renderer.addTextureFromFile('models/gamedev/sparkle.png')
        p0.renderer.setColor(Vec4(1.00, 1.00, 1.00, 1.00))
        p0.renderer.setXScaleFlag(1)
        p0.renderer.setYScaleFlag(1)
        p0.renderer.setAnimAngleFlag(0)
        p0.renderer.setInitialXScale(0.5000)
        p0.renderer.setFinalXScale(2.0000)
        p0.renderer.setInitialYScale(1.0000)
        p0.renderer.setFinalYScale(2.0000)
        p0.renderer.setNonanimatedTheta(0.0000)
        p0.renderer.setAlphaBlendMethod(BaseParticleRenderer.PPNOBLEND)
        p0.renderer.setAlphaDisable(0)
        # Emitter parameters
        p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE)
        p0.emitter.setAmplitude(1.0000)
        p0.emitter.setAmplitudeSpread(0.0000)
        p0.emitter.setOffsetForce(Vec3(0.0000, 0.0000, 3.0000))
        p0.emitter.setExplicitLaunchVector(Vec3(1.0000, 0.0000, 0.0000))
        p0.emitter.setRadiateOrigin(Point3(0.0000, 0.0000, 0.0000))
        # Disc parameters
        p0.emitter.setRadius(0.5000)
        self.fire.addParticles(p0)
        
        self.fire.setPos(self.playerModel2.getPos())
        
        t = Sequence(Func(self.fire.start, render, render),Wait(20),Func(self.cleanFire))
        t.start()
 
    def cleanFire(self):
        self.fire.cleanup()

    def explode(self,cEntry):

        self.explosion = ParticleEffect()
        
        self.explosion.reset()
        self.explosion.setPos(cEntry.getIntoNodePath().getParent().getPos())
        self.explosion.setHpr(0.000, 0.000, 0.000)
        self.explosion.setScale(10.000, 10.000, 10.000)
        p0 = Particles('particles-1')
        # Particles parameters
        p0.setFactory("PointParticleFactory")
        p0.setRenderer("LineParticleRenderer")
        p0.setEmitter("SphereVolumeEmitter")
        p0.setPoolSize(10000)
        p0.setBirthRate(0.0500)
        p0.setLitterSize(10000)
        p0.setLitterSpread(0)
        p0.setSystemLifespan(2.0000)
        p0.setLocalVelocityFlag(1)
        p0.setSystemGrowsOlderFlag(1)
        # Factory parameters
        p0.factory.setLifespanBase(2.0000)
        p0.factory.setLifespanSpread(0.0000)
        p0.factory.setMassBase(.5000)
        p0.factory.setMassSpread(0.0500)
        p0.factory.setTerminalVelocityBase(400.0000)
        p0.factory.setTerminalVelocitySpread(0.0000)
        # Point factory parameters
        # Renderer parameters
        p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAOUT)
        p0.renderer.setUserAlpha(1.00)
        # Line parameters
        p0.renderer.setHeadColor(Vec4(1.00, 0.00, 0.00, 1.00))
        p0.renderer.setTailColor(Vec4(1.00, 1.00, 0.00, 1.00))
        p0.renderer.setLineScaleFactor(3.00)
        # Emitter parameters
        p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE)
        p0.emitter.setAmplitude(10.0000)
        p0.emitter.setAmplitudeSpread(0.0000)
        p0.emitter.setOffsetForce(Vec3(0.0000, 0.0000, -0.4930))
        p0.emitter.setExplicitLaunchVector(Vec3(1.0000, 0.0000, 0.0000))
        p0.emitter.setRadiateOrigin(Point3(0.0000, 0.0000, 0.0000))
        # Sphere Volume parameters
        p0.emitter.setRadius(0.5000)
        self.explosion.addParticles(p0)
        f0 = ForceGroup('gravity')
        # Force parameters
        self.explosion.addForceGroup(f0)
        
	cHandler = CollisionHandlerEvent()
	cHandler.addInPattern('%fn-into-%in')
	cSphereB = CollisionSphere(cEntry.getIntoNodePath().getParent().getPos(),1)
	cNodeB = CollisionNode("explosion")
	cNodeB.addSolid(cSphereB)
	cNodePathB = self.explosion.attachNewNode(cNodeB)
	self.cTrav.addCollider(cNodePathB,cHandler)
	cNodePathB.show()
        
	self.accept("player1-into-explosion",self.player2Wins)
	self.accept("player2-into-explosion",self.player1Wins)
        #f.reparentTo(self.playerModel)
        #self.explosion.setPos(self.playerModel.getPos())

        t = Sequence(Func(self.explosion.start, render, render),Wait(2),Func(self.cleanExplo))
        t.start()
	cEntry.getFromNodePath().getParent().removeNode()
        
    def cleanExplo(self):
        self.explosion.cleanup()

    def endGame(self,task):
        taskMgr.removeTasksMatching('returnSpeedsToNormal')
        taskMgr.removeTasksMatching('restoreCamera')
	taskMgr.removeTasksMatching('clockTask')
	taskMgr.removeTasksMatching('ballMoveTask')
	
	self.music.stop()

        self.music3  = loader.loadMusic("models/gamedev/CSTAR.mp3")
        self.music3.play()
        
        self.speed1 = 0
        self.speed2 = 0

    def getScores(self):
	return (self.player1Score, self.player2Score)
		
    def getGameLen(self):
	return self.gameLen
		
    def stopMusic(self):
	self.music3.stop()
	
    def destroy(self):
	self.playerModel.detachNode()
	self.playerModel2.detachNode()
	self.background.destroy()
	self.lava.detachNode()
	self.ladder.detachNode()
	self.ladder2.detachNode()
	
	for i in range(self.ballNum+1):
	    self.ball[i].detachNode()
	    
    def stopMusic(self):
        self.music3.stop()
        
#world = Lvl03()
#world.start()
#run()
Exemple #23
0
 def cleanup(self):
     self.__stopCleanupTask()
     try:
         ParticleEffect.cleanup(self)
     except:
         pass
Exemple #24
0
class GrenadeLauncher:
    """Grenade launcher locomotive upgrade.

    Represents an active weapon, which can
    do a lot of damage on some radius.

    Args:
        loc_model (panda3d.core.NodePath): The locomotive model.
    """

    def __init__(self, loc_model):
        self.is_up = False
        # flag, which indicates if the launcher
        # is in (un-)loading process
        self._is_loading = False
        self._range_col_np = None

        self._loc_model = loc_model

        self._model = Actor(address("grenade_launcher"))
        self._model.reparentTo(loc_model)

        self._sight = loader.loadModel(address("grenade_sight"))  # noqa: F821
        self._sight.reparentTo(loc_model)
        self._sight.hide()

        self._grenade_explosion = ParticleEffect()
        self._grenade_explosion.loadConfig("effects/grenade_explode.ptf")

        self._grenade_smoke = ParticleEffect()
        self._grenade_smoke.loadConfig("effects/bomb_smoke1.ptf")

        self._hole_sprite = loader.loadModel(address("ground_hole"))  # noqa: F821
        self._hole_sprite.reparentTo(loc_model)
        self._hole_sprite.setTransparency(TransparencyAttrib.MAlpha)
        self._hole_sprite.hide()

        base.accept("1", self.change_state)  # noqa: F821

        self._shot_snd = loader.loadSfx(  # noqa: F821
            "sounds/combat/grenade_launcher_shot.ogg"
        )
        self._explosion_snd = loader.loadSfx(  # noqa: F821
            "sounds/combat/bomb_explosion1.ogg"
        )
        self._explosion_snd.setVolume(0.15)

        self._load_snd = loader.loadSfx(  # noqa: F821
            "sounds/combat/grenade_launcher_load.ogg"
        )

    def _change_mode(self, task):
        """Change controls mode - common or grenade launcher shooting."""
        if self.is_up:
            self._sight.hide()
            self._end_aiming()
        else:
            self._smoke = ParticleEffect()
            self._smoke.loadConfig("effects/grenade_launcher_smoke.ptf")
            self._smoke.setPos(0.026, -0.15, 0.35)

            taskMgr.doMethodLater(  # noqa: F821
                0.05, self._sight.show, "show_sight", extraArgs=[]
            )
            base.common_ctrl.deselect()  # noqa: F821
            self._start_aiming()

        self.is_up = not self.is_up
        self._is_loading = False
        return task.done

    def change_state(self):
        """Change the launcher state."""
        if not base.world.is_on_et or self._is_loading:  # noqa: F821
            return

        base.train.disable_enabled_weapon(self)  # noqa: F821

        self._is_loading = True
        self._model.setPlayRate(-4 if self.is_up else 4, "gun_up")
        self._model.play("gun_up")

        if not self.is_up:
            self._load_snd.play()

        taskMgr.doMethodLater(  # noqa: F821
            0.2, self._change_mode, "grenade_launcher_aim"
        )

    def _do_grenade_damage(self, event):
        """Event which is called by the grenade explosion.

        The method do damage to the enemy units, which
        were in the grenade explosion area.
        """
        base.world.enemy.active_units[  # noqa: F821
            event.getFromNodePath().getName()
        ].get_damage(40)

    def _end_aiming(self):
        """Stop aiming and disable aiming GUI."""
        self._range_col_np.removeNode()
        base.common_ctrl.set_mouse_events()  # noqa: F82

    def _explode_grenade(self, grenade_pos):
        """Explode the grenade, shot from the launcher.

        Args:
            grenade_pos (panda3d.core.Point3):
                The position, where the sight was
                when player made the shot.
        """
        col_node = CollisionNode("grenade_explosion")
        col_node.setFromCollideMask(NO_MASK)
        col_node.setIntoCollideMask(SHOT_RANGE_MASK)
        col_node.addSolid(CollisionSphere(0, 0, 0, 0.096))

        base.accept("into-grenade_explosion", self._do_grenade_damage)  # noqa: F821

        col_np = self._model.attachNewNode(col_node)
        col_np.setPos(grenade_pos)

        self._hole_sprite.setPos(grenade_pos)
        self._hole_sprite.wrtReparentTo(
            base.world.current_block.rails_mod  # noqa: F821
        )
        self._hole_sprite.show()

        self._grenade_explosion.setPos(grenade_pos)
        self._grenade_explosion.start(self._model, render)  # noqa: F821
        self._grenade_explosion.softStart()

        self._grenade_smoke.setPos(grenade_pos)
        self._grenade_smoke.start(self._model, render)  # noqa: F82
        self._grenade_smoke.softStart()

        self._explosion_snd.play()

        taskMgr.doMethodLater(  # noqa: F821
            1, self._grenade_explosion.softStop, "stop_grenade_explosion", extraArgs=[]
        )
        taskMgr.doMethodLater(  # noqa: F821
            2.5, self._grenade_smoke.softStop, "stop_grenade_smoke", extraArgs=[]
        )
        taskMgr.doMethodLater(  # noqa: F821
            0.1, col_np.removeNode, "remove_grenade_solid", extraArgs=[]
        )
        taskMgr.doMethodLater(  # noqa: F821
            4, self._return_hole_sprite, "hide_ground_hole",
        )

    def _return_hole_sprite(self, task):
        """Return the hole sprite to the grenade launcher model."""
        self._hole_sprite.hide()
        self._hole_sprite.reparentTo(self._loc_model)
        return task.done

    def _move_sight(self, event):
        """Move the launcher sight sprite.

        The launcher sight can be moved only
        within the Train part shooting range.
        """
        if event.getIntoNodePath().getName() != "grenade_launcher_range":
            return

        point = event.getSurfacePoint(base.train.model)  # noqa: F821
        self._sight.setPos(point.getX(), point.getY(), 0.01)

    def _shot(self):
        """Make a shot."""
        self._shot_snd.play()
        self.change_state()
        base.ignore("1")  # noqa: F82

        self._smoke.start(self._model, render)  # noqa: F82
        self._smoke.softStart()

        taskMgr.doMethodLater(  # noqa: F82
            0.5,
            self._explode_grenade,
            "explode_grenade",
            extraArgs=[self._sight.getPos()],
        )
        taskMgr.doMethodLater(  # noqa: F82
            1.45, self._stop_smoke, "stop_launcher_smoke"
        )
        taskMgr.doMethodLater(  # noqa: F82
            13,
            base.accept,  # noqa: F82
            "unblock_launcher",
            extraArgs=["1", self.change_state],
        )
        base.train.make_shot("Grenade Launcher")  # noqa: F82

    def _start_aiming(self):
        """Show aiming GUI and tweak shooting events."""
        col_node = CollisionNode("grenade_launcher_range")
        col_node.setFromCollideMask(NO_MASK)
        col_node.setIntoCollideMask(MOUSE_MASK)

        col_node.addSolid(
            CollisionPolygon(
                Point3(-1.2, -0.3, 0),
                Point3(-1.2, 1.5, 0),
                Point3(1.2, 1.5, 0),
                Point3(1.2, -0.3, 0),
            )
        )
        self._range_col_np = base.train.model.attachNewNode(col_node)  # noqa: F821

        base.accept("mouse1", self._shot)  # noqa: F821
        base.accept("mouse_ray-into", self._move_sight)  # noqa: F821
        base.accept("mouse_ray-again", self._move_sight)  # noqa: F82

    def _stop_smoke(self, task):
        """Stop the launcher shot smoke."""
        self._smoke.disable()
        self._smoke.cleanup()
        return task.done
class TossTrapGag(TrapGag):
    def __init__(self,
                 name,
                 model,
                 damage,
                 hitSfx,
                 idleSfx=None,
                 particlesFx=None,
                 anim=None,
                 wantParticles=True):
        TrapGag.__init__(self, name, model, damage, hitSfx, anim)
        self.wantParticles = wantParticles
        self.particles = None
        self.particlesFx = particlesFx
        self.idleSfx = None
        self.timeout = 5.0

        if game.process == 'client':
            if idleSfx:
                self.idleSfx = base.audio3d.loadSfx(idleSfx)

    def startTrap(self):
        TrapGag.startTrap(self)
        if not self.gag:
            self.build()
            self.setHandJoint()
        self.gag.reparentTo(self.handJoint)
        self.avatar.play('toss', fromFrame=22)

    def build(self):
        TrapGag.build(self)
        self.buildParticles()
        self.setHandJoint()

    def buildParticles(self):
        self.cleanupParticles()
        if hasattr(self, 'wantParticles') and hasattr(self, 'particlesFx'):
            if self.wantParticles and self.particlesFx:
                self.particles = ParticleEffect()
                self.particles.loadConfig(self.particlesFx)

    def buildCollisions(self):
        TrapGag.buildCollisions(self)
        gagSph = CollisionSphere(0, 0, 0, 1)
        gagSph.setTangible(0)
        gagNode = CollisionNode('gagSensor')
        gagNode.addSolid(gagSph)
        gagNP = self.entity.attachNewNode(gagNode)
        gagNP.setScale(0.75, 0.8, 0.75)
        gagNP.setPos(0.0, 0.1, 0.5)
        gagNP.setCollideMask(BitMask32.bit(0))
        gagNP.node().setFromCollideMask(CIGlobals.FloorBitmask)

        event = CollisionHandlerEvent()
        event.setInPattern("%fn-into")
        event.setOutPattern("%fn-out")
        base.cTrav.addCollider(gagNP, event)
        self.avatar.acceptOnce('gagSensor-into', self.onCollision)

    def onCollision(self, entry):
        TrapGag.onCollision(self, entry)
        x, y, z = self.entity.getPos(render)
        base.localAvatar.sendUpdate('setGagPos', [self.getID(), x, y, z])

    def release(self):
        throwPath = NodePath('ThrowPath')
        throwPath.reparentTo(self.avatar)
        throwPath.setScale(render, 1)
        throwPath.setPos(0, 160, -120)
        throwPath.setHpr(0, 90, 0)

        if not self.gag:
            self.build()

        self.entity = self.gag
        self.gag = None
        self.entity.wrtReparentTo(render)
        self.entity.setHpr(throwPath.getHpr(render))

        self.setHandJoint()
        self.track = ProjectileInterval(self.entity,
                                        startPos=self.handJoint.getPos(render),
                                        endPos=throwPath.getPos(render),
                                        gravityMult=0.9,
                                        duration=3)
        self.track.start()

        if self.isLocal():
            self.startTimeout()
            self.buildCollisions()
            self.avatar.acceptOnce('gagSensor-into', self.onCollision)

        self.reset()
        TrapGag.release(self)

    def delete(self):
        TrapGag.delete(self)
        self.cleanupParticles()

    def unEquip(self):
        TrapGag.unEquip(self)
        self.cleanupParticles()

    def cleanupParticles(self):
        if self.particles:
            self.particles.cleanup()
            self.particles = None
Exemple #26
0
class Tower(DirectObject.DirectObject):
    def __init__(self, pos):
        self.node = NodePath('tower-base-node')
        self.node.setTag('targetID', str(id(self)) )
        self.node.reparentTo(render)
        self.node.setPos(pos[0],pos[1],pos[2])
        self.collisionHandler = CollisionHandlerEvent()
        self.HP = 4
        
        self.loadModel()
        self.createCollisions()
        self.setUpEvents()
        self.aimTaskPointer = taskMgr.doMethodLater(0.04, self.aimTask, 'aim-task')
        self.target = render.find('**/player')
        
    '''
    aimTask
    Keeps the gun of the tower pointing at the player 
    '''        
    def aimTask(self,task):
        self.gun.lookAt(self.target)
        return task.again
    
    '''
    createCollisions
    This will add a collision sphere that can be hit by player
    and a segment for aiming. The segment will always point to the player,
    if the player touches the segment, the tower will start to fire.
    If the segment looses contact, the tower will hold it's fire.
    '''
    def createCollisions(self):
        # Set up the collision sphere
        self.cNode = CollisionNode('tower-cNode')
        self.cNode.addSolid(CollisionSphere(0,0,3, 3.0))
        # there is a list of all bitmasks in game.py
        self.cNode.setIntoCollideMask(BitMask32(0x2))
        self.cNode.setFromCollideMask(BitMask32.allOff())
        
        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        
        # add the aim segment
        self.aimCNodeSegment = CollisionNode('aimRay')
        self.aimCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 520, 0))
        # there is a list of all bitmasks in game.py
        self.aimCNodeSegment.setIntoCollideMask(BitMask32.allOff())
        self.aimCNodeSegment.setFromCollideMask(BitMask32(0x4))
        
        self.aimCNodeSegmentPath = self.gun.attachNewNode(self.aimCNodeSegment)
        #self.aimCNodeSegmentPath.show()
        self.collisionHandler.addInPattern('TowerShootStart')
        self.collisionHandler.addOutPattern('TowerShootStop')
        base.cTrav.addCollider(self.aimCNodeSegmentPath, self.collisionHandler)
        
    '''
    deleteTask
    task which calls the destructor after a given time (after the explosion animation)
    '''
    def deleteTask(self, task):
        self.__del__()
        return task.done
    
    '''
    explode
    this will cause the tower to explode with a nice particle effect.
    '''
    def explode(self):
        self.node.hide()
        self.cNodePath.removeNode()
        taskMgr.remove(self.aimTaskPointer)
        taskMgr.remove(self.shootTaskPointer)        
        
        self.particleEffect = ParticleEffect()
        self.particleEffect.loadConfig('media/explosion.ptf')
        self.particleEffect.start(self.node)
        self.particleEffect.setLightOff()
        self.deleteTask = taskMgr.doMethodLater(1, self.deleteTask, 'delete task')
 
        
    '''
    loadModel
    This will load all the visible stuff
    '''    
    def loadModel(self):
        self.nodeModel = loader.loadModel('tower')
        self.nodeModel.reparentTo(self.node)
        self.nodeModelIsland = loader.loadModel('turretIsland.egg')
        self.nodeModelIsland.reparentTo(self.node)

        self.gun = self.nodeModel.find('**/gun')
      
    '''
    setUpEvents
    This will set up the events the class will accept
    '''    
    def setUpEvents(self):
        # we use the unique id of the class here to prevent other towers to
        # react on this event
        self.accept(str(id(self))+'-evtGotHit', self.evtGotHit)
        self.accept('TowerShootStart', self.evtShootStart)
        self.accept('TowerShootStop', self.evtShootStop)
    
    '''
    shootTask
    this task will shoot  missiles until it gets removed
    '''    
    def shootTask(self, task):
        x = math.sin(math.radians(-self.gun.getH())) *(100)
        y = math.cos(math.radians(-self.gun.getH())) *(100)
        z = math.sin(math.radians(self.gun.getP())) *(100)
        x *= math.cos(math.radians(self.gun.getP()))
        y *= math.cos(math.radians(self.gun.getP()))
        
        Projectile(self.gun.getPos(render), Point3(x,y,z), self.gun.getHpr(), "tower-base-node")
        return task.again
    
    '''
    evtGotHit
    This event will be called if the tower gehts hit by a missile.
    It will reduce the HP by 1 each time.
    If HP reaches 0, the tower will explode
    '''
    def evtGotHit(self):
        self.HP -= 1
        if self.HP == 0:
            self.explode()
    
    '''
    evtShootStart
    This will make the tower start shooting by adding a "shootTask"
    '''
    def evtShootStart(self, entry):
        if entry.getIntoNodePath().getName() == 'player' and entry.getFromNodePath() == self.aimCNodeSegmentPath:
           self.shootTaskPointer = taskMgr.doMethodLater(0.8, self.shootTask, 'shoot task')
           
    '''
    evtShootStop
    This will make the tower stop shooting by removing the "shootTask"
    '''
    def evtShootStop(self, entry):
        if entry.getIntoNodePath().getName() == 'player' and entry.getFromNodePath() == self.aimCNodeSegmentPath:
            taskMgr.remove(self.shootTaskPointer)
    
    '''
    __del__
    destructor will remove particle effect, tasks and the whole node
    '''
    def __del__(self):
        self.particleEffect.cleanup()
        taskMgr.remove(self.deleteTask)
        messenger.send( 'tower-down' )
        self.node.removeNode()
Exemple #27
0
class Player(object,
             DirectObject.DirectObject):  #Class Player for the airplane
    def __init__(self):  #Class constructor
        self.node = 0  #the player main node
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 70
        self.speedMax = 100
        self.agility = 5
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        self.msg = MessageManager()
        self.roll = 0
        self.camHeight = 0
        global actualScore
        global firstRun
        firstRun = 0
        self.thisScore = OnscreenText(text='Score: ' + str(actualScore),
                                      pos=(1.32, 0.95),
                                      scale=0.07,
                                      fg=(1, 1, 1, 1),
                                      bg=(0.2, 0.2, 0.2, 0.4),
                                      align=TextNode.ARight)
        self.death = 0

        self.ultimaColisao = "InicioUltimaColisao"
        self.atualColisao = "InicioAtualColisao"

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)
        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    def loadModel(self):  #Function to load models and set physics
        #node path for player
        self.node = NodePath('player')
        self.node.setPos(1000, 500, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('gaivota')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #gravity (aceleration 9.82)
        self.gravityFN = ForceNode('world-forces')
        self.gravityFNP = render.attachNewNode(self.gravityFN)
        self.gravityForce = LinearVectorForce(0, 0, -9.82 / 8)
        self.gravityFN.addForce(self.gravityForce)

        #add gravity to engine
        base.physicsMgr.addLinearForce(self.gravityForce)

        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)

        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)

        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)

        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)

    def addCamera(self):  #Function that add camera to airplane
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    def addEvents(self):  #Functions for airplane events
        #self.accept( "wheel_up" , self.evtSpeedUp )#DEBUG
        #self.accept( "wheel_down" , self.evtSpeedDown )#DEBUG
        self.accept('hit', self.evtHit)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        #self.accept('mouse3',self.evtBoostOn) #DEBUG
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    def addCollisions(self):  #Functions that add collisions for the airplane
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNodePath = self.node.attachNewNode(self.cNode)

        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        #raio de colisao:
        self.cNodeRay = CollisionNode('playerDuto')
        self.cNodeRay.addSolid(CollisionRay(0, 0, -1, 0, 0, -1))
        self.cNodePathRay = self.node.attachNewNode(self.cNodeRay)
        base.cTrav.addCollider(self.cNodePathRay, self.collisionHandler)

        self.collisionHandler.addInPattern('hit')
        self.cNode.setIntoCollideMask(0)
        self.cNodeRay.setIntoCollideMask(0)

    def addSound(self):  #Function to add sound to airplane
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

        #Add environment music
        self.MusicSound = loader.loadSfx("warm-interlude.mp3")
        self.MusicSound.setLoop(True)
        self.MusicSound.play()
        self.MusicSound.setVolume(1.5)
        self.MusicSound.setPlayRate(1)

    def deleteTask(self, task):  #Function to delete task
        self.__del__()
        return task.done

    def mouseUpdateTask(self, task):  #Function that update mouse moviments
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    def moveUpdateTask(self, task):  #Function that update players position
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))
        # update scoring system
        global actualScore
        actualScore = actualScore - int((100 * globalClock.getDt()))
        self.thisScore.setText('Score: ' + str(actualScore))
        return task.cont

    def explode(self):  #Function that control the explosion of the airplane
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()

        #add explosion sound
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0],
                                                     base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('explosion.mp3')
        self.audio3d.detachSound(self.Sound)
        self.audio3d.attachSoundToObject(self.Sound, self.node)
        self.Sound.play()

        self.deleteTask = taskMgr.doMethodLater(
            2, self.deleteTask,
            'delete task')  # will delete Player within 1 second

    def beatLevel(self):  #Function that control the explosion of the airplane
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        self.MusicSound.stop()
        #Add end of level music
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0],
                                                     base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('FF7Fanfare.mp3')
        self.audio3d.detachSound(self.Sound)
        self.audio3d.attachSoundToObject(self.Sound, self.node)
        self.Sound.play()

        messenger.send('game-levelwin')
        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    def zoomTask(self, task):  #Function for zoom
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    def evtBoostOn(self):  #Function that increase speed
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    def evtBoostOff(self):  #Function that decrease speed
        self.speed -= 200
        self.ignore('mouse3-up')
        self.addEvents()
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    def evtHit(
        self, entry
    ):  #Function that controls the event when the airplane hit something
        #print "INTO " + entry.getIntoNodePath().getName()
        #print "FROM " + entry.getFromNodePath().getName()
        #print "PARENT " + entry.getIntoNodePath().getParent().getName()

        if entry.getFromNodePath().getName(
        ) == "playerDuto":  #if it's the collision ray
            self.ultimaColisao = self.atualColisao
            self.atualColisao = entry.getIntoNodePath().getName()
            #print "Ultima Colisao: "+self.ultimaColisao +" | Atual Colisao: " +self.atualColisao #Activate this when debugging
            if self.atualColisao == "duto":  #Plane entering wind area
                #print "ENTROU NO VENTO"  #Activate this when debugging
                #self.msg.addMessage("ENTROU NO VENTO", 1) #DEBUG
                self.vento = LinearVectorForce(0, 0, 50)
                self.gravityFN.addForce(self.vento)
                self.gNode.getPhysical(0).addLinearForce(self.vento)
            if self.ultimaColisao == "duto" and self.atualColisao != "duto":  #Plane entering wind area
                #print "SAIU DO VENTO"  #Activate this when debugging
                #self.msg.addMessage("SAIU DO VENTO", 1) #DEBUG
                self.vento = LinearVectorForce(0, 0, -65)
                self.gravityFN.addForce(self.vento)
                self.gNode.getPhysical(0).addLinearForce(self.vento)

        if entry.getFromNodePath().getName() == self.node.getName(
        ):  #if it's the player itself
            if entry.getIntoNodePath().getParent().getName(
            ) == "EndOfLevel":  #Plane entering Finish area
                self.myImage.hide()  #hide cursor image during death animation
                self.beatLevel()
                base.disableParticles()  #disable physics when hit
                self.engineSound.stop()  #control volume
                self.MusicSound.setVolume(0.5)  #control volume
                #self.msg.addMessage("FINAL DA FASE", 3) #DEBUG
                #print "FINAL DA FASE" #Activate this when debugging
            else:
                self.myImage.hide()  #hide cursor image during death animation
                self.explode()
                self.death = 1
                base.disableParticles()  #disable physics when hit
                self.engineSound.stop()  #control volume
                self.MusicSound.setVolume(0.5)  #control volume

    def evtFreeLookON(self):  #Function for freelook on
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    def evtFreeLookOFF(self):  #Function for freelook off
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    def __del__(self):  #Function that delete features of the airplane
        self.ignoreAll()
        self.contrail.cleanup()

        #delete stop the sound
        self.Sound.stop()
        self.audio3d.detachSound(self.Sound)
        self.engineSound.stop()
        self.MusicSound.stop()

        base.camera.reparentTo(render)
        base.camera.setPos(1000, 1000, 200)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        #hide cursor image after death
        self.myImage.hide()

        if self.death == 1:
            messenger.send('player-death')

    def evtSpeedUp(self):  #Function that conrol event that increse speed
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1.5)
        self.zoom = -5 - (self.speed / 10)

    def evtSpeedDown(self):  #Function that control event that decrease speed
        if self.landing:
            return 0
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            self.engineSound.setPlayRate(0.5)
        self.zoom = -5 - (self.speed / 10)

    def evtMenuOpen(self):  #Function that control open menu event(ESC)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)
        #disable physics when esc is pressed
        base.disableParticles()
        #control volume
        self.engineSound.stop()
        self.MusicSound.setVolume(0.5)

    def evtMenuClose(self):  #Function that control close menu event(ESC)
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
        #enable physics after menu closed
        base.enableParticles()
        #control volume
        self.engineSound.play()
        self.MusicSound.setVolume(1.5)
Exemple #28
0
class Labryn(ShowBase):
    def setCamera(self, spin):
        # set camera spin state
        self.spin = spin

    def displayInformation(self):
        self.title = addTitle("Single Player")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[wasd]: Move")
        self.inst3 = addInstructions(0.85, "[q/e]: spin camera")
        self.inst4 = addInstructions(0.80, "[z/c]: zoom in/out")
        self.inst5 = addInstructions(0.75, "[shift]: hold and pan")
        self.inst6 = addInstructions(0.70, "[1/2/3]: use moves")
        self.inst7 = addInstructions(0.65, "[h]: hide instructions")
        self.insts = [self.title, self.inst1, self.inst2, self.inst3,
                      self.inst4, self.inst5, self.inst6, self.inst7]

    def hideInstructions(self):
        if self.instStatus == "show":
            self.instStatus = "hide"
            groupHide(self.insts)
        else: # instructions are hidden
            self.instStatus = "show"
            groupShow(self.insts)        
        
    def loadNextMusic(self, task):
        # random load background music
        if (self.music.status()!=self.music.PLAYING):
            # not playing
            self.musicCounter += 1
            index = self.musicCounter % len(_BGMUSIC)
            self.music = load_bgmusic(_BGMUSIC[index])
            self.music.play()
        return task.cont
        
    def spinCamera(self, task):
        # deal with spinning the camera
        # _FOCUS: focus point, changed by panning the camera
        # CAM_R: radius, changed by zooming
        # cameraSpinCount: amount of spinning, changed by spinning
        if self.spin == 1: # spin counter-clockwise
            self.cameraSpinCount += 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R) 
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 2: # spin clockwise
            self.cameraSpinCount  -= 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 3: # ZOOM IN not spin
            self.cameraZoomCount += 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*new_R)
        elif self.spin == 4: # ZOOM OUT
            self.cameraZoomCount -= 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
        return Task.cont

    def takeRecord(self):
        def myCMP(aString, bString):
            a = float(aString.split(',')[0])
            b = float(bString.split(',')[0])
            return int(10*(a - b))
        
        msg = "%.2f,%s\n" %(self.clock/100.0, time.ctime())
        with open('record.txt') as f:
            data = f.readlines()
        # if has no previous data
        if len(data) == 0:
            data.append(msg)
            with open('record.txt','w') as f:
                f.writelines(data)
        else:
            data.append(msg)
            processedData = sorted(data, myCMP)
            with open('record.txt', 'w') as f:
                f.writelines(processedData)

    def printResults(self):
        addEndMessage(self.clock)
        with open('record.txt') as f:
            data = f.readlines()
        for i in xrange(0, len(data)):
            if i < 5: # only print the top 5
                string = data[i]
                printRank(i, string)
        
    def checkForWin(self, task):
        if (checkWin(self.pikachu.getX(), self.pikachu.getY(),
                    self.ballRoot.getX(), self.ballRoot.getY()) and
            self.gameOver == False):
            self.takeRecord()
            self.printResults()
            self.gameOver = True
            # if top 10, if top 1,
            print "WIN"
            # print previous best 10 results
        return Task.cont
    
    def pikachuBark(self, task):
        if self.distance < 3:
            if random.randint(1,200) == 1:
            # randomly bark dangerous sound
                if self.dangerous.status() != self.dangerous.PLAYING:
                    self.dangerous.play()
        elif self.distance > 10:
            if random.randint(1,430) == 1:
                if self.safe.status() != self.safe.PLAYING:
                    self.safe.play()
        return Task.cont
            
    def checkMouse(self, task):
        # get mouse position 
        if base.mouseWatcherNode.hasMouse():
            self.mouseX=base.mouseWatcherNode.getMouseX()
            self.mouseY=base.mouseWatcherNode.getMouseY()
        return Task.cont

    def dropRock(self):
        # when the user clicks, rock is dropped
        if self.pokeMoveChoice == 1: # selected Geodude
            result = MAZE.canDropRock(self.rockX, self.rockY)
            if result != False: # can place rock here
                MAZE.dropRock(result[0],result[1])
                self.rock.setPos(self.rockX, self.rockY, 1)
                self.rockOnMaze = True
                self.pokeMoveChoice = None
                self.myPokeName.hide()
                self.myPokeName = None
                self.updateTwoD()
                self.playerCandyCount -= 1

    def restart(self):
        sys.exit()
                
    def useFlame(self):
        # use flame to Pikachu -> cannot move
        self.onFire = True # on fire
        self.playerCandyCount -= 1
        self.pokeStatus = 1
        self.flame = ParticleEffect()
        self.flame.loadConfig("fireish.ptf")
        self.flame.setPos(self.pikachu.getPos())
        self.flame.start(parent=render, renderParent=render)
        self.updateTwoD()

    def useStringShot(self):
        # use string shot -> speed goes down
        self.pokeStatus = 2
        self.updateTwoD()

    def useThunder(self):
        self.onThunder = True
        self.pokeCandyCount -= 1
        self.thunder = ParticleEffect()
        self.thunder.loadConfig("thunder.ptf")
        self.thunder.start(parent=render, renderParent=render)
        self.use.play()
                
    def placeRock(self, task):
        # rock moves with mouse cursor
        if self.pokeMoveChoice == 1: # selected Geodude
            dX,dY = ((self.mouseX-self.rockRefX),
                     (self.mouseY-self.rockRefY))
            self.rockX, self.rockY = MAZE.translateRockPosition(self.rockRefX,
                                                      self.rockRefY,
                                                      dX, dY)
            self.rock.show()
            self.rock.setPos(self.rockX, self.rockY, 1)
        self.updateTwoD()
        return Task.cont
    
    def placeRareCandy(self, task):
        # place rare candy with interval
        # needs to be improved
        if int(task.time) % 4 == 9 and self.candyOnBoard:
            self.candy.hide()
            self.candyOnBoard = False
            MAZE.clearCandy()
        if int(task.time) % 10 ==  0 and (self.candyOnBoard == False):
            # every 10 seconds
            self.candy.setPos(MAZE.generateCandyPos())
            self.candy.show()
            self.candyOnBoard = True
        return Task.cont

    def updateTwoD(self):
        # update player candy count
        self.playerCandyStatus.destroy()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        self.pokeCandyStatus.destroy()
        self.pokeCandyStatus = candyStatus(1, self.pokeCandyCount)
        # update my pokes color     
        if self.playerCandyCount == 0 :
            groupHide(self.myPokesBright)
            groupShow(self.myPokesDark)
            # update name
            if self.myPokeName != None:
                self.myPokeName.destroy()

    def clearRock(self):
        # clear rock 
        self.rock.hide()
        self.rockOnMaze = False
        MAZE.clearRock() # clear it in 2D

    def clearFlame(self):
        # clear flame
        self.onFire = False
        self.flame.cleanup()
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

    def clearString(self):
        # clear string shot
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

    def clearThunder(self):
        self.onThunder = False
        try:
            self.thunder.cleanup()
        except:
            pass
        
    def timer(self, task): # deals with moves' lasting effects
        ##############################################################
        self.clock += 1
        if self.rockOnMaze: # rock on maze
            self.rockCounter += 1
        elif self.rockCounter != 1: # rock not on maze, counter not cleared
            self.rockCounter = 0

        if self.onFire:
            self.fireCounter += 1
        elif self.fireCounter != 1:
            self.fireCounter = 0

        if self.pokeStatus == 2: # string shot
            self.stringCounter += 1
        elif self.stringCounter != 1:
            self.stringCounter = 0

        if self.onThunder: # thunderbolt
            self.thunderCounter += 1
        elif self.thunderCounter != 1:
            self.thunderCounter = 0

        if self.gameOver == True: # game is over
            self.gameOverCounter += 1

        ##################################################################
        if self.rockCounter >= 100:
            self.clearRock()

        if self.fireCounter >= 80:
            self.clearFlame()

        if self.thunderCounter >= 150:
            self.clearThunder()
            
        if self.stringCounter >= 120:
            self.clearString()

        if self.gameOverCounter >= 800: # quit the game
            sys.exit()
            
        return Task.cont
    
    def usePokeMove(self, number):
        # use pokemon move
        if self.playerCandyCount > 0: # have more than one candy
            if number == 1 and self.rockOnMaze == False:
                if self.pokeMoveChoice == None: # no choice
                    # set to center position
                    centerx =  base.win.getProperties().getXSize()/2
                    centery =  base.win.getProperties().getYSize()/2
                    base.win.movePointer(0,centerx,centery)
                    self.pokeMoveChoice = 1 # placeRock called here
                    self.rockRefX, self.rockRefY = 0,0
                    self.rock.show()
                    self.rock.setPos(0,0,1)
                elif self.pokeMoveChoice != 1:
                    pass

                else: # self.pokeMoveChoice is already 1, cancel the choice
                    self.pokeMoveChoice = None
                    self.clearRock() # clear rock
            elif number == 2:
                if self.pokeMoveChoice == None:
                    self.pokeMoveChoice = 2
                    self.useFlame()
                elif self.pokeMoveChoice != 2:
                    pass
                else:
                    self.pokeMoveChoice = None

            elif number == 3:
                if self.pokeMoveChoice == None:
                    self.pokeMoveChoice = 3
                    self.useStringShot()
                elif self.pokeMoveChoice != 3:
                    pass
                else: # already 3
                    self.pokeMoveChoice = None

            if self.pokeMoveChoice == None: # no choice
                if self.myPokeName != None: # there is a name on board
                    self.myPokeName.destroy() # kill it
                else: # no name
                    pass
            else: # there is a choice
                if self.myPokeName != None:
                    self.myPokeName.destroy()
                self.myPokeName = writePokeName(self.pokeMoveChoice)
  
    def loadRareCandy(self):
        # load rare candy (a box)
        # needs to be improved
        self.candy = Model_Load.loadRareCandy()
        self.candy.reparentTo(render)
        self.candy.setScale(0.1)
        self.candy.hide()
        
    def eatRareCandy(self, task):
        # check who eats candy
        if self.candyOnBoard: # candy on board
            if checkEat(self.ballRoot.getX(), self.ballRoot.getY(),
                        self.candy.getX(), self.candy.getY()): # ball eats
                self.candy.hide() # eaten
                self.candyOnBoard = False
                if self.playerCandyCount < 3:
                    self.playerCandyCount += 1
                groupShow(self.myPokesBright)
                MAZE.clearCandy()
            elif checkEatPika(self.pikachu.getX(), self.pikachu.getY(),
                          self.candy.getX(), self.candy.getY()):
                self.candy.hide()
                self.candyOnBoard = False
                if self.pokeCandyCount < 3:
                    self.pokeCandyCount += 1
                MAZE.clearCandy()                
        return Task.cont

    def setFocus(self, changing):
        # set focus of the camera while panning
        self.changingFocus = changing
        if changing == True: # Just Pressed
            self.referenceX, self.referenceY = self.mouseX, self.mouseY
        else: # cursor moves up
            self.referenceX, self.referenceY = None, None

    def resetView(self):
        # reset the view to default
        self.CAM_R, self.CAM_RAD = 12, 0
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        # _FOCUS = [0,0,0] does not work WHY???
        _FOCUS[0], _FOCUS[1], _FOCUS[2] = 0,0,0
        self.changingFocus = False
        self.referenceX, self.referenceY = None, None
        camera.setPos(_FOCUS[0], _FOCUS[1]-self.CAM_R, 25)
        camera.setHpr(0, -65, 0)
        
    def changeFocus(self, task):
        # change focus with displacement of mouse cursor
        if (self.changingFocus == True and self.mouseX != None and
            self.mouseY != None ):
            dX, dY = ((self.mouseX - self.referenceX)*0.1,
                      (self.mouseY - self.referenceY)*0.1)
            _FOCUS[0] += dX
            _FOCUS[1] += dY
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
        return Task.cont

    def thunderbolt(self, task):
        if self.onThunder == True:
            self.thunder.setPos(self.ballRoot.getPos())
        return Task.cont

    def displayClock(self, task):
        msg = "Time: %.2f" %(self.clock/100.0)
        if self.clockMSG == None:
            self.clockMSG = OnscreenText(text=msg, style=1, fg=(1,1,1,1),
                                         pos=(1.3, .95), align=TextNode.ALeft,
                                         scale = .05)
        else:
            self.clockMSG.destroy()
            self.clockMSG = OnscreenText(text=msg, style=1, fg=(1,1,1,1),
                                         pos=(1.3, .95), align=TextNode.ALeft,
                                         scale = .05)
        return task.cont
    
    def initialize(self):
        taskMgr.stop()
        self.musicCounter, self.clock = 0, 0
        self.gameOverCounter = 0
        self.clockMSG = None
        self.music = load_bgmusic(_BGMUSIC[0])
        self.background = loadBackground()
        base.cam2dp.node().getDisplayRegion(0).setSort(-20)
        self.candyOnBoard = False
        self.playerCandyCount, self.pokeCandyCount = 0, 0
        self.gameOver = False
        self.displayInformation()
        self.instStatus = "show"
        ######################Rare Candy###############################
        pokes=['caterpie', 'charmander', 'geodude']
        self.myPokesDark = loadMyPokemon_Dark(pokes) # my pokemons
        self.myPokesBright = loadMyPokemon_Bright()
        groupHide(self.myPokesBright)
        self.loadRareCandy() # load rare candy
        ######################Camera Initialization####################
        self.CAM_R, self.CAM_RAD = 12, 0
        camera.setPos(_FOCUS[0],_FOCUS[1]-12,_FOCUS[2]+25)
        camera.setHpr(0, -65, 0)
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        self.changingFocus = False
        self.spin = 0
        #######################ICONS###################################
        self.myIcon = loadMyIcon()
        self.pokeIcon = loadPokeIcon()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        self.pokeCandyStatus = candyStatus(1, self.pokeCandyCount)
        self.rareCandyImage = loadRareCandyImage()
        self.pokeRareCandyImage = loadRareCandyImage(pos=(-.3,0,-.75))
        #######################FLAMES##################################
        base.enableParticles()
        self.fireCounter = 0
        self.onFire = False
        #######################STRINGSHOT#############################
        self.stringCounter = 0
        #######################THUNDER################################
        self.thunderCounter = 0
        #######################SOUND##################################
        self.dangerous = load_sound("pikachu_d.wav")
        self.safe = load_sound("pikachu_s1.wav")
        self.use = load_sound("pikachu_u.wav")
        #######################"GLOBALS"##############################
        self.speedCounter = 0
        self.onThunder = False
        self.direction = 's'
        self.myDirection = ['zx', 'zy']
        self.rockCounter  = 0
        self.rockX, self.rockY = None, None
        self.rockOnMaze = False
        self.pokeMoveChoice = None
        self.myPokeName = None
        self.arrowKeyPressed = False
        self.pokemonDirection = 'd'
        self.mouseX, self.mouseY = None, None
        # direction the ball is going
        self.jerkDirection = None
        base.disableMouse()
        self.jerk = Vec3(0,0,0)
        self.MAZE = Model_Load.loadLabyrinth()
        Control.keyControl(self)
        self.loadPokemonLevel1()
        self.light()
        self.loadBall()
        self.pokeStatus = 0 # 0 is normal, 1 is burned, 2 is slow-speed
        ########################################ROCK###################
        self.rock = Model_Load.loadRock()
        self.rock.reparentTo(render)
        self.rock.hide() # Do not show, but load beforehand for performance
        
    def loadPokemonLevel1(self):
        self.pikachu = load_model("pikachu.egg")
        self.pikachu.reparentTo(render)
        self.pikachu.setScale(0.3)
        endPos = self.MAZE.find("**/end").getPos()
        self.pikachu.setPos(endPos)
        
    def light(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    def loadBall(self):
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = load_model("ball")
        self.ball.reparentTo(self.ballRoot)
        self.ball_tex = load_tex("pokeball.png")
        self.ball.setTexture(self.ball_tex,1)
        self.ball.setScale(0.8)
        # Find the collision sphere for the ball in egg.
        self.ballSphere = self.ball.find("**/ball")
        self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())
        #self.ballSphere.show()
        # Now we create a ray to cast down at the ball.
        self.ballGroundRay = CollisionRay()
        self.ballGroundRay.setOrigin(0,0,10)
        self.ballGroundRay.setDirection(0,0,-1)

        # Collision solids go in CollisionNode
        self.ballGroundCol =  CollisionNode('groundRay')
        self.ballGroundCol.addSolid(self.ballGroundRay)
        self.ballGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
        
        # light
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0,0,-1))
        directionalLight.setColor(Vec4(0.375,0.375,0.375,1))
        directionalLight.setSpecularColor(Vec4(1,1,1,1))
        self.ballRoot.setLight(render.attachNewNode(ambientLight))
        self.ballRoot.setLight(render.attachNewNode(directionalLight))
        # material to the ball
        m = Material()
        m.setSpecular(Vec4(1,1,1,1))
        m.setShininess(96)
        self.ball.setMaterial(m,1)
        
    def __init__(self):

        self.initialize()
        self.WALLS = self.MAZE.find("**/Wall.004")
        self.WALLS.node().setIntoCollideMask(BitMask32.bit(0))
        # collision with the ground. different bit mask
        #self.mazeGround = self.maze.find("**/ground_collide")
        #self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
        self.MAZEGROUND = self.MAZE.find("**/Cube.004")
        self.MAZEGROUND.node().setIntoCollideMask(BitMask32.bit(1))

        # add collision to the rock
        cs = CollisionSphere(0, 0, 0, 0.5)
        self.cnodePath = self.rock.attachNewNode(CollisionNode('cnode'))
        self.cnodePath.node().addSolid(cs)
        self.cnodePath.node().setIntoCollideMask(BitMask32.bit(0))
        
        # CollisionTraversers calculate collisions
        self.cTrav = CollisionTraverser()
        #self.cTrav.showCollisions(render)
        #self.cTrav.showCollisions(render)
        # A list collision handler queue
        self.cHandler = CollisionHandlerQueue()
        # add collision nodes to the traverse.
        # maximum nodes per traverser: 32
        self.cTrav.addCollider(self.ballSphere,self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp,self.cHandler)
        self.cTrav.addCollider(self.cnodePath, self.cHandler)
        # collision traversers have a built-in tool to visualize collisons
        #self.cTrav.showCollisions(render)
        self.start()

    def pokemonTurn(self, pokemon, direction):
        if direction  == 'l' and self.pokemonDirection != 'l':
            self.pokemonDirection = 'l'
            pokemon.setH(-90)
        if direction  == 'r' and self.pokemonDirection != 'r':
            self.pokemonDirection = 'r'
            pokemon.setH(90)
        if direction  == 'd' and self.pokemonDirection != 'd':
            self.pokemonDirection = 'd'
            pokemon.setH(0)
        if direction  == 'u' and self.pokemonDirection != 'u':
            self.pokemonDirection = 'u'
            pokemon.setH(180)
                        
    def pokemonMove(self, pokemon, direction):
        self.pokemonTurn(pokemon, direction)
        if self.pokeStatus == 0: speed = _SPEED
        elif self.pokeStatus == 1: speed = 0
        else: # self.pokeStatus == 2
            speed = _SPEED/2.0
        if direction == 'l':
            newX = pokemon.getX() - speed
            pokemon.setX(newX)
        elif direction == 'r':
            newX = pokemon.getX() + speed
            pokemon.setX(newX)
        elif direction == 'u':
            newY = pokemon.getY() + speed
            pokemon.setY(newY)
        elif direction == 'd':
            newY = pokemon.getY() - speed
            pokemon.setY(newY)
        elif direction == "s": # stop
            pass
        
    def whereToGo(self, task):
        # this returns the direction pokemon should go
        # tell MAZE pokemon and ball's board position
        self.pokemonMove(self.pikachu, self.direction)
        MAZE.setPokeCoord(self.pikachu.getX(), self.pikachu.getY(),
                          self.pokemonDirection)
        MAZE.setBallCoord(self.ballRoot.getX(), self.ballRoot.getY())
        MAZE.sendInformation(self.myDirection, self.rockOnMaze,
                             self.onThunder, self.playerCandyCount,
                             self.pokeCandyCount, self.distance)
        # find out which direction to go
        self.direction = MAZE.getDecision()
        self.pokemonMove(self.pikachu,self.direction)
        return Task.cont

    def whatToDo(self, task):
        # determines when to use thunder
        if self.pokeCandyCount > 0: # Pikachu has candies
            decision = MAZE.useThunderDecision()
            if decision == True:
                self.useThunder()
        return Task.cont
    
    def getInformation(self, task):
        # get information on the board
        self.speedCounter += 1 # sample every other call to avoid 
        if self.speedCounter % 2 == 0:
            dX = self.ballRoot.getX() - self.oldPos[0]
            dY = self.ballRoot.getY() - self.oldPos[1]
            if dX < 0 :
                # print "going left"
                self.myDirection[0] = 'l'
            elif abs(dX) < _EPSILON:
                # print "not moving horiz"
                self.myDirection[0] = 'zx'
            else:
                # print "going right"
                self.myDirection[0] = 'r'
            if dY < 0 :
                # print "going down"
                self.myDirection[1] = 'd'
            elif abs(dY) < _EPSILON:
                # print "not moving verti"
                self.myDirection[1] = 'zy'
            else:
                # print "going up"
                self.myDirection[1] = 'u'
            self.oldPos = self.ballRoot.getPos()
        # calculate distance
        self.distance = MAZE.getDistance()
        return Task.cont
    
    def start(self):
        # maze model has a locator in it
        # self.ballRoot.show()
        self.startPos = self.MAZE.find("**/start").getPos()
        self.oldPos = self.MAZE.find("**/start").getPos()
        self.ballRoot.setPos(self.startPos) # set the ball in the pos
        self.ballV = Vec3(0,0,0) # initial velocity
        self.accelV = Vec3(0,0,0) # initial acceleration

        # for a traverser to work, need to call traverser.traverse()
        # base has a task that does this once a frame
        base.cTrav = self.cTrav

        # create the movement task, make sure its not already running
        taskMgr.remove("rollTask")
        taskMgr.add(self.placeRock, "placeRock")
        taskMgr.add(self.displayClock, "displayClock")
        taskMgr.add(self.timer, "timer")
        taskMgr.add(self.loadNextMusic, "loadNextMusic")
        taskMgr.add(self.getInformation, "getInformation")
        taskMgr.add(self.eatRareCandy, "eatRareCandy")
        taskMgr.add(self.placeRareCandy, "placeRareCandy")
        taskMgr.add(self.checkMouse, "checkMouse")
        taskMgr.add(self.spinCamera, "spinCamera")
        taskMgr.add(self.changeFocus, "changeFocus")
        taskMgr.add(self.whereToGo, "whereToGo")
        taskMgr.add(self.whatToDo, "whatToDo")
        taskMgr.add(self.moveBall, "moveBall")
        taskMgr.add(self.thunderbolt, "thunderbolt")
        taskMgr.add(self.checkForWin, "checkForWin")
        taskMgr.add(self.pikachuBark, "pikachuBark")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
        self.mainLoop.last = 0

    def moveBallWrapper(self, direction):
        # wrapper for moving the ball
        # needs to be improved
        if direction == False:
            self.arrowKeyPressed = False
        else:
            self.arrowKeyPressed = True
            self.jerkDirection = direction
    
    def moveBall(self, task):
        # move the ball
        # a key press changes the jerk
        direction = self.jerkDirection
        if self.arrowKeyPressed == True and self.onThunder == False:
            if direction == "u":
                self.jerk = Vec3(0,_JERK,0)
            elif direction == "d":
                self.jerk = Vec3(0,-_JERK,0)
            elif direction == "l":
                self.jerk = Vec3(-_JERK,0,0)
            elif direction == "r":
                self.jerk = Vec3(_JERK,0,0)
        elif self.onThunder == True:
            self.jerk = self.jerk
        return Task.cont        

    # collision between ray and ground
    # info about the interaction is passed in colEntry
    
    def groundCollideHandler(self,colEntry):
        # set the ball to the appropriate Z for it to be on the ground
        newZ = colEntry.getSurfacePoint(render).getZ()
        self.ballRoot.setZ(newZ+.4)

        # up vector X normal vector
        norm = colEntry.getSurfaceNormal(render)
        accelSide = norm.cross(UP)
        self.accelV = norm.cross(accelSide)

    # collision between the ball and a wall
    def wallCollideHandler(self,colEntry):
        # some vectors needed to do the calculation
        norm = colEntry.getSurfaceNormal(render) * -1
        norm.normalize()
        curSpeed = self.ballV.length()
        inVec = self.ballV/curSpeed
        velAngle = norm.dot(inVec) # angle of incidance
        hitDir = colEntry.getSurfacePoint(render) - self.ballRoot.getPos()
        hitDir.normalize()
        hitAngle = norm.dot(hitDir)
    # deal with collision cases
        if velAngle > 0 and hitAngle >.995:
            # standard reflection equation
            reflectVec = (norm * norm.dot(inVec*-1)*2) + inVec
            # makes velocity half of hitting dead-on
            self.ballV = reflectVec * (curSpeed * (((1-velAngle)*.5)+.5))
            # a collision means the ball is already a little bit buried in
            # move it so exactly touching the wall
            disp = (colEntry.getSurfacePoint(render) -
                    colEntry.getInteriorPoint(render))
            newPos = self.ballRoot.getPos() + disp
            self.ballRoot.setPos(newPos)
            
    def rollTask(self,task):
        # standard technique for finding the amount of time
        # since the last frame
        dt = task.time - task.last
        task.last = task.time
        # If dt is large, then there is a HICCUP
        # ignore the frame
        if dt > .2: return Task.cont
        # dispatch which function to handle the collision based on name
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()
            if name == "Wall.004":
                self.wallCollideHandler(entry)
            elif name=="Cube.004":
                self.groundCollideHandler(entry)
            else:
                if self.rockOnMaze == True:
                    self.wallCollideHandler(entry)
                    
        self.accelV += self.jerk
        # move the ball, update the velocity based on accel
        self.ballV += self.accelV * dt * ACCELERATION
        # clamp the velocity to the max speed
        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED
        # update the position
        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV*dt))

        # uses quaternion to rotate the ball
        prevRot = LRotationf(self.ball.getQuat())
        axis = UP.cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)
        return Task.cont # continue the task     
Exemple #29
0
class Kamikaze(EnemyMotorcyclist):
    """An enemy type, which can do a lot of damage, but only once.

    Player can protect against Kamikaze's explosion with the
    Armor Plate locomotive upgrade. If a Kamikaze was destroyed
    before a self-explosion, he will do a lot of damage to other
    enemy units nearby.

    Args:
        model (actor.Actor): Enemy character model.
        id_ (int): Enemy unit id.
        y_positions (list): Free positions along Y.
        enemy_handler (CollisionHandlerEvent): Enemy collisions handler.
        class_data (dict): This unit class description.
    """
    def __init__(self, model, id_, y_positions, enemy_handler, class_data):
        EnemyMotorcyclist.__init__(self, id_, "Kamikaze", class_data, model,
                                   y_positions, enemy_handler)

        self._train_captured = False
        self._explosion_col_np = None
        self.is_jumping = False

        self._side = "left" if self._y_pos > 0 else "right"

        self._jump_path = Mopath.Mopath(
            objectToLoad=loader.loadModel(  # noqa: F821
                address(self._side[0] + "_kamikaze_jump")))
        self._jump_path.fFaceForward = True

        self._jump_snd = base.sound_mgr.loadSfx(
            "sounds/moto_jump.ogg")  # noqa: F821
        base.sound_mgr.attachSoundToObject(self._jump_snd,
                                           self.model)  # noqa: F821

        self._wick_snd = base.sound_mgr.loadSfx(
            "sounds/combat/wick.ogg")  # noqa: F821
        base.sound_mgr.attachSoundToObject(self._wick_snd,
                                           self.model)  # noqa: F821

        self._wick = ParticleEffect()

        self._fire_ring = ParticleEffect()
        self._fire_ring.loadConfig("effects/fire_ring.ptf")
        self._fire_ring.setZ(0.2)

    def _ignite_the_wick(self):
        """Ignite the kamikaze's wick.

        Play the sound and start particle effect.
        """
        self._wick.loadConfig("effects/kamikaze_wick.ptf")
        self._wick.start(self.model, render)  # noqa: F821

        self._wick_snd.play()

    def _explode(self, kamikaze=False):
        """Explode the kamikaze.

        Args:
            kamikaze (bool):
                If True, than the unit self-exploded.
                Destroyed by a player otherwise.
        """
        if kamikaze:
            self.model.hide()
            base.train.explode_rocket(self._side)  # noqa: F821
            self._wick.softStop()
            return

        EnemyMotorcyclist._explode(self)

        self._fire_ring.start(self.model, render)  # noqa: F821
        taskMgr.doMethodLater(  # noqa: F821
            0.95,
            self._fire_ring.softStop,
            self.id + "_cleanup_ring_of_fire",
            extraArgs=[],
        )

        col_node = CollisionNode("kamikaze_explosion")
        col_node.setFromCollideMask(NO_MASK)
        col_node.setIntoCollideMask(SHOT_RANGE_MASK)
        col_node.addSolid(CollisionSphere(0, 0, 0, 0.2))

        base.accept("into-kamikaze_explosion",
                    self._do_kamikaze_damage)  # noqa: F821

        self._explosion_col_np = self.model.attachNewNode(col_node)

        taskMgr.doMethodLater(  # noqa: F821
            0.05,
            self._clear_explosion_collisions,
            self.id + "_clear_explosion_collisions",
        )

    def _clear_explosion_collisions(self, task):
        """
        Erase the collision node, which was used
        to do damage for other enemy units.
        """
        self._explosion_col_np.removeNode()
        return task.done

    def _do_kamikaze_damage(self, event):
        """Do damage because of the kamikaze explosion.

        The method is used only when the
        kamikaze was destroyed by a player.
        """
        base.world.enemy.active_units[  # noqa: F821
            event.getFromNodePath().getName()].get_damage(35)

    def _jump_and_explode(self, task):
        """Jump to the Adjutant and self-explode."""
        if self.current_part is None:
            return task.done

        for char in base.world.enemy.active_units.values():  # noqa: F821
            if type(char
                    ) == Kamikaze and char.id != self.id and char.is_jumping:
                return task.again

        self.is_jumping = True
        self._stop_tasks("_float_move")
        self._move_int.pause()

        Sequence(
            LerpPosInterval(self.node,
                            2.5, (self._y_pos, -0.5, 0),
                            blendType="easeInOut"),
            Func(self._ignite_the_wick),
            LerpPosInterval(
                self.node,
                4.5,
                (-0.45 if self._y_pos < 0 else 0.45, -0.8, 0),
                blendType="easeInOut",
            ),
            Func(self._jump_snd.play),
            MopathInterval(self._jump_path,
                           self.model,
                           duration=0.8,
                           name=self.id + "_jump"),
            Func(self._die, True),
        ).start()
        return task.done

    def _release_pos(self):
        """Release the position currently taken by the unit."""
        self._y_positions.append(self._y_pos)

    def capture_train(self):
        """The Train got critical damage - stop near it."""
        self._train_captured = True

        self._stop_tasks("_jump_and_explode")
        EnemyMotorcyclist.capture_train(self)

    def enter_the_part(self, part):
        """Start fighting on the given part.

        Args:
            part (train.part.TrainPart): Train part this enemy entered.
        """
        if self._train_captured:
            return

        self.current_part = part
        taskMgr.doMethodLater(  # noqa: F821
            10, self._jump_and_explode, self.id + "_jump_and_explode")

    def leave_the_part(self, part):
        """Stop fighting on the current part.

        Args:
            part (train.part.TrainPart): Train part this enemy entered.
        """
        self._release_pos()
        self.current_part = None

    def _die(self, kamikaze=False):
        """Make this enemy unit die.

        Play death sequence of movements and sounds,
        stop all the tasks for this enemy, plan clearing.

        Returns:
            bool: True, if the unit dies for the first time.
        """
        if not Unit._die(self):
            return False

        self.model.setColorScale(1, 1, 1, 1)
        self._stop_tasks("_float_move", "_jump_and_explode")
        self._move_int.pause()

        if self.id in base.world.enemy.active_units:  # noqa: F821
            base.world.enemy.active_units.pop(self.id)  # noqa: F821
            if self.current_part and self in self.current_part.enemies:
                self.current_part.enemies.remove(self)

        self._explode(kamikaze=kamikaze)
        self.transport_snd.stop()
        self._y_positions.append(self._y_pos)

        if not kamikaze:
            base.add_head(self.class_data["class"].__name__)  # noqa: F821

        return True

    def stop(self):
        """Smoothly stop this unit following the Train."""
        self._stop_tasks("_jump_and_explode")
        EnemyUnit.stop(self)

    def clear(self, task=None):
        """Clear all the graphical data of this unit."""
        self._wick.cleanup()
        self._fire_ring.cleanup()

        base.sound_mgr.detach_sound(self._jump_snd)  # noqa: F821
        base.sound_mgr.detach_sound(self._wick_snd)  # noqa: F821

        EnemyUnit.clear(self, task)
Exemple #30
0
class TossTrapGag(TrapGag):

    def __init__(self, name, model, damage, hitSfx, idleSfx = None, particlesFx = None, anim = None, wantParticles = True):
        TrapGag.__init__(self, name, model, damage, hitSfx, anim)
        self.wantParticles = wantParticles
        self.particles = None
        self.particlesFx = particlesFx
        self.idleSfx = None
        if game.process == 'client':
            if idleSfx:
                self.idleSfx = base.audio3d.loadSfx(idleSfx)
        return

    def startTrap(self):
        TrapGag.startTrap(self)
        if not self.gag:
            self.build()
            self.setHandJoint()
        self.gag.reparentTo(self.handJoint)
        self.avatar.play('toss', fromFrame=22)

    def build(self):
        TrapGag.build(self)
        self.buildParticles()
        self.setHandJoint()

    def buildParticles(self):
        self.cleanupParticles()
        if hasattr(self, 'wantParticles') and hasattr(self, 'particlesFx'):
            if self.wantParticles and self.particlesFx:
                self.particles = ParticleEffect()
                self.particles.loadConfig(self.particlesFx)

    def buildCollisions(self):
        TrapGag.buildCollisions(self)
        gagSph = CollisionSphere(0, 0, 0, 1)
        gagSph.setTangible(0)
        gagNode = CollisionNode('gagSensor')
        gagNode.addSolid(gagSph)
        gagNP = self.gag.attachNewNode(gagNode)
        gagNP.setScale(0.75, 0.8, 0.75)
        gagNP.setPos(0.0, 0.1, 0.5)
        gagNP.setCollideMask(BitMask32.bit(0))
        gagNP.node().setFromCollideMask(CIGlobals.FloorBitmask)
        event = CollisionHandlerEvent()
        event.setInPattern('%fn-into')
        event.setOutPattern('%fn-out')
        base.cTrav.addCollider(gagNP, event)

    def onCollision(self, entry):
        TrapGag.onCollision(self, entry)
        gag = self.gag
        if not gag:
            gag = self.entity
        x, y, z = gag.getPos(render)
        self.avatar.sendUpdate('setGagPos', [self.getID(),
         x,
         y,
         z])

    def release(self):
        TrapGag.release(self)
        throwPath = NodePath('ThrowPath')
        throwPath.reparentTo(self.avatar)
        throwPath.setScale(render, 1)
        throwPath.setPos(0, 160, -120)
        throwPath.setHpr(0, 90, 0)
        if not self.gag:
            self.build()
        self.gag.wrtReparentTo(render)
        self.gag.setHpr(throwPath.getHpr(render))
        self.setHandJoint()
        self.track = ProjectileInterval(self.gag, startPos=self.handJoint.getPos(render), endPos=throwPath.getPos(render), gravityMult=0.9, duration=3)
        self.track.start()
        if base.localAvatar == self.avatar:
            self.buildCollisions()
            self.avatar.acceptOnce('gagSensor-into', self.onCollision)
        self.reset()

    def delete(self):
        TrapGag.delete(self)
        self.cleanupParticles()

    def unEquip(self):
        TrapGag.unEquip(self)
        self.cleanupParticles()

    def cleanupParticles(self):
        if self.particles:
            self.particles.cleanup()
            self.particles = None
        return
Exemple #31
0
class Bullet(object):
    Forward = Vec3(0, 1, 0)
    Start = Vec3(0, 5, 0)
    speed = 1000
    time = 0
    shoot = None
    Move = 0
    Stop = 1
    Hit = 2
    state = Stop
    HitPosition = Vec3(0, 0, 0)
    HitNormal = Vec3(0, 0, 0)

    # CheckPostion = False

    def __init__(self, nodeGroundHandler, name):
        self.name = name
        self.bullet = NodePath(
            "bullet")  # loader.loadModel('res/models/box.egg')
        self.bullet.setScale(1)
        self.shoot = NodePath("shoot")
        self.shoot.setPos(self.Start)
        self.bullet.reparentTo(self.shoot)
        DoorImage = OnscreenImage(image="res/portal/door.png",
                                  pos=(0, -2, 0),
                                  scale=(8.8, 1, 14.2))
        DoorImage.setTransparency(TransparencyAttrib.MAlpha)
        DoorImage.setSa(0.5)
        self.Portal = NodePath("Portal")
        DoorImage.reparentTo(self.Portal)
        self.Portal.setScale(5)
        # forward Segment
        forwardSegment = CollisionRay(0, 0, 0, 0, 1, 0)
        self.cn = CollisionNode(name)
        self.cn.addSolid(forwardSegment)
        self.cn.setFromCollideMask(BitMask32.bit(0))
        self.cn.setIntoCollideMask(BitMask32.allOff())
        self.solid = self.shoot.attachNewNode(self.cn)
        base.cTrav.addCollider(self.solid, nodeGroundHandler)
        # Right Segment
        RightSegment = CollisionSegment(-20, -0.2, 0, 20, -0.2, 0)
        self.cnRight = CollisionNode(name + 'right')
        self.cnRight.addSolid(RightSegment)
        self.cnRight.setFromCollideMask(BitMask32.allOff())
        self.cnRight.setIntoCollideMask(BitMask32.allOff())
        self.solid = self.Portal.attachNewNode(self.cnRight)
        self.RightSegmentCollisionHandlerQueue = CollisionHandlerQueue()
        base.cTrav.addCollider(self.solid,
                               self.RightSegmentCollisionHandlerQueue)
        # self.solid.show()
        # Up Segment
        UpSegment = CollisionSegment(0, -0.2, -15, 0, -0.2, 15)
        self.cnUp = CollisionNode(name + 'up')
        self.cnUp.addSolid(UpSegment)
        self.cnUp.setFromCollideMask(BitMask32.allOff())
        self.cnUp.setIntoCollideMask(BitMask32.allOff())
        self.solid = self.Portal.attachNewNode(self.cnUp)
        # self.solid.show()
        base.cTrav.addCollider(self.solid,
                               self.RightSegmentCollisionHandlerQueue)
        Sphere = CollisionSphere(0, 0, 0, 60)
        self.cnout = CollisionNode(name + 'out')
        self.cnout.addSolid(Sphere)
        self.cnout.setFromCollideMask(BitMask32.bit(0))
        self.cnout.setIntoCollideMask(BitMask32.allOff())
        self.solid = self.shoot.attachNewNode(self.cnout)
        # self.solid.show()
        base.cTrav.addCollider(self.solid, nodeGroundHandler)
        self.NeedCheckPos = False
        self.initParticle()

    def initParticle(self):
        base.enableParticles()
        self.particle = ParticleEffect()
        self.loadParticleConfig("res/particles/light.ptf")

    def loadParticleConfig(self, filename):
        self.particle.cleanup()
        self.particle = ParticleEffect()
        self.particle.loadConfig(Filename(filename))
        self.particle.start(self.bullet)
        self.particle.setPos(0, 0, 0)
        self.particle.setScale(10)

    def Instance(self, Player):
        self.time = 0
        self.Start = Player.getPos()
        self.Start.z += base.camera.getZ() * Player.getScale().z
        self.Start.x += -base.camera.getY() * Player.getScale().x * sin(
            Player.getH() / 180 * pi)
        self.Start.y += base.camera.getY() * Player.getScale().y * cos(
            Player.getH() / 180 * pi)
        self.Forward = Vec3(
            -sin(Player.getH() / 180 * pi) *
            cos(base.camera.getP() / 180 * pi),
            cos(Player.getH() / 180 * pi) * cos(base.camera.getP() / 180 * pi),
            sin(base.camera.getP() / 180 * pi))
        # self.Start += self.Forward * 100.
        self.shoot.setHpr(Player.getH(), base.camera.getP(), 0)
        self.shoot.reparentTo(render)
        self.shoot.setPos(self.Start)

    def MoveUpdate(self):
        self.shoot.setPos(self.Start + self.Forward * self.time * self.speed)
        self.time += globalClock.getDt()

    def Disappera(self):
        self.state = self.Stop
        self.shoot.detachNode()
        self.cn.setFromCollideMask(BitMask32.allOff())

    def isMove(self):
        return self.state == self.Move

    def isHit(self):
        return self.state == self.Hit

    def SetMove(self):
        self.state = self.Move
        self.shoot.reparentTo(render)
        self.bullet.reparentTo(self.shoot)
        self.cn.setFromCollideMask(BitMask32.bit(0))
        self.Portal.detachNode()

    def SetStop(self):
        self.state = self.Hit
        self.NeedCheckPos = True
        self.Portal.reparentTo(self.shoot)
        self.cn.setFromCollideMask(BitMask32.allOff())
        self.bullet.detachNode()
        self.shoot.setHpr(0, 0, 0)
        self.shoot.setPos(self.HitPosition)
        cos = -self.HitNormal.y
        theta = acos(cos)
        if self.HitNormal.x < 0: theta = -theta
        self.Portal.setH(theta * 180 / pi)

    def checkPosition(self):
        self.cnRight.setFromCollideMask(BitMask32.bit(0))
        self.cnUp.setFromCollideMask(BitMask32.bit(0))
        base.cTrav.traverse(render)
        FinalPos = self.shoot.getPos()
        for i in range(self.RightSegmentCollisionHandlerQueue.getNumEntries()):
            entry = self.RightSegmentCollisionHandlerQueue.getEntry(i)
            if entry.getFromNode().getName() == self.name + 'right':
                offset = entry.getSurfacePoint(render) - self.shoot.getPos()
                newPosition = Vec3(0, 0, 0) + offset
                offset.normalize()
                offset *= 36
                newPosition -= offset
                FinalPos += newPosition
            if entry.getFromNode().getName() == self.name + 'up':
                offset = entry.getSurfacePoint(render) - self.shoot.getPos()
                # print offset
                newPosition = Vec3(0, 0, 0) + offset
                offset.normalize()
                offset *= 60
                newPosition -= offset
                FinalPos += newPosition
                # print entry.getSurfacePoint(self.render) - self.
        self.shoot.setPos(FinalPos)
        self.cnRight.setFromCollideMask(BitMask32.allOff())
        self.cnUp.setFromCollideMask(BitMask32.allOff())
        self.NeedCheckPos = False

    def ActivePortal(self):
        self.cnout.setFromCollideMask(BitMask32.bit(0))

    def ClosePortal(self):
        self.cnout.setFromCollideMask(BitMask32.allOff())
Exemple #32
0
class Effects(ShowBase):
	def __init__(self):
		#ShowBase.__init__(self)
		
		#################fulscreen###############
		root = Tkinter.Tk()
		w = root.winfo_screenwidth()
		h = root.winfo_screenheight()
		props = WindowProperties() 
		props.setSize(w, h) 
		base.win.requestProperties(props)
		#################end####################3
		
		
		#camera.setPos(-500,-80,0)
		base.enableParticles()
		self.txt = ""
		self.p = ParticleEffect()
		
		st_x = 5.0 ####-515,-60,0
		st_y = 8.0
		st_z = 0.0
		
		
		self.c2 = Actor('Models/dancer/dancer')#Actor("Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve",{"run":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-run",	"jump":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-jump",	"offbalance":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-offbalance",	"tireroll":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-tireroll"})
		self.c2.setPos(offset_x+st_x,offset_y+st_y+7,offset_z+st_z)
		self.c2.reparentTo(render)
		self.c2.loadAnims({'win':'Models/dancer/dancer'})
		self.c2.loop('win')
		
		'''self.tex = Texture()
		self.tex.setMinfilter(Texture.FTLinear)
		base.win.addRenderTexture(self.tex, GraphicsOutput.RTMTriggeredCopyTexture)
		
		self.backcam = base.makeCamera2d(base.win, sort=-10)
		self.background = NodePath("background")
		self.backcam.reparentTo(self.background)
		self.background.setDepthTest(0)
		self.background.setDepthWrite(0)
		self.backcam.node().getDisplayRegion(0).setClearDepthActive(0)
		
		#taskMgr.add(self.takeSnapShot, "takeSnapShot")
		
		self.bcard = base.win.getTextureCard()
		self.bcard.reparentTo(self.background)
		self.bcard.setTransparency(1)
		self.fcard = base.win.getTextureCard()
		self.fcard.reparentTo(render2d)
		self.fcard.setTransparency(1)
		
		base.setBackgroundColor(0,0,0,1)
		self.bcard.hide()
		self.fcard.show()
		self.fcard.setColor(1.0,1.0,1.0,0.99)
		self.fcard.setScale(1.00)
		self.fcard.setPos(0,0,0)
		self.fcard.setR(0)
		self.clickrate = 30
		self.nextclick = 0'''
		
		self.c4 = Actor('Models/dancer/dancer')
		#self.c2.loadModel('Models/dancer/dancer')
		self.c4.setPos(offset_x-st_x,offset_y+st_y+7,offset_z+st_z)
		self.c4.reparentTo(render)
		self.c4.loadAnims({'win':'Models/dancer/dancer'})
		self.c4.loop('win')
		
		#self.c2.setR(-90)
		
		#self.c2.loop('tireroll')
		#base.setSleep(0.5)
		self.c3 = Actor("Models/cat-humans/bvw-f2004--ralph-egg/bvw-f2004--ralph/ralph")
		self.c3.setScale(2)
		self.c3.setPos(offset_x+0,offset_y+20,offset_z+(-1))
		self.c3.reparentTo(render)
		self.c3.listJoints()
		#self.c4.listJoints()
		self.actorRh = self.c3.controlJoint(None, 'modelRoot', 'RightShoulder')
		self.actorLh = self.c3.controlJoint(None, 'modelRoot', 'LeftShoulder')
		self.actorNeck = self.c3.controlJoint(None, 'modelRoot', 'Neck')
		
		self.actorNeck1 = self.c3.controlJoint(None, 'modelRoot', 'Neck')
		
		#self.actorNeck.hprInterval(3,Point3(0,90,0)).loop()
		self.actorLh.hprInterval(3,Point3(90,0,0)).loop()
		self.actorRh.hprInterval(3,Point3(0,0,-180)).loop()
		#self.actorRh.hprInterval(3,Point3(0,90,0)).loop()
		self.actorRh.setHpr(180,180,-60) # For Both hands upward
		self.actorLh.setHpr(90,-90,120)
		
		
		self.loadchar('','')
		self.duckPlane = loader.loadModel('Models/plane/plane')
		self.duckPlane.setPos(offset_x-2, offset_y+8, offset_z+10)         #set its position
		self.duckPlane.reparentTo(render)       #reparent to render
		self.duckPlane.setTransparency(1)
		self.duckTexs = self.loadTextureMovie(24, 'duck/duck_fly_left',
                                          'png', padding = 2)
		self.duckTask = taskMgr.add(self.textureMovie, "duckTask")
		self.duckTask.fps = 36
		self.duckTask.obj = self.duckPlane  
		self.duckTask.textures = self.duckTexs
		self.duckPlane.node().setEffect(BillboardEffect.makePointEye())
		
		self.expPlane = loader.loadModel('Models/plane/plane')  #load the object
		self.expPlane.setScale(18,10,10)
		self.expPlane.setPos(offset_x+0, offset_y+22, offset_z+4)                         #set the position
		self.expPlane.reparentTo(render)                      #reparent to render
		self.expPlane.setTransparency(1)                      #enable transparency

		self.expTexs = self.loadTextureMovie(50, 'explosion/def','png', padding = 4)
    #create the animation task
		self.expTask = taskMgr.add(self.textureMovie, "movieTask")
		self.expTask.fps = 30                                 #set framerate
		self.expTask.obj = self.expPlane                      #set object
		self.expTask.textures = self.expTexs                  #set texture list
		#self.expPlane.node().setEffect(BillboardEffect.makePointEye())
		
		
		self.c1 = loader.loadModel("Models/Dynamite/Dynamite")
		self.c1.setPos(offset_x-6,offset_y+10,offset_z+2)
		self.c1.reparentTo(render)
		
		self.expPlane1 = loader.loadModel('Models/plane/plane')  #load the object
		#self.expPlane1.setScale(1,10,10)
		self.expPlane1.setPos(offset_x-8, offset_y+10, offset_z+3)                         #set the position
		self.expPlane1.reparentTo(render)                      #reparent to render
		self.expPlane1.setTransparency(1)
		
		self.expTexs1 = self.loadTextureMovie(50, 'explosion1/explosion','png', padding = 4)
    #create the animation task
		self.expTask1 = taskMgr.add(self.textureExplosion, "explosionTask")
		self.expTask1.fps = 30                                 #set framerate
		self.expTask1.obj = self.expPlane1                      #set object
		self.expTask1.textures = self.expTexs1                  #set texture list
		self.expPlane1.node().setEffect(BillboardEffect.makePointEye())
		
		self.orientPlane = loader.loadModel('Models/plane/plane') #Load the object
		#self.orientPlane.setScale(1)
		self.orientTex = loader.loadTexture("Models/plane/textures/carpet.jpg")
		self.orientPlane.setTexture(self.orientTex, 1)        #Set the texture
		self.orientPlane.reparentTo(render)		#Parent to render
    #Set the position, orientation, and scale
		self.orientPlane.setPosHprScale(offset_x+0, offset_y+18, offset_z, 0, -90, 0, 20, 20, 20)

	def textureMovie(self, task):
		currentFrame = int(task.time * task.fps)
		task.obj.setTexture(task.textures[currentFrame % len(task.textures)], 1)
		return Task.cont
	def textureExplosion(self, task):
		currentFrame = int(task.time * task.fps)
		#print "curr  "
		#print currentFrame%51
		if((currentFrame%len(task.textures)) > 10):
			self.c1.hide()
		elif((currentFrame%len(task.textures)) <= 0):
			self.c1.show()
		task.obj.setTexture(task.textures[currentFrame % len(task.textures)], 1)
		return Task.cont
	def takeSnapShot(self, task):
		if (task.time > self.nextclick):
			self.nextclick += 1.0 / self.clickrate
			if (self.nextclick < task.time):
				self.nextclick = task.time
			base.win.triggerCopy()
		return Task.cont
	def loadTextureMovie(self, frames, name, suffix, padding = 1):
		return [loader.loadTexture((name+"%0"+str(padding)+"d."+suffix) % i) 
        for i in range(frames)]
	def loadchar(self,main_char,txt):
		self.txt = txt
		if(txt == ''):
			self.t = loader.loadModel("Models/DJTable/DJTable")
			self.t.setPos(offset_x+0,offset_y+20,offset_z)
			self.t.setH(180)
			self.t.reparentTo(render)
			self.setupLights()
			self.loadParticleConfig('fountain2.ptf')
		else:
			self.t = main_char#loader.loadModel("Models/cat-vehicles-road/bvw-f2004--girlscar-egg/bvw-f2004--girlscar/girlcar")#loader.loadModel("Models/cat-vehicles-road/bvw-f2004--carnsx-egg/bvw-f2004--carnsx/carnsx")
			#self.t.setPos(0,20,0)
			#self.t.reparentTo(render)
			self.setupLights()
			self.loadParticleConfig('steam.ptf')
	def loadParticleConfig(self, file):
        #Start of the code from steam.ptf
		self.p.cleanup()
		self.p = ParticleEffect()
		if(self.txt == ''):
			self.txt = ''
			self.p.loadConfig(Filename(file))
			self.p.setPos(0.000, 0, 2.500)  
		elif(self.txt == 'blue'):
			self.txt = ''
			self.p.loadConfig(Filename('steam_front.ptf'))        
			self.p.setPos(0.000, -1.8, -0.800)
			
		elif(self.txt == 'red'):
			self.txt = ''
			self.p.loadConfig(Filename(file))
			self.p.setPos(0.000, 1.800, 0.250)
		self.p.start(self.t)
	def setupLights(self):
		ambientLight = AmbientLight("ambientLight")
		ambientLight.setColor(Vec4(.4, .4, .35, 1))
		directionalLight = DirectionalLight("directionalLight")
		directionalLight.setDirection(Vec3( 0, 8, -2.5 ) )
		directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) )
		
		self.t.setLight(self.t.attachNewNode(directionalLight))
		self.t.setLight(self.t.attachNewNode(ambientLight)) 
#w = Effects()
#run()
Exemple #33
0
class Explosion:
    """An explosion effect.

    Includes sound, light and particle effects.

    Args:
        explode_lights (list): Explosion lights pool.
        parent (object): Object to explode.
        ptf (str): Name of the particles file to use.
        length (float): The length of the effect.
    """

    def __init__(self, explode_lights, parent, ptf, length):
        self._length = length
        self._parent = parent

        self._lights = explode_lights
        self._light_coef = 1.5

        self._sparks = ParticleEffect()
        self._sparks.loadConfig("effects/explode_sparks.ptf")
        self._sparks.setY(0.2)

        self._fire = ParticleEffect()
        self._fire.loadConfig("effects/{}.ptf".format(ptf))
        self._fire.setY(0.1)

        self._snd = base.sound_mgr.loadSfx("sounds/combat/explosion1.ogg")  # noqa: F821
        base.sound_mgr.attachSoundToObject(self._snd, parent.model)  # noqa: F821

    def _clear(self, task):
        """Clear this explosion effect."""
        self._sparks.cleanup()
        self._fire.cleanup()
        base.sound_mgr.detach_sound(self._snd)  # noqa: F821
        return task.done

    def _light_change(self, light, task):
        """Change the explosion light attenuation.

        Implements a gradual (but fast) fall off of the light power.

        Args:
            light (panda3d.core.NodePath): Explosion light object.
        """
        self._light_coef += 0.1

        if self._light_coef >= 10:
            self._lights.append(light)
            light.detachNode()
            light.node().setAttenuation((0, 0, 1))
            return task.done

        light.node().setAttenuation((self._light_coef - 1, 0, self._light_coef))
        return task.again

    def play(self):
        """Do the actual explosion and plan its clearing."""
        self._snd.play()
        self._sparks.start(self._parent.model, render)  # noqa: F821
        self._fire.start(self._parent.model, render)  # noqa: F821

        if self._lights:
            light = self._lights.pop()
            light.reparentTo(self._parent.model)
            light.setPos(0)

            taskMgr.doMethodLater(  # noqa: F821
                0.02,
                self._light_change,
                self._parent.id + "_explosion_light",
                extraArgs=[light],
                appendTask=True,
            )

        taskMgr.doMethodLater(  # noqa: F821
            self._length,
            self._fire.disable,
            self._parent.id + "_disable_exlode_fire",
            extraArgs=[],
        )
        taskMgr.doMethodLater(  # noqa: F821
            4.95,
            self._sparks.disable,
            self._parent.id + "_disable_exlode_sparks",
            extraArgs=[],
        )
        taskMgr.doMethodLater(  # noqa: F821
            5.05, self._clear, self._parent.id + "_clear_explode"
        )
Exemple #34
0
class Player(object, DirectObject.DirectObject):
    #------------------------------------------------------------------------------------------------------
    #Class constructor
    #------------------------------------------------------------------------------------------------------
    def __init__(self):
        self.node = 0  #the player main node
        self.modelNode = 0  #the node of the actual model
        self.cNode = 0  #the player collision node attached to node
        self.cNodePath = 0  #node path to cNode
        self.contrail = ParticleEffect(
        )  #QUANDO BATE, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail.setTransparency(TransparencyAttrib.MDual)
        self.contrail2 = ParticleEffect(
        )  #QUANDO ACIONA TURBO, CRIA EFEITO (LINHA DE BAIXO TB)
        self.contrail2.setTransparency(TransparencyAttrib.MDual)
        self.landing = False
        self.freeLook = False
        self.speed = 10
        self.speedMax = 100
        self.agility = 3
        self.HP = 10
        self.collisionHandler = CollisionHandlerEvent(
        )  # the collision handlers
        self.collisionHandlerQueue = CollisionHandlerQueue()
        self.zoom = -5
        self.gnodePath = 0  #node to phisics
        self.gNode = 0  #node of gravity
        self.gNodePath = 0  #node path to actorNode
        #self

        #add text speed
        #---------------------------------------------------------------------------------
        #self.textSpeed = OnscreenText(text = 'Speed: '+str(self.speed), pos = (-1.34, 0.95), scale = 0.07, fg=(1,1,1,1), bg=(0.2,0.2,0.2,0.4), align=TextNode.ALeft)
        #self.textHP = OnscreenText(text = 'Health:    '+str(self.HP), pos = (-1.33, 0.85), scale = 0.07, fg=(1,1,1,1), bg=(0.2,0.2,0.2,0.4), align=TextNode.ALeft)
        #---------------------------------------------------------------------------------

        self.roll = 0
        self.camHeight = 0

        base.win.movePointer(0,
                             base.win.getXSize() / 2,
                             base.win.getYSize() / 2)

        self.myImage = OnscreenImage(image='cursor.png',
                                     pos=(0, 0, -0.02),
                                     scale=(0.05))
        self.myImage.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModel()
        self.addCamera()
        self.addEvents()
        self.addCollisions()
        self.addSound()

        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.zoomTaskPointer = taskMgr.add(self.zoomTask, 'zoom-task')

    #------------------------------------------------------------------------------------------------------
    #Function to load models and set physics
    #------------------------------------------------------------------------------------------------------
    def loadModel(self):
        #node path for player
        self.node = NodePath('player')
        self.node.setPos(1000, 1000, 200)
        self.node.reparentTo(render)
        self.node.lookAt(0, 0, 200)

        self.modelNode = loader.loadModel('gaivota')
        self.modelNode.reparentTo(self.node)
        self.modelNode.setScale(0.3)
        playerMaterial = Material()
        playerMaterial.setShininess(22.0)  #Make this material shiny
        playerMaterial.setAmbient(VBase4(1, 1, 1, 1))
        playerMaterial.setSpecular(VBase4(0.7, 0.7, 0.7, 0.7))
        self.modelNode.setMaterial(playerMaterial)
        self.modelNode.setShaderAuto()

        self.aimNode = NodePath('aimNode')
        self.aimNode.reparentTo(self.node)
        self.aimNode.setPos(0, 15, 2)

        #self.contrail.loadConfig('media/contrail.ptf')
        #self.contrail.start(self.node,render)
        '''
        --------------------------------------------------------------------------------
        #gravity (aceleration 9.82)
        self.gravityFN=ForceNode('world-forces')
        self.gravityFNP=render.attachNewNode(self.gravityFN)
        self.gravityForce=LinearVectorForce(0,0,-9.82) 
        self.gravityFN.addForce(self.gravityForce)
        
        #add gravity to engine
        #base.physicsMgr.addLinerForce(self.gravityForce)
        
        #Physics node
        self.gnodePath = NodePath(PandaNode("physics"))
        self.gNode = ActorNode("plane-actornode")
        self.gNodePath = self.gnodePath.attachNewNode(self.gNode)
        
        #object weigth
        self.gNode.getPhysicsObject().setMass(0.004)
        
        #add gravity force
        base.physicsMgr.addLinearForce(self.gravityForce)
        base.physicsMgr.attachPhysicalNode(self.gNode)
        
        #render object with physics
        self.gnodePath.reparentTo(render)
        self.node.reparentTo(self.gNodePath)
        --------------------------------------------------------------------------------
        '''

    #------------------------------------------------------------------------------------------------------
    #Function that add camera to airplane
    #------------------------------------------------------------------------------------------------------
    def addCamera(self):
        base.disableMouse()
        base.camera.reparentTo(self.node)
        base.camera.setPos(0, self.zoom, 2)
        base.camera.lookAt(self.aimNode)

    #------------------------------------------------------------------------------------------------------
    #Functions for airplane events
    #------------------------------------------------------------------------------------------------------
    def addEvents(self):
        self.accept("wheel_up", self.evtSpeedUp)
        self.accept("wheel_down", self.evtSpeedDown)
        self.accept('hit', self.evtHit)
        self.accept('f', self.evtFreeLookON)
        self.accept('f-up', self.evtFreeLookOFF)
        self.accept('mouse3', self.evtBoostOn)
        self.accept("menuOpen", self.evtMenuOpen)
        self.accept("menuClosed", self.evtMenuClose)

    #------------------------------------------------------------------------------------------------------
    #Functions that add collisions for the airplane
    #------------------------------------------------------------------------------------------------------
    def addCollisions(self):
        self.cNode = CollisionNode('player')
        self.cNode.addSolid(CollisionSphere(0, 0, 0, 2.3))
        self.cNode.setFromCollideMask(BitMask32(0x1A))
        self.cNode.setIntoCollideMask(BitMask32(0x4))

        self.cNodePath = self.node.attachNewNode(self.cNode)
        #self.cNodePath.show()
        self.collisionHandler.addInPattern('hit')
        base.cTrav.addCollider(self.cNodePath, self.collisionHandler)

        # landing segment:
        self.landingCNodeSegment = CollisionNode('playerRay')
        self.landingCNodeSegment.addSolid(CollisionSegment(0, 0, 0, 0, 0, -20))
        self.landingCNodeSegment.setIntoCollideMask(BitMask32.allOff())
        self.landingCNodeSegment.setFromCollideMask(BitMask32(0x8))

        self.landingCNodeSegmentPath = self.node.attachNewNode(
            self.landingCNodeSegment)
        #self.landingCNodeSegmentPath.show()
        base.cTrav.addCollider(self.landingCNodeSegmentPath,
                               self.collisionHandlerQueue)

    #------------------------------------------------------------------------------------------------------
    #Function to add sound to airplane
    #------------------------------------------------------------------------------------------------------
    def addSound(self):
        self.engineSound = loader.loadSfx("engine.mp3")
        self.engineSound.setLoop(True)
        #self.engineSound.play()
        self.engineSound.setVolume(2.0)
        self.engineSound.setPlayRate(0)

        #Add environment music
        #-------------------------------------------------------------------------------
        self.MusicSound = loader.loadSfx("warm-interlude.mp3")
        self.MusicSound.setLoop(True)
        #self.MusicSound.play()
        self.MusicSound.setVolume(1.5)
        self.MusicSound.setPlayRate(0)

    #------------------------------------------------------------------------------------------------------
    #Function to delete task
    #------------------------------------------------------------------------------------------------------
    def deleteTask(self, task):
        self.__del__()
        return task.done

    #------------------------------------------------------------------------------------------------------
    #Function that update mouse moviments
    #------------------------------------------------------------------------------------------------------
    def mouseUpdateTask(self, task):
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        deltaX = 0
        deltaY = 0
        if base.win.movePointer(0,
                                base.win.getXSize() / 2,
                                base.win.getYSize() / 2):
            deltaX = (
                x - base.win.getXSize() / 2
            ) * 0.06  #* globalClock.getDt() *70 #* self.agility * (0.5+abs(self.roll)/50)
            deltaY = (y - base.win.getYSize() / 2) * 0.06
            if deltaX > self.agility:
                deltaX = self.agility
            if deltaX < -self.agility:
                deltaX = -self.agility
            if deltaY > self.agility:
                deltaY = self.agility
            if deltaY < -self.agility:
                deltaY = -self.agility

            # don't move ship while in freelook mode
            if not self.freeLook:
                self.node.setH(self.node.getH() - deltaX)
                self.node.setP(self.node.getP() - deltaY)

        # don't move ship while in freelook mode
        if not self.freeLook:
            self.roll += deltaX
            self.camHeight += deltaY

        self.roll *= 0.95  #/ (globalClock.getDt() * 60)#* globalClock.getDt() * 700
        self.camHeight *= 0.95  #* globalClock.getDt() * 700

        if self.roll < -25 * self.speed / self.speedMax:
            self.roll = -25 * self.speed / self.speedMax
        if self.roll > 25 * self.speed / self.speedMax:
            self.roll = 25 * self.speed / self.speedMax

        self.node.setR(self.roll * 3)
        base.camera.setZ(2 - self.camHeight * 0.5 * self.speed / self.speedMax)
        base.camera.lookAt(self.aimNode)
        base.camera.setR(-self.roll * 2)
        #base.camera.setY(-30+self.speed/10)
        #base.camera.setX(self.roll*0.5)

        # freelook mode:
        if self.freeLook:
            self.camRotH -= deltaX * 3
            self.camRotV -= deltaY * 3
            if self.camRotV < 1:
                self.camRotV = 1
            if self.camRotV > 179:
                self.camRotV = 179

            base.camera.setX(
                math.cos(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setY(
                math.sin(math.radians(self.camRotH)) *
                math.sin(math.radians(self.camRotV)) * 30)
            base.camera.setZ(math.cos(math.radians(self.camRotV)) * 30)
            base.camera.lookAt(self.node)

        return task.cont

    #------------------------------------------------------------------------------------------------------
    #Function that update players position
    #------------------------------------------------------------------------------------------------------
    def moveUpdateTask(self, task):
        # move where the keys set it
        self.node.setPos(self.node,
                         Vec3(0, 1.0 * globalClock.getDt() * self.speed, 0))

        #self.node.setPos(self.node,self.strafe*globalClock.getDt()*self.speed)
        return task.cont

    #------------------------------------------------------------------------------------------------------
    #Function that control the explosion of the airplane
    #------------------------------------------------------------------------------------------------------
    def explode(self):
        self.ignoreAll()
        self.cNode.setIntoCollideMask(BitMask32.allOff())
        taskMgr.remove(self.moveTask)
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.zoomTaskPointer)
        self.moveTask = 0
        self.mouseTask = 0

        if self.contrail != 0:
            self.contrail.cleanup()
        self.modelNode.hide()

        self.contrail = ParticleEffect()
        self.contrail.loadConfig('media/explosion.ptf')
        self.contrail.start(self.node)
        self.contrail.setLightOff()
        self.contrail2.cleanup()

        #add explosion sound
        #------------------------------------------------------------------------------
        self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0],
                                                     base.camera)
        self.audio3d.setDropOffFactor(0.2)
        self.Sound = self.audio3d.loadSfx('explosion.mp3')
        self.audio3d.detachSound(self.Sound)
        self.audio3d.attachSoundToObject(self.Sound, self.node)
        #self.Sound.play()
        #------------------------------------------------------------------------------

        self.deleteTask = taskMgr.doMethodLater(4, self.deleteTask,
                                                'delete task')

    #------------------------------------------------------------------------------------------------------
    #Function for zoom
    #------------------------------------------------------------------------------------------------------
    def zoomTask(self, task):
        if base.camera.getY() != self.zoom and self.freeLook == False:
            base.camera.setY(base.camera.getY() +
                             (self.zoom - base.camera.getY()) *
                             globalClock.getDt() * 2)
        return task.cont

    #------------------------------------------------------------------------------------------------------
    #Function that increase speed
    #------------------------------------------------------------------------------------------------------
    def evtBoostOn(self):
        #taskMgr.remove(self.mouseTask)
        self.ignore("wheel_up")
        self.ignore("wheel_down")
        self.ignore('f')
        self.ignore('f-up')
        self.accept('mouse3-up', self.evtBoostOff)
        self.speed += 200
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.contrail2.loadConfig('media/contrail-boost.ptf')
        self.contrail2.start(self.node)
        self.zoom = -25
        self.evtFreeLookOFF()

    #------------------------------------------------------------------------------------------------------
    #Function that decrease speed
    #------------------------------------------------------------------------------------------------------
    def evtBoostOff(self):
        self.speed -= 200
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.ignore('mouse3-up')
        self.addEvents()
        #self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        #self.contrail.loadConfig('../../media/contrail.ptf')
        self.contrail2.softStop()
        self.zoom = -5 - (self.speed / 10)

    #------------------------------------------------------------------------------------------------------
    #Function that controls the event when the airplane hit something
    #------------------------------------------------------------------------------------------------------
    def evtHit(self, entry):
        if entry.getIntoNodePath().getParent().getTag(
                "orign") != self.node.getName():

            #if entry.getIntoNodePath().getName() == "projectile":
            #self.HP -= 1
            #self.textHP.setText('HP   : '+str(self.HP))
            if self.HP == 0:
                self.explode()
            else:
                self.explode()

    #------------------------------------------------------------------------------------------------------
    #Function for freelook on
    #------------------------------------------------------------------------------------------------------
    def evtFreeLookON(self):
        if self.landing == False:
            self.freeLook = True
            self.camRotH = 270
            self.camRotV = 80
            self.myImage.hide()

    #------------------------------------------------------------------------------------------------------
    #Function for freelook off
    #------------------------------------------------------------------------------------------------------
    def evtFreeLookOFF(self):
        if self.landing == False:
            self.freeLook = False
            base.camera.setPos(0, -20, 2)
            base.camera.lookAt(self.aimNode)
            self.myImage.show()

    #------------------------------------------------------------------------------------------------------
    #Function that delete features of the airplane
    #------------------------------------------------------------------------------------------------------
    def __del__(self):
        self.ignoreAll()
        self.contrail.cleanup()

        #delete stop the sound
        #-------------------------------------------------------------------------------
        self.Sound.stop()
        self.audio3d.detachSound(self.Sound)
        self.engineSound.stop()
        self.MusicSound.stop()
        #-------------------------------------------------------------------------------

        base.camera.reparentTo(render)
        base.camera.setPos(2000, 2000, 800)
        base.camera.lookAt(0, 0, 0)
        if self.moveTask != 0:
            taskMgr.remove(self.moveTask)
        if self.mouseTask != 0:
            taskMgr.remove(self.mouseTask)
        self.node.removeNode()
        messenger.send('player-death')

    #------------------------------------------------------------------------------------------------------
    #Function that conrol event that increse speed
    #------------------------------------------------------------------------------------------------------
    def evtSpeedUp(self):
        if self.landing:
            return 0
        self.speed += 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() + 0.05)
        if self.speed > self.speedMax:
            self.speed = self.speedMax
            #self.engineSound.setVolume(1)
            self.engineSound.setPlayRate(1.5)
        self.zoom = -5 - (self.speed / 10)
        #speed text
        #self.textSpeed.setText('Speed: '+str(self.speed))

    #------------------------------------------------------------------------------------------------------
    #Function that control event that decrease speed
    #------------------------------------------------------------------------------------------------------
    def evtSpeedDown(self):
        if self.landing:
            return 0
        #speed text
        #self.textSpeed.setText('Speed: '+str(self.speed))
        self.speed -= 5
        self.engineSound.setPlayRate(self.engineSound.getPlayRate() - 0.05)
        if self.speed < 0:
            self.speed = 0
            #self.engineSound.setVolume(0)
            self.engineSound.setPlayRate(0.5)
        self.zoom = -5 - (self.speed / 10)

    #------------------------------------------------------------------------------------------------------
    #Function that control open menu event(ESC)
    #------------------------------------------------------------------------------------------------------
    def evtMenuOpen(self):
        taskMgr.remove(self.mouseTask)
        taskMgr.remove(self.moveTask)
        self.myImage.hide()
        props = WindowProperties()
        props.setCursorHidden(0)
        base.win.requestProperties(props)
        #disable physics when esc is pressed
        base.disableParticles()
        #control volume
        self.engineSound.stop()
        self.MusicSound.setVolume(0.5)

    #------------------------------------------------------------------------------------------------------
    #Function that control close menu event(ESC)
    #------------------------------------------------------------------------------------------------------
    def evtMenuClose(self):
        #self.addEvents()
        props = WindowProperties()
        props.setCursorHidden(1)
        base.win.requestProperties(props)
        self.mouseTask = taskMgr.add(self.mouseUpdateTask, 'mouse-task')
        self.moveTask = taskMgr.add(self.moveUpdateTask, 'move-task')
        self.myImage.show()
        #enable physics after menu closed
        base.enableParticles()
        #control volume
        #self.engineSound.play()
        self.MusicSound.setVolume(1.5)
Exemple #35
0
class Arena:
    def __init__(self, arenaNr):
        arenaPath = "levels/arena%d/" % arenaNr
        self.arena = loader.loadModel(arenaPath + "arena")
        self.arena.setScale(2)
        self.arena.reparentTo(render)
        self.arena.hide()

        ambientLight = AmbientLight("ambient_light")
        ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.alnp = render.attachNewNode(ambientLight)

        sunLens = PerspectiveLens()
        sunLens.setFilmSize(50)
        sun = DirectionalLight("sun")
        sun.setColor((1, 1, 1, 1))
        sun.setShadowCaster(True, 2048, 2048)
        sun.setScene(render)
        #sun.showFrustum()

        self.ambientSound = None
        self.levelParticles = None
        if arenaNr == 1:
            sunLens.setNearFar(25,45)
            sun.setLens(sunLens)
            self.sunNp = render.attachNewNode(sun)
            self.sunNp.setPos(-10, -10, 30)
            self.sunNp.lookAt(0,0,0)

            self.ambientSound = loader.loadSfx("assets/audio/ambientLevel1.ogg")
            self.ambientSound.setLoop(True)

            self.fog = Fog("Outside Fog")
            self.fog.setColor(0.3,0.3,0.5)
            self.fog.setExpDensity(0.025)

            self.levelParticles = ParticleEffect()
            self.levelParticles.loadConfig("assets/fx/Leafs.ptf")
            self.levelParticles.start(parent = render2d, renderParent = render2d)
        elif arenaNr == 2:
            sunLens.setFov(120, 40)
            sunLens.setNearFar(2,10)
            sun.setLens(sunLens)
            self.sunNp = render.attachNewNode(sun)
            self.sunNp.setPos(0, 0, 5)
            self.sunNp.lookAt(0,0,0)

            self.fog = Fog("Temple Fog")
            self.fog.setColor(0,0,0)
            self.fog.setExpDensity(0.065)

    def start(self):
        self.arena.show()
        render.setLight(self.alnp)
        render.setLight(self.sunNp)
        if self.ambientSound != None:
            self.ambientSound.play()
        render.setFog(self.fog)

    def stop(self):
        self.arena.hide()
        render.clearLight()
        if self.ambientSound != None:
            self.ambientSound.stop()
        render.clearFog()
        if self.levelParticles != None:
            self.levelParticles.cleanup()

    def getStartPos(self, charNr):
        if charNr == 1:
            return self.arena.find("**/StartPosA").getPos() * 2
        elif charNr == 2:
            return self.arena.find("**/StartPosB").getPos() * 2
        else:
            return (0,0,0)
class RoamingPenguinDemo(ShowBase):
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0,
        }

    

        ###########################################################################

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)

        # We do not have a skybox, so we will just use a sky blue background color
        #self.setBackgroundColor(0.53, 0.80, 0.92, 1)
        self.setBackgroundColor(.1, .1, .1, 1)
        # Create the main character, person

        #personStartPos = self.environ.find("**/start_point").getPos()
        #self.person = Actor("models/panda",
         #                  {"run": "models/panda-walk",
          #                  "walk": "models/panda-walk"})

        person2StartPos = self.environ.find("**/start_point").getPos()
        self.person2 = Actor("models/passenger_penguin",
                           {"run": "models/passenger_penguin",
                            "walk": "models/passenger_penguin"})

       
        self.person2.reparentTo(render)
        self.person2.setScale(.1)
   
        self.person2.setPos(person2StartPos + (px, py, 1))


        person3StartPos = self.environ.find("**/start_point").getPos()
        self.person3 = Actor("models/MagicBunny",
                           {"run": "models/MagicBunny",
                            "walk": "models/MagicBunny"})

        #px = random.randint(-1,1)
        #py = random.randint(-1,1)


        self.person3.reparentTo(render)
        self.person3.setScale(.04)
        #self.person.setPos(personStartPos + (0, 0, 2))
        self.person3.setPos(person3StartPos + (px/1.5+3, py/2, 0))

        personStartPos = self.environ.find("**/start_point").getPos()
        self.person = Actor("models/panda",
                           {"run": "models/panda-walk",
                            "walk": "models/panda-walk"})


        self.person.reparentTo(render)
        self.person.setScale(.1)
        self.person.setPos(personStartPos + (0, 0, 1.5))
        self.person.loop("run")


        arenaStartPos = self.environ.find("**/start_point").getPos()
        self.arena = Actor("models/FarmHouse")


        self.arena.reparentTo(render)
        self.arena.setScale(.1)
        self.arena.setPos(arenaStartPos + (-1, 0, 0))


        arena2StartPos = self.environ.find("**/start_point").getPos()
        self.arena2 = Actor("models/fence")


        self.arena2.reparentTo(render)
        self.arena2.setScale(5.9)
        self.arena.setPos(arenaStartPos + (px, py-12, 1))
        self.arena2.setPos(arenaStartPos + (8, 5, -1))


        arena2StartPos = self.environ.find("**/start_point").getPos()
        self.arena3 = Actor("models/gate")


        self.arena3.reparentTo(render)
        self.arena3.setScale(.01)

        self.arena3.setPos(arenaStartPos + (px/2+random.randint(12,15), py/2, -1))

        self.arena4 = Actor("models/FarmHouse")
        self.arena4.reparentTo(render)
        self.arena4.setScale(.1)

        self.arena4.setPos(arenaStartPos + (px/3-random.randint(18,22), py/3, -1))


        self.arena5 = Actor("models/gate")
        self.arena5.reparentTo(render)
        self.arena5.setScale(.008)

        self.arena5.setPos(arenaStartPos + (px/1.2-9, py/1.2, -1))

        #####################################################################################################################################
        base.enableParticles()
        self.t = loader.loadModel("teapot") # for the particle enhancer
        self.t.setScale(10)
        self.t.setPos(-10, -20, -1)
        self.t.reparentTo(render)
        #self.setupLights()
        self.p = ParticleEffect()
        self.p.setScale(1000)
        self.loadParticleConfig('smoke.ptf') # looks like a storm at night
        self.p.setScale(20)




        #################################################3

        # Create a floater object, which floats 2 units above person.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.person)
        self.floater.setZ(2.0)

        # Accept the control keys for movement and rotation


        taskMgr.add(self.move, "moveTask")

        # Set up the camera
        self.disableMouse()
        self.camera.setPos(self.person.getX(), self.person.getY() + 10, 2)

        self.cTrav = CollisionTraverser()

    
        self.personCol = CollisionNode('person')
        self.personCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5))
        self.personCol.addSolid(CollisionSphere(center=(0, -0.25, 4), radius=1.5))
        self.personCol.setFromCollideMask(CollideMask.bit(0))
        self.personCol.setIntoCollideMask(CollideMask.allOff())
        self.personColNp = self.person.attachNewNode(self.personCol)
        self.personPusher = CollisionHandlerPusher()
        self.personPusher.horizontal = True

        self.personPusher.addCollider(self.personColNp, self.person)
        self.cTrav.addCollider(self.personColNp, self.personPusher)

        
        self.personGroundRay = CollisionRay()
        self.personGroundRay.setOrigin(0, 0, 9)
        self.personGroundRay.setDirection(0, 0, -1)
        self.personGroundCol = CollisionNode('personRay')
        self.personGroundCol.addSolid(self.personGroundRay)
        self.personGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.personGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.personGroundColNp = self.person.attachNewNode(self.personGroundCol)
        self.personGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.personGroundColNp, self.personGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

       
   

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, .2))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((.2, .2, .2, 1))
        directionalLight.setSpecularColor((.1, .1, .1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    def loadParticleConfig(self, filename):
        # Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(filename))
    
        self.p.start(self.t)
        self.p.setPos(3.000, 0.000, 2.250)




    # Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value


    def move(self, task):

      
        dt = globalClock.getDt()
       

        #z = abs(py)
        self.person.setX(self.person, 4 * dt)
        self.person.setX(self.person, -4 * dt)

        ## this is how the Panda finds his friend

        if px < 0 :
            #if self.person.getPos() - self.person2.getPos() < (0, 0, 0) :
            if self.person.getY() - self.person2.getY() < 6 :
            #self.person.getPos(personStartPos + (0, py, 1.5))
                self.person.setY(self.person, 0 * dt)
                self.person.stop()
                self.person.pose("walk", 5)
                self.isMoving = False
            else:
                self.person.setY(self.person, py * dt)
                self.person.setX(self.person, px * dt)
                self.person.setH(self.person, px/(abs(px)+6)* dt)
        else:
            if self.person.getY() - self.person2.getY() < 6 :
            #self.person.getPos(personStartPos + (0, py, 1.5))
                self.person.setY(self.person, 0 * dt)
                self.person.stop()
                self.person.pose("walk", 5)
                self.isMoving = False
            else:
                self.person.setY(self.person, py * dt)
                self.person.setX(self.person, px * dt)
                self.person.setH(self.person, px/(abs(px)+6)* dt)


        if self.keyMap["cam-left"]:
            self.camera.setX(self.camera, -20 * dt)
        if self.keyMap["cam-right"]:
            self.camera.setX(self.camera, +20 * dt)

       
        camvec = self.person.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

    

        entries = list(self.personGroundHandler.entries)
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())

        for entry in entries:
            if entry.getIntoNode().getName() == "terrain":
                self.person.setZ(entry.getSurfacePoint(render).getZ())

     

        entries = list(self.camGroundHandler.entries)
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())

        for entry in entries:
            if entry.getIntoNode().getName() == "terrain":
                self.camera.setZ(entry.getSurfacePoint(render).getZ() + 3.5)
        if self.camera.getZ() < self.person.getZ() + 4.0:
            self.camera.setZ(self.person.getZ() + 4.0)

       
        self.camera.lookAt(self.floater)

        return task.cont
Exemple #37
0
class PipeWires:
    """
    Creates self contained pipe objects with methods that create,
    reference, and destroy models, collision tubes, lights,
    particles, and ActionCommand sequences.
    """



    def __init__(self):

        #SoundIntervals
        #base = ShowBase()
        self.sound = loader.loadSfx("../audio/sparks.wav")
        self.sound.setLoop(True)
        self.sound.play()

        #pick file
        self.fileName = "../models/tunnelwires"
        
        #load model
        self.model = loader.loadModel(self.fileName)
        self.model.setScale(.0175)
        #print self.model.ls()

        self.nodePath = NodePath(self.model)
        self.model.reparentTo(render)
        self.key = self.model.getKey()


        ##self.addModel(bag)
        self.addPointLight(self.model)
        self.shaderEnabled = 0
        #self.addShader()        
        #self.addCollision()
        ##self.addParticle(self.model)

        base.enableParticles()

        self.particle = ParticleEffect()
        self.loadParticleConfig('../models/', 'spark.ptf')
        #self.loadParticleConfig("spark.ptf")

        self.addActionCommand("ru")
        self.type = "wires"

        #rotate by 0, 90, 180, or 270 degrees
        self.model.setR(random.randint(0,3)*90)
        #print self.model.getR()

    def addPointLight(self, pipe):
        """create a point light for pipe"""

        #The redpoint light and helper
        #RED
        # r = random.uniform(700, 900) / 1000
        # g = random.uniform(0, 300) / 1000
        # b = g

        #ORANGE
        r = 1
        b = random.randint(0,91)
        g = (b / 2) + 102
        b = b / 255.0
        g = g / 255.0
        self.helper = loader.loadModel("../models/sphere.egg.pz")

        self.helper.setColor( Vec4( r, g, b, 1 ) )
        self.helper.setPos(pipe.getPos())
        #print self.helper.getColor()

        #This is value is irrelevent at the moment unless I move the lights
        self.helper.setScale(.25*1) #must be greater than 0.001


        #optionally set location of light within pipe
        self.helper.setY(self.helper.getY()-50*35 ) #moves to inbetween segments
        self.helper.setZ(self.helper.getZ()-50*6 ) #makes 3 sided lights

        self.light = self.helper.attachNewNode( PointLight( "self.light" ) )
        self.light.node().setAttenuation( Vec3( .1, 0.04, 0.1 )/2.5 )
        self.light.node().setColor( Vec4( r, g, b, 1 ) )
        self.light.node().setSpecularColor( Vec4( 1 ) )
        self.helper.reparentTo( pipe )
        render.setLight( self.light )
        ###
        self.h = loader.loadModel("../models/sphere.egg.pz")
        self.h.setPos(0, -300, 200)
        self.h.setScale(.25*1)
        self.spl = self.h.attachNewNode( Spotlight( "self.spl") )
        self.spl.node().setColor( Vec4( 5, 5, 5, 1 ) )
        #self.spl.node().setAttenuation( Vec3( 0.003, 0.003, 0.003 ) )
        self.spl.lookAt(0, 20, -200)
        
        self.h.reparentTo( pipe)
        render.setLight( self.spl)
        

    ###def addModel(self, bag):
        """Adds the model to the pipe object"""        
        ####moved to init for some reason


    def addShader(self):
        self.model.setShaderAuto()
        self.shaderEnabled = 1


    def addCollision(self):
        #Finding and adding collision tube to the pipe
        #cSphere = CollisionSphere((200,0,0), 100)
        cNode = self.nodePath.find("**/tube_collision").node()
        #cNode = CollisionNode("pipeCollision")
        #cNode.addSolid(solid)
        self.collision = self.model.attachNewNode(cNode)
        self.collision.show()


    def loadParticleConfig(self, path, file):
        #Start of the code from steam.ptf
        self.particle.cleanup()
        self.particle = ParticleEffect()
        self.particle.loadConfig(Filename(path, file))
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.particle.start(self.model)
        self.particle.setScale(100)
        self.particle.setPos(0.00, -200.000, -200.00)



    def addActionCommand(self, command):
        self.actionCommand = ActionCommand(command.__len__(), command, command)


    def destroy(self):
        #Remove particles from particle list
        #Idea: Instead of deleting particle effects, try moving them
        #to new pipe segment?
        # self.particle.cleanup()
        # self.particle.removeNode()

        #stop sound
        self.sound.setLoop(False)
        self.sound.stop()

        #remove pointLight from segment
        render.clearLight(self.light)
        render.clearLight(self.spl)
        #render.clearLight(self.plight)
        self.helper.removeNode()

        #remove pipe segment
        self.model.removeNode()

    def reactivate(self, pipe):
        print pipe.nodePath.ls()
        print "\n\n\n\n"
        self.model = pipe.model
        self.helper = pipe.helper
        self.light = pipe.light.node()
        self.shaderEnabled = 0
        self.collision = pipe.collision.node()
        #self.particle = pipe.particle
        
        #rotate by 0, 90, 180, or 270 degrees
        self.model.setR(random.randint(0,3)*90)

    def recycle(self):
        #rotate by 0, 90, 180, or 270 degrees
        self.model.setR(random.randint(0,3)*90)

        #ORANGE
        r = 1
        b = random.randint(0,91)
        g = (b / 2) + 102
        b = b / 255.0
        g = g / 255.0
        self.helper.setColor( Vec4( r, g, b, 1 ) )
        self.light.node().setColor( Vec4( r, g, b, 1 ) )
        self.actionCommand.resetCommand()

    def isCommandEmpty(self):
        print "LETS FIND OUT"
        return self.actionCommand.isEmpty()
class Demo(ShowBase):

    def __init__(self):

        ShowBase.__init__(self)

        self.title = OnscreenText(
            text = "Panda3D : Tutorial - Particles",
            parent = self.a2dBottomCenter,
            style = 1,
            fg = (1, 1, 1, 1),
            pos = (0.06, -0.06),
            align = TextNode.ALeft,
            scale = 0.05
        )

        self.accept("escape", sys.exit)
        self.accept("1", self.loadParticleConfig, ["steam.ptf"])
        self.accept("2", self.loadParticleConfig, ["dust.ptf"])
        self.accept("3", self.loadParticleConfig, ["fountain.ptf"])
        self.accept("4", self.loadParticleConfig, ["smoke.ptf"])
        self.accept("5", self.loadParticleConfig, ["smokering.ptf"])
        self.accept("6", self.loadParticleConfig, ["fireish.ptf"])

        self.disableMouse()
        self.cam.setPos(0, -20, 2)
        self.camLens.setFov(25)
        self.setBackgroundColor(0, 1, 0)

        self.enableParticles()
        self.teapot = self.loader.loadModel("teapot")
        self.teapot.setPos(0, 10, 0)
        self.teapot.reparentTo(self.render)
        self.setupLights()
        self.particle = ParticleEffect()
        self.loadParticleConfig("steam.ptf")

        self.accept("w", self.toggle_particle)

    def toggle_particle(self):

        particleSeq = Sequence(Func(self.particle_start),
                               Wait(2),
                               Func(self.particle_end))

        particleSeq.start()

    def loadParticleConfig(self, filename):

         self.particle.cleanup()
         self.particle = ParticleEffect()
         self.particle.loadConfig("/e/Panda3D-1.9.2-x64/samples/particles/"+filename)

         #self.particle.start(self.teapot)
         self.particle.setPos(3, 0, 2.225)

    def particle_start(self):

        self.particle.start(self.teapot)

    def particle_end(self):

        self.particle.softStop()

    def setupLights(self):

        ambientLight = AmbientLight("ambiengtLight")
        ambientLight.setColor((0.4, 0.4, 0.35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 8, -2.5))
        directionalLight.setColor((0.9, 0.8, 0.9, 1))
        directionalLight.setColor((0.9, 0.8, 0.9, 1))

        self.teapot.setLight(self.teapot.attachNewNode(directionalLight))
        self.teapot.setLight(self.teapot.attachNewNode(ambientLight))
Exemple #39
0
class Balle(ShowBase):

    balleID = 0

    def __init__(self, identifiantLanceur,mondePhysique):
        self.mondePhysique = mondePhysique
        self.lanceurId = identifiantLanceur
        self.balleId = Balle.balleID
        Balle.balleID += 1

        self.forceApplique = Vec3(0,0,0)

        # On charge le modèles
        self.modele = loader.loadModel("../asset/Balle/ball")
        self.modele.reparentTo(render)
        #On réduit sa taille un peu...
        self.modele.setScale(0.5,0.5,0.5)

        #On ajoute une sphere de physique
        forme = BulletSphereShape(0.2)
        noeud = BulletRigidBodyNode("Balle")
        noeud.addShape(forme)
        self.noeudPhysique = render.attachNewNode(noeud)
        self.noeudPhysique.node().setMass(1.0)
        self.modele.reparentTo(self.noeudPhysique)

        self.accept("detonateur-explosion",self.detonateurDistance)

        self.noeudPhysique.setTag("EntiteTankem","Balle")
        self.noeudPhysique.setTag("balleId",str(self.balleId))
        self.noeudPhysique.setTag("lanceurId",str(self.lanceurId))

        self.pftExplosion = ParticleEffect()
        self.pftExplosion.loadConfig("../asset/Particle/tankemExplode.ptf")

        self.pftRacine = NodePath("Racine pfx expolision")
        self.pftRacine.reparentTo(render)

    def detonateurDistance(self, identifiantDetonateur):
        if(identifiantDetonateur == self.lanceurId):
            self.exploser()

    def exploser(self):
        if(self.etat == "actif"):
            self.etat = "explose"

            #Arrêt de la sequence de destruction automatique
            if hasattr(self, 'sequenceExplosionAutomatique'):
               self.sequenceExplosionAutomatique.finish()

            if hasattr(self, 'sequenceMissileGuide'):
               self.sequenceMissileGuide.finish()

            #On désactive le mouvement sur cette balle
            #Les collisions seront détectées mais la balle
            #ne bougera pas
            self.noeudPhysique.node().setKinematic(True)

            #self.modele.setTransparency(TransparencyAttrib.MAlpha)
            grosseurScaleFinal = 10.0
            self.modele.removeNode()

            intervalPhysique = LerpScaleInterval(self.noeudPhysique, 0.2, grosseurScaleFinal, 1.0)
            #intervalCouleur = LerpColorScaleInterval(self.modele,0.3,LVecBase4(0.8,0.2,0.2,0),self.modele.getColorScale())
            fonctionDetruire = Func(self.destroy)
            self.sequenceDetruire = Sequence(Wait(0.5),fonctionDetruire)

            intervalPhysique.start()
            self.sequenceDetruire.start()
            self.pftRacine.setPos(self.noeudPhysique.getPos())
            self.pftExplosion.start(parent = self.pftRacine, renderParent = self.pftRacine)

    def projetter(self, position, direction):
        self.etat = "actif"

        self.noeudPhysique.setPos(position)

        self.modele.setColorScale(0.8,0.3,0,1)
        
        self.noeudPhysique.node().setGravity(0.0)
        self.noeudPhysique.node().setLinearDamping(0.0)
        self.noeudPhysique.node().setFriction(0.0)
        self.noeudPhysique.node().setRestitution(2.0)
        vitesseBalle = 14
        self.noeudPhysique.node().applyCentralImpulse(direction * vitesseBalle)
        self.mondePhysique.attachRigidBody(self.noeudPhysique.node())

        self.intervalExplosion(1.2)

    def projetterRapide(self, position, direction):
        self.etat = "actif"

        self.noeudPhysique.setPos(position)

        self.modele.setColorScale(0.1,0.1,0,1)
        
        self.noeudPhysique.node().setGravity(0.0)
        self.noeudPhysique.node().setLinearDamping(0.0)
        self.noeudPhysique.node().setFriction(0.0)
        self.noeudPhysique.node().setRestitution(2.0)
        vitesseBalle = 18
        self.noeudPhysique.node().applyCentralImpulse(direction * vitesseBalle)
        self.mondePhysique.attachRigidBody(self.noeudPhysique.node())

        self.intervalExplosion(0.8)

    def projetterVariable(self, position, direction):
        self.etat = "actif"

        self.noeudPhysique.setPos(position)

        self.modele.setColorScale(0.9,0.9,0.9,1)
        
        self.noeudPhysique.node().setGravity(0.0)
        self.noeudPhysique.node().setLinearDamping(0.0)
        self.noeudPhysique.node().setFriction(0.0)
        self.noeudPhysique.node().setRestitution(2.0)
        vitesseBalle = 13
        self.noeudPhysique.node().applyCentralImpulse(direction * vitesseBalle)
        self.mondePhysique.attachRigidBody(self.noeudPhysique.node())

        self.intervalExplosion(0.5)

    def deposer(self, position, direction):
        self.etat = "actif"

        self.noeudPhysique.setPos(position)

        self.modele.setColorScale(0.3,0.9,0.3,1)
        
        self.noeudPhysique.node().setLinearDamping(0.7)
        self.noeudPhysique.node().setFriction(0.7)
        self.noeudPhysique.node().setRestitution(0.0)
        vitesseBalle = 4
        self.noeudPhysique.node().applyCentralImpulse(direction * vitesseBalle)
        self.mondePhysique.attachRigidBody(self.noeudPhysique.node())

        self.intervalExplosion(10)

    def appliquerForce(self):
        self.noeudPhysique.node().applyCentralForce(self.forceApplique)

    def lancer(self, position, direction, vitesseInitialeBalle=16):
        self.etat = "actif"

        self.modele.setColorScale(0.8,0.1,0.6,1)

        self.noeudPhysique.setPos(position)
        self.noeudPhysique.node().setMass(2.0)
        self.noeudPhysique.node().setLinearDamping(0.1)
        self.noeudPhysique.node().setAngularDamping(0.99)
        self.noeudPhysique.node().setFriction(0.9)
        self.noeudPhysique.node().setRestitution(1.0)

        self.accept("appliquerForce",self.appliquerForce)
        self.forceApplique = Vec3(0.0,0.0,-50)
        
        #On lancera à enciron 60 degré la balle
        directionFinale = direction + Vec3(0,0,3)
        directionFinale.normalize()
        self.noeudPhysique.node().setLinearVelocity(directionFinale * vitesseInitialeBalle)
        self.mondePhysique.attachRigidBody(self.noeudPhysique.node())

        self.intervalExplosion(3.0)

    def lancerGuide(self, position, noeudCible):
        #On ignore la direction du tank, on lance la balle dans les airs
        self.lancer(position, Vec3(0,0,1),vitesseInitialeBalle=18)

        #C'est un ange de la mort... on le colore rouge foncé!
        self.modele.setColorScale(0.3,0,0.1,1)

        #On créé ensuite une séquence pour le guidage automatique
        attendre = Wait(0.65)
        fonctionViser = Func(self.lancerSurCible, noeudCible)
        self.sequenceMissileGuide = Sequence(attendre,fonctionViser)
        self.sequenceMissileGuide.start()

    def lancerSurCible(self,noeudCible):
        #Calcul de la direction de la balle
        vecteurDifference = noeudCible.getPos() - self.noeudPhysique.getPos()
        vecteurDifference.normalize()
        vitesseInitialeBalle = 30
        self.noeudPhysique.node().setLinearVelocity(vecteurDifference * vitesseInitialeBalle)


    def intervalExplosion(self, delai):
        #On fait exploser la balle dans quelques secondes
        delai = Wait(delai)
        fonctionExploser = Func(self.exploser)
        self.sequenceExplosionAutomatique = Sequence(delai,fonctionExploser)
        self.sequenceExplosionAutomatique.start()

    def destroy(self):
        self.etat = "Detruit"
        self.pftExplosion.cleanup()
        self.mondePhysique.removeRigidBody(self.noeudPhysique.node())
        self.noeudPhysique.removeNode()

        #Enlève l'écoute des messages
        self.ignoreAll()
class Player(DirectObject):
    def __init__(self, dogSelection):
        self.playing_dead = False
        self._keymap = {
                'forward' : 0,
                'reverse' : 0,
                'right'   : 0,
                'left'    : 0,
                'jump'    : 0,
                'bark'    : 0,
        }
        self._dir = 0
        self.dogSelection = dogSelection
        if self.dogSelection == 2:
            self._coll_dist = 4
            self._coll_dist_h = 1.5
        else:
            self._coll_dist = 6
            self._coll_dist_h = 3
        self._scale = .5 * settings.GLOBAL_SCALE
        self._load_models()
        self._load_sounds()
        self._load_lights()
        self._setup_actions()
        self._setup_tasks()
        self._setup_collisions()
        self.bag = None
        self.gravity = 0
        self.jumping = 15
        self.falling = 0
        self.package = False
        self.jumpingCurrently = False
        self.chase = False
        self.chasetimer = settings.PLAYER_CHASE_LENGTH
        self.inst1 = addInstructions(0.95, str(self._model.getPos()))
        self.blocks = []
        self.currentRoom = 1
        self.lose = False
        
        self.win = False
    def _load_models(self):
        if self.dogSelection == 2:
            self._model = Actor("models/sdog.egg", {"walking":"models/sdoganim.egg"})
            #self._model2 = Actor("models/sdogb.egg", {"walking":"models/sdoganimb.egg"})
        else:
            self._model = Actor("models/bdog", {"walking":"models/bdoganim.egg"})
            #self._model2 = Actor("models/bdogb", {"walking":"models/bdoganimb.egg"})
        self.animControl =self._model.getAnimControl('walking')
        self.currentFrame = self.animControl.getFrame()
        self._model.reparentTo(render)
        self._model.setScale(.5 * settings.GLOBAL_SCALE)
        self._model.setPos(550, 0, 5)
        self._model.setH(-90)
        self.p = ParticleEffect()

    def _load_sounds(self):
        self.sound_bark = loader.loadSfx(os.path.join("sound files", "Dog Barking.mp3"))
        self.sound_dog_footsteps = loader.loadSfx(os.path.join("sound files", "Dog Footsteps.mp3"))

    def _load_lights(self):
        pass

    def _setup_actions(self):
        """
        self.accept("arrow_up", self._set_key, ["reverse", 1])
        self.accept("arrow_up-up", self._set_key, ["reverse", 0])
        self.accept("arrow_down", self._set_key, ["forward", 1])
        self.accept("arrow_down-up", self._set_key, ["forward", 0])
        self.accept("arrow_left", self._set_key, ["left", 1])
        self.accept("arrow_left-up", self._set_key, ["left", 0])
        self.accept("arrow_right", self._set_key, ["right", 1])
        self.accept("arrow_right-up", self._set_key, ["right", 0])
        """
        self.accept("w", self._set_key, ["reverse", 1])
        self.accept("w-up", self._set_key, ["reverse", 0])
        self.accept("s", self._set_key, ["forward", 1])
        self.accept("s-up", self._set_key, ["forward", 0])
        self.accept("a", self._set_key, ["left", 1])
        self.accept("a-up", self._set_key, ["left", 0])
        self.accept("d", self._set_key, ["right", 1])
        self.accept("d-up", self._set_key, ["right", 0])
        self.accept("e", self._set_key, ["bark", 1])
        self.accept('space',self._set_key, ["jump", 1])
        self.accept('space-up', self._set_key, ["jump", 0])
        self.accept('f', self.play_dead)

    def _setup_tasks(self):
        self._prev_move_time = 0
        taskMgr.add(self._task_move, "player-task-move")
        taskMgr.add(self._update_camera, "update-camera")

    def _setup_collisions(self):
        self._coll_trav = CollisionTraverser()
        # Front collision
        self._gnd_handler_front = CollisionHandlerQueue()
        self._gnd_ray_front = CollisionRay()
        self._gnd_ray_front.setOrigin(0, self._coll_dist, 1)
        self._gnd_ray_front.setDirection(0, 0, -1)
        self._gnd_coll_front = CollisionNode('collision-ground-front')
        self._gnd_coll_front.addSolid(self._gnd_ray_front)
        self._gnd_coll_front.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_front.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_front = self._model.attachNewNode(self._gnd_coll_front)
        #self._gnd_coll_path_front.show()
        self._coll_trav.addCollider(self._gnd_coll_path_front, self._gnd_handler_front)
         # Front-left collision
        self._gnd_handler_front_left = CollisionHandlerQueue()
        self._gnd_ray_front_left = CollisionRay()
        self._gnd_ray_front_left.setOrigin(-self._coll_dist_h, self._coll_dist/2, 1)
        self._gnd_ray_front_left.setDirection(0, 0, -1)
        self._gnd_coll_front_left = CollisionNode('collision-ground-front-left')
        self._gnd_coll_front_left.addSolid(self._gnd_ray_front_left)
        self._gnd_coll_front_left.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_front_left.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_front_left = self._model.attachNewNode(self._gnd_coll_front_left)
        #self._gnd_coll_path_front_left.show()
        self._coll_trav.addCollider(self._gnd_coll_path_front_left, self._gnd_handler_front_left)
         # Front-right collision
        self._gnd_handler_front_right = CollisionHandlerQueue()
        self._gnd_ray_front_right = CollisionRay()
        self._gnd_ray_front_right.setOrigin(self._coll_dist_h, self._coll_dist/2, 1)
        self._gnd_ray_front_right.setDirection(0, 0, -1)
        self._gnd_coll_front_right = CollisionNode('collision-ground-front-right')
        self._gnd_coll_front_right.addSolid(self._gnd_ray_front_right)
        self._gnd_coll_front_right.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_front_right.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_front_right = self._model.attachNewNode(self._gnd_coll_front_right)
        #self._gnd_coll_path_front_right.show()
        self._coll_trav.addCollider(self._gnd_coll_path_front_right, self._gnd_handler_front_right)
        # Back collision
        self._gnd_handler_back = CollisionHandlerQueue()
        self._gnd_ray_back = CollisionRay()
        self._gnd_ray_back.setOrigin(0, -self._coll_dist, 1)
        self._gnd_ray_back.setDirection(0, 0, -1)
        self._gnd_coll_back = CollisionNode('collision-ground-back')
        self._gnd_coll_back.addSolid(self._gnd_ray_back)
        self._gnd_coll_back.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_back.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_back = self._model.attachNewNode(self._gnd_coll_back)
        #self._gnd_coll_path_back.show()
        self._coll_trav.addCollider(self._gnd_coll_path_back, self._gnd_handler_back)
        # Back-left collision
        self._gnd_handler_back_left = CollisionHandlerQueue()
        self._gnd_ray_back_left = CollisionRay()
        self._gnd_ray_back_left.setOrigin(-self._coll_dist_h, -self._coll_dist/2, 1)
        self._gnd_ray_back_left.setDirection(0, 0, -1)
        self._gnd_coll_back_left = CollisionNode('collision-ground-back-left')
        self._gnd_coll_back_left.addSolid(self._gnd_ray_back_left)
        self._gnd_coll_back_left.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_back_left.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_back_left = self._model.attachNewNode(self._gnd_coll_back_left)
        #self._gnd_coll_path_back_left.show()
        self._coll_trav.addCollider(self._gnd_coll_path_back_left, self._gnd_handler_back_left)
        # Back-right collision
        self._gnd_handler_back_right = CollisionHandlerQueue()
        self._gnd_ray_back_right = CollisionRay()
        self._gnd_ray_back_right.setOrigin(self._coll_dist_h, -self._coll_dist/2, 1)
        self._gnd_ray_back_right.setDirection(0, 0, -1)
        self._gnd_coll_back_right = CollisionNode('collision-ground-back-right')
        self._gnd_coll_back_right.addSolid(self._gnd_ray_back_right)
        self._gnd_coll_back_right.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_back_right.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_back_right = self._model.attachNewNode(self._gnd_coll_back_right)
        #self._gnd_coll_path_back_right.show()
        self._coll_trav.addCollider(self._gnd_coll_path_back_right, self._gnd_handler_back_right)
        # Left collision
        self._gnd_handler_left = CollisionHandlerQueue()
        self._gnd_ray_left = CollisionRay()
        self._gnd_ray_left.setOrigin(-self._coll_dist_h, 0, 1)
        self._gnd_ray_left.setDirection(0, 0, -1)
        self._gnd_coll_left = CollisionNode('collision-ground-left')
        self._gnd_coll_left.addSolid(self._gnd_ray_left)
        self._gnd_coll_left.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_left.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_left = self._model.attachNewNode(self._gnd_coll_left)
        #self._gnd_coll_path_left.show()
        self._coll_trav.addCollider(self._gnd_coll_path_left, self._gnd_handler_left)
        # Right collision
        self._gnd_handler_right = CollisionHandlerQueue()
        self._gnd_ray_right = CollisionRay()
        self._gnd_ray_right.setOrigin(self._coll_dist_h, 0, 1)
        self._gnd_ray_right.setDirection(0, 0, -1)
        self._gnd_coll_right = CollisionNode('collision-ground-right')
        self._gnd_coll_right.addSolid(self._gnd_ray_right)
        self._gnd_coll_right.setFromCollideMask(BitMask32.bit(0))
        self._gnd_coll_right.setIntoCollideMask(BitMask32.allOff())
        self._gnd_coll_path_right = self._model.attachNewNode(self._gnd_coll_right)
        #self._gnd_coll_path_right.show()
        self._coll_trav.addCollider(self._gnd_coll_path_right, self._gnd_handler_right)
        
        #Wall collision
        self._wall_handler = CollisionHandlerQueue()
        self._wall_ray = CollisionSegment()
        self._wall_ray.setPointA(0, self._coll_dist, 2)
        self._wall_ray.setPointB(0, -self._coll_dist, 2)
        self._wall_coll = CollisionNode('collision-wall')
        self._wall_coll.addSolid(self._wall_ray)
        self._wall_coll.setFromCollideMask(BitMask32.bit(0))
        self._wall_coll.setIntoCollideMask(BitMask32.allOff())
        self._wall_coll_path = self._model.attachNewNode(self._wall_coll)
        #self._wall_coll_path.show()
        self._coll_trav.addCollider(self._wall_coll_path, self._wall_handler)
        
        # Enemy sight target
        self._sphere_handler = CollisionHandlerQueue()
        self._sphere = CollisionSphere(0, 0, 0, 4)
        self._coll_sphere = CollisionNode('collision-player-sphere')
        self._coll_sphere.addSolid(self._sphere)
        self._coll_sphere.setFromCollideMask(BitMask32.bit(0))
        self._coll_sphere.setIntoCollideMask(BitMask32.bit(5))
        self._coll_sphere_path = self._model.attachNewNode(self._coll_sphere)
        #self._coll_sphere_path.show()
        self._coll_trav.addCollider(self._coll_sphere_path, self._sphere_handler)
        # Inner sphere collision
        self._inner_sphere_handler = CollisionHandlerQueue()
        self._inner_sphere = CollisionSphere(0, 0, 0, 4)
        self._coll_inner_sphere = CollisionNode('collision-player-sphere-inner')
        self._coll_inner_sphere.addSolid(self._inner_sphere)
        self._coll_inner_sphere.setFromCollideMask(BitMask32.bit(7))
        self._coll_inner_sphere.setIntoCollideMask(BitMask32.bit(7))
        self._coll_inner_sphere_path = self._model.attachNewNode(self._coll_inner_sphere)
        #self._coll_inner_sphere_path.show()
        self._coll_trav.addCollider(self._coll_inner_sphere_path, self._inner_sphere_handler)
        # Sight collision (Mid)
        self._sight_handler_mi = CollisionHandlerQueue()
        self._sight_ray_mi = CollisionRay()
        self._sight_ray_mi.setOrigin(1, 0, 1)
        self._sight_ray_mi.setDirection(0, -1, 0)
        self._sight_coll_mi = CollisionNode('collision-sight-mi')
        self._sight_coll_mi.addSolid(self._sight_ray_mi)
        self._sight_coll_mi.setFromCollideMask(BitMask32.bit(6))
        self._sight_coll_mi.setIntoCollideMask(BitMask32.allOff())
        self._sight_coll_mi_path = self._model.attachNewNode(self._sight_coll_mi)
        #self._sight_coll_mi_path.show()
        self._coll_trav.addCollider(self._sight_coll_mi_path, self._sight_handler_mi)
        # Sight collision (left)
        self._sight_handler_le = CollisionHandlerQueue()
        self._sight_ray_le = CollisionRay()
        self._sight_ray_le.setOrigin(1, 0, 1)
        self._sight_ray_le.setDirection(-.1, -1, 0)
        self._sight_coll_le = CollisionNode('collision-sight-le')
        self._sight_coll_le.addSolid(self._sight_ray_le)
        self._sight_coll_le.setFromCollideMask(BitMask32.bit(6))
        self._sight_coll_le.setIntoCollideMask(BitMask32.allOff())
        self._sight_coll_le_path = self._model.attachNewNode(self._sight_coll_le)
        #self._sight_coll_le_path.show()
        self._coll_trav.addCollider(self._sight_coll_le_path, self._sight_handler_le)
        # Sight collision (right)
        self._sight_handler_ri = CollisionHandlerQueue()
        self._sight_ray_ri = CollisionRay()
        self._sight_ray_ri.setOrigin(1, 0, 1)
        self._sight_ray_ri.setDirection(.1, -1, 0)
        self._sight_coll_ri = CollisionNode('collision-sight-ri')
        self._sight_coll_ri.addSolid(self._sight_ray_ri)
        self._sight_coll_ri.setFromCollideMask(BitMask32.bit(6))
        self._sight_coll_ri.setIntoCollideMask(BitMask32.allOff())
        self._sight_coll_ri_path = self._model.attachNewNode(self._sight_coll_ri)
        #self._sight_coll_ri_path.show()
        self._coll_trav.addCollider(self._sight_coll_ri_path, self._sight_handler_ri)

    def _set_key(self, key, value):
        self._keymap[key] = value

    def _update_camera(self, task):
        if self.playing_dead == False:
            camera_h = base.camera.getH()
            camera_p = base.camera.getP()
            base.camera.lookAt(self._model)
            target_h = base.camera.getH()
            target_p = base.camera.getP()

            if camera_h < -180:
                camera_h = (180 - (camera_h + 180))
            elif camera_h > 180:
                camera_h = (-180 + (camera_h - 180))

            if camera_h == target_h and camera_p == target_p:
                return Task.cont

            diff_h = camera_h-target_h
            diff_p = camera_p-target_p

            if abs(diff_h) > abs(diff_p):
                if diff_h==0:
                    p_p = 1
                    p_h = 0
                else:
                    p_p = abs(diff_p / diff_h)
                    p_h = 1
            else:
                if diff_p==0:
                    p_h = 1
                    p_p = 1
                else:
                    p_h = abs(diff_h / diff_p)
                    p_p = 1

            if camera_h == target_h:
                dest_h = target_h
                dest_p = target_p
            elif diff_h > 180 or (diff_h < 0 and diff_h > -180):
                dest_h = camera_h+(.5*p_h)
                if dest_h > target_h:
                    dest_h = target_h
            elif diff_h <= -180 or (diff_h > 0 and diff_h <= 180):
                dest_h = camera_h-(.5*p_h)
                if dest_h < target_h:
                    dest_h = target_h
            else:
                dest_h=target_h

            if target_p > camera_p:
                dest_p = min(camera_p+(.5*p_p), target_p)
            elif target_p < camera_p:
                dest_p = max(camera_p-(.5*p_p), target_p)
            else:
                dest_p=target_p

            base.camera.setP(dest_p)
            base.camera.setH(dest_h)
        return Task.cont
    
    def _switch_models(self):
        if self.bag == None:
            print "making bag"
            self.bag = loader.loadModel("models/bag")
            self.bag.setScale(0.8)
            if self.dogSelection == 2:
                self.bag.setPos(0,1.5,6)
            else:
                self.bag.setPos(0,2.5,9)
            self.bag.reparentTo(self._model)
        
    def _task_move(self, task):
        pos_z = self._model.getZ()
        for i in range(self._inner_sphere_handler.getNumEntries()):
            if self._inner_sphere_handler.getEntry(i).getIntoNode().getName()=='collision-with-player-cat':
                if self.chasetimer >= settings.PLAYER_CHASE_LENGTH:
                    self.chase = True
            elif self._inner_sphere_handler.getEntry(i).getIntoNode().getName()=='collision-with-player-dcatcher':
                self.game_over()
            elif self._inner_sphere_handler.getEntry(i).getIntoNode().getName()=='collision-package':
                self._switch_models()
                self.package = True

        if self.playing_dead or self._model.getR()>0:
            if self.playing_dead:
                if self._model.getR() < 90:
                    self._model.setR(self._model.getR()+10)
                if self._model.getZ() < 9:
                    self._model.setZ(self._model.getZ()+1)
            else:
                if self._model.getR() > 0:
                    self._model.setR(self._model.getR()-10)
                if self._model.getZ() > 0:
                    self._model.setZ(self._model.getZ()-1)
            self._prev_move_time = task.time
            return Task.cont
        elif self._model.getZ() < 0:
            self._model.setZ(self._model.getZ()+.1)

        et = task.time - self._prev_move_time
        rotation_rate = settings.PLAYER_ROTATION_RATE
        walk_rate = settings.PLAYER_WALK_RATE
        # Get current values
        rotation = self._model.getH()
        pos_x = self._model.getX()
        pos_y = self._model.getY()
        pos = self._model.getPos()
        
        if self.chase:
            self._inner_sphere_handler.sortEntries()
            if self._inner_sphere_handler.getNumEntries() and self._inner_sphere_handler.getEntry(0).getIntoNode().getName() == 'collision-enemy-sphere':
                    self._prev_move_time = task.time
                    return Task.cont

            self._sight_handler_mi.sortEntries()
            self._sight_handler_ri.sortEntries()
            self._sight_handler_le.sortEntries()
            
            if self._sight_handler_mi.getNumEntries() and self._sight_handler_mi.getEntry(0).getIntoNode().getName() == 'collision-chase-sphere':
                rotation_rad = deg2Rad(rotation)
                dx = et * walk_rate * math.sin(rotation_rad)
                dy = et * walk_rate * -math.cos(rotation_rad)
                pos_x += dx
                pos_y += dy
            elif self._sight_handler_ri.getNumEntries() and self._sight_handler_ri.getEntry(0).getIntoNode().getName() == 'collision-chase-sphere':
                rotation += et * rotation_rate
                rotation_rad = deg2Rad(rotation)
                dx = et * walk_rate * math.sin(rotation_rad)
                dy = et * walk_rate * -math.cos(rotation_rad)
                pos_x += dx
                pos_y += dy
            elif self._sight_handler_le.getNumEntries() and self._sight_handler_le.getEntry(0).getIntoNode().getName() == 'collision-chase-sphere':
                rotation -= et * rotation_rate
                rotation_rad = deg2Rad(rotation)
                dx = et * walk_rate * math.sin(rotation_rad)
                dy = et * walk_rate * -math.cos(rotation_rad)
                pos_x += dx
                pos_y += dy
            else:
                rotation += et * rotation_rate
            

            self._model.setH(rotation)
            self._model.setX(pos_x)
            self._model.setY(pos_y)

            self.chasetimer -= 1
            if self.chasetimer == 0:
                self.chase = False

        # Rotate the player
        dr = et * rotation_rate
        rotation += self._keymap['left'] * dr
        rotation -= self._keymap['right'] * dr
        # Move the player
        rotation_rad = deg2Rad(rotation)
        dx = et * walk_rate * -math.sin(rotation_rad)
        dy = et * walk_rate * math.cos(rotation_rad)
        pos_x += self._keymap['forward'] * dx
        pos_y += self._keymap['forward'] * dy
        pos_x -= self._keymap['reverse'] * dx
        pos_y -= self._keymap['reverse'] * dy

        if self._keymap['jump'] and not self.jumpingCurrently and self.dogSelection==2:
            self.jumpingCurrently=True

        if self.jumpingCurrently:
                temp=self.jump()
                if (temp+pos_z) < 190:
                    pos_z+=temp
                else:
                    self.jumping=0

        if self._keymap['bark'] and self.dogSelection == 1:
            self.sound_bark.play()
            self._keymap['bark'] = 0
            self.chase = False
            for x in self.blocks:
                if x.getRoom() == self.currentRoom:
                    x.destroyBlock()
                    #self.loadParticleConfig(x.getPosition())
            
        
        if self._keymap['forward'] == 1 or self._keymap['reverse'] == 1 or self._keymap['left'] == 1 or self._keymap['right'] == 1:
            if not self.animControl.isPlaying(): 
                self._model.loop('walking')
        elif not self.chase:
            self.currentFrame = self.animControl.getFrame()
            self._model.pose('walking', self.currentFrame)
        
        if self.sound_dog_footsteps.status() == 1:
            if self._keymap['forward'] == 1 or self._keymap['reverse'] == 1 or self._keymap['left'] == 1 or self._keymap['right'] == 1:
                self.sound_dog_footsteps.play()
                self.sound_dog_footsteps.setLoop(True)
        elif self.sound_dog_footsteps.status() == 2:
            if self._keymap['forward'] == 0 and self._keymap['reverse'] == 0 and self._keymap['left'] == 0 and self._keymap['right'] == 0:
                self.sound_dog_footsteps.stop()


        # Save back to the model
        self._model.setH(rotation)
        self._model.setX(pos_x)
        self._model.setY(pos_y)

        self._coll_trav.traverse(render)

        entries_wall = []
        entries_front = []
        entries_front_left = []
        entries_front_right = []
        entries_back = []
        entries_back_left = []
        entries_back_right = []
        entries_left = []
        entries_right = []

        for i in range(self._wall_handler.getNumEntries()):
            entries_wall.append(self._wall_handler.getEntry(i))
        for i in range(self._gnd_handler_front.getNumEntries()):
            entries_front.append(self._gnd_handler_front.getEntry(i))
        for i in range(self._gnd_handler_back.getNumEntries()):
            entries_back.append(self._gnd_handler_back.getEntry(i))
        for i in range(self._gnd_handler_left.getNumEntries()):
            entries_left.append(self._gnd_handler_left.getEntry(i))
        for i in range(self._gnd_handler_right.getNumEntries()):
            entries_right.append(self._gnd_handler_right.getEntry(i))
        for i in range(self._gnd_handler_front_left.getNumEntries()):
            entries_front_left.append(self._gnd_handler_front_left.getEntry(i))
        for i in range(self._gnd_handler_back_left.getNumEntries()):
            entries_back_left.append(self._gnd_handler_back_left.getEntry(i))
        for i in range(self._gnd_handler_front_right.getNumEntries()):
            entries_front_right.append(self._gnd_handler_front_right.getEntry(i))
        for i in range(self._gnd_handler_back_right.getNumEntries()):
            entries_back_right.append(self._gnd_handler_back_right.getEntry(i))

        entries_all = entries_front + entries_back + entries_left + entries_right + entries_front_right + entries_back_right + entries_front_left + entries_back_left
        srt = lambda x, y: cmp(y.getSurfacePoint(render).getZ(),
                               x.getSurfacePoint(render).getZ())
        entries_front.sort(srt)
        entries_back.sort(srt)
        entries_left.sort(srt)
        entries_right.sort(srt)
        entries_front_right.sort(srt)
        entries_front_left.sort(srt)
        entries_back_left.sort(srt)
        entries_back_right.sort(srt)
        entries_wall.sort(srt)

        if entries_all:
            if self.gravity == 1:
                self._model.setZ(pos_z)
                if entries_back:
                    if entries_back[0].getSurfacePoint(render).getZ()>self._model.getZ():
                        self._model.setZ(entries_back[0].getSurfacePoint(render).getZ())
                        self.gravity=0
                        self.jumpingCurrently=False
                        self.jumping=15
                        self.falling=0
                    if self.gravity == 1 and not self.jumpingCurrently:
                        pos_z+=self.fall()
                        self._model.setZ(pos_z)
                else:
                    if len(entries_front) > 0 and entries_front[0].getSurfacePoint(render).getZ()>self._model.getZ():
                        self._model.setZ(entries_front[0].getSurfacePoint(render).getZ())
                        self.gravity=0
                        self.jumpingCurrently=False
                        self.jumping=15
                        self.falling=0
                    if self.gravity == 1 and not self.jumpingCurrently:
                        pos_z+=self.fall()
                        self._model.setZ(pos_z)
            #elif self.is_valid(entries_front) and self.is_valid(entries_back) and self.is_valid(entries_left) and self.is_valid(entries_right) and self.is_valid(entries_front_right) and self.is_valid(entries_front_left) and self.is_valid(entries_back_left) and self.is_valid(entries_back_right):
            elif self.is_valid(entries_wall):
                if len(entries_front) > 0 and len(entries_back) > 0:
                    f = entries_front[0].getSurfacePoint(render).getZ()
                    b = entries_back[0].getSurfacePoint(render).getZ()
                    #l = entries_left[0].getSurfacePoint(render).getZ()
                    #r = entries_right[0].getSurfacePoint(render).getZ()
                    z = (f + b) / 2
                    if abs(z - self._model.getZ()) > 5:
                        self.gravity=1
                    else:
                        #self._model.setZ(z)
                        #self._model.setP(rad2Deg(math.atan2(f - z, self._coll_dist * self._scale)))
                        #self._model.setR(rad2Deg(math.atan2(l - z, self._coll_dist_h * self._scale)))
                        pass
            else:
                self._model.setPos(pos)


        if not self.chase and self.chasetimer < settings.PLAYER_CHASE_LENGTH:
            self.chasetimer += 1

        self._prev_move_time = task.time


        self.inst1.destroy()
        self.inst1 = addInstructions(0.95, str(self._model.getPos()))
            
        return Task.cont
    
    def is_valid(self, entries):
        #if len(entries) == 0:
         #return False
        for x in entries:
             if x.getIntoNode().getName()!='ground1':
                return False
        return True
    
    def jump(self):
        if self.jumping>0:
            self.gravity=1
            self.jumping-=.5
            return self.jumping*.5
        else:
            return self.fall()
    def fall(self):
            self.falling-=.5
            return self.falling*.5
    
    def loadParticleConfig(self, position):
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(os.path.join("models", "smokering.ptf"))   
        self.p.accelerate(.25) 
        self.p.setPos(position) 
        self.p.reparentTo(render) 
        self.p.setScale(30)  
        self.p.start()
        #taskMgr.doMethodLater(5, self.cleanParticles, 'Stop Particles')
        
    def cleanParticles(self, random):
        self.p.softStop()
        
    def play_dead(self):
        self.playing_dead = not self.playing_dead
        if self.playing_dead:
            self._model.setR(self._model.getR()+10)
            self._model.setZ(self._model.getZ()+1)
        else:
            self._model.setR(self._model.getR()-10)
            self._model.setZ(self._model.getZ()-1)
            
    def passBlocks(self, blocks):
        self.blocks = blocks
    
    def passCurrentRoom(self, currentRoom):
        self.currentRoom = currentRoom

    def game_over(self):
        self.lose = True
        taskMgr.doMethodLater(3, sys.exit, "game_over")
        if self.dogSelection == 2: #small
            self.a = OnscreenImage(parent=render2d, image=os.path.join("image files", "Game-Over-Screen-Small.png"))
        else:
            self.a = OnscreenImage(parent=render2d, image=os.path.join("image files", "Game-Over-Screen-Big.png"))
class Vehicle(object):
    COUNT = 0

    def __init__(self, main, username, pos = LVecBase3(-5, -5, 1), isCurrentPlayer = False, carId=3):
        self.username = username
        self.main = main
        self.isCurrentPlayer = isCurrentPlayer
        self.boostCount = 0
        self.boostActive = False
        self.boostStep = 2
        self.boostDuration = 0
        self.moveStartTime = self.startTime = self.boostStartTime = time.time()
        self.pos = pos
        self.boostFactor = 1.2
        self.specs = {"mass": 800.0,
                    "maxWheelForce": 2000.0,
                    "brakeForce": 100.0,
                    "steeringLock": 45.0,
                    "maxSpeed": 33.0,
                    "maxReverseSpeed": 10.0}
        self.vehicleControlState = {"throttle": 0, "reverse": False, "brake": 0.0, "steering": 0.0, "health": 1}

        # Steering change per second, normalised to steering lock
        # Eg. 45 degrees lock and 1.0 rate means 45 degrees per second
        self.steeringRate = 0.8
        self.centreingRate = 1.2
        self.speed = 0

        self.setupVehicle(main)

        self.props = VehicleProps(carId)

        self.currentPowerups = {"powerup1": None, "powerup2": None, "powerup3": None}
        if isCurrentPlayer:
            #This command is required for Panda to render particles
            base.enableParticles()
            self.p = ParticleEffect()
        #     self.loadParticleConfig('steam.ptf')

    def setPropHealth(self, health):
        self.props.setHealth(health)
        if not self.isCurrentPlayer:
            self.main.updateStatusBars(self.username, self.props.health)

    def loadParticleConfig(self, file):
        #Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))
        # print type(main.worldNp)
        self.p.softStart()
        self.p.start(self.yugoNP)
        # self.p.setPos(0.000, -0.700, 0.250)
        self.p.setPos(0.000, -0.700, 0)

        #self.setupVehicle(bulletWorld)
        self.startTime = time.time()
        #COUNT = 1

    def move(self, steering, wheelForce, brakeForce, x, y, z, h, p, r):
        self.applyForcesAndSteering(steering, wheelForce, brakeForce)
        self.endTime = time.time()
        #print self.endTime
        elapsed = self.endTime - self.moveStartTime
        #self.startTime = self.endTime
        #if elapsed > 1:
        self.moveStartTime = self.endTime
        if not self.isCurrentPlayer:
            self.setVehiclePos(x, y, z, h, p, r)

        #print "Do Move"

    def applyForcesAndSteering(self, steering, wheelForce, brakeForce):
        # Apply steering to front wheels
        self.vehicle.setSteeringValue(steering, 0);
        self.vehicle.setSteeringValue(steering, 1);
        # Apply engine and brake to rear wheels
        self.vehicle.applyEngineForce(wheelForce, 2);
        self.vehicle.applyEngineForce(wheelForce, 3);
        self.vehicle.setBrake(brakeForce, 2);
        self.vehicle.setBrake(brakeForce, 3);
    def addBoost(self):
        if self.boostCount > 0:
            self.boostCount -= 1
            if not self.boostActive:
                self.boostStartTime = time.time()
                self.boostActive = True
            self.boostDuration += self.boostStep
    def checkDisableBoost(self):
        if time.time() - self.boostStartTime > self.boostDuration:
            self.boostActive = False

    def reset(self):
        self.chassisNP.setP(0)
        self.chassisNP.setR(0)

    def processInput(self, inputState, dt):
        # print self.chassisNP.getPos()
        #print self.chassisNP.getH()
        """Use controls to update the player's car"""
        # For keyboard throttle and brake are either 0 or 1
        self.checkDisableBoost()
        if inputState.isSet('forward'):
            self.vehicleControlState["throttle"] = 1.0
        else:
            self.vehicleControlState["throttle"] = 0.0

        velocity = self.chassisNode.getLinearVelocity()
        speed = math.sqrt(sum(v ** 2 for v in velocity))
        self.speed = speed
        # Update braking and reversing
        if inputState.isSet('brake'):
            if speed < 0.5 or self.vehicleControlState["reverse"]:
                # If we're stopped, then start reversing
                # Also keep reversing if we already were
                self.vehicleControlState["reverse"] = True
                self.vehicleControlState["throttle"] = 1.0
                self.vehicleControlState["brake"] = 0.0
            else:
                self.vehicleControlState["reverse"] = False
                self.vehicleControlState["brake"] = 1.0
        else:
            self.vehicleControlState["reverse"] = False
            self.vehicleControlState["brake"] = 0.0

        # steering is normalised from -1 to 1, corresponding
        # to the steering lock right and left
        steering = self.vehicleControlState["steering"]
        if inputState.isSet('left'):
            steering += dt * self.steeringRate
            steering = min(steering, 1.0)
        elif inputState.isSet('right'):
            steering -= dt * self.steeringRate
            steering = max(steering, -1.0)
        else:
            # gradually re-center the steering
            if steering > 0.0:
                steering -= dt * self.centreingRate
                if steering < 0.0:
                    steering = 0.0
            elif steering < 0.0:
                steering += dt * self.centreingRate
                if steering > 0.0:
                    steering = 0.0
        self.vehicleControlState["steering"] = steering

        # """Updates acceleration, braking and steering
        # These are all passed in through a controlState dictionary
        # """
        # Update acceleration and braking
        self.reversing = self.vehicleControlState["reverse"]
        brakeForce = self.vehicleControlState["brake"] * self.specs["brakeForce"]

        if self.reversing and self.speed > self.specs["maxReverseSpeed"]:
            self.applyForcesAndSteering(steering, 0, brakeForce)
            return
        if not self.reversing and self.speed > self.specs["maxSpeed"]:
            self.applyForcesAndSteering(steering, 0, brakeForce)
            return

        wheelForce = self.vehicleControlState["throttle"] * self.specs["maxWheelForce"]

        if self.reversing:
            # Make reversing a bit slower than moving forward
            wheelForce *= -0.5

        # Update steering
        # Steering control state is from -1 to 1
        steering = self.vehicleControlState["steering"] * self.specs["steeringLock"]
        if self.boostActive:
            wheelForce *= self.boostFactor
        self.applyForcesAndSteering(steering, wheelForce, brakeForce)
        return [steering, wheelForce, brakeForce]

    def getSpeed(self):
        velocity = self.chassisNode.getLinearVelocity()
        speed = math.sqrt(sum(v ** 2 for v in velocity))
        return speed, speed/self.specs["maxSpeed"]

    def getBoost(self):
        maxBoost = 3.0
        currentScaledBoost = self.boostCount / maxBoost
        return currentScaledBoost

    def updateHealth(self, damage):
        self.vehicleControlState["health"] -= 0.25
        if self.vehicleControlState["health"] <= 0.0:
            self.killVehicle("Lost health")

    def killVehicle(self, reason = ""):
        print "Sent request to server for killing this player because: ", reason

    def updateMovement(self, move, dt):
        """Use controls to update the player's car"""
        # For keyboard throttle and brake are either 0 or 1
        if move == 'f':
            self.vehicleControlState["throttle"] = 1.0
        else:
            self.vehicleControlState["throttle"] = 0.0

        velocity = self.chassisNode.getLinearVelocity()
        speed = math.sqrt(sum(v ** 2 for v in velocity))
        # Update braking and reversing
        if move == 'b':
            if speed < 0.5 or self.vehicleControlState["reverse"]:
                # If we're stopped, then start reversing
                # Also keep reversing if we already were
                self.vehicleControlState["reverse"] = True
                self.vehicleControlState["throttle"] = 1.0
                self.vehicleControlState["brake"] = 0.0
            else:
                self.vehicleControlState["reverse"] = False
                self.vehicleControlState["brake"] = 1.0
        else:
            self.vehicleControlState["reverse"] = False
            self.vehicleControlState["brake"] = 0.0

        # steering is normalised from -1 to 1, corresponding
        # to the steering lock right and left
        steering = self.vehicleControlState["steering"]
        if move == 'l':
            steering += dt * self.steeringRate
            steering = min(steering, 1.0)
        elif move == 'r':
            steering -= dt * self.steeringRate
            steering = max(steering, -1.0)
        else:
            # gradually re-center the steering
            if steering > 0.0:
                steering -= dt * self.centreingRate
                if steering < 0.0:
                    steering = 0.0
            elif steering < 0.0:
                steering += dt * self.centreingRate
                if steering > 0.0:
                    steering = 0.0
        self.vehicleControlState["steering"] = steering

        # """Updates acceleration, braking and steering
        # These are all passed in through a controlState dictionary
        # """
        # Update acceleration and braking
        wheelForce = self.vehicleControlState["throttle"] * self.specs["maxWheelForce"]
        self.reversing = self.vehicleControlState["reverse"]
        if self.reversing:
            # Make reversing a bit slower than moving forward
            wheelForce *= -0.5

        brakeForce = self.vehicleControlState["brake"] * self.specs["brakeForce"]

        # Update steering
        # Steering control state is from -1 to 1
        steering = self.vehicleControlState["steering"] * self.specs["steeringLock"]

        self.applyForcesAndSteering(steering, wheelForce, brakeForce)

        return [steering, wheelForce, brakeForce]

    def setVehiclePos(self, x,y, z, h, p, r):
        #self.chassisNP.setX(x)
        #self.chassisNP.setY(y)
        #self.chassisNP.setP(p)
        #self.chassisNP.setR(r)
        self.chassisNP.setPosHpr(x, y, z, h, p, r)
        return

    def setupVehicle(self, main):
        scale = 0.5
        # Chassis
        shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
        ts = TransformState.makePos(Point3(0, 0, 0.5 * scale))

        name = self.username
        self.chassisNode = BulletRigidBodyNode(name)
        self.chassisNode.setTag('username', str(name))
        self.chassisNP = main.worldNP.attachNewNode(self.chassisNode)
        self.chassisNP.setName(str(name))
        self.chassisNP.node().addShape(shape, ts)
        self.chassisNP.setScale(scale)

        self.chassisNP.setPos(self.pos)
        if self.isCurrentPlayer:
            self.chassisNP.node().notifyCollisions(True)
            self.chassisNP.node().setMass(800.0)
        else:
            self.chassisNP.node().notifyCollisions(True)
            self.chassisNP.node().setMass(400.0)
        self.chassisNP.node().setDeactivationEnabled(False)

        main.world.attachRigidBody(self.chassisNP.node())

        #np.node().setCcdSweptSphereRadius(1.0)
        #np.node().setCcdMotionThreshold(1e-7)

        # Vehicle
        self.vehicle = BulletVehicle(main.world, self.chassisNP.node())
        self.vehicle.setCoordinateSystem(ZUp)
        main.world.attachVehicle(self.vehicle)

        self.yugoNP = loader.loadModel('models/yugo/yugo.egg')
        self.yugoNP.reparentTo(self.chassisNP)

        #self.carNP = loader.loadModel('models/batmobile-chassis.egg')
        #self.yugoNP.setScale(.7)
        #self.carNP.reparentTo(self.chassisNP)

        # Right front wheel
        np = loader.loadModel('models/yugo/yugotireR.egg')
        np.reparentTo(main.worldNP)
        self.addWheel(Point3( 0.70 * scale,  1.05 * scale, 0.3), True, np)

        # Left front wheel
        np = loader.loadModel('models/yugo/yugotireL.egg')
        np.reparentTo(main.worldNP)
        self.addWheel(Point3(-0.70 * scale,  1.05 * scale, 0.3), True, np)

        # Right rear wheel
        np = loader.loadModel('models/yugo/yugotireR.egg')
        np.reparentTo(main.worldNP)
        self.addWheel(Point3( 0.70 * scale, -1.05 * scale, 0.3), False, np)

        # Left rear wheel
        np = loader.loadModel('models/yugo/yugotireL.egg')
        np.reparentTo(main.worldNP)
        self.addWheel(Point3(-0.70 * scale, -1.05 * scale, 0.3), False, np)

    def addWheel(self, pos, front, np):
        wheel = self.vehicle.createWheel()

        wheel.setNode(np.node())
        wheel.setChassisConnectionPointCs(pos)
        wheel.setFrontWheel(front)

        wheel.setWheelDirectionCs(Vec3(0, 0, -1))
        wheel.setWheelAxleCs(Vec3(1, 0, 0))
        wheel.setWheelRadius(0.25)
        wheel.setMaxSuspensionTravelCm(40.0)

        wheel.setSuspensionStiffness(40.0)
        wheel.setWheelsDampingRelaxation(2.3)
        wheel.setWheelsDampingCompression(4.4)
        wheel.setFrictionSlip(100.0);
        wheel.setRollInfluence(0.1)


    def reset(self):
        #self.chassisNP.setP(0)
        #self.chassisNP.setR(0)
        #print "kegwe", self.chassisNP.getX(),self.chassisNP.getY(),self.chassisNP.getZ(),self.chassisNP.getH(),0,0
        self.chassisNP.setPosHpr(self.chassisNP.getX(),self.chassisNP.getY(),self.chassisNP.getZ(),self.chassisNP.getH(),0,0)


    def pickedPowerup(self, powerup):
        if not powerup.pickable:
            powerup.useAbility()
        else:
            if self.currentPowerups["powerup1"] is None:
                self.currentPowerups["powerup1"] = powerup
            elif self.currentPowerups["powerup2"] is None:
                self.currentPowerups["powerup2"] = powerup
            elif self.currentPowerups["powerup3"] is None:
                self.currentPowerups["powerup3"] = powerup


    def canPickUpPowerup(self):
        return (self.currentPowerups["powerup1"] is None or
                self.currentPowerups["powerup2"] is None or
                self.currentPowerups["powerup3"] is None)


    def usePowerup(self, powerupIndex):
        # Move usePowerupN to this function
        if powerupIndex == 0 and self.currentPowerups["powerup1"] is not None:
            self.currentPowerups["powerup1"].useAbility()
            self.currentPowerups["powerup1"] = None
        elif powerupIndex == 1 and self.currentPowerups["powerup2"] is not None:
            self.currentPowerups["powerup2"].useAbility()
            self.currentPowerups["powerup2"] = None
        elif powerupIndex == 2 and self.currentPowerups["powerup3"] is not None:
            self.currentPowerups["powerup3"].useAbility()
            self.currentPowerups["powerup3"] = None