Пример #1
0
    def __init__(self):

        self.setAI()

        self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0}
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # the menu
        self.loadAudio()
        self.showMenu()

        # keyboard and mouse events
        self.accept("escape", sys.exit)
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["left", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])

        # create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(0.3, 0.3, 0.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))
Пример #2
0
    def createEnvironment(self):
        # Fog to hide a performance tweak:
        colour = (0.0, 0.0, 0.0)
        expfog = Fog("scene-wide-fog")
        expfog.setColor(*colour)
        expfog.setExpDensity(0.001)  # original : 0.004
        render.setFog(expfog)
        base.setBackgroundColor(*colour)

        # Our sky
        skydome = loader.loadModel('sky.egg')
        skydome.setEffect(CompassEffect.make(self.render))
        skydome.setScale(self.maxdistance / 2)  # bit less than "far"
        skydome.setZ(-65)  # sink it
        # NOT render - you'll fly through the sky!:
        skydome.reparentTo(self.camera)

        # Our lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.6, .6, .6, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0, -10, -10))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Пример #3
0
    def createLighting(self):
        #creates lighting for the scene
        aLightVal = 0.3
        dLightVal1 = -5
        dLightVal2 = 5

        #set up the ambient light
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(aLightVal, aLightVal, aLightVal, 1))
        ambientLight1 = AmbientLight("ambientLight1")
        ambientLight1.setColor(Vec4(aLightVal, aLightVal, aLightVal, 1))
        ambientLight2 = AmbientLight("ambientLight2")
        ambientLight2.setColor(Vec4(aLightVal, aLightVal, aLightVal, 1))

        #sets a directional light
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(dLightVal1, dLightVal1, dLightVal1))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(0, 0, 0, 1))

        #sets a directional light
        directionalLight1 = DirectionalLight("directionalLight2")
        directionalLight1.setDirection(Vec3(dLightVal2, dLightVal1, dLightVal1))
        directionalLight1.setColor(Vec4(1, 1, 1, 1))
        directionalLight1.setSpecularColor(Vec4(1, 1, 1, 1))


        #attaches lights to scene
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(ambientLight1))
        render.setLight(render.attachNewNode(ambientLight1))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight1))
Пример #4
0
    def Start(self,pl_name,pl_char,pl_count,pl_list):



        # Set up the environment
        #

        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
    	self.environ.setTexture(self.moon_tex, 1)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # # add spheres
        earth = Earth(self)
        sun = Sun(self)
        venus = Venus(self)



        controls = Control()
        chat = Chat(self)


        if pl_char == "Panda1"  or pl_char == "Panda2":
            print "hi"
            player = Panda(self)
        elif pl_char == "Car":
            player = Car(self)
        else :
            player = Ralph(self)

        #player = Car(self)


        # player = Panda(self)
        # player = Car(self)



        taskMgr.add(player.move,"moveTask" )
        taskMgr.add(sun.rotatePlanets,"rotateSun", extraArgs = [self.sun,self.player], appendTask = True)
        taskMgr.add(earth.rotatePlanets,"rotateEarth", extraArgs = [self.earth, self.player], appendTask = True)
        taskMgr.add(venus.rotatePlanets,"rotateVenus", extraArgs = [self.venus, self.player], appendTask = True)


        # Create some lighting
        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))
Пример #5
0
    def __init__(self):
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Network Setup
        print "before"
        self.cManager = ConnectionManager(self)
        self.startConnection()
        print "after"

        # Set up the environment
        #

        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(100, 100, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # add spheres
        earth = Earth(self)

        sun = Sun(self)
        venus = Venus(self)

        controls = Control()
        chat = Chat(self)
        player = Ralph(self)

        # player = Panda(self)
        # player = Car(self)

        taskMgr.add(player.move, "moveTask")
        taskMgr.add(sun.rotatePlanets,
                    "rotateSun",
                    extraArgs=[self.player],
                    appendTask=True)
        taskMgr.add(earth.rotatePlanets,
                    "rotateEarth",
                    extraArgs=[self.player],
                    appendTask=True)
        taskMgr.add(venus.rotatePlanets,
                    "rotateVenus",
                    extraArgs=[self.player],
                    appendTask=True)

        # Create some lighting
        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))
Пример #6
0
    def __init__(self):
        __builtin__.main = self
        self.taskMgr = taskMgr
        self.base = base
        
        # Connect to the server
        self.cManager = ConnectionManager()
        self.startConnection()
    
        self.characters = dict()
        self.cpList = dict()

        base.win.setClearColor(Vec4(0,0,0,1))


        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.ralphStartPos = self.environ.find("**/start_point").getPos()

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        self.accept("escape", sys.exit)
        
        # Login as 'CPHandler'
        # Temporary workaround, can add a seperate request/response for client/NPC client logins later
        self.name = "CPHandler"
        factionId = 0
        self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId])

        # Create two control points
        cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED)
        cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE)

        self.cpList[1] = cp1
        self.cpList[2] = cp2

        taskMgr.doMethodLater(0.1, self.refresh, "heartbeat")
        taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler')

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

        # Create some lighting
        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))
Пример #7
0
 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))
Пример #8
0
    def __init__(self):
        __builtin__.main = self
        self.taskMgr = taskMgr
        self.base = base

        # Connect to the server
        self.cManager = ConnectionManager()
        self.startConnection()

        self.characters = dict()
        self.cpList = dict()

        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.ralphStartPos = self.environ.find("**/start_point").getPos()

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        self.accept("escape", sys.exit)

        # Login as 'CPHandler'
        # Temporary workaround, can add a seperate request/response for client/NPC client logins later
        self.name = "CPHandler"
        factionId = 0
        self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId])

        # Create two control points
        cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED)
        cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE)

        self.cpList[1] = cp1
        self.cpList[2] = cp2

        taskMgr.doMethodLater(0.1, self.refresh, "heartbeat")
        taskMgr.doMethodLater(1, self.CPHandler, 'CPHandler')

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

        # Create some lighting
        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 __init__(self, aCol, dDir, dCol):
		render.setAttrib(LightRampAttrib.makeHdr1())
		ambientLight = AmbientLight("ambientLight")
		ambientLight.setColor(aCol)
		directionalLight = DirectionalLight("directionalLight")
		directionalLight.setDirection(dDir)
		directionalLight.setColor(dCol)
		directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 0))
		render.setLight(render.attachNewNode(ambientLight))
		render.setLight(render.attachNewNode(directionalLight))
 def __init__(self, aCol, dDir, dCol):
     render.setAttrib(LightRampAttrib.makeHdr1())
     ambientLight = AmbientLight("ambientLight")
     ambientLight.setColor(aCol)
     directionalLight = DirectionalLight("directionalLight")
     directionalLight.setDirection(dDir)
     directionalLight.setColor(dCol)
     directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 0))
     render.setLight(render.attachNewNode(ambientLight))
     render.setLight(render.attachNewNode(directionalLight))
Пример #11
0
    def init(self):
        # window setup
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # display instructions
        addTitle("CS454 HW2")
        addInstructions(0.95, "[ESC]: Quit")
        addInstructions(0.90, "[Mouse Move]: Move camera")
        addInstructions(0.85, "[Mouse Wheel]: Zoom camera")
        addInstructions(0.80, "[W,A,S,D]: Move character")
        addInstructions(0.75, "[T]: Open chat box")
        addInstructions(0.70, "[Y]: Open whisper box")
        addInstructions(0.65, "[Up,Down]: Select whisper target")
        addInstructions(0.60, "[Tab]: Show players")

        # create environment
        environ = loader.loadModel("models/square")
        environ.reparentTo(render)
        environ.setPos(0, 0, 0)
        environ.setScale(100, 100, 1)
        environ.setTexture(loader.loadTexture("models/moon_1k_tex.jpg"), 1)

        # create lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(0.3, 0.3, 0.3, 1))
        render.setLight(render.attachNewNode(ambientLight))

        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(directionalLight))

        # accept special keys
        base.accept("escape", self.exit)
        base.accept("shift-escape", self.exit)

        # create spheres
        sun = Sphere(self, "sun")
        sun.model.setPos(-15, -15, 8)

        earth = Sphere(self, "earth")
        earth.model.setPos(-12, 12, 5)

        venus = Sphere(self, "venus")
        venus.model.setPos(10, 10, 3.5)

        # track game entities
        self.character = None
        self.player = None
        self.camera = None
        self.characters = {}

        self.chat = Chat(self)
        self.playerList = PlayerList(self)
    def __init__(self):
        base.win.setClearColor(Vec4(0,0,0,1))

        # Network Setup
        print "before"
        self.cManager = ConnectionManager(self)
        self.startConnection()
        print "after"

        # Set up the environment
        #

        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
    	self.environ.setTexture(self.moon_tex, 1)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # add spheres
        earth = Earth(self)

        sun = Sun(self)
        venus = Venus(self)



        controls = Control()
        chat = Chat(self)
        player = Ralph(self)


        # player = Panda(self)
        # player = Car(self)



        taskMgr.add(player.move,"moveTask" )
        taskMgr.add(sun.rotatePlanets,"rotateSun", extraArgs = [self.player], appendTask = True)
        taskMgr.add(earth.rotatePlanets,"rotateEarth", extraArgs = [self.player], appendTask = True)
        taskMgr.add(venus.rotatePlanets,"rotateVenus", extraArgs = [self.player], appendTask = True)


        # Create some lighting
        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 __init__(self):

        self.root = render.attachNewNode("Root")
        base.setBackgroundColor(0, 0, 0)
        # This code puts the standard title and instruction text on screen
        self.title = OnscreenText(text="Ball In Maze",
                                  style=1,
                                  fg=(1, 1, 0, 1),
                                  pos=(0.7, -0.95),
                                  scale=.07)
        self.instructions = OnscreenText(text="Press Esc to exit",
                                         pos=(-1.3, .95),
                                         fg=(1, 1, 0, 1),
                                         align=TextNode.ALeft,
                                         scale=.05)
        self.central_msg = OnscreenText(text="",
                                        pos=(0, 0),
                                        fg=(1, 1, 0, 1),
                                        scale=.1)
        self.central_msg.hide()

        self.accept("escape", sys.exit)  # Escape quits
        base.disableMouse()  # Disable mouse-based camera control
        camera.setPosHpr(0, 0, 25, 0, -90, 0)  # Place the camera

        # Load the maze and place it in the scene
        self.maze = loader.loadModel("models/maze")
        self.maze.reparentTo(render)

        # Load the ball and attach it to the scene
        # It is on a root dummy node so that we can rotate the ball itself without
        # rotating the ray that will be attached to it
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = loader.loadModel("models/ball")
        self.ball.reparentTo(self.ballRoot)
        # This section deals with lighting for the ball. Only the ball was lit
        # because the maze has static lighting pregenerated by the modeler
        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))

        # This section deals with adding a specular highlight to the ball to make
        # it look shiny
        m = Material()
        m.setSpecular(Vec4(1, 1, 1, 1))
        m.setShininess(96)
        self.ball.setMaterial(m, 1)
Пример #14
0
    def setupLights(self):    

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight1 = DirectionalLight("directionalLight")
        directionalLight1.setDirection(Vec3(5, 5, -5))
        directionalLight1.setColor(Vec4(1, 1, 1, 1))
        directionalLight1.setSpecularColor(Vec4(1, 1, 1, 1))
        directionalLight2 = DirectionalLight("directionalLight")
        directionalLight2.setDirection(Vec3(5, -5, -5))
        directionalLight2.setColor(Vec4(1, 1, 1, 1))
        directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1))
        directionalLight3 = DirectionalLight("directionalLight")
        directionalLight3.setDirection(Vec3(-5, -5, -5))
        directionalLight3.setColor(Vec4(1, 1, 1, 1))
        directionalLight3.setSpecularColor(Vec4(1, 1, 1, 1))
        directionalLight4 = DirectionalLight("directionalLight")
        directionalLight4.setDirection(Vec3(-5, 5, -5))
        directionalLight4.setColor(Vec4(1, 1, 1, 1))
        directionalLight4.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight1))
        render.setLight(render.attachNewNode(directionalLight2))
        render.setLight(render.attachNewNode(directionalLight3))
        render.setLight(render.attachNewNode(directionalLight4))
Пример #15
0
    def setup(self):
        ambient_light = AmbientLight("ambientLight")
        ambient_light.setColor(self.config.get('ambient_color'))
        directional_light = DirectionalLight("directionalLight")
        directional_light.setDirection(self.config.get('direction'))
        directional_light.setColor(self.config.get('directional_color'))
        directional_light.setSpecularColor(
            self.config.get('directional_specular_color'))
        # directionalLight.showFrustum()

        self.render.setLight(self.render.attachNewNode(ambient_light))
        self.render.setLight(self.render.attachNewNode(directional_light))

        # Important! Enable the shader generator.
        self.render.setShaderAuto()
Пример #16
0
	def __init__(self):
		
		self.root = render.attachNewNode("Root")
		base.setBackgroundColor(0,0,0)
		# This code puts the standard title and instruction text on screen
    		self.title = OnscreenText(text="Ball In Maze",
                              		style=1, fg=(1,1,0,1),
                              		pos=(0.7,-0.95), scale = .07)
    		self.instructions = OnscreenText(text="Press Esc to exit",
                                     		pos = (-1.3, .95), fg=(1,1,0,1),
                                     		align = TextNode.ALeft, scale = .05)
		self.central_msg = OnscreenText(text="",
      				pos = (0, 0), fg=(1, 1, 0, 1),
      				scale = .1
    						)
    		self.central_msg.hide()
    
    		self.accept("escape", sys.exit)        # Escape quits
    		base.disableMouse()                    # Disable mouse-based camera control
    		camera.setPosHpr(0, 0, 25, 0, -90, 0)  # Place the camera

    		# Load the maze and place it in the scene
    		self.maze = loader.loadModel("models/maze")
    		self.maze.reparentTo(render)

		# Load the ball and attach it to the scene
    		# It is on a root dummy node so that we can rotate the ball itself without
    		# rotating the ray that will be attached to it
    		self.ballRoot = render.attachNewNode("ballRoot")
    		self.ball = loader.loadModel("models/ball")
    		self.ball.reparentTo(self.ballRoot)
		# This section deals with lighting for the ball. Only the ball was lit
    		# because the maze has static lighting pregenerated by the modeler
    		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))
    
    		# This section deals with adding a specular highlight to the ball to make
    		# it look shiny
    		m = Material()
    		m.setSpecular(Vec4(1,1,1,1))
    		m.setShininess(96)
    		self.ball.setMaterial(m, 1)
Пример #17
0
    def setup_lights(self):
        render = self.render
        ambientLight = AmbientLight('ambient')
        ambientLight.setColor(Vec4(.5, .5, .5, 1))
        render.setLight(render.attachNewNode(ambientLight))

        directionalLight = DirectionalLight('directional')
        directionalLight.setDirection(Vec3(10, 10, -10))
        directionalLight.setColor(Vec4(.75, .6, .6, 1))
        directionalLight.setSpecularColor(directionalLight.getColor())
        render.setLight(render.attachNewNode(directionalLight))

        skyLight = DirectionalLight('sky')
        skyLight.setDirection(Vec3(-25, 10, -25))
        skyLight.setColor(Vec4(.25, .25, .5, 1))
        skyLight.setSpecularColor(skyLight.getColor())
        render.setLight(render.attachNewNode(skyLight))
Пример #18
0
    def start(self, myPlayerName, players):
        """
        Takes a list of player names and positions, 
        initializes the players and sets up the scene
        """
        # Load the environment model.
        self.levelNode = render.attachNewNode("Level node")
        self.level = LevelContainer(self.levelName)
        self.level.render(self.levelNode, base.loader)
        self.levelNode.setAttrib(ShadeModelAttrib.make(ShadeModelAttrib.MFlat))

        base.win.setClearColor(Vec4(0,0,0,1))
        self.title = addTitle("PushBack")
        self.players = dict()
        
        self.playersNode = render.attachNewNode("Players Root Node")
        self.healthbar = DirectWaitBar(range=1.0, barColor=(1.0, 0.0, 0.0, 1.0), 
                        value=1.0, frameSize=(-0.45,0.45,1.0,0.98))
        base.disableMouse()
        base.cam.reparentTo(self.playersNode)
        base.cam.setCompass()
        base.cam.setH(0)
        base.cam.setZ(CAM_HEIGHT)
        base.cam.setY(-CAM_HEIGHT)
        base.cam.setP(-CAM_ANGLE)
        
        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))
        skins = ["stony_green", "stony_red", "stony_blue", "bonbon_blue","bonbon_green", "red", "pushette", "blue"]
        for player in players:
            print "Init player %s" % player[0]
            p = Player(player[0])
            p.reparentTo(self.playersNode)
            p.setPos(player[1])
            p.setColor(skins.pop())
            self.players[player[0]] = p
            if myPlayerName == player[0]:
                self.myPlayer = p
                base.cam.reparentTo(self.myPlayer)
Пример #19
0
    def setupSimpleLighting(self,
                            ambientLightLevel=.3,
                            directionalLightLevel=1):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(
            (ambientLightLevel, ambientLightLevel, ambientLightLevel, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor(
            (directionalLightLevel, directionalLightLevel,
             directionalLightLevel, 1))
        directionalLight.setSpecularColor(
            (directionalLightLevel, directionalLightLevel,
             directionalLightLevel, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        return [ambientLight, directionalLight]
Пример #20
0
    def setUpWindow(self):
        # set up the egg files needed
        # since this method is made for python 2.7 but these objects are made for python 3.5, seems to be incompatible
        #m = Mountain("TestMountain", 60)
        #m.editFile()
        #p = Pole("TestPole", 0, 0, 0)
        #p.editFile()
        #c = Car("TestCar", 0,0,0)
        #c.editFile()
        #b = BeaconLight("BeaconLight",0,0,0)
        #b.editFile()
        # Set up the window, camera, etc
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 1, 1, 1))
        # this is the model I created using mountainMaker.py
        self.environ = loader.loadModel("TestMountain1")
        self.environ.reparentTo(render)

        self.car = loader.loadModel("TestCar")
        # found how to solve the problem of only being able to see objects from
        # certain angles with this:
        # http://www.panda3d.org/manual/index.php/Backface_Culling_and_Frontface_Culling
        self.car.setTwoSided(True)
        self.car.reparentTo(render)

        # Create some lighting
        # this is a part that is completely unchanged from demo
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        # to get light from other direction to light up things on both sides
        directionalLight2 = DirectionalLight("directionalLight")
        directionalLight2.setDirection((5, 5, 5))
        directionalLight2.setColor((1, 1, 1, 1))
        directionalLight2.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight2))
Пример #21
0
    def __init__(self):

        #Load switch model
        self.glowswitch = loader.loadModel("glowswitch")
        self.sphere=self.glowswitch.find("**/sphere") #finds a subcomponent of the .egg model... sphere is the name of the sphere geometry in the .egg file
        self.glowswitch.reparentTo(render)

        base.disableMouse() #mouse-controlled camera cannot be moved within the program
        camera.setPosHpr( 0, -6.5, 1.4, 0, -2, 0)

        #Light up everything an equal amount
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.95, .95, 1.05, 1))
        render.setLight(render.attachNewNode(ambientLight))

        #Add lighting that only casts light on one side of everything in the scene
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(.2, .2, .2, .1)) #keepin it dim
        directionalLight.setSpecularColor(Vec4(0.2, 0.2, 0.2, 0.2))
        render.setLight(render.attachNewNode(directionalLight))

        #initalize sequence variable
        self.ChangeColorSeq = Sequence(Wait(.1))

        #start with blue by default
        self.changeOrbColor(.1,0,.6,.3,.2,1)
                            #^(R min, Gmin, Bmin, Rmax, Gmax, Bmax)
        
        #user controls
        #note that changing the color means it will "pulse" that color and therefore needs a range of color values
        self.accept("1", self.changeOrbColor,[.6,.1,.1,1,.3,.3]) #change orb color to red
        self.accept("2", self.changeOrbColor,[.1,.6,.1,.3,1,.3])#change orb color to green
        self.accept("3", self.changeOrbColor,[.1,0,.6,.3,.2,1]) #change orb color to blue
        self.accept("escape", sys.exit)

        instructions = OnscreenText(text="1: Change to red \n2: Change to Green \n3: Change to Blue \nEsc: Exit",
                                     fg=(1,1,1,1), pos = (-1.3, -.82), scale = .05, align = TextNode.ALeft)
Пример #22
0
    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)
Пример #23
0
    def __init__(self):
        #try:
        #if(co == 0):
        ShowBase.__init__(self)
        #	co += 1
        self.disableMouse()
        base.setBackgroundColor(0, 0, 1)
        #camera.setPosHpr(45, -45, 45, 45, -45, 45)
        self.accept("escape", sys.exit)  # Escape quits

        # Disable default mouse-based camera control.  This is a method on the
        # ShowBase class from which we inherit.
        #self.disableMouse()
        camera.setPosHpr(-10, -50, 10, -10, -7, 0)
        #camera.setPosHpr(-50, 40, 0, 270, 0, 0)
        #base.setBackgroundColor(0,1,0)
        #base
        net = loader.loadModel("models/drawnNet")
        net.setColor(1, 1, 0)
        net.setScale(2.5, 2.5, 1.5)
        net.setPosHpr(0, 53, -2, 0, -10, 0)
        net.reparentTo(render)

        global targetY
        targetY = 40

        postR = loader.loadModel("models/box")
        postR.setColor(0.75, 0, 0.25)
        postR.setScale(0.03, 0.03, 1)
        LidR = postR.find('**/lid')
        PandaR = postR.find('**/turningthing')
        HingeNodeR = postR.find('**/box').attachNewNode('nHingeNode')
        HingeNodeR.setPos(.8659, 6.5, 5.4)
        LidR.wrtReparentTo(HingeNodeR)
        HingeNodeR.setHpr(0, 90, 0)
        lidCloseR = Parallel(
            LerpHprInterval(HingeNodeR, 2.0, (0, 90, 0),
                            blendType='easeInOut'))
        postR.setPosHpr(18, 55.5, -2, 0, 0, 0)
        postR.reparentTo(render)

        postGR = loader.loadModel("models/box")
        postGR.setColor(0.75, 0, 0.25)
        postGR.setScale(0.03, 0.03, 1)
        lidGR = postGR.find('**/lid')
        PandaGR = postGR.find('**/turningthing')
        HingeNodeGR = postGR.find('**/box').attachNewNode('nHingeNode')
        HingeNodeGR.setPos(.8659, 6.5, 5.4)
        #lidGR.wrtReparentTo(HingeNodeR)
        HingeNodeGR.setHpr(0, 90, 0)
        lidCloseGR = Parallel(
            LerpHprInterval(HingeNodeGR,
                            2.0, (0, 90, 0),
                            blendType='easeInOut'))
        postGR.setPosHpr(18, 58.5, -4, 90, 0, 90)
        postGR.reparentTo(render)

        postL = loader.loadModel("models/box")
        postL.setColor(0.75, 0, 0.25)
        postL.setScale(0.03, 0.03, 2)
        LidL = postL.find('**/lid')
        PandaL = postL.find('**/turningthing')
        HingeNodeL = postL.find('**/box').attachNewNode('nHingeNode')
        HingeNodeL.setPos(.8659, 6.5, 5.4)
        LidL.wrtReparentTo(HingeNodeL)
        HingeNodeL.setHpr(0, 90, 0)
        lidCloseL = Parallel(
            LerpHprInterval(HingeNodeL, 2.0, (90, 0, 0),
                            blendType='easeInOut'))
        postL.setPosHpr(-18, 55.5, -1, 0, 0, 0)
        postL.reparentTo(render)

        postGL = loader.loadModel("models/box")
        postGL.setColor(0.75, 0, 0.25)
        postGL.setScale(0.03, 0.03, 1)
        lidGL = postGL.find('**/lid')
        PandaGL = postGL.find('**/turningthing')
        HingeNodeGL = postGL.find('**/box').attachNewNode('nHingeNode')
        HingeNodeGL.setPos(.8659, 6.5, 5.4)
        #lidGR.wrtReparentTo(HingeNodeR)
        HingeNodeGL.setHpr(0, 90, 0)
        lidCloseGL = Parallel(
            LerpHprInterval(HingeNodeGL,
                            2.0, (0, 90, 0),
                            blendType='easeInOut'))
        postGL.setPosHpr(-18, 58.5, -4.5, 90, 0, 90)
        postGL.reparentTo(render)
        #camera.setPosHpr(20, 45, 0, 90, 0, 0)

        postT = loader.loadModel("models/box")
        postT.setColor(0.75, 0, 0.25)
        postT.setScale(1.70, 0.03, 0.03)
        LidT = postL.find('**/lid')
        PandaT = postT.find('**/turningthing')
        HingeNodeT = postT.find('**/box').attachNewNode('nHingeNode')
        HingeNodeT.setPos(.8659, 6.5, 5.4)
        LidT.wrtReparentTo(HingeNodeT)
        HingeNodeT.setHpr(0, 90, 0)
        lidCloseT = Parallel(
            LerpHprInterval(HingeNodeT, 2.0, (0, 90, 0),
                            blendType='easeInOut'))
        postT.setPosHpr(0, 55.5, 9.8, 0, 0, 0)
        postT.reparentTo(render)

        global ball
        ballRoot = render.attachNewNode("ballRoot")
        ball = loader.loadModel("models/ball")
        ball.reparentTo(ballRoot)
        #ball.setColor(0.5, 0, 1)
        ball.setScale(6, 6, 6)
        ball.setPosHpr(0, -12, -3, 0, -20, 0)
        #self.kick.setPos(0, 40, 0)
        ballTex = loader.loadTexture("pictures/ball.jpg")
        ball.setTexture(ballTex)
        ball.reparentTo(render)
        ballSphere = ball.find("**/ball")
        ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        ballSphere.node().setIntoCollideMask(BitMask32.allOff())

        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 0, -1))
        directionalLight.setColor((0.375, 0.375, 0.375, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))

        ballRoot.setLight(render.attachNewNode(ambientLight))
        ballRoot.setLight(render.attachNewNode(directionalLight))
        m = Material()
        m.setSpecular((1, 1, 1, 1))
        m.setShininess(96)
        ball.setMaterial(m, 1)

        cs = CollisionSphere(0, 0, 0, 0.41)
        cNodePath = ball.attachNewNode(CollisionNode('cnode'))
        cNodePath.node().addSolid(cs)
        #cNodePath.show()
        #0, 53, -2
        cW = CollisionPolygon(Point3(-1, 40, -4), Point3(-1, 40, 8),
                              Point3(1, 40, 8), Point3(1, 40, -4))
        cwNodePath = net.attachNewNode(CollisionNode('cwnode'))
        cwNodePath.node().addSolid(cW)
        #cwNodePath.show()

        #queue = CollisionHandlerQueue()
        #traverser.addCollider(cs, queue)
        #traverser.traverse(render)

        ground = loader.loadModel("models/square")
        ground.setPosHpr(0, 35, -5, 0, 0, 0)
        ground.setScale(120, 120, 120)
        #ground.setColor(0.2, 1, 0)
        grass = loader.loadTexture("pictures/grass_1.jpg")
        ground.setTexture(grass)
        ground.reparentTo(render)

        wall = loader.loadModel("models/square")
        wall.setPosHpr(5, 100, 18, 0, 90, 0)
        wall.setScale(90, 50, 75)
        #camera.setPos(0, -150, 0)
        #wall.setColor(0.5, 0.5, 0.5)
        crowd = loader.loadTexture("pictures/crowd.png")
        wall.setTexture(crowd)
        wall.reparentTo(render)

        rightWall = loader.loadModel("models/square")
        rightWall.setPosHpr(48, 45, 0, -90, 90, 0)
        rightWall.setScale(100, 100, 100)
        rightWall.setColor(0.75, 0.75, 0.75)
        rightWall.reparentTo(render)

        global angle
        angle = loader.loadModel("models/box")
        angle.setColor(0.25, 0.25, 0.25)
        angle.setScale(1.0, 0.25, 0.03)
        LidA = angle.find('**/lid')
        PandaA = angle.find('**/turningthing')
        HingeNodeA = angle.find('**/box').attachNewNode('nHingeNode')
        HingeNodeA.setPos(.8659, 6.5, 5.4)
        LidA.wrtReparentTo(HingeNodeA)
        HingeNodeA.setHpr(0, 90, 0)
        lidCloseA = Parallel(
            LerpHprInterval(HingeNodeA, 2.0, (0, 90, 0),
                            blendType='easeInOut'))
        angle.setPosHpr(0, 10.5, -3, 0, 90, 0)
        #bar = loader.loadTexture("pictures/bar.png")
        #angle.setTexture(bar)
        angle.reparentTo(render)

        global angleD
        angleD = loader.loadModel("models/box")
        angleD.setColor(0, 0, 1)
        angleD.setScale(0.1, 0.25, 0.03)
        LidD = angleD.find('**/lid')
        PandaD = angleD.find('**/turningthing')
        HingeNodeD = angleD.find('**/box').attachNewNode('nHingeNode')
        HingeNodeD.setPos(.8659, 6.5, 5.4)
        LidD.wrtReparentTo(HingeNodeD)
        HingeNodeD.setHpr(0, 90, 0)
        lidCloseD = Parallel(
            LerpHprInterval(HingeNodeD, 2.0, (0, 90, 0),
                            blendType='easeInOut'))
        angleD.setPosHpr(0, 10.4, -3, 0, 90, 0)
        angleD.reparentTo(render)

        global power
        power = loader.loadModel("models/box")
        power.setColor(0.25, 0.25, 0.25)
        power.setScale(0.12, 2.2, 0.03)
        LidP = power.find('**/lid')
        PandaP = power.find('**/turningthing')
        HingeNodeP = power.find('**/box').attachNewNode('nHingeNode')
        HingeNodeP.setPos(.8659, 6.5, 5.4)
        LidP.wrtReparentTo(HingeNodeP)
        HingeNodeP.setHpr(0, 90, 0)
        lidCloseP = Parallel(
            LerpHprInterval(HingeNodeP, 2.0, (0, 90, 0),
                            blendType='easeInOut'))
        power.setPosHpr(-18, 10.5, -3, 0, 90, 0)

        global powerD
        powerD = loader.loadModel("models/box")
        powerD.setColor(1, 0, 0)
        powerD.setScale(0.12, 0.05, 0.03)
        LidD = power.find('**/lid')
        PandaD = power.find('**/turningthing')
        HingeNodeD = power.find('**/box').attachNewNode('nHingeNode')
        HingeNodeD.setPos(.8659, 6.5, 5.4)
        LidD.wrtReparentTo(HingeNodeD)
        HingeNodeD.setHpr(0, 90, 0)
        lidCloseD = Parallel(
            LerpHprInterval(HingeNodeD, 2.0, (0, 90, 0),
                            blendType='easeInOut'))
        powerD.setPosHpr(-18, 10, -4.5, 0, 50, 0)

        global bishop
        bishop = loader.loadModel("models/bishop")
        bs = loader.loadTexture("pictures/bishop.png")
        bishop.setTexture(bs)
        bishop.setScale(10, 10, 10)
        #bishop.setColor(0, 0.4, 1)
        bishop.setPosHpr(0, 42, -5, 90, 0, 0)
        bishop.reparentTo(render)

        global bArmL
        bArmL = loader.loadModel("models/bishop")
        bArmL.setScale(2, 2, 4)
        bishop.setTexture(bs)
        #bArmL.setColor(0, 0.4, 1)
        bArmL.setPos(-1, 55, 6)
        #bArmL.reparentTo(render)

        global bArmR
        bArmR = loader.loadModel("models/bishop")
        bArmR.setScale(2, 2, 4)
        bishop.setTexture(bs)
        #bArmR.setColor(0, 0.4, 1)
        bArmR.setPos(1, 55, 6)
        #bArmR.reparentTo(render)

        global start
        start = loader.loadModel("models/square")
        start.setPosHpr(5, -25, 18, 0, 90, 0)
        start.setScale(90, 50, 75)
        #camera.setPos(0, -150, 0)
        start.setColor(0.5, 0.5, 0.5)
        #crowd = loader.loadTexture("pictures/crowd.png")
        #start.setTexture(crowd)
        start.reparentTo(render)

        title = TextNode('title')
        title.setText("Welcome to Penalty Kick!")
        global textNodePath
        textNodePath = aspect2d.attachNewNode(title)
        textNodePath.setScale(0.25)
        title.setWordwrap(8)
        title.setCardColor(0, 0, 0, 0)
        title.setCardAsMargin(0, 0, 0, 0)
        title.setCardDecal(True)
        textNodePath.setPos(-0.75, 0, 0.5)
        self.instructions = \
               OnscreenText(text="Press any key to begin",
                           parent=base.a2dBottomRight, align=TextNode.ARight,
                           pos=(-1, +0.08), fg=(1, 1, 1, 1), scale=.06,
                           shadow=(0, 0, 0, 0.5))
        #self.accept('ball-into-net', ballCollideHandler)
        base.buttonThrowers[0].node().setKeystrokeEvent('keystroke')
        self.accept('keystroke', self.next)
Пример #24
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left trackpad]: Rotate Left")
        self.inst3 = addInstructions(0.18, "[Right trackpad]: Rotate Right")
        self.inst4 = addInstructions(0.24, "[Up trackpad]: Walk Forward")
        self.inst4 = addInstructions(0.30, "[Down trackpad]: Walk Backward")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

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

        # Create the main character, Ralph

        self.vr = RoamingRalphVR()
        self.vr.init(msaa=4)

        self.ralph = render.attachNewNode('ralph')
        self.ralphStartPos = self.environ.find("**/start_point").getPos()
        self.vr.tracking_space.setPos(self.ralphStartPos)
        self.ralph.setPos(self.vr.hmd_anchor.getPos(render))

        self.accept("escape", sys.exit)

        taskMgr.add(self.collision, "collisionTask")

        # Set up the camera
        self.disableMouse()

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
    def __init__(self):
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))


        self.speed = 0



        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')


        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1),
                     font=self.font_digital, scale=.07, pos=(1.25, -.92))


        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital)

        # Health Bar

        self.bars = {'H' : 100, 'EH' : 0 ,'A' : 0 }

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text = "", value = 100, pos = (0.280,0,0.475), barColor= (1,0,0,1), frameSize = (0,.705,.3,.35))

        self.EHealth_bar = DirectWaitBar(text = "", value = 0, pos = (1,0,0.475), barColor= (0,1,0,1), frameSize = (0,.23,.3,.35),range = 50 )

        self.Armour_bar = DirectWaitBar(text = "", value = 0, pos = (.43,0,.593), barColor= (159,0,255,1), frameSize = (0,.8,.3,.35))

        self.Health = DirectWaitBar(text = "", value = 100,  barColor= (1,0,0,1), frameSize = (-1,1,.3,.5),scale = 2)

        # create a frame
        # myFrame = DirectFrame(frameColor=(1, 0, 0, 1),
        #               frameSize=(0, .8, 0, .2))
                      



        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0), 
        #     barColor = (0.97,0,0,1), 
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025, 
        #     text_pos = (0,0.01,0))


        def getHealthStatus() :
            return self.bars

        def displayBars() :
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']
            self.Health['value'] = health['H']


        def armourPickup() :
            self.bars['A'] += 25
            displayBars()

        def healthPickup() :
            self.bars['EH'] += 25
            displayBars()

        def decHealth() :
            self.bars['H'] -= 10
            displayBars()


        def initialiseSound(audioManager):
            """Start the engine sound and set collision sounds"""

            # Set sounds to play for collisions
            # self.collisionSound = CollisionSound(
            #     nodePath=self.np,
            #     sounds=["data/sounds/09.wav"],
            #     thresholdForce=600.0,
            #     maxForce=800000.0)

            # np - nodePath

            self.engineSound = audioManager.loadSfx("sound/engine.wav")
            audioManager.attachSoundToObject(self.engineSound, self.ralph)
            self.engineSound.setLoop(True)
            self.engineSound.setPlayRate(0.6)
            self.engineSound.play()

            # self.gearSpacing = (self.specs["sound"]["maxExpectedRotationRate"] /
            #     self.specs["sound"]["numberOfGears"])

            self.gearSpacing = (150 / 4)

            self.reversing = False

              


        # Post the instructions
        self.frame = OnscreenImage(image = "models/gframe.png", pos = (0,0,0), scale = (1.25, 1, 1) )
        self.frame.setTransparency(TransparencyAttrib.MAlpha)


        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        
        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
    	self.environ.setTexture(self.moon_tex, 1)
        
        # Create the main character, Ralph

        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0,0,0)


        # # Load and place the model
        # self.eNode = render.attachNewNode('enemyBaseNode')
        # self.eNode.setPos( 0,0,0 )
        
        # self.model = loader.loadModel( 'models/ralph' )
        # self.model.reparentTo( self.eNode )


        
        
        # # Setup the rest of what the enemy needs
        
        # self.setupHealthBar()

        # self.Health.setBillboardAxis()
        # self.Health.setBillboardPointWorld()
        # self.Health.setBillboardPointEye()
        # self.Health.setLightOff()



        self.Health.setPos(0, 0, 5)
        self.Health.setBillboardPointEye()
        self.Health.setBin('fixed', 0)
        self.Health.setDepthWrite(False)
        self.Health.reparentTo(self.ralph)



        # myFrame.setPos(0, 0, 8)
        # myFrame.setBillboardPointEye()
        # myFrame.reparentTo(self.ralph)

        # self.Health.clearBillboard()

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

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

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

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

        # Create some lighting
        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))



        # Create an audio manager. This is attached to the camera for
        # player 1, so sounds close to other players might not be very
        # loud
        self.audioManager = Audio3DManager.Audio3DManager(base.sfxManagerList[0],base.camera)

        # Distance should be in m, not feet
        self.audioManager.setDistanceFactor(3.28084)


        initialiseSound(self.audioManager)

        displayBars()
    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))
Пример #27
0
    def __init__(self):

        self.startvar = 0
        self.startdialog = YesNoDialog(dialogName="START GAME",
                                       text="START GAME",
                                       command=self.endbox)
        self.timepass = model()
        self.timepass1 = model1()
        self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0}
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # number of collectibles
        self.numObjects = 0

        #music
        self.backmusic = base.loader.loadSfx("sounds/tales.mp3")
        self.backmusic.setLoop(True)
        self.backmusic.setVolume(0.2)
        self.backmusic.play()

        self.skatemusic = base.loader.loadSfx("sounds/skate.mp3")
        self.skatemusic.setVolume(.65)
        self.skatemusic.setLoop(True)

        self.bombmusic = base.loader.loadSfx("sounds/bomb.mp3")
        self.bombmusic.setVolume(.85)

        self.springmusic = base.loader.loadSfx("sounds/spring.mp3")
        self.springmusic.setVolume(.65)
        self.springmusic.setLoop(True)

        self.colmusic = base.loader.loadSfx("sounds/collect.mp3")
        self.colmusic.setVolume(.65)

        # print the number of objects
        printNumObj(self.numObjects)

        # Post the instructions
        # self.title = addTitle("Roaming Ralph (Edited by Adam Gressen)")
        # self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        # self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left")
        # self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right")
        # self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward")
        # self.inst5 = addInstructions(0.75, "[S]: Run Ralph Backward")
        # self.inst6 = addInstructions(0.70, "[Space]: Run, Ralph, Run")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

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

        # Timer to increment in the move task
        self.time = 0

        # Get bounds of environment
        min, max = self.environ.getTightBounds()
        self.mapSize = max - min

        # Create the main character, Ralph
        self.ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor(
            "models/ralph", {
                "run": "models/ralph-run",
                "jump": "models/ralph-jump",
                "walk": "models/ralph-walk"
            })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.30)
        self.ralph.setPos(self.ralphStartPos)
        #skate
        self.skate = loader.loadModel("models/Skateboard")
        self.skate.reparentTo(render)
        self.skate.setScale(.02)
        self.skate.setPos(-random.randint(38, 50), -random.randint(15, 37),
                          -0.015)
        # ralph's health
        self.health = 100

        #spring
        self.spring = loader.loadModel("models/spring")
        self.spring.reparentTo(render)
        self.spring.setScale(.8)
        self.spring.setPos(-random.randint(72, 78), -random.randint(10, 15),
                           6.715)
        # ralph's stamina
        self.stamina = 100

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation
        self.accept("escape", sys.exit)

        # these don't work well in combination with the space bar
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_down", self.setKey, ["backward", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down-up", self.setKey, ["backward", 0])

        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])

        # Game state variables
        self.isMoving = False
        self.isRunning = False
        self.onboard = 0
        self.boardtime = 0
        self.onspring = 0
        self.isjumping = False
        # Set up the camera
        base.disableMouse()
        #base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        base.camera.setPos(0, 0, 0)
        base.camera.reparentTo(self.ralph)
        base.camera.setPos(0, 40, 2)
        base.camera.lookAt(self.ralph)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        base.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 300)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        base.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # camera ground collision handler
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 300)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        base.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Place the health items
        self.placeHealthItems()

        # Place the collectibles
        self.placeCollectibles()

        # Place the bomb
        self.placebombItems()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #base.cTrav.showCollisions(render)

        # Create some lighting
        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))
        #print self.startvar

        taskMgr.add(self.move, "moveTask")
Пример #28
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

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

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")
        self.dirText = addInstructions(0.42, "pos")
        self.anglesText = addInstructions(0.48, "angle")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

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

        self.createArm()

        # Create the main character, Ralph

        #ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                           {"run": "models/ralph-run",
                            "walk": "models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        #self.ralph.setPos(ralphStartPos + (0, 0, 0.5))

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

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

        # Accept the control keys for movement and rotation

        self.accept("escape", self.exitButton)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera
        self.disableMouse()
        self.camera.setPos(15, 0, 3)#self.ralph.getX(), self.ralph.getY() + 10, 2)
        self.camera.setHpr(90, -5, 0)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        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)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Пример #29
0
    def __init__(self):

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.speed = 0

        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')

        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png",
                                       scale=.5,
                                       pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h",
                     style=1,
                     fg=(1, 1, 1, 1),
                     font=self.font_digital,
                     scale=.07,
                     pos=(1.25, -.92))

        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed),
                                          style=1,
                                          fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95),
                                          align=TextNode.ARight,
                                          scale=.07,
                                          font=self.font_digital)

        # Health Bar

        self.bars = {'H': 100, 'EH': 0, 'A': 0}

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text="",
                                        value=100,
                                        pos=(0.280, 0, 0.475),
                                        barColor=(1, 0, 0, 1),
                                        frameSize=(0, .705, .3, .35))

        self.EHealth_bar = DirectWaitBar(text="",
                                         value=0,
                                         pos=(1, 0, 0.475),
                                         barColor=(0, 1, 0, 1),
                                         frameSize=(0, .23, .3, .35),
                                         range=50)

        self.Armour_bar = DirectWaitBar(text="",
                                        value=0,
                                        pos=(.43, 0, .593),
                                        barColor=(159, 0, 255, 1),
                                        frameSize=(0, .8, .3, .35))

        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0),
        #     barColor = (0.97,0,0,1),
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025,
        #     text_pos = (0,0.01,0))

        def getHealthStatus():
            return self.bars

        def displayBars():
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']

        def armourPickup():
            self.bars['A'] += 25
            displayBars()

        def healthPickup():
            self.bars['EH'] += 25
            displayBars()

        def decHealth():
            self.bars['H'] -= 10
            displayBars()

        # Post the instructions
        self.frame = OnscreenImage(image="models/gframe.png",
                                   pos=(0, 0, 0),
                                   scale=(1.25, 1, 1))
        self.frame.setTransparency(TransparencyAttrib.MAlpha)

        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(100, 100, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0, 0, 0)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

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

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # Create some lighting
        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))

        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()

        self.audioManager.initialiseSound(self.ralph)
Пример #30
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        base.render.setAttrib(LightRampAttrib.makeHdr0())

        # Configure depth pre-pass
        prepass_pass = lionrender.DepthScenePass()

        # Configure scene pass
        scene_fb_props = FrameBufferProperties()
        scene_fb_props.set_rgb_color(True)
        scene_fb_props.set_rgba_bits(8, 8, 8, 0)
        scene_fb_props.set_depth_bits(32)
        scene_pass = lionrender.ScenePass(
            frame_buffer_properties=scene_fb_props,
            clear_color=LColor(0.53, 0.80, 0.92, 1),
            share_depth_with=prepass_pass)
        scene_pass.node_path.set_depth_write(False)

        # Configure post processing
        filter_pass = lionrender.FilterPass(fragment_path='shaders/fsq.frag')
        filter_pass.node_path.set_shader_input('inputTexture',
                                               scene_pass.output)

        # Enable FXAA
        fxaa_pass = lionrender.FxaaFilterPass()
        fxaa_pass.node_path.set_shader_input('inputTexture',
                                             filter_pass.output)

        # Output result
        fxaa_pass.output_to(render2d)

        # 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,
        }

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward")
        self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        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)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 1.5))

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

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

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])
        self.accept("v", self.toggleCards)

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

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

        self.cTrav = CollisionTraverser()

        # Use a CollisionHandlerPusher to handle collisions between Ralph and
        # the environment. Ralph is added as a "from" object which will be
        # "pushed" out of the environment if he walks into obstacles.
        #
        # Ralph is composed of two spheres, one around the torso and one
        # around the head.  They are slightly oversized since we want Ralph to
        # keep some distance from obstacles.
        self.ralphCol = CollisionNode('ralph')
        self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5))
        self.ralphCol.addSolid(
            CollisionSphere(center=(0, -0.25, 4), radius=1.5))
        self.ralphCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphColNp = self.ralph.attachNewNode(self.ralphCol)
        self.ralphPusher = CollisionHandlerPusher()
        self.ralphPusher.horizontal = True

        # Note that we need to add ralph both to the pusher and to the
        # traverser; the pusher needs to know which node to push back when a
        # collision occurs!
        self.ralphPusher.addCollider(self.ralphColNp, self.ralph)
        self.cTrav.addCollider(self.ralphColNp, self.ralphPusher)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.
        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        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)

        # Uncomment this line to see the collision rays
        #self.ralphColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

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

        # Clean up texture attributes
        for texture in self.render.find_all_textures():
            texture.set_format(Texture.F_srgb)
Пример #31
0
    def __init__(self):
        ShowBase.__init__(self)

        self.dirTypes = ['heading', 'pitch', 'roll']
        self.dirType = 0

        # Display instructions
        add_title("Panda3D Tutorial: Portal Culling")
        add_instructions(0.06, "[Esc]: Quit")
        self.posText = add_instructions(0.12, "pos")
        self.anglesText = add_instructions(0.18, "angle")
        self.armHprText = add_instructions(0.24, "hpr")
        self.dirText = add_instructions(.30, self.dirTypes[0])
        self.forearmText = add_instructions(0.36, "angle")
        self.baseText = add_instructions(0.42, "angle")
        """add_instructions(0.12, "[W]: Move Forward")
        add_instructions(0.18, "[A]: Move Left")
        add_instructions(0.24, "[S]: Move Right")
        add_instructions(0.30, "[D]: Move Back")
        add_instructions(0.36, "Arrow Keys: Look Around")
        add_instructions(0.42, "[F]: Toggle Wireframe")
        add_instructions(0.48, "[X]: Toggle X-Ray Mode")
        add_instructions(0.54, "[B]: Toggle Bounding Volumes")"""

        # Setup controls
        self.keys = {}
        for key in ['arrow_left', 'arrow_right', 'arrow_up', 'arrow_down',
                    'a', 'd', 'w', 's', 'q', 'e']:
            self.keys[key] = 0
            self.accept(key, self.push_key, [key, 1])
            self.accept('shift-%s' % key, self.push_key, [key, 1])
            self.accept('%s-up' % key, self.push_key, [key, 0])

        self.accept("b", self.push_key, ["Rleft", True])
        self.accept("b-up", self.push_key, ["Rleft", False])
        self.accept("n", self.push_key, ["Rright", True])
        self.accept("n-up", self.push_key, ["Rright", False])
        self.accept("h", self.push_key, ["Rforward", True])
        self.accept("h-up", self.push_key, ["Rforward", False])
        self.keys['Rleft'] = self.keys['Rright'] = self.keys['Rforward'] = 0

        self.accept('escape', self.exitButton)
        self.accept('p', self.selectDir)
        self.accept('[', self.incDir, [-15])
        self.accept(']', self.incDir, [15])
        #self.disableMouse()

        # Setup camera
        lens = PerspectiveLens()
        lens.setFov(60)
        lens.setNear(0.01)
        lens.setFar(1000.0)
        self.cam.node().setLens(lens)
        self.camera.setPos(-50, 0, 0)
        self.pitch = 0.0
        self.heading = 0
        
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        # Load level geometry
        self.level = self.loader.loadModel('models/theater')
        self.level.reparentTo(self.render)

        self.isMoving = False
        self.ralph = Actor("models/ralph",
                           {"run": "models/ralph-run",
                            "walk": "models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)


        self.arms = []
        idMap = {0:9, 1:11, 2:17, 3:27, 4:29}

        for node in self.level.get_children():
          if not node.getName().startswith('arm'): continue
          arm = Actor("models/robotarm")
          self.arms.append(arm)
          arm.reparentTo(render)
          arm.setName(node.getName())
          arm.setPos(node.getPos())
          arm.setHpr(node.getHpr())
          #arm.setScale(.2)

          tokens = node.getName().split('.')
          try: id = int(tokens[1])
          except: id = 0
          arm.baseID = idMap[id]

          arm.jointForearm = arm.controlJoint(None, "modelRoot", "forearm")
          arm.jointBase = arm.controlJoint(None, "modelRoot", "base")
          print node.getName(), str(node.getPos()), str(node.getHpr())
   
        taskMgr.add(self.printLoc, "printLoc")
        taskMgr.add(self.monitorArms, "robot arms")
        self.taskMgr.add(self.update, 'main loop')
Пример #32
0
    def __init__(self):

        self.room = loader.loadModel("models/world")
        self.room.reparentTo(render)
        self.room.setShaderAuto()
        #self.room.setScale(100,100,100)

        self.character = loader.loadModel("assets/characters/knight")
        self.character.reparentTo(render)
        self.character.setPos(0, 0, 0)

        self.character2 = loader.loadModel("assets/characters/king")
        self.character2.reparentTo(render)
        self.character2.setPos(0, 0, 0)
        self.character2.setColor((1, 0, 0, 1))

        base.camera.reparentTo(self.character)
        base.camera.setPos(0, -50, 5)
        base.camera.lookAt(self.character)

        # Make the mouse invisible, turn off normal mouse controls
        base.disableMouse()
        props = WindowProperties()
        #props.setCursorHidden(True)
        base.win.requestProperties(props)

        # Set the current viewing target
        self.focus = Vec3(0, 0, 0)
        self.heading = 0
        self.pitch = 0
        self.mousex = 0
        self.mousey = 0
        self.last = 0
        self.keys = {
            'move forward': False,
            'move backward': False,
            'strafe left': False,
            'strafe right': False,
            'zoom-out': False
        }

        # Start the camera control task:
        taskMgr.add(self.controlCamera, "camera-task")
        self.accept("escape", sys.exit, [0])

        #Define a keymap for 'WASD' Movement
        self.accept("w", self.setKeys, ['move forward', True])
        self.accept("w-up", self.setKeys, ['move forward', False])
        self.accept("s", self.setKeys, ['move backward', True])
        self.accept("s-up", self.setKeys, ['move backward', False])
        self.accept("a", self.setKeys, ['strafe left', True])
        self.accept("a-up", self.setKeys, ['strafe left', False])
        self.accept("d", self.setKeys, ['strafe right', True])
        self.accept("d-up", self.setKeys, ['strafe right', False])
        self.accept("q", self.setKeys, ['zoom-out', True])
        self.accept("q-up", self.setKeys, ['zoom-out', False])

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Пример #33
0
    def __init__(self):
        ## Add the default values to the dictionary.
        self.keyMap = {"left":0, "right":0, "forward":0, \
                       "boost":0, "strafeL":0, "strafeR":0, \
                       "cam-left":0, "cam-right":0}
        
        base.win.setClearColor(Vec4(0,0,0,1))
        self.jump = False
        self.jumped = False

        # Post the instructions
        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[D]: Rotate Camera Right")
        self.inst8 = addInstructions(0.60, "[B]: Ralph Boost")
        self.inst9 = addInstructions(0.55, "[V]: Strafe Left")
        self.inst10 = addInstructions(0.50, "[N]: Strafe Right")
        
        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  

        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        ## Stops the sound as soon as the world renders 
        ## Note:Sound won't play very long becasue the game takes seconds to compile and load
        ## Remove loading screen after world is rendered and ready to go.
        
        loadingText.cleanup()
        mySound.stop()
        
        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("d", self.setKey, ["cam-right",1])
        self.accept("b", self.setKey, ["boost",1])
        self.accept("v", self.setKey, ["strafeL",1])
        self.accept("n", self.setKey, ["strafeR",1])
        
        ## -up to signify what happens when you let go of the key
        self.accept("b-up", self.setKey, ["boost",0])
        self.accept("v-up", self.setKey, ["strafeL",0])
        self.accept("n-up", self.setKey, ["strafeR",0])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("d-up", self.setKey, ["cam-right",0])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        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))
Пример #34
0
    def __init__(self):
        base.enableParticles()
        self.keyMap = {"left":0, "right":0, "forward":0,"backward":0,
                       "upward":0, "downward":0, "leftward":0,"rightward":0,
                       "cam-left":0, "cam-right":0}
        _GOLD_PARTICLES.start(parent=render, renderParent=render)
        _GOLD_PARTICLES.setScale(200)
        self.instStatus = "show"
        self.musicCounter = 0
        self.music = load_bgmusic(_BGMUSIC[0])
        # self.music.play()
        self.volume = 0
        self.music.setVolume(self.volume)
        base.win.setClearColor(Vec4(0,0,0,1))
        self.above = 3.0
        # load environment
        self.loadEnviron()
        # load ralph
        self.loadRalph()
        # load sky box
        self.skyBoxLoad()
        # load pokemon
        self.loadPokemon()

        self.displayInformation()
        self.keyControl()
        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)
        taskMgr.add(self.move,"moveTask")
        taskMgr.add(self.setAbove,"setAbove")
        taskMgr.add(self.loadNextMusic, "loadRandomMusic")
        taskMgr.add(self.gold, "gold")
        # Game state variables
        self.isMoving = False
        # Set up the camera
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY(),2)
        self.cTrav = CollisionTraverser()
        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        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 __init__(self):

        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
    	self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(10,10,0)

        # Create 2 panda
        # Actors at 000 and 10,0,0 position

        self.pandaActor1 = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})

        self.pandaActor1.setScale(0.004)
        self.pandaActor1.reparentTo(render)
        self.pandaActor1.setPos(30,30,0)

        self.pandaActor2 = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
        self.pandaActor2.setScale(0.005, 0.005, 0.005)
        self.pandaActor2.reparentTo(render)
        self.pandaActor2.setPos(15,-15,0)

        self.car = loader.loadModel("models/RaceCar")
        self.car_tex = loader.loadTexture("models/tex/Mesh_3_TX.jpg")
        self.car_tex = loader.loadTexture("models/tex/Cylinder_TX.jpg")
        self.car_tex = loader.loadTexture("models/tex/Cylinder_2_TX.jpg")
        self.car_tex = loader.loadTexture("models/tex/Mesh_3_TX_2.jpg")
        self.car_tex = loader.loadTexture("models/tex/Mesh_3_TX_3.jpg")
        # self.car.setScale(2.5)
        self.car.reparentTo(render)
        self.car.setPos(20,30,0)
        self.x=0
        # self.pandaActor1.loop("walk")

        # self.pandaActor2.loop("walk")
        self.panda1AnimControl=self.pandaActor1.getAnimControl("walk")
        self.panda2AnimControl=self.pandaActor2.getAnimControl("walk")

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.


        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])

        taskMgr.add(self.move,"moveTask")
        taskMgr.add(self.jump1, "jumpPanda1")
        taskMgr.add(self.jump2, "jumpPanda2")

        # Game state variables
        self.isMoving = False
        self.pandaisMoving = False
        self.hasMoved = False
        self.hasMoved1 = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)


        # Create some lighting
        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))
Пример #36
0
    def __init__(self):
        self.itemID = 0
        self.switchState = True
        self.iAktion = "E"
        self.altIPos = [0,0]
        self.switchCam = False
        self.kampf = Battle.Kampf()
        self.itemDa = False
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

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

 
        self.spieler = Players.Player(Actor("models/box.x"))
        self.spieler.actor.reparentTo(render)
        spielerStartPos = (-107.575, 26.6066, -0.490075)
        self.spieler.actor.setPos(spielerStartPos)
        self.textObjectSpieler = OnscreenText(text = self.spieler.name+":  "+str(self.spieler.energie)+"/"+str(self.spieler.maxenergie)+" HP", pos = (-0.90, -0.98), scale = 0.07, fg = (1,0,0,1))        

        # Erstellt Gegner
        
        self.gegnerStartPos = ([(-39.1143569946,25.1781406403,-0.136657714844),
                                (-102.375793457,-30.6321983337,0.0),
                                (-56.927986145, -34.6329650879, -0.16748046875),
                                (-79.6673126221,30.8231620789,2.89721679688),
                                (-4.37648868561,30.5158863068,2.18450927734),
                                (22.6527004242,4.99837779999,3.11364746094),
                                (-23.8257598877,-7.87773084641,1.36920166016),
                                (-80.6140823364,19.5769443512,4.70764160156),
                                (-75.0773696899,-15.2991075516,6.24676513672)
                                ])
        
        gegnerPos = random.choice(self.gegnerStartPos)
        self.gegnerErstellen(gegnerPos)
        self.textObjectGegner = OnscreenText(text = str(self.gegner.name)+": "+str(self.gegner.energie)+"/"+str(self.gegner.maxenergie)+" HP", pos = (0.90, -0.98), scale = 0.07, fg = (1,0,0,1))
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        self.item = None
        
        # Handling der Usereingaben für Bewegung

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("i", self.setKey, ["inventar",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])

        self.accept("e", self.iAktionsHandler,["e"])
        self.accept("v", self.iAktionsHandler,["v"])
        self.accept("w", self.iAktionsHandler,["w"])
        
        taskMgr.add(self.move,"moveTask")
        taskMgr.add(self.erkenneKampf,"Kampferkennung")
        taskMgr.add(self.screentexts,"Screentexte")


        # Menü erstellen

        self.createMenu()
        
        # Kameraeinstellungen
        
        base.disableMouse()
        base.camera.setPos(self.spieler.actor.getX(),self.spieler.actor.getY()+10,2)
        
        self.collisionInit();
        
        self.setAI()
        
        # Licht
        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))

        # Hintergrund (Himmel)

        self.setupSkySphere()
Пример #37
0
    def __init__(self):
        ShowBase.__init__(self)

        # initalize the window
        base.disableMouse()
        self.win.setClearColor((0, 0, 0, 1))
        props = WindowProperties()
        props.setCursorHidden(True)
        props.setSize(1700,1000)
        base.win.requestProperties(props)

        # store keys
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0, "backward": 0, 
            "drift-left": 0, "drift-right": 0, "up": 0, "down": 0,
            "restart": 0, "firstPerson": 0, "gravity": 0}

        #instructions
        self.ins2 = addInstructions(0.12, "[Left/Right Arrow]: Rotate Left/Right")
        self.ins3 = addInstructions(0.18, "[Up/Down Arrow]: Fly Forward/Backward")
        self.ins4 = addInstructions(0.24, "[A, D]: Move Camera")
        self.ins5 = addInstructions(0.30, "[W, S]: Lift / Descent")
        self.ins6 = addInstructions(0.36, "[F]: Toggle First Person/ Third Person")
        self.ins7 = addInstructions(0.42, "[G]: Toggle Gravity")
        self.ins8 = addInstructions(0.48, "[R]: Restart")

        # Set up the playground
        # other maps:
        # models/toon/phase_15/hood/toontown_central.bam
        # models/world
        # CS_Map/myCSMAP.egg
        # Race/RaceTrack/FullTrack.blend

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

        """
        self.environ = loader.loadModel("The City/The City.obj")
        self.environ.reparentTo(render)
        myTexture = loader.loadTexture("The City/Maps/cty1.jpg")
        self.environ.setTexture(myTexture)
        self.environ.setHpr(0,90,0)
        self.environ.setScale(.1)
        """

        # Create drone and initalize drone position
        self.Drone = Actor("models/mydrone.egg")
        self.Drone.reparentTo(render)

        # resize and reposition the drone
        self.Drone.setScale(.1)
        self.Drone.setPos(5,5,8)
        self.Drone.setH(180)
        # initial position is saved for restarting the game
        self.DroneStartPos = self.Drone.getPos()


        # User Controls
        self.accept('escape', __import__('sys').exit, [0])
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("a", self.setKey, ["drift-left", True])
        self.accept("d", self.setKey, ["drift-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("a-up", self.setKey, ["drift-left", False])
        self.accept("d-up", self.setKey, ["drift-right", False])
        self.accept("w", self.setKey, ["up", True])
        self.accept("w-up", self.setKey, ["up", False])
        self.accept("s", self.setKey, ["down", True])
        self.accept("s-up", self.setKey, ["down", False])
        self.accept("r", self.setKey, ["restart", True])
        self.accept("r-up", self.setKey, ["restart", False])
        self.accept("f", self.setKey, ["firstPerson", True])
        self.accept("f-up", self.setKey, ["firstPerson", False])
        self.accept("g", self.setKey, ["gravity", True])
        self.accept("g-up", self.setKey, ["gravity", False])

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

        # Disable Mouse
        self.disableMouse()

        # Camera settings
        self.cameraDistance = 5
        self.cameraPitch = -10

        # create the collision box for the drone 
        # this collision box will be used for collision detection
        self.droneBox = CollisionBox((0,0,2.5), 3, 3, 0.7)
        self.cnodePath = self.Drone.attachNewNode(CollisionNode('cnode'))
        self.cnodePath.node().addSolid(self.droneBox)

        # collision detection set up
        self.cTrav = CollisionTraverser()
        self.queue = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cnodePath, self.queue)
        self.cTrav.traverse(render)


        # Lighting portion are modified from an example provided by Panda3d – Roaming Ralph 
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((1, 1, 1, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        # Crashed Text
        self.crashed = OnscreenText()
        self.firstPerson = False

        # HPR setting
        self.angle = 0
        self.angleChange = 0.5
        self.maxAngle = 15

        # Speed Control
        self.FBSpeed = self.mapScale * 6
        self.LRSpeed = self.mapScale * 4
        self.turnSpeed = 80
        self.liftSpeed = self.mapScale * 80
        self.downSpeed = self.mapScale * 80


        # AI set up
        self.AI = True
        if self.AI:
            self.droneAI = Actor("models/mydrone.egg")
            self.droneAI.reparentTo(render)
            self.droneAI.setScale(.1)
            self.droneAI.setPos(5,5,5)
            self.AI_actions = open("AI/RoamingRalph/AI_easy.txt", "r").readlines()

        #######################
        # additional features #
        #######################

        # acceleration
        self.FBacceleration = 0
        self.LRacceleration = 0
        self.accelMax = 40
        self.accelIncrement = 2

        # gravity 
        self.gravity = True
        self.gravity_value = 15 * self.mapScale
Пример #38
0
    def initWorld(self, playerId, chosenCharId, x, y, h):

        self.keyMap = {"hello":0, "left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "chat":0, "fast":0, "chat0": 0, "chat1": 0, "users": 0}
        base.win.setClearColor(Vec4(0,0,0,1))
		# chat box
        self.chatbox = Chat(self.cManager, self)
        self.activeUsers = Users(self.cManager, self)

        taskMgr.add(self.message, 'message')


        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward")
        self.inst4 = addInstructions(0.75, "[S]: Run Ralph Backward")
        self.inst6 = addInstructions(0.70, "[Left Arrow]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[Right Arrow]: Rotate Camera Right")
        self.inst8 = addInstructions(0.60, "[0]: Toggle Chat Broadcast")
        self.inst9 = addInstructions(0.55, "[1]: Toggle Private Chat - username/")
        self.inst10 = addInstructions(0.50, "[L]: List Connected Users")


        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
      	self.environ.setTexture(self.moon_tex, 1)

        #Collision Code
        # Initialize the collision traverser.
        base.cTrav = CollisionTraverser()
        # Initialize the Pusher collision handler.
        self.pusher = CollisionHandlerPusher()

        self.bTrav = base.cTrav
        # Create the main character, Ralph
        self.mainCharRef = Character(self, chosenCharId, True)
        self.mainCharRef.setPlayerId(playerId)
        self.characters.append(self.mainCharRef)
        self.mainChar = self.mainCharRef.getActor()


        #Create second bike
        self.mainCharRef2 = Character(self, 3, True)
        self.mainCharRef2.setPlayerId(2)
        self.characters.append(self.mainCharRef2)
        self.mainChar2 = self.mainCharRef2.getActor()

        resetPos = True
        if (x == 0 and y == 0):
            resetPos = False
        if resetPos:
            self.mainChar.setPos(x, y, 0)
        self.mainChar.setH(h)

        self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, [playerId,
                                                                    chosenCharId,
                                                                    self.mainChar.getX(),
                                                                    self.mainChar.getY(),
                                                                    self.mainChar.getZ()])


        self.previousPos = self.mainChar.getPos()
        taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')

        # Creating Stationary spheres
        self.spheres = []
        self.sphereCount = 3
        for x in range(self.sphereCount):
            self.spheres.append(StationarySphere(self))
        for sphere in self.spheres:
            taskMgr.add(sphere.rotateForAll, "rotateSphere")

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)


        floorNode = render.attachNewNode("Floor NodePath")
        # Create a collision plane solid.
        collPlane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        # Call our function that creates a nodepath with a collision node.
        floorCollisionNP = self.makeCollisionNodePath(floorNode, collPlane)

        # Accept the control keys for movement and rotation
        self.accept("escape", self.quitGame)
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("lshift", self.setKey, ["fast", 1])
        self.accept("arrow_left", self.setKey, ["cam-left",1])
        self.accept("arrow_right", self.setKey, ["cam-right",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("lshift-up", self.setKey, ["fast", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left",0])
        self.accept("arrow_right-up", self.setKey, ["cam-right",0])
        self.accept("h", self.setKey, ["hello",1])
        self.accept("h-up", self.setKey, ["hello",0])
        self.accept("0", self.setKey, ["chat0", 1])
        self.accept("0-up", self.setKey, ["chat0", 0])
        self.accept("1", self.setKey, ["chat1", 1])
        self.accept("1-up", self.setKey, ["chat1", 0])
        self.accept("l", self.setKey, ["users", 1])
        self.accept("l-up", self.setKey, ["users", 0])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.mainChar.getX(),self.mainChar.getY()+10,2)

        # Create some lighting
        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))
Пример #39
0
    def __init__(self):

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.speed = 0

        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')

        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png",
                                       scale=.5,
                                       pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h",
                     style=1,
                     fg=(1, 1, 1, 1),
                     font=self.font_digital,
                     scale=.07,
                     pos=(1.25, -.92))

        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed),
                                          style=1,
                                          fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95),
                                          align=TextNode.ARight,
                                          scale=.07,
                                          font=self.font_digital)

        # Health Bar

        self.bars = {'H': 100, 'EH': 0, 'A': 0}

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text="",
                                        value=100,
                                        pos=(0.280, 0, 0.475),
                                        barColor=(1, 0, 0, 1),
                                        frameSize=(0, .705, .3, .35))

        self.EHealth_bar = DirectWaitBar(text="",
                                         value=0,
                                         pos=(1, 0, 0.475),
                                         barColor=(0, 1, 0, 1),
                                         frameSize=(0, .23, .3, .35),
                                         range=50)

        self.Armour_bar = DirectWaitBar(text="",
                                        value=0,
                                        pos=(.43, 0, .593),
                                        barColor=(159, 0, 255, 1),
                                        frameSize=(0, .8, .3, .35))

        self.Health = DirectWaitBar(text="",
                                    value=100,
                                    barColor=(1, 0, 0, 1),
                                    frameSize=(-1, 1, .3, .5),
                                    scale=2)

        # create a frame
        # myFrame = DirectFrame(frameColor=(1, 0, 0, 1),
        #               frameSize=(0, .8, 0, .2))

        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0),
        #     barColor = (0.97,0,0,1),
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025,
        #     text_pos = (0,0.01,0))

        def getHealthStatus():
            return self.bars

        def displayBars():
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']
            self.Health['value'] = health['H']

        def armourPickup():
            self.bars['A'] += 25
            displayBars()

        def healthPickup():
            self.bars['EH'] += 25
            displayBars()

        def decHealth():
            self.bars['H'] -= 10
            displayBars()

        def initialiseSound(audioManager):
            """Start the engine sound and set collision sounds"""

            # Set sounds to play for collisions
            # self.collisionSound = CollisionSound(
            #     nodePath=self.np,
            #     sounds=["data/sounds/09.wav"],
            #     thresholdForce=600.0,
            #     maxForce=800000.0)

            # np - nodePath

            self.engineSound = audioManager.loadSfx("sound/engine.wav")
            audioManager.attachSoundToObject(self.engineSound, self.ralph)
            self.engineSound.setLoop(True)
            self.engineSound.setPlayRate(0.6)
            self.engineSound.play()

            # self.gearSpacing = (self.specs["sound"]["maxExpectedRotationRate"] /
            #     self.specs["sound"]["numberOfGears"])

            self.gearSpacing = (150 / 4)

            self.reversing = False

        # Post the instructions
        self.frame = OnscreenImage(image="models/gframe.png",
                                   pos=(0, 0, 0),
                                   scale=(1.25, 1, 1))
        self.frame.setTransparency(TransparencyAttrib.MAlpha)

        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(100, 100, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0, 0, 0)

        # # Load and place the model
        # self.eNode = render.attachNewNode('enemyBaseNode')
        # self.eNode.setPos( 0,0,0 )

        # self.model = loader.loadModel( 'models/ralph' )
        # self.model.reparentTo( self.eNode )

        # # Setup the rest of what the enemy needs

        # self.setupHealthBar()

        # self.Health.setBillboardAxis()
        # self.Health.setBillboardPointWorld()
        # self.Health.setBillboardPointEye()
        # self.Health.setLightOff()

        self.Health.setPos(0, 0, 5)
        self.Health.setBillboardPointEye()
        self.Health.setBin('fixed', 0)
        self.Health.setDepthWrite(False)
        self.Health.reparentTo(self.ralph)

        # myFrame.setPos(0, 0, 8)
        # myFrame.setBillboardPointEye()
        # myFrame.reparentTo(self.ralph)

        # self.Health.clearBillboard()

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

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

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # Create some lighting
        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))

        # Create an audio manager. This is attached to the camera for
        # player 1, so sounds close to other players might not be very
        # loud
        self.audioManager = Audio3DManager.Audio3DManager(
            base.sfxManagerList[0], base.camera)

        # Distance should be in m, not feet
        self.audioManager.setDistanceFactor(3.28084)

        initialiseSound(self.audioManager)

        displayBars()
Пример #40
0
    def __init__(self):
        base.setBackgroundColor(0.1, 0.1, 0.8, 1)
        base.setFrameRateMeter(True)

        base.cam.setPosHpr(0, 0, 25, 0, -90, 0)
        base.disableMouse()

        # Input
        self.accept('escape', self.exitGame)
        self.accept('f1', self.toggleWireframe)
        self.accept('f2', self.toggleTexture)
        self.accept('f3', self.toggleDebug)
        self.accept('f5', self.doScreenshot)

        # Setup scene 1: World
        self.debugNP = render.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(True)
        self.debugNP.node().showNormals(True)
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Setup scene 2: Ball
        visNP = loader.loadModel('models/ball.egg')
        visNP.clearModelNodes()

        bodyNPs = BulletHelper.fromCollisionSolids(visNP, True)
        self.ballNP = bodyNPs[0]
        self.ballNP.reparentTo(render)
        self.ballNP.node().setMass(1.0)
        self.ballNP.setPos(4, -4, 1)
        self.ballNP.node().setDeactivationEnabled(False)

        visNP.reparentTo(self.ballNP)

        # Setup scene 3: Maze
        visNP = loader.loadModel('models/maze.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(render)

        self.holes = []
        self.maze = []
        self.mazeNP = visNP

        bodyNPs = BulletHelper.fromCollisionSolids(visNP, True)
        for bodyNP in bodyNPs:
            bodyNP.reparentTo(render)

            if isinstance(bodyNP.node(), BulletRigidBodyNode):
                bodyNP.node().setMass(0.0)
                bodyNP.node().setKinematic(True)
                self.maze.append(bodyNP)

            elif isinstance(bodyNP.node(), BulletGhostNode):
                self.holes.append(bodyNP)

        # Lighting and material for the ball
        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor(Vec4(0.55, 0.55, 0.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.ballNP.setLight(render.attachNewNode(ambientLight))
        self.ballNP.setLight(render.attachNewNode(directionalLight))

        m = Material()
        m.setSpecular(Vec4(1, 1, 1, 1))
        m.setShininess(96)
        self.ballNP.setMaterial(m, 1)

        # Startup
        self.startGame()
Пример #41
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 1, 1, 1))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0,
            "backward": 0, "cam-up": 0, "cam-down": 0, "add-car": 0,
            "switch-mode":0, "mouse-click":0}

        # this is the egg that came with the module
        # environ = loader.loadModel("models/world")
        # this is the one I created using mountainMaker.py
        self.environ = loader.loadModel("TestMountain1")
        self.environ.reparentTo(render)

        self.car = loader.loadModel("TestCar")
        #self.car = loader.loadModel("testModel/ball")
        self.car.reparentTo(render)

        #instructions
        self.inst = [""]*5
        self.setUpFlyingInstructions()

        # for adjusting so that the position is the center of the car
        self.adjustedXForCenter = 10/2
        self.adjustedYForCenter = 20/2

        # important for setting the size relative to everything else
        # found it here : https://www.panda3d.org/manual/index.php/Common_State_Changes
        # set the mode that the player is currently in
        self.mode = 0
        self.modeFly = 0
        self.modeRace = 1

        # to ensure that when pressing h it only switches once each press
        self.hasSwitched = False

        self.carPositionX = 10
        self.carPositionY = 10
        self.carPositionZ = 100
        # note for rotating camera: from this website: 
        # https://www.panda3d.org/manual/index.php/Common_State_Changes
        # setHpr(Yaw, Pitch, Roll)

        # setting up initial conditions for which way camera is rotated
        self.carYaw = 0
        self.carPitch = 0

        self.setUpCarCollider()
        self.setUpMouseCollider()

        # make the rocks and other stuff that will show up
        self.objects = []

        # Accept the control keys for movement and rotation

        #setting up keys for movement
        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])

        # adding car
        self.accept("mouse1", self.setKey, ["mouse-click", True])
        self.accept("mouse1-up", self.setKey, ["mouse-click", False])

        # setting up orientation of the camera
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-down", True])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-down", False])
        self.accept("d", self.setKey, ["cam-right", True])
        self.accept("d-up", self.setKey, ["cam-right", False])
        self.accept("w", self.setKey, ["cam-up", True])
        self.accept("w-up", self.setKey, ["cam-up", False])


        # to switch between tasks
        self.accept("h", self.setKey, ["switch-mode", True])
        self.accept("h-up", self.setKey, ["switch-mode", False])

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

        # Game state variables
        self.isMoving = False

        self.cameraPositionX = 0
        self.cameraPositionY = 0
        self.cameraPositionZ = 0
        # note for rotating camera: from this website: 
        # https://www.panda3d.org/manual/index.php/Common_State_Changes
        # setHpr(Yaw, Pitch, Roll)
        
        # setting up initial conditions for which way camera is rotated
        self.cameraYaw = 0
        self.cameraPitch = 0
        
        # Set up the camera
        self.disableMouse()
        
        # should probably clean up these magic numbers
        self.camera.setPos(20, 20, 20)


        # Create some lighting
        # this is a part that is completely unchanged from demo
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Пример #42
0
    def __init__(self):
        __builtin__.main = self
        self.taskMgr = taskMgr
        self.base = base
        
        # Connect to the server
        self.cManager = ConnectionManager()
        self.startConnection()
    
        self.characters = dict()
        self.cpList = dict()

        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.ralphStartPos = self.environ.find("**/start_point").getPos()

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        
        # Placeholder Login
        self.name = str(raw_input("Name: "))
        factionId = int(input("Faction ID: "))
        self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId])

        # Create two control points
        cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED)
        cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE)

        self.cpList[1] = cp1
        self.cpList[2] = cp2
        
        # Create the control point Bar UI
        self.cp_bar = ControlPointBar()
        self.resource_bar = ResourceBar()

        taskMgr.doMethodLater(0.1, self.refresh, "heartbeat")
        taskMgr.doMethodLater(1, self.CPHandler, "CPHandler")
        taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler')

        # Game state variables
        self.isMoving = False

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

        # Create some lighting
        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))
Пример #43
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        base.setBackgroundColor(0, 0, 0)

        self.accept("escape", sys.exit)  # Escape quits
        self.disableMouse()
        camera.setPosHpr(0, 0, 0, 0, 0, 0)

        lens = PerspectiveLens()
        lens.setFov(90, 60)
        lens.setNear(0.01)
        lens.setFar(100000)
        self.cam.node().setLens(lens)

        self.ballSize = 0.025
        self.cueLength = 0.2
        # self.ballRoot = render.attachNewNode("ballRoot")
        # #self.ball = loader.loadModel("models/ball")
        # self.ball = loader.loadModel("models/ball_0_center.egg")
        # #self.ball = loader.loadModel("models/ball.dae")
        # self.ball.setScale(ballSize, ballSize, ballSize)
        # self.ball.reparentTo(self.ballRoot)
        # #print(self.ball.getBounds())
        # #exit(1)
        # #self.ballSphere = self.ball.find("**/ball")
        # #print(self.ball.getScale()[0])
        # cs = CollisionSphere(0, 0, 0, 1)
        # self.ballSphere = self.ball.attachNewNode(CollisionNode('ball'))
        # self.ballSphere.node().addSolid(cs)

        # self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        # self.ballSphere.node().setIntoCollideMask(BitMask32.bit(1))

        self.sceneIndex = 0
        self.planeInfo = PlaneScene(self.sceneIndex)

        self.planeScene = self.planeInfo.generateEggModel()
        self.planeScene.setTwoSided(True)
        self.planeScene.reparentTo(render)
        self.planeScene.hide()

        #get geometries from plane predictions
        planeTriangles, horizontalPlaneTriangles, self.gravityDirection = self.planeInfo.getPlaneTriangles(
        )

        # add pool balls
        self.ballRoots = []
        self.balls = []
        self.ballSpheres = []
        self.ballGroundRays = []
        for ballIndex in xrange(3):
            ballRoot = render.attachNewNode("ballRoot_" + str(ballIndex))
            ball = loader.loadModel("models/ball_" + str(ballIndex) +
                                    "_center.egg")
            ball.setScale(self.ballSize, self.ballSize, self.ballSize)

            cs = CollisionSphere(0, 0, 0, 1)
            ballSphere = ball.attachNewNode(
                CollisionNode('ball_' + str(ballIndex)))
            ballSphere.node().addSolid(cs)
            ballSphere.node().setFromCollideMask(
                BitMask32.bit(0) | BitMask32.bit(1) | BitMask32.bit(3)
                | BitMask32.bit(4))
            ballSphere.node().setIntoCollideMask(BitMask32.bit(1))

            ball.reparentTo(ballRoot)
            self.ballRoots.append(ballRoot)
            self.balls.append(ball)
            self.ballSpheres.append(ballSphere)

            ballGroundRay = CollisionRay()  # Create the ray
            ballGroundRay.setOrigin(0, 0, 0)  # Set its origin
            ballGroundRay.setDirection(
                self.gravityDirection[0], self.gravityDirection[1],
                self.gravityDirection[2])  # And its direction
            # Collision solids go in CollisionNode
            # Create and name the node
            ballGroundCol = CollisionNode('ball_ray_' + str(ballIndex))
            ballGroundCol.addSolid(ballGroundRay)  # Add the ray
            ballGroundCol.setFromCollideMask(
                BitMask32.bit(2))  # Set its bitmasks
            ballGroundCol.setIntoCollideMask(BitMask32.allOff())
            # Attach the node to the ballRoot so that the ray is relative to the ball
            # (it will always be 10 feet over the ball and point down)
            ballGroundColNp = ballRoot.attachNewNode(ballGroundCol)
            self.ballGroundRays.append(ballGroundColNp)

            ballRoot.hide()
            continue

        # Finally, we create a CollisionTraverser. CollisionTraversers are what
        # do the job of walking the scene graph and calculating collisions.
        # For a traverser to actually do collisions, you need to call
        # traverser.traverse() on a part of the scene. Fortunately, ShowBase
        # has a task that does this for the entire scene once a frame.  By
        # assigning it to self.cTrav, we designate that this is the one that
        # it should call traverse() on each frame.
        self.cTrav = CollisionTraverser()

        # Collision traversers tell collision handlers about collisions, and then
        # the handler decides what to do with the information. We are using a
        # CollisionHandlerQueue, which simply creates a list of all of the
        # collisions in a given pass. There are more sophisticated handlers like
        # one that sends events and another that tries to keep collided objects
        # apart, but the results are often better with a simple queue
        self.cHandler = CollisionHandlerQueue()
        # Now we add the collision nodes that can create a collision to the
        # traverser. The traverser will compare these to all others nodes in the
        # scene. There is a limit of 32 CollisionNodes per traverser
        # We add the collider, and the handler to use as a pair

        #self.cTrav.addCollider(self.ballSphere, self.cHandler)
        for ballSphere in self.ballSpheres:
            self.cTrav.addCollider(ballSphere, self.cHandler)
            continue
        for ballGroundRay in self.ballGroundRays:
            self.cTrav.addCollider(ballGroundRay, self.cHandler)
            continue
        #self.cTrav.addCollider(self.ballGroundColNp, self.cHandler)

        # Collision traversers have a built in tool to help visualize collisions.
        # Uncomment the next line to see it.
        #self.cTrav.showCollisions(render)

        # This section deals with lighting for the ball. Only the ball was lit
        # because the maze has static lighting pregenerated by the modeler
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 0, -1))
        directionalLight.setColor((0.375, 0.375, 0.375, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))

        for ballRoot in self.ballRoots:
            ballRoot.setLight(render.attachNewNode(ambientLight))
            ballRoot.setLight(render.attachNewNode(directionalLight))
            continue

        # This section deals with adding a specular highlight to the ball to make
        # it look shiny.  Normally, this is specified in the .egg file.
        m = Material()
        m.setSpecular((1, 1, 1, 1))
        m.setShininess(96)
        for ball in self.balls:
            ball.setMaterial(m, 1)
            continue

        # self.original = False
        # if self.original:
        #     camera.setPosHpr(0, 0, 25, 0, -90, 0)
        #     self.maze = loader.loadModel("models/maze")
        #     self.maze.reparentTo(render)
        #     self.walls = self.maze.find("**/wall_collide")
        #     self.walls.node().setIntoCollideMask(BitMask32.bit(0))
        #     self.walls.show()
        #     pass

        # create collision entities from plane predictions
        self.triNPs = []
        for triangleIndex, triangle in enumerate(planeTriangles):
            #print(triangleIndex)
            #for triangle in triangles:
            #print(triangle)
            tri = CollisionPolygon(
                Point3(triangle[0][0], triangle[0][1], triangle[0][2]),
                Point3(triangle[1][0], triangle[1][1], triangle[1][2]),
                Point3(triangle[2][0], triangle[2][1], triangle[2][2]))
            triNP = render.attachNewNode(
                CollisionNode('tri_' + str(triangleIndex)))
            triNP.node().setIntoCollideMask(BitMask32.bit(0))
            triNP.node().addSolid(tri)
            self.triNPs.append(triNP)
            #triNP.show()
            continue

        # create special collision entities for horizontal planes so that balls can fall on one horizontal plane and bounce on it
        for triangleIndex, triangle in enumerate(horizontalPlaneTriangles):
            #print(triangleIndex)
            #for triangle in triangles:
            #print(triangle)
            tri = CollisionPolygon(
                Point3(triangle[0][0], triangle[0][1], triangle[0][2]),
                Point3(triangle[1][0], triangle[1][1], triangle[1][2]),
                Point3(triangle[2][0], triangle[2][1], triangle[2][2]))
            triNP = render.attachNewNode(
                CollisionNode('ground_' + str(triangleIndex)))
            triNP.node().setIntoCollideMask(BitMask32.bit(2))
            triNP.node().addSolid(tri)
            self.triNPs.append(triNP)
            #triNP.show()
            continue

        # tri = CollisionPolygon(Point3(-1, 4, -1), Point3(2, 4, -1), Point3(2, 4, 2))
        # triNP = render.attachNewNode(CollisionNode('tri'))
        # triNP.node().setIntoCollideMask(BitMask32.bit(0))
        # triNP.node().addSolid(tri)
        # triNP.show()

        #self.planeScene.node().setIntoCollideMask(BitMask32.bit(0))
        # roomRootNP = self.planeScene
        # roomRootNP.flattenLight()
        # mesh = BulletTriangleMesh()
        # polygons = roomRootNP.findAllMatches("**/+GeomNode")

        # # p0 = Point3(-10, 4, -10)
        # # p1 = Point3(-10, 4, 10)
        # # p2 = Point3(10, 4, 10)
        # # p3 = Point3(10, 4, -10)
        # # mesh.addTriangle(p0, p1, p2)
        # # mesh.addTriangle(p1, p2, p3)

        # print(polygons)
        # for polygon in polygons:
        #     geom_node = polygon.node()
        #     #geom_node.reparentTo(self.render)
        #     #print(geom_node.getNumGeoms())
        #     ts = geom_node.getTransform()
        #     #print(ts)
        #     for geom in geom_node.getGeoms():
        #         mesh.addGeom(geom, ts)
        #         continue
        #     continue
        # #self.scene = roomRootNP
        # shape = BulletTriangleMeshShape(mesh, dynamic=False)
        # #shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        # room = BulletRigidBodyNode('scene')
        # room.addShape(shape)
        # #room.setLinearDamping(0.0)
        # #room.setFriction(0.0)
        # print(shape)
        # room.setDeactivationEnabled(False)
        # roomNP = render.attachNewNode(room)
        # roomNP.setPos(0, 0, 0)
        # roomNP.node().setIntoCollideMask(BitMask32.bit(0))
        # self.world = BulletWorld()
        # self.world.setGravity(Vec3(0, 0, 0))
        # self.world.attachRigidBody(roomNP.node())
        #room.setRestitution(1)

        #self.roomNP = self.scene

        # create the cue
        self.cueRoot = render.attachNewNode("cueRoot")
        self.cue = loader.loadModel("models/cue_center.egg")
        self.cue.setScale(self.cueLength * 3, self.cueLength * 3,
                          self.cueLength)
        self.cue.reparentTo(self.cueRoot)

        self.cuePos = (10, 0, 0)

        self.pickerNode = CollisionNode('mouseRay')
        # Attach that node to the camera since the ray will need to be positioned
        # relative to it
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        # Everything to be picked will use bit 1. This way if we were doing other
        # collision we could separate it
        self.pickerNode.setFromCollideMask(BitMask32.bit(2))
        self.pickerNode.setIntoCollideMask(BitMask32.allOff())
        self.pickerRay = CollisionRay()  # Make our ray
        # Add it to the collision node
        self.pickerNode.addSolid(self.pickerRay)
        # Register the ray as something that can cause collisions
        self.cTrav.addCollider(self.pickerNP, self.cHandler)

        self.accept("mouse1", self.hit)  # left-click grabs a piece

        # create holes
        self.holeLength = 0.06
        holePos, holeHpr = self.planeInfo.getHolePos()
        self.holeRoot = render.attachNewNode("holeRoot")
        #self.hole = loader.loadModel("models/hole_horizontal_center.egg")
        self.hole = loader.loadModel("models/hole_color.egg")
        #self.hole = loader.loadModel("models/billiards_hole_center.egg")
        self.hole.setScale(self.holeLength, self.holeLength, self.holeLength)
        self.hole.reparentTo(self.holeRoot)
        self.hole.setTwoSided(True)
        self.holeRoot.setPos(holePos[0], holePos[1], holePos[2])
        self.holeRoot.setHpr(holeHpr[0], holeHpr[1], holeHpr[2])
        #tex = loader.loadTexture('models/Black_Hole.jpg')
        #self.hole.setTexture(tex, 1)
        self.holeRoot.hide()

        ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 0.5)
        self.holeTube = self.hole.attachNewNode(CollisionNode('hole'))
        self.holeTube.node().addSolid(ct)
        self.holeTube.node().setFromCollideMask(BitMask32.allOff())
        self.holeTube.node().setIntoCollideMask(BitMask32.bit(4))
        #self.holeTube.show()

        # create portals
        inPortalPos, inPortalHpr, outPortalPos, outPortalHpr, self.portalNormal = self.planeInfo.getPortalPos(
        )
        self.portalLength = 0.06
        self.inPortalRoot = render.attachNewNode("inPortalRoot")
        self.inPortal = loader.loadModel("models/portal_2_center.egg")
        self.inPortal.setScale(self.portalLength, self.portalLength,
                               self.portalLength)
        self.inPortal.reparentTo(self.inPortalRoot)
        self.inPortalRoot.setPos(inPortalPos[0], inPortalPos[1],
                                 inPortalPos[2])
        self.inPortalRoot.setHpr(inPortalHpr[0], inPortalHpr[1],
                                 inPortalHpr[2])
        self.inPortalRoot.hide()

        ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1)
        self.inPortalTube = self.inPortal.attachNewNode(
            CollisionNode('portal_in'))
        self.inPortalTube.node().addSolid(ct)
        self.inPortalTube.node().setFromCollideMask(BitMask32.allOff())
        self.inPortalTube.node().setIntoCollideMask(BitMask32.bit(3))
        #self.inPortalTube.hide()

        self.outPortalRoot = render.attachNewNode("outPortalRoot")
        self.outPortal = loader.loadModel("models/portal_2_center.egg")
        self.outPortal.setScale(self.portalLength, self.portalLength,
                                self.portalLength)
        self.outPortal.reparentTo(self.outPortalRoot)
        self.outPortalRoot.setPos(outPortalPos[0], outPortalPos[1],
                                  outPortalPos[2])
        self.outPortalRoot.setHpr(outPortalHpr[0], outPortalHpr[1],
                                  outPortalHpr[2])
        self.outPortalRoot.hide()

        ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1)
        self.outPortalTube = self.outPortal.attachNewNode(
            CollisionNode('portal_out'))
        self.outPortalTube.node().addSolid(ct)
        self.outPortalTube.node().setFromCollideMask(BitMask32.allOff())
        self.outPortalTube.node().setIntoCollideMask(BitMask32.bit(3))
        #self.outPortalTube.hide()
        #self.inPortalTube.show()
        #self.outPortalTube.show()
        #self.holeTube.show()

        #self.cTrav.addCollider(self.holeTube, self.cHandler)

        # create background image
        background_image = loader.loadTexture('dump/' + str(self.sceneIndex) +
                                              '_image.png')
        cm = CardMaker('background')
        cm.setHas3dUvs(True)
        info = np.load('dump/' + str(self.sceneIndex) + '_info.npy')
        #self.camera = getCameraFromInfo(self.info)
        depth = 10.0
        sizeU = info[2] / info[0] * depth
        sizeV = info[6] / info[5] * depth
        cm.setFrame(Point3(-sizeU, depth, -sizeV),
                    Point3(sizeU, depth, -sizeV), Point3(sizeU, depth, sizeV),
                    Point3(-sizeU, depth, sizeV))
        self.card = self.render.attachNewNode(cm.generate())
        self.card.setTransparency(True)
        self.card.setTexture(background_image)
        self.card.hide()

        self.ballGroundMap = {}
        self.ballBouncing = np.full(len(self.balls), 3)

        self.started = False
        self.start()

        #self.hitIndex = -1

        self.showing = 'parts'
        self.showingProgress = 0

        partsScene = PartsScene(self.sceneIndex)
        self.planeNPs, self.planeCenters = partsScene.generateEggModel()
        return
Пример #44
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

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

        # Post the Instruction
        self.title = add_title("Panda 3D Demo")

        # Instructions
        self.inst1 = add_instructions(0.06, "[ESC]: Quit")
        self.inst2 = add_instructions(0.12, "[Left Arrow]: Rotate Left")
        self.inst3 = add_instructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = add_instructions(0.24, "[Up Arrow]: Run Ralph Forward")
        # self.inst6 = add_instructions(0.30, "[A]: Rotate Camera Left")
        # self.inst7 = add_instructions(0.36, "[S]: Rotate Camera Right")

        # Load the Environment Model
        self.environ = self.loader.loadModel(ENVIRONMENT)
        # Reparent the model to the render controller
        self.environ.reparentTo(render)

        # Apply scale and position transform on the model
        # self.environ.setScale(0.25, 0.25, 0.25)
        # self.environ.setPos(-8, 42, 0)

        # Create the Main Character
        # Load and transform the panda actor
        ralph_start_pos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor(RALPH_ACTOR, RALPH_ACTIONS)

        # self.ralph.setScale(0.005, 0.005, 0.005)
        self.ralph.reparentTo(render)
        # Loop it's animation
        self.ralph.setScale(0.2)
        self.ralph.setPos(ralph_start_pos + (0, 0, 0.5))
        # self.ralph.loop("walk")

        # Create a floater object, which floats 2 units above rlaph. We use this as a target for the camera to look at
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        # 2 Units above Ralph
        self.floater.setZ(2.0)

        # Configure the Camera
        # Add the spin camera taks procedure to the taks manager
        # self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")

        # Accept certain control keys
        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.set_key, ["left", True])
        self.accept("arrow_right", self.set_key, ["right", True])
        self.accept("arrow_up", self.set_key, ["forward", True])
        self.accept("a", self.set_key, ["cam-left", True])
        self.accept("s", self.set_key, ["cam-right", True])
        self.accept("arrow_left-up", self.set_key, ["left", False])
        self.accept("arrow_right-up", self.set_key, ["right", False])
        self.accept("arrow_up-up", self.set_key, ["forward", False])
        self.accept("a-up", self.set_key, ["cam-left", False])
        self.accept("s-up", self.set_key, ["cam-right", False])

        # Game States
        taskMgr.add(self.move, "moveTask")
        self.is_moving = False

        self.disableMouse()
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)
        self.camera.lookAt(self.floater)

        """
        Detect the height of hte terrain by creating a collision ray and casting it down towards the terrain.

        One ray will start above ralph's head and the other will start above the camera.
        A ray may hit the terrain, or it may hit a rock or a tree.
        If it hits the terrain we ca ndetect the height.

        If it hits anything else, we rule that the move is illegal.
        """
        self.cTrav = CollisionTraverser()

        # Create a vector, it's location is at the top of ralph's head
        self.ralph_ground_ray = CollisionRay()
        self.ralph_ground_ray.setOrigin(0, 0, 9)  # Top of ralph's head
        self.ralph_ground_ray.setDirection(0, 0, -1)  # Points -Z axis

        # Create a Collision node
        self.ralph_ground_col = CollisionNode("ralph_ray")  # Give the node a name
        self.ralph_ground_col.addSolid(self.ralph_ground_ray)  # the vector from ralph's head to the ground is solid
        self.ralph_ground_col.setFromCollideMask(CollideMask.bit(0))  # ??
        self.ralph_ground_col.setIntoCollideMask(
            CollideMask.allOff()
        )  # ?? This seems like it defines the behavior of ray
        self.ralph_ground_col_np = self.ralph.attachNewNode(self.ralph_ground_col)  # Attach the ray to ralph
        self.ralph_ground_handler = (
            CollisionHandlerQueue()
        )  # I think that when a collision occurs it sends through this
        self.cTrav.addCollider(self.ralph_ground_col_np, self.ralph_ground_handler)  # Attach the collision

        """
        Attach the a camera ray to the camera
        """
        self.cam_ground_ray = CollisionRay()
        self.cam_ground_ray.setOrigin(0, 0, 9)
        self.cam_ground_ray.setDirection(0, 0, -1)
        self.cam_ground_col = CollisionNode("camera_ray")
        self.cam_ground_col.addSolid(self.cam_ground_ray)
        self.cam_ground_col.setFromCollideMask(CollideMask.bit(0))
        self.cam_ground_col.setIntoCollideMask(CollideMask.allOff())
        self.cam_ground_col_np = self.camera.attachNewNode(self.cam_ground_col)
        self.cam_ground_handler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cam_ground_col_np, self.cam_ground_handler)

        # Uncomment the following lines to view the rays
        self.ralph_ground_col_np.show()
        self.cam_ground_col_np.show()

        # Uncomment this line to show a visual representation of the Collision occuring
        self.cTrav.showCollisions(render)

        # Create some lighting
        ambient_light = AmbientLight("ambient_light")
        ambient_light.setColor((0.3, 0.3, 0.3, 1))
        directional_light = DirectionalLight("directional_light")
        directional_light.setDirection((-5, -5, -5))
        directional_light.setColor((1, 1, 1, 1))
        directional_light.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambient_light))
        render.setLight(render.attachNewNode(directional_light))

        # Add Cube
        X_OFFSET = 0
        Y_OFFSET = -3
        Z_OFFSET = 1

        CUBE_SIZE = 2

        x, y, z = ralph_start_pos
        x += X_OFFSET
        y += Y_OFFSET
        z += Z_OFFSET
Пример #45
0
    def __init__(self):
        #create Queue to hold the incoming chat
        #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0, "charge":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        self.cManager = ConnectionManager()
        self.cManager.startConnection()
        #------------------------------
        #Chat
        Chat(self.cManager)
        
        
        #send dummy login info of the particular client
        #send first chat info 
        #---------------------------------------
        self.userName = username
        dummy_login ={'user_id' : self.userName, 'factionId': faction, 'password': '******'}
        self.cManager.sendRequest(Constants.RAND_STRING, dummy_login)
        
        
        chat = { 'userName' : self.userName,     #username
                 'message'    : '-------Login------' }
        self.cManager.sendRequest(Constants.CMSG_CHAT, chat)

        #--------------------------------------
        #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8))

        #frame = DirectFrame(text="Resource Bar", scale=0.001)

        resource_bar = DirectWaitBar(text="",
            value=35, range=100, pos=(0,0,0.9), barColor=(255,255,0,1),
            frameSize=(-0.3,0.3,0,0.03))
        cp_bar = DirectWaitBar(text="",
            value=70, range=100, pos=(1.0,0,0.9), barColor=(0,0,255,1),
            frameSize=(-0.3,0.3,0,0.03), frameColor=(255,0,0,1))

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  

        

        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        nameplate = TextNode('textNode username_' + str(self.userName))
        nameplate.setText(self.userName)
        npNodePath = self.ralph.attachNewNode(nameplate)
        npNodePath.setScale(0.8)
        npNodePath.setBillboardPointEye()
        #npNodePath.setPos(1.0,0,6.0)
        npNodePath.setZ(6.5)

        bar = DirectWaitBar(value=100, scale=1.0)
        bar.setColor(255,0,0)
        #bar.setBarRelief()
        bar.setZ(6.0)
        bar.setBillboardPointEye()
        bar.reparentTo(self.ralph)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("c", self.setKey, ["charge",1])
        self.accept("c-up", self.setKey, ["charge",0])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        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))
Пример #46
0
    def __init__(self):
        # Setup window size, title and so on
        load_prc_file_data(
            "", """
            win-size 1600 900
            window-title Render Pipeline - Roaming Ralph Demo
        """)

        if alt:
            ShowBase.__init__(self)
            self.render_pipeline = render_pipeline
            self.render_pipeline.create(self)
        else:
            # ------ Begin of render pipeline code (else case) ------

            # Insert the pipeline path to the system path, this is required to be
            # able to import the pipeline classes
            #pipeline_path = "../../"

            # Just a special case for my development setup, so I don't accidentally
            # commit a wrong path. You can remove this in your own programs.
            #if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../tobsprRenderPipeline"

            sys.path.insert(0, pipeline_path)

            from rpcore import RenderPipeline, SpotLight
            self.render_pipeline = RenderPipeline()
            self.render_pipeline.create(self)

            # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "7:40"

        # Use a special effect for rendering the scene, this is because the
        # roaming ralph model has no normals or valid materials
        self.render_pipeline.set_effect(
            render, "roaming_ralph_pipeline_scene-effect.yaml", {}, sort=250)

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        self.speed = 1.0
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Post the instructions

        self.inst1 = addInstructions(0.95, "[ESC]  Quit")
        self.inst4 = addInstructions(0.90, "[W]  Run Ralph Forward")
        self.inst4 = addInstructions(0.85, "[S]  Run Ralph Backward")
        self.inst2 = addInstructions(0.80, "[A]  Rotate Ralph Left")
        self.inst3 = addInstructions(0.75, "[D]  Rotate Ralph Right")
        self.inst6 = addInstructions(0.70, "[Left Arrow]  Rotate Camera Left")
        self.inst7 = addInstructions(0.65,
                                     "[Right Arrow]  Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel(
            "roaming_ralph_pipeline_resources/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)

        # Remove wall nodes
        self.environ.find("**/wall").remove_node()

        # Create the main character, Ralph
        self.ralph = Actor(
            "roaming_ralph_pipeline_resources/ralph", {
                "run": "roaming_ralph_pipeline_resources/ralph-run",
                "walk": "roaming_ralph_pipeline_resources/ralph-walk"
            })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(Vec3(-110.9, 29.4, 1.8))

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX() + 10, self.ralph.getY() + 10, 2)
        base.camLens.setFov(80)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        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))
Пример #47
0
    def __init__(self):
        
        self.keyMap = {"left":0, "right":0, "forward":0,"backward":0,
                       "upward":0, "downward":0, "leftward":0,"rightward":0,
                       "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        self.above = 3.0
        # Post the instructions

        self.title = addTitle("My Pokemon - Roam Mode")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Arrow Keys]: Move")
        self.inst4 = addInstructions(0.85, "[w]: look up")
        self.inst4 = addInstructions(0.80, "[s]: look down")
        self.environ = load_model("secondWorld.egg")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Create the main character, Ralph
        
        self.spaceSkyBox = load_model('skybox1.egg')
        self.spaceSkyBox.setScale(150)
        self.spaceSkyBox.setLightOff()
        self.spaceSkyBox.reparentTo(render)
        self.spaceSkyBox.setPos(0,0,-200)
        self.spaceSkyBox.setHpr(0,0,0)
        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("../google_drive/ball/data/models/ralph",
                                 {"run":"../google_drive/ball/data/models/ralph-run",
                                  "walk":"../google_drive/ball/data/models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)
        #self.ralph.hide()

        self.pikachu = load_model("pikachu.egg")
        self.pikachu.reparentTo(render)
        self.pikachu.setScale(1)
        self.pikachu.setPos(ralphStartPos)
        
        self.Groudon = load_model("Groudon.egg")
        self.Groudon.reparentTo(render)
        self.Groudon.setPos(ralphStartPos)
        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("w",self.setKey,["upward",1])
        self.accept("w-up",self.setKey,["upward",0])
        self.accept("s",self.setKey,["downward",1])
        self.accept("s-up",self.setKey,["downward",0])
        

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



        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY(),2)
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        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))
Пример #48
0
class RoamingRalphDemo(CosmoniumBase):

    def get_local_position(self):
        return base.camera.get_pos()

    def create_terrain_appearance(self):
        self.terrain_appearance.set_shadow(self.shadow_caster)

    def create_terrain_heightmap(self):
        self.heightmap = PatchedHeightmap('heightmap',
                                          self.noise_size,
                                          self.height_scale,
                                          self.size,
                                          self.size,
                                          True,
                                          ShaderHeightmapPatchFactory(self.noise))

    def create_terrain_biome(self):
        self.biome = PatchedHeightmap('biome',
                                      self.biome_size,
                                      1.0,
                                      self.size,
                                      self.size,
                                      False,
                                      ShaderHeightmapPatchFactory(self.biome_noise))

    def create_terrain_shader(self):
#         control4 = HeightColorMap('colormap',
#                 [
#                  ColormapLayer(0.00, top=LRGBColor(0, 0.1, 0.24)),
#                  ColormapLayer(0.40, top=LRGBColor(0, 0.1, 0.24)),
#                  ColormapLayer(0.49, top=LRGBColor(0, 0.6, 0.6)),
#                  ColormapLayer(0.50, bottom=LRGBColor(0.9, 0.8, 0.6), top=LRGBColor(0.5, 0.4, 0.3)),
#                  ColormapLayer(0.80, top=LRGBColor(0.2, 0.3, 0.1)),
#                  ColormapLayer(0.90, top=LRGBColor(0.7, 0.6, 0.4)),
#                  ColormapLayer(1.00, bottom=LRGBColor(1, 1, 1), top=LRGBColor(1, 1, 1)),
#                 ])
        appearance = DetailMap(self.terrain_control, self.heightmap, create_normals=True)
        data_source = [HeightmapDataSource(self.heightmap, PatchedGpuTextureSource, filtering=HeightmapDataSource.F_none),
                       HeightmapDataSource(self.biome, PatchedGpuTextureSource, filtering=HeightmapDataSource.F_none),
                       TextureDictionaryDataSource(self.terrain_appearance, TextureDictionaryDataSource.F_hash)]
        if settings.allow_tesselation:
            tesselation_control = ConstantTesselationControl(invert_v=False)
        else:
            tesselation_control = None
        if self.fog is not None:
            after_effects = [Fog(**self.fog)]
        else:
            after_effects = None
        self.terrain_shader = BasicShader(appearance=appearance,
                                          tesselation_control=tesselation_control,
                                          geometry_control=DisplacementGeometryControl(self.heightmap),
                                          data_source=data_source,
                                          after_effects=after_effects)

    def create_tile(self, x, y):
        self.terrain_shape.add_root_patch(x, y)

    def create_terrain(self):
        self.tile_factory = TileFactory(self.tile_density, self.size, self.has_water, self.water)
        self.terrain_shape = TiledShape(self.tile_factory, self.size, self.max_lod, lod_control=VertexSizeMaxDistancePatchLodControl(self.max_distance, self.max_vertex_size))
        self.create_terrain_heightmap()
        self.create_terrain_biome()
        self.create_terrain_appearance()
        self.create_terrain_shader()
        self.terrain = HeightmapSurface(
                               'surface',
                               0,
                               self.terrain_shape,
                               self.heightmap,
                               self.biome,
                               self.terrain_appearance,
                               self.terrain_shader,
                               self.size,
                               clickable=False,
                               average=True)
        self.terrain.set_parent(self)
        self.terrain.create_instance()

    def toggle_water(self):
        if not self.has_water: return
        self.water.visible = not self.water.visible
        self.terrain_shape.check_settings()

    def get_height(self, position):
        height = self.terrain.get_height(position)
        if self.has_water and self.water.visible and height < self.water.level:
            height = self.water.level
        return height

    #Used by populator
    def get_height_patch(self, patch, u, v):
        height = self.terrain.get_height_patch(patch, u, v)
        if self.has_water and self.water.visible and height < self.water.level:
            height = self.water.level
        return height

    def skybox_init(self):
        skynode = base.cam.attachNewNode('skybox')
        self.skybox = loader.loadModel('ralph-data/models/rgbCube')
        self.skybox.reparentTo(skynode)

        self.skybox.setTextureOff(1)
        self.skybox.setShaderOff(1)
        self.skybox.setTwoSided(True)
        # make big enough to cover whole terrain, else there'll be problems with the water reflections
        self.skybox.setScale(1.5* self.size)
        self.skybox.setBin('background', 1)
        self.skybox.setDepthWrite(False)
        self.skybox.setDepthTest(False)
        self.skybox.setLightOff(1)
        self.skybox.setShaderOff(1)
        self.skybox.setFogOff(1)

        #self.skybox.setColor(.55, .65, .95, 1.0)
        self.skybox_color = LColor(pow(0.5, 1/2.2), pow(0.6, 1/2.2), pow(0.7, 1/2.2), 1.0)
        self.skybox.setColor(self.skybox_color)

    def objects_density_for_patch(self, patch):
        scale = 1 << patch.lod
        return int(self.objects_density / scale + 1.0)

    def create_populator(self):
        if settings.allow_instancing:
            TerrainPopulator = GpuTerrainPopulator
        else:
            TerrainPopulator = CpuTerrainPopulator
        self.rock_collection = TerrainPopulator(RockFactory(self), self.objects_density_for_patch, self.objects_density, RandomObjectPlacer(self))
        self.tree_collection = TerrainPopulator(TreeFactory(self), self.objects_density_for_patch, self.objects_density, RandomObjectPlacer(self))
        self.object_collection = MultiTerrainPopulator()
        self.object_collection.add_populator(self.rock_collection)
        self.object_collection.add_populator(self.tree_collection)

    def set_light_angle(self, angle):
        self.light_angle = angle
        self.light_quat.setFromAxisAngleRad(angle * pi / 180, LVector3.forward())
        self.light_dir = self.light_quat.xform(LVector3.up())
        cosA = self.light_dir.dot(LVector3.up())
        self.vector_to_star = self.light_dir
        if self.shadow_caster is not None:
            self.shadow_caster.set_direction(-self.light_dir)
        if self.directionalLight is not None:
            self.directionalLight.setDirection(-self.light_dir)
        if cosA >= 0:
            coef = sqrt(cosA)
            self.light_color = (1, coef, coef, 1)
            self.directionalLight.setColor(self.light_color)
            self.skybox.setColor(self.skybox_color * cosA)
        else:
            self.light_color = (1, 0, 0, 1)
            self.directionalLight.setColor(self.light_color)
            self.skybox.setColor(self.skybox_color * 0)
        self.update()

    def update(self):
        self.object_collection.update_instance()
        self.terrain.update_instance(None, None)

    def apply_instance(self, instance):
        pass

    def create_instance_delayed(self):
        pass

    def get_apparent_radius(self):
        return 0

    def get_name(self):
        return "terrain"

    def is_emissive(self):
        return False

    def __init__(self):
        CosmoniumBase.__init__(self)

        config = RalphConfigParser()
        (self.noise, self.biome_noise, self.terrain_control, self.terrain_appearance, self.water, self.fog) = config.load_and_parse('ralph-data/ralph.yaml')

        self.tile_density = 64
        self.default_size = 128
        self.max_vertex_size = 64
        self.max_lod = 10

        self.size = 128 * 8
        self.max_distance = 1.001 * self.size * sqrt(2)
        self.noise_size = 512
        self.biome_size = 128
        self.noise_scale = 0.5 * self.size / self.default_size
        self.objects_density = int(25 * (1.0 * self.size / self.default_size) * (1.0 * self.size / self.default_size))
        self.objects_density = 250
        self.height_scale = 100 * 5.0
        self.has_water = True
        self.fullscreen = False
        self.shadow_caster = None
        self.light_angle = None
        self.light_dir = LVector3.up()
        self.vector_to_star = self.light_dir
        self.light_quat = LQuaternion()
        self.light_color = (1.0, 1.0, 1.0, 1.0)
        self.directionalLight = None
        self.shadow_size = self.default_size / 8
        self.shadow_box_length = self.height_scale

        self.observer = RalphCamera(self.cam, self.camLens)
        self.observer.init()

        self.distance_to_obs = float('inf')
        self.height_under = 0.0
        self.scene_position = LVector3()
        self.scene_scale_factor = 1
        self.scene_orientation = LQuaternion()

        #Size of an edge seen from 4 units above
        self.edge_apparent_size = (1.0 * self.size / self.tile_density) / (4.0 * self.observer.pixel_size)
        print("Apparent size:", self.edge_apparent_size)

        self.win.setClearColor((135.0/255, 206.0/255, 235.0/255, 1))

        # 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, "cam-up": 0, "cam-down": 0,
            "sun-left": 0, "sun-right": 0,
            "turbo": 0}

        # Set up the environment
        #
        # Create some lighting
        self.vector_to_obs = base.cam.get_pos()
        self.vector_to_obs.normalize()
        if True:
            self.shadow_caster = ShadowCaster(1024)
            self.shadow_caster.create()
            self.shadow_caster.set_lens(self.shadow_size, -self.shadow_box_length / 2.0, self.shadow_box_length / 2.0, -self.light_dir)
            self.shadow_caster.set_pos(self.light_dir * self.shadow_box_length / 2.0)
            self.shadow_caster.bias = 0.1
        else:
            self.shadow_caster = None

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLight.setColor((settings.global_ambient, settings.global_ambient, settings.global_ambient, 1))
        self.directionalLight = DirectionalLight("directionalLight")
        self.directionalLight.setDirection(-self.light_dir)
        self.directionalLight.setColor(self.light_color)
        self.directionalLight.setSpecularColor(self.light_color)
        render.setLight(render.attachNewNode(self.ambientLight))
        render.setLight(render.attachNewNode(self.directionalLight))

        render.setShaderAuto()
        base.setFrameRateMeter(True)

        self.create_terrain()
        self.create_populator()
        self.terrain_shape.set_populator(self.object_collection)
        self.create_tile(0, 0)
        self.skybox_init()

        self.set_light_angle(45)

        # Create the main character, Ralph

        ralphStartPos = LPoint3()
        self.ralph = Actor("ralph-data/models/ralph",
                           {"run": "ralph-data/models/ralph-run",
                            "walk": "ralph-data/models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))
        self.ralph_shape = InstanceShape(self.ralph)
        self.ralph_shape.parent = self
        self.ralph_shape.set_owner(self)
        self.ralph_shape.create_instance()
        self.ralph_appearance = ModelAppearance(self.ralph)
        self.ralph_appearance.set_shadow(self.shadow_caster)
        self.ralph_shader = BasicShader()
        self.ralph_appearance.bake()
        self.ralph_appearance.apply(self.ralph_shape, self.ralph_shader)
        self.ralph_shader.apply(self.ralph_shape, self.ralph_appearance)
        self.ralph_shader.update(self.ralph_shape, self.ralph_appearance)

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

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

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("control-q", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("shift", self.setKey, ["turbo", True])
        self.accept("a", self.setKey, ["cam-left", True], direct=True)
        self.accept("s", self.setKey, ["cam-right", True], direct=True)
        self.accept("u", self.setKey, ["cam-up", True], direct=True)
        self.accept("u-up", self.setKey, ["cam-up", False])
        self.accept("d", self.setKey, ["cam-down", True], direct=True)
        self.accept("d-up", self.setKey, ["cam-down", False])
        self.accept("o", self.setKey, ["sun-left", True], direct=True)
        self.accept("o-up", self.setKey, ["sun-left", False])
        self.accept("p", self.setKey, ["sun-right", True], direct=True)
        self.accept("p-up", self.setKey, ["sun-right", False])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("shift-up", self.setKey, ["turbo", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])
        self.accept("w", self.toggle_water)
        self.accept("h", self.print_debug)
        self.accept("f2", self.connect_pstats)
        self.accept("f3", self.toggle_filled_wireframe)
        self.accept("shift-f3", self.toggle_wireframe)
        self.accept("f5", self.bufferViewer.toggleEnable)
        self.accept("f8", self.terrain_shape.dump_tree)
        self.accept('alt-enter', self.toggle_fullscreen)

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

        # Game state variables
        self.isMoving = False

        # Set up the camera
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)
        self.camera_height = 2.0
        render.set_shader_input("camera", self.camera.get_pos())

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        #self.terrain_shape.test_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance)
        #self.terrain_shape.update_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance)
        #self.terrain.shape_updated()
        self.terrain.update_instance(LPoint3d(*self.ralph.getPos()), None)

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

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        dt = globalClock.getDt()

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        if self.keyMap["cam-left"]:
            self.camera.setX(self.camera, -20 * dt)
        if self.keyMap["cam-right"]:
            self.camera.setX(self.camera, +20 * dt)
        if self.keyMap["cam-up"]:
            self.camera_height *= (1 + 2 * dt)
        if self.keyMap["cam-down"]:
            self.camera_height *= (1 - 2 * dt)
        if self.camera_height < 1.0:
            self.camera_height = 1.0

        if self.keyMap["sun-left"]:
            self.set_light_angle(self.light_angle + 30 * dt)
        if self.keyMap["sun-right"]:
            self.set_light_angle(self.light_angle - 30 * dt)

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        delta = 25
        if self.keyMap["turbo"]:
            delta *= 10
        if self.keyMap["left"]:
            self.ralph.setH(self.ralph.getH() + 300 * dt)
        if self.keyMap["right"]:
            self.ralph.setH(self.ralph.getH() - 300 * dt)
        if self.keyMap["forward"]:
            self.ralph.setY(self.ralph, -delta * dt)
        if self.keyMap["backward"]:
            self.ralph.setY(self.ralph, delta * dt)

        #self.limit_pos(self.ralph)

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if self.keyMap["forward"] or self.keyMap["backward"] or self.keyMap["left"] or self.keyMap["right"]:
            if self.isMoving is False:
                self.ralph.loop("run")
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.ralph.pose("walk", 5)
                self.isMoving = False

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

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

        # Normally, we would have to call traverse() to check for collisions.
        # However, the class ShowBase that we inherit from has a task to do
        # this for us, if we assign a CollisionTraverser to self.cTrav.
        self.cTrav.traverse(render)

        if False:
            # Adjust ralph's Z coordinate.  If ralph's ray hit anything, put
            # him back where he was last frame.

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

            if len(entries) > 0:
                self.ralph.setPos(startpos)
        ralph_height = self.get_height(self.ralph.getPos())
        self.ralph.setZ(ralph_height)

        # Keep the camera at one foot above the terrain,
        # or two feet above ralph, whichever is greater.

        camera_height = self.get_height(self.camera.getPos()) + 1.0
        if camera_height < ralph_height + self.camera_height:
            self.camera.setZ(ralph_height + self.camera_height)
        else:
            self.camera.setZ(camera_height)
        #self.limit_pos(self.camera)

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.
        self.camera.lookAt(self.floater)

        #self.shadow_caster.set_pos(self.ralph.get_pos())
        self.shadow_caster.set_pos(self.ralph.get_pos() - camvec * camdist + camvec * self.shadow_size / 2)

        render.set_shader_input("camera", self.camera.get_pos())
        self.vector_to_obs = base.cam.get_pos()
        self.vector_to_obs.normalize()

        if self.isMoving:
            #self.terrain_shape.test_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance)
            pass#self.terrain_shape.update_lod(LPoint3d(*self.ralph.getPos()), self.distance_to_obs, self.pixel_size, self.terrain_appearance)

        self.object_collection.update_instance()
        self.terrain.update_instance(LPoint3d(*self.ralph.getPos()), None)
        return task.cont

    def print_debug(self):
        print("Height:", self.get_height(self.ralph.getPos()), self.terrain.get_height(self.ralph.getPos()))
        print("Ralph:", self.ralph.get_pos())
        print("Camera:", base.camera.get_pos())
Пример #49
0
    def __init__(self):

        self.loading = LoadingScreen()

        base.setFrameRateMeter(True)
        #input states
        inputState.watchWithModifiers('forward', 'w')
        inputState.watchWithModifiers('left', 'a')
        inputState.watchWithModifiers('brake', 's')
        inputState.watchWithModifiers('right', 'd')
        inputState.watchWithModifiers('turnLeft', 'q')
        inputState.watchWithModifiers('turnRight', 'e')

        self.keyMap = {"hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0,
                       "chat0": 0, "powerup": 0, "reset": 0}
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Network Setup
        self.cManager = ConnectionManager(self)
        self.startConnection()
        #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"])
        # chat box
        # self.chatbox = Chat(self.cManager, self)


        # Set up the environment
        #
        self.initializeBulletWorld(False)

        #self.createEnvironment()
        Track(self.bulletWorld)

        # Create the main character, Ralph

        self.mainCharRef = Vehicle(self.bulletWorld, (0, 25, 16, 0, 0, 0), self.login)
        #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me")
        self.mainChar = self.mainCharRef.chassisNP
        #self.mainChar.setPos(0, 25, 16)

#         self.characters.append(self.mainCharRef)

#         self.TestChar = Character(self, self.bulletWorld, 0, "test")
#         self.TestChar.actor.setPos(0, 0, 0)

        self.previousPos = self.mainChar.getPos()
        taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')

        # Set Dashboard
        self.dashboard = Dashboard(self.mainCharRef, taskMgr)


        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation
        self.accept("escape", self.doExit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("h", self.setKey, ["hello", 1])
        self.accept("h-up", self.setKey, ["hello", 0])
        self.accept("0", self.setKey, ["chat0", 1])
        self.accept("0-up", self.setKey, ["chat0", 0])
        self.accept("1", self.setKey,["powerup", 1])
        self.accept("1-up", self.setKey,["powerup", 0])
        self.accept("2", self.setKey,["powerup", 2])
        self.accept("2-up", self.setKey,["powerup", 0])
        self.accept("3", self.setKey,["powerup", 3])
        self.accept("3-up", self.setKey,["powerup", 0])
        self.accept("r", self.doReset)
        self.accept("p", self.setTime)

        #self.loading.finish()
        #taskMgr.doMethodLater(5, self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Sky Dome
        self.sky = SkyDome()

        # Set up the camera
        self.camera = Camera(self.mainChar, self.bulletWorld)
        #base.disableMouse()
        #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2)

        # Create some lighting
        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))
        directionalLight2 = DirectionalLight("directionalLight2")
        directionalLight2.setDirection(Vec3(5, 5, -5))
        directionalLight2.setColor(Vec4(1, 1, 1, 1))
        directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight2))

        # Game initialisation
        self.gameState = self.gameStateDict["Login"]
        self.responseValue = -1

        self.cManager.sendRequest(Constants.CMSG_LOGIN,[self.login,"1234"])
        taskMgr.add(self.enterGame,"EnterGame")

    # Create Powerups
        self.createPowerups()
        taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask")
        taskMgr.add(self.usePowerup, "usePowerUp")
Пример #50
0
    def __init__(self):
        # This code puts the standard title and instruction text on screen
        self.title = OnscreenText(text="Ball in Maze",
                                  style=1,
                                  fg=(1, 1, 1, 1),
                                  pos=(0.7, -0.95),
                                  scale=.07)
        self.instructions = OnscreenText(text="Press Esc to exit.",
                                         pos=(-1.3, .95),
                                         fg=(1, 1, 1, 1),
                                         align=TextNode.ALeft,
                                         scale=.05)

        base.setBackgroundColor(0, 0, 0)

        self.central_msg = OnscreenText(text="",
                                        pos=(0, 0),
                                        fg=(1, 1, 0, 1),
                                        scale=.1)
        self.central_msg.hide()

        self.accept("escape", sys.exit)  # Escape quits
        base.disableMouse()  # Disable mouse-based camera control
        camera.setPosHpr(0, 0, 25, 0, -90, 0)  # Place the camera

        # Load the maze and place it in the scene
        self.maze = loader.loadModel("models/maze")
        self.maze.reparentTo(render)

        # Most times, you want collisions to be tested against invisible geometry
        # rather than every polygon. This is because testing against every polygon
        # in the scene is usually too slow. You can have simplified or approximate
        # geometry for the solids and still get good results.
        #
        # Sometimes you'll want to create and position your own collision solids in
        # code, but it's often easier to have them built automatically. This can be
        # done by adding special tags into an egg file. Check maze.egg and ball.egg
        # and look for lines starting with <Collide>. The part is brackets tells
        # Panda exactly what to do. Polyset means to use the polygons in that group
        # as solids, while Sphere tells panda to make a collision sphere around them
        # Keep means to keep the polygons in the group as visable geometry (good
        # for the ball, not for the triggers), and descend means to make sure that
        # the settings are applied to any subgroups.
        #
        # Once we have the collision tags in the models, we can get to them using
        # NodePath's find command

        # Find the collision node named wall_collide
        self.walls = self.maze.find("**/wall_collide")

        # Collision objects are sorted using BitMasks. BitMasks are ordinary numbers
        # with extra methods for working with them as binary bits. Every collision
        # solid has both a from mask and an into mask. Before Panda tests two
        # objects, it checks to make sure that the from and into collision masks
        # have at least one bit in common. That way things that shouldn't interact
        # won't. Normal model nodes have collision masks as well. By default they
        # are set to bit 20. If you want to collide against actual visable polygons,
        # set a from collide mask to include bit 20
        #
        # For this example, we will make everything we want the ball to collide with
        # include bit 0
        self.walls.node().setIntoCollideMask(BitMask32.bit(0))
        # CollisionNodes are usually invisible but can be shown. Uncomment the next
        # line to see the collision walls
        # self.walls.show()

        # We will now find the triggers for the holes and set their masks to 0 as
        # well. We also set their names to make them easier to identify during
        # collisions
        self.loseTriggers = []
        for i in range(6):
            trigger = self.maze.find("**/hole_collide" + str(i))
            trigger.node().setIntoCollideMask(BitMask32.bit(0))
            trigger.node().setName("loseTrigger")
            self.loseTriggers.append(trigger)
            # Uncomment this line to see the triggers
            # trigger.show()

        # Ground_collide is a single polygon on the same plane as the ground in the
        # maze. We will use a ray to collide with it so that we will know exactly
        # what height to put the ball at every frame. Since this is not something
        # that we want the ball itself to collide with, it has a different
        # bitmask.
        self.mazeGround = self.maze.find("**/ground_collide")
        self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))

        # Load the ball and attach it to the scene
        # It is on a root dummy node so that we can rotate the ball itself without
        # rotating the ray that will be attached to it
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = loader.loadModel("models/ball")
        self.ball.reparentTo(self.ballRoot)

        # Find the collison sphere for the ball which was created in the egg file
        # Notice that it has a from collision mask of bit 0, and an into collison
        # mask of no bits. This means that the ball can only cause collisions, not
        # be collided into
        self.ballSphere = self.ball.find("**/ball")
        self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())

        # No we create a ray to start above the ball and cast down. This is to
        # Determine the height the ball should be at and the angle the floor is
        # tilting. We could have used the sphere around the ball itself, but it
        # would not be as reliable
        self.ballGroundRay = CollisionRay()  # Create the ray
        self.ballGroundRay.setOrigin(0, 0, 10)  # Set its origin
        self.ballGroundRay.setDirection(0, 0, -1)  # And its direction
        # Collision solids go in CollisionNode
        self.ballGroundCol = CollisionNode(
            'groundRay')  # Create and name the node
        self.ballGroundCol.addSolid(self.ballGroundRay)  # Add the ray
        self.ballGroundCol.setFromCollideMask(
            BitMask32.bit(1))  # Set its bitmasks
        self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
        # Attach the node to the ballRoot so that the ray is relative to the ball
        # (it will always be 10 feet over the ball and point down)
        self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
        # Uncomment this line to see the ray
        # self.ballGroundColNp.show()

        # Finally, we create a CollisionTraverser. CollisionTraversers are what
        # do the job of calculating collisions
        self.cTrav = CollisionTraverser()
        # Collision traverservs tell collision handlers about collisions, and then
        # the handler decides what to do with the information. We are using a
        # CollisionHandlerQueue, which simply creates a list of all of the
        # collisions in a given pass. There are more sophisticated handlers like
        # one that sends events and another that tries to keep collided objects
        # apart, but the results are often better with a simple queue
        self.cHandler = CollisionHandlerQueue()
        # Now we add the collision nodes that can create a collision to the
        # traverser. The traverser will compare these to all others nodes in the
        # scene. There is a limit of 32 CollisionNodes per traverser
        # We add the collider, and the handler to use as a pair
        self.cTrav.addCollider(self.ballSphere, self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp, self.cHandler)

        # Collision traversers have a built in tool to help visualize collisions.
        # Uncomment the next line to see it.
        # self.cTrav.showCollisions(render)

        # This section deals with lighting for the ball. Only the ball was lit
        # because the maze has static lighting pregenerated by the modeler
        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))

        # This section deals with adding a specular highlight to the ball to make
        # it look shiny
        m = Material()
        m.setSpecular(Vec4(1, 1, 1, 1))
        m.setShininess(96)
        self.ball.setMaterial(m, 1)

        # Finally, we call start for more initialization
        self.start()
Пример #51
0
    def __init__(self):
        #base = ShowBase()
        ShowBase.__init__(self)
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))
        self.texto1 = OnscreenText(text="Collect 8 balls and meet Sonic behind the building", style=1, fg=(1,1,1,1), pos=(0,-0.1), align=TextNode.ACenter, scale = .07)
        self.texto2 = OnscreenText(text="Eat bananas for energy and avoid green stones", style=1, fg=(1,1,1,1), pos=(0,-0.2), align=TextNode.ACenter, scale = .07)
        self.texto3 = OnscreenText(text="Arrow keys move the player", style=1, fg=(1,1,1,1), pos=(0,-0.3), align=TextNode.ACenter, scale = .07)
        self.texto4 = OnscreenText(text="a and s help you view the scene", style=1, fg=(1,1,1,1), pos=(0,-0.4), align=TextNode.ACenter, scale = .07)

        
        mySound = base.loader.loadSfx("models/Theme_song.ogg")
        mySound.setLoop(True)
        mySound.play()
		#mySound.setLoop(true)
        self.noOfbanana = self.makeStatusLabel(0)
        self.noOfBalls = self.makeStatusLabel(1)
        self.points = self.makeStatusLabel(2)
            
        self.environ = self.loader.loadModel("models/moonsurface.egg")
        self.environ.reparentTo(self.render)
        self.environ.setScale(0.25, 0.25, 0.25)
        self.environ.setPos(-8, 42, -3)
        self.environ1 = self.loader.loadModel("models/env")
        self.environ1.reparentTo(self.render)
        self.environ1.setScale(50,50,30)
        self.environ1.setPos(0, -170, -3)
        #self.environ1.setHpr(90,0,0)
		
        self.chair1=self.loader.loadModel("models/BeachChair")
        #self.chair1=self.reaparentTo(self.render)
        #self.setScale(1000)
        #self.setPos(25,-160,-3)
        #self.chair1.setHpr(90,0,0)
        self.house1 = self.loader.loadModel("models/houses/church")
        self.house1.reparentTo(self.render)
        self.house1.setScale(0.30)
        self.house1.setPos(25, -150, -3)
        self.house1.setHpr(90,0,0)
        self.house2 = self.loader.loadModel("models/houses/building")
        self.house2.reparentTo(self.render)
        self.house2.setScale(0.30)
        self.house2.setPos(18, -200, -3)
        self.house2.setHpr(180,0,0)
        self.house3 = self.loader.loadModel("models/houses/farmhouse")
        self.house3.reparentTo(self.render)
        self.house3.setScale(0.30)
        self.house3.setPos(20, -130, -3)
        self.house3.setHpr(90,0,0)
        self.house4 = self.loader.loadModel("models/houses/dojo")
        self.house4.reparentTo(self.render)
        self.house4.setScale(0.05)
        self.house4.setPos(5, -220, -3)
        self.house5 = self.loader.loadModel("models/houses/beachhouse2")
        self.house5.reparentTo(self.render)
        self.house5.setScale(0.30)
        self.house5.setPos(-10, -180, -3)
        self.house5.setHpr(-90,0,0)

        self.house6 = self.loader.loadModel("models/houses/gazebo")
        self.house6.reparentTo(self.render)
        self.house6.setScale(0.50)
        self.house6.setPos(-10, -200, -3)
        self.house7 = self.loader.loadModel("models/houses/building")
        self.house7.reparentTo(self.render)
        self.house7.setScale(0.30)
        self.house7.setPos(-10, -120, -3)

        '''  for x in range(0,8):
            self.load4 = loader.loadModel("models/fence")
            self.load4.reparentTo(render)
            self.load4.setScale(.5, .5, 1.3)
            self.load4.setPos(28-x*7,0,1.8)
            cp = self.load4.attachNewNode(CollisionNode('box'))
            cp.node().addSolid(CollisionPolygon(
            Point3(-10.0,0.0,4),Point3(10,0,4),
            Point3(10,-1,-2),Point3(-10,-1,-2))) '''

        self.tunnel = [None for i in range(10)]
    
        for x in range(10):
          #Load a copy of the tunnel
          self.tunnel[x] = loader.loadModel('models/tunnel')
          self.tunnel[x].setHpr(0,90,0)
          self.tunnel[x].setScale(0.5)
          self.tunnel[x].setPos(0,177.5 + 25*x, 0)
          self.tunnel[x].reparentTo(self.render)
##        ###World specific-code
##    
##        #Create an instance of fog called 'distanceFog'.
##        #'distanceFog' is just a name for our fog, not a specific type of fog.
##        self.fog = Fog('distanceFog')
##        #Set the initial color of our fog to black.
##        self.fog.setColor(0, 0, 0)
##        #Set the density/falloff of the fog.  The range is 0-1.
##        #The higher the numer, the "bigger" the fog effect.
##        self.fog.setExpDensity(.08)
##        #We will set fog on render which means that everything in our scene will
##        #be affected by fog. Alternatively, you could only set fog on a specific
##        #object/node and only it and the nodes below it would be affected by
##        #the fog.
##        render.setFog(self.fog)
        self.banana = [None for i in range(20)]
        self.flag = [0 for i in range(20)]
        self.fla = [0 for i in range(5)]
        self.fl = [0 for i in range(8)]
        for x in range(10):
          #Load a copy of the tunnel
          self.banana[x] = loader.loadModel('models/banana/banana')
          #self.banana[x].setHpr(0,90,0)
          self.banana[x].setScale(0.7)
          if(x%2==0):
              self.banana[x].setPos(-1,180 + 25*x, -2)
          else:
              self.banana[x].setPos(1,177.5 + 25*x, -2)
          self.banana[x].reparentTo(self.render)

        self.banana[11] = self.loader.loadModel("models/banana/banana")
        self.banana[11].reparentTo(self.render)
        self.banana[11].setPos(12, 8, -2)
        self.banana[12] = self.loader.loadModel("models/banana/banana")
        self.banana[12].reparentTo(self.render)
        self.banana[12].setPos(0, 120, -2)
        self.banana[13] = self.loader.loadModel("models/banana/banana")
        self.banana[13].reparentTo(self.render)
        self.banana[13].setPos(12, 100, -2)
        self.banana[14] = self.loader.loadModel("models/banana/banana")
        self.banana[14].reparentTo(self.render)
        self.banana[14].setPos(22, 80, -2)
        self.banana[15] = self.loader.loadModel("models/banana/banana")
        self.banana[15].reparentTo(self.render)
        self.banana[15].setPos(12, 50, -2)
        self.banana[16] = self.loader.loadModel("models/banana/banana")
        self.banana[16].reparentTo(self.render)
        self.banana[16].setPos(15, 30, -2)
        self.banana[17] = self.loader.loadModel("models/banana/banana")
        self.banana[17].reparentTo(self.render)
        self.banana[17].setPos(-10, 8, -2)
        self.banana[18] = self.loader.loadModel("models/banana/banana")
        self.banana[18].reparentTo(self.render)
        self.banana[18].setPos(-20, -30, -2)
        self.banana[19] = self.loader.loadModel("models/banana/banana")
        self.banana[19].reparentTo(self.render)
        self.banana[19].setPos(-50, -50, -2)
        
        self.candy = self.loader.loadModel("models/candy/candycane2")
        self.candy.reparentTo(self.render)
        self.candy.setScale(0.001)
        self.candy.setPos(-6, 10, -2)

        self.fire = self.loader.loadModel("models/candy/candycane2")
        self.fire.reparentTo(self.render)
        self.fire.setScale(0.001)
        self.fire.setPos(0, 2, -2)

        self.ball = [None for i in range(8)]
        self.ball[0] = self.loader.loadModel("models/ball/soccerball")
        self.ball[0].reparentTo(self.render)
        self.ball[0].setPos(-6, 6, -2)
        self.ball[0].setScale(0.7)
        self.ball[1] = self.loader.loadModel("models/ball/soccerball")
        self.ball[1].reparentTo(self.render)
        self.ball[1].setPos(-6, -6, -2)
        self.ball[1].setScale(0.7)
        self.ball[2] = self.loader.loadModel("models/ball/soccerball")
        self.ball[2].reparentTo(self.render)
        self.ball[2].setPos(-15, 10, -2)
        self.ball[2].setScale(0.7)
        self.ball[3] = self.loader.loadModel("models/ball/soccerball")
        self.ball[3].reparentTo(self.render)
        self.ball[3].setPos(-19, 0, -2)
        self.ball[3].setScale(0.7)
        self.ball[4] = self.loader.loadModel("models/ball/soccerball")
        self.ball[4].reparentTo(self.render)
        self.ball[4].setPos(-6, -20, -2)
        self.ball[4].setScale(0.7)
        self.ball[5] = self.loader.loadModel("models/ball/soccerball")
        self.ball[5].reparentTo(self.render)
        self.ball[5].setPos(6, 6, -2)
        self.ball[5].setScale(0.7)
        self.ball[6] = self.loader.loadModel("models/ball/soccerball")
        self.ball[6].reparentTo(self.render)
        self.ball[6].setPos(19, 10, -2)
        self.ball[6].setScale(0.7)
        self.ball[7] = self.loader.loadModel("models/ball/soccerball")
        self.ball[7].reparentTo(self.render)
        self.ball[7].setPos(-15, 12, -2)
        self.ball[7].setScale(0.7)

        self.rock = [None for i in range(8)]
        self.rock[0] = self.loader.loadModel("models/greencrystal")
        self.rock[0].reparentTo(self.render)
        self.rock[0].setPos(0,306, -4)
        self.rock[0].setScale(0.007)
        self.rock[0].setHpr(90,0,0)
        self.rock[1] = self.loader.loadModel("models/greencrystal")
        self.rock[1].reparentTo(self.render)
        self.rock[1].setPos(-2, 150, -3)
        self.rock[1].setScale(0.007)
        self.rock[1].setHpr(90,0,0)
        self.rock[2] = self.loader.loadModel("models/greencrystal")
        self.rock[2].reparentTo(self.render)
        self.rock[2].setPos(-10, 10, -3)
        self.rock[2].setScale(0.007)
        self.rock[2].setHpr(90,0,0)
        self.rock[3] = self.loader.loadModel("models/greencrystal")
        self.rock[3].reparentTo(self.render)
        self.rock[3].setPos(5, 0, -3)
        self.rock[3].setScale(0.007)
        self.rock[3].setHpr(90,0,0)
        self.rock[4] = self.loader.loadModel("models/greencrystal")
        self.rock[4].reparentTo(self.render)
        self.rock[4].setPos(-2, -120, -3)
        self.rock[4].setScale(0.007)
        self.rock[4].setHpr(90,0,0)

        self.tire = self.loader.loadModel("models/tire/tire")
        self.tire.reparentTo(self.render)
        self.tire.setScale(0.25, 0.25, 0.25)
        self.tire.setPos(-20, 3, -2)
        
        self.bunny1 = self.loader.loadModel("models/bunny")
        self.bunny1.reparentTo(self.render)
        self.bunny1.setScale(0.2)
        self.bunny1.setPos(15, -160, -3)
        self.bunny1.setHpr(-60,0,0)
        self.bunny2 = self.loader.loadModel("models/bunny")
        self.bunny2.reparentTo(self.render)
        self.bunny2.setScale(0.2)
        self.bunny2.setPos(15, -161, -3)
        self.bunny2.setHpr(-145,0,0)
        # Add the spinCameraTask procedure to the task manager.
        #self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
 
 
        
        # Load and transform the panda actor.
        self.pandaActor = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
        self.pandaActor.setScale(0.005, 0.005, 0.005)
        #self.pandaActor.setPos(0,100,-3)
        self.pandaActor.reparentTo(self.render)
        # Loop its animation.
        self.pandaActor.loop("walk")
 
        # Create the four lerp intervals needed for the panda to
        # walk back and forth.
        pandaPosInterval1 = self.pandaActor.posInterval(20,
                                                        Point3(0, -110, -3),
                                                        startPos=Point3(0, -90, -3))
        pandaPosInterval2 = self.pandaActor.posInterval(20,
                                                        Point3(0, -90, -3),
                                                        startPos=Point3(0, -110, -3))
        pandaHprInterval1 = self.pandaActor.hprInterval(3,
                                                        Point3(180, 0, 0),
                                                        startHpr=Point3(0, 0, 0))
        pandaHprInterval2 = self.pandaActor.hprInterval(3,
                                                        Point3(0, 0, 0),
                                                        startHpr=Point3(180, 0, 0))
 
        # Create and play the sequence that coordinates the intervals.
        self.pandaPace = Sequence(pandaPosInterval1,
                                  pandaHprInterval1,
                                  pandaPosInterval2,
                                  pandaHprInterval2,
                                  name="pandaPace")
        self.pandaPace.loop()
        self.eve = Actor("models/eve",
                                {"walk": "models/eve-walk"})
        self.eve.setScale(0.5, 0.5, 0.5)
        self.eve.setPos(-1,-140,-3)
        self.eve.reparentTo(self.render)
        # Loop its animation.
        self.eve.loop("walk")
 
        # Create the four lerp intervals needed for the panda to
        # walk back and forth.
        evePosInterval1 = self.eve.posInterval(20,
                                                        Point3(-1, -160, -3),
                                                        startPos=Point3(-1, -140, -3))
        evePosInterval2 = self.eve.posInterval(20,
                                                        Point3(-1, -140, -3),
                                                        startPos=Point3(-1, -160, -3))
        eveHprInterval1 = self.eve.hprInterval(3,
                                                        Point3(180, 0, 0),
                                                        startHpr=Point3(0, 0, 0))
        eveHprInterval2 = self.eve.hprInterval(3,
                                                        Point3(0, 0, 0),
                                                        startHpr=Point3(180, 0, 0))
 
        # Create and play the sequence that coordinates the intervals.
        self.evePace = Sequence(evePosInterval1,eveHprInterval1,evePosInterval2,eveHprInterval2,name="evePace")
        self.evePace.loop()
        self.ralph = Actor("models/r/ralph",
                                {"run":"models/ralph-run",
                                 "walk": "models/ralph-walk"})
        self.ralph.setScale(0.5, 0.5, 0.5)
        self.ralph.setPos(0, 420, -3)
        self.ralph.reparentTo(self.render)
        self.boy = Actor("models/soni/sonic",
                                {"anim":"models/soni/sonic-win"})
        self.boy.setScale(0.05, 0.05, 0.05)
        self.boy.setPos(33, -203, -2)
        self.boy.setHpr(-90,0,0)
        self.boy.reparentTo(self.render)
        self.boy.loop("anim")

        self.boy1 = Actor("models/boy/boymodel",
                                {"anim":"models/boy/boyanimation"})
        self.boy1.setScale(0.007)
        self.boy1.setPos(-5, -200, -2)
        self.boy1.setHpr(180,0,0)
        self.boy1.reparentTo(self.render)
        self.boy1.loop("anim")

        self.character=Actor()
        self.character.loadModel('models/dancer')
        self.character.setPos(3,150,-3)
        self.character.reparentTo(render)
        self.character.setHpr(180,0,0)
        self.character.setScale(0.6)
        self.character.loadAnims({'win':'models/dancer'})
        self.character.loop('win')

        self.character1=Actor()
        self.character1.loadModel('models/gorillawalking')
        self.character1.setPos(2,-13,-3)
        self.character1.setScale(0.6)
        self.character1.reparentTo(render)
        self.character1.setHpr(180,0,0)
        self.character1.loadAnims({'win':'models/gorillawalking'})
        self.character1.loop('win')
        
        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])

        taskMgr.add(self.move,"moveTask")
        taskMgr.add(self.find,"fisdTask")
        taskMgr.add(self.potask,"potaskTask")
        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,-1)
        #print self.ralph.getX(), self.ralph.getY()

        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))
        self.updateStatusLabel()
		
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
Пример #52
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

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

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

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

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))

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

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

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])

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

        # Game state variables
        self.isMoving = False

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

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        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)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Пример #53
0
    def __init__(self):
        ## Add the default values to the dictionary.
        self.keyMap = {"left":0, "right":0, "forward":0, \
                       "boost":0, "strafeL":0, "strafeR":0, \
                       "cam-left":0, "cam-right":0}

        base.win.setClearColor(Vec4(0, 0, 0, 1))
        self.jump = False
        self.jumped = False

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[D]: Rotate Camera Right")
        self.inst8 = addInstructions(0.60, "[B]: Ralph Boost")
        self.inst9 = addInstructions(0.55, "[V]: Strafe Left")
        self.inst10 = addInstructions(0.50, "[N]: Strafe Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

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

        ## Stops the sound as soon as the world renders
        ## Note:Sound won't play very long becasue the game takes seconds to compile and load
        ## Remove loading screen after world is rendered and ready to go.

        loadingText.cleanup()
        mySound.stop()

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("d", self.setKey, ["cam-right", 1])
        self.accept("b", self.setKey, ["boost", 1])
        self.accept("v", self.setKey, ["strafeL", 1])
        self.accept("n", self.setKey, ["strafeR", 1])

        ## -up to signify what happens when you let go of the key
        self.accept("b-up", self.setKey, ["boost", 0])
        self.accept("v-up", self.setKey, ["strafeL", 0])
        self.accept("n-up", self.setKey, ["strafeR", 0])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("d-up", self.setKey, ["cam-right", 0])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        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 __init__(self):
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        
        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  

        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Create the main character, Ralph
        ralphStartPos = self.environ.find("**/start_point").getPos()
        
        #self.addRalph(ralphStartPos)
       

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

       

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        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))
        
        # Add some text
        '''
Пример #55
0
    def __init__(self):
        #Let's start the Music
        mySound = base.loader.loadSfx("music/music.mp3")
        mySound.setLoopCount(0) #And Keep it On Loop
        mySound.play()
       

        base.setFrameRateMeter(True) #Shows the FrameRate in The Top Corner

        self.walking = Vec3()
        self.isMoving = False
        self.dest = None
        base.win.setClearColor(Vec4(0,0,0,1))


        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        #Here is the number of collectibles in the game
        
        self.rare = 1; 
        self.vasenum = 10;
        self.coinnum = 30;
        self.silvernum = 5;
        self.chestnum = 2;

        #Here is the Obstacles in the game
        self.rocknum = 500;

        #Here is the Score
        self.score = 0;

        #Here is the total Number of Objects to collect
        self.numObjects = self.rare + self.vasenum + self.coinnum + self.silvernum + self.chestnum
   
        # print the number of objects
        printNumObj(self.score)

        # Post the instructions
        self.title = addTitle("Mighty Mountain")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward")
        self.inst5 = addInstructions(0.75, "[S]: Run Ralph Backward")
        self.inst6 = addInstructions(0.70, "[Space]: Run, Ralph, Run")
        
        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  

        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Timer to increment in the move task
        self.time = 0
        
        # Get bounds of environment
        min, max = self.environ.getTightBounds()
        self.mapSize = max-min
        
        # Create the main character, Ralph
        self.ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(self.ralphStartPos)


        # ralph's stamina
        self.stamina = 200
        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation
        self.accept("escape", self.endgame)
        
        # these don't work well in combination with the space bar
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("arrow_down", self.setKey, ["backward",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("arrow_down-up", self.setKey, ["backward",0])
        
        self.accept("space", self.runRalph, [True])
        self.accept("space-up", self.runRalph, [False])
        
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])

        # Game state variables
        self.isMoving = False
        self.isRunning = False

        # Set up the camera
        base.disableMouse()
        #base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        base.camera.setPos(0, 0, 0)
        base.camera.reparentTo(self.ralph)
        base.camera.setPos(0, 40, 2)
        base.camera.lookAt(self.ralph)
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        base.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,300)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        base.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # camera ground collision handler
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,300)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        base.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        
        # Place the collectibles
        self.placeCollectibles() #Platinum 
        self.placeVases()
        self.placeCoins()
        self.placeSilver()
        self.placeGold()
        self.placeChests()

        #Place the obstacles
        self.placeRocks() #Cactus 
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #base.cTrav.showCollisions(render)
        
        # Create some lighting
        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))
        
        taskMgr.add(self.move,"moveTask")
Пример #56
0
    def __init__(self):
        #create Queue to hold the incoming chat
        #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0,
            "charge": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.cManager = ConnectionManager()
        self.cManager.startConnection()
        #------------------------------
        #Chat
        Chat(self.cManager)

        #send dummy login info of the particular client
        #send first chat info
        #---------------------------------------
        self.userName = username
        dummy_login = {
            'user_id': self.userName,
            'factionId': faction,
            'password': '******'
        }
        self.cManager.sendRequest(Constants.RAND_STRING, dummy_login)

        chat = {
            'userName': self.userName,  #username
            'message': '-------Login------'
        }
        self.cManager.sendRequest(Constants.CMSG_CHAT, chat)

        #--------------------------------------
        #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8))

        #frame = DirectFrame(text="Resource Bar", scale=0.001)

        resource_bar = DirectWaitBar(text="",
                                     value=35,
                                     range=100,
                                     pos=(0, 0, 0.9),
                                     barColor=(255, 255, 0, 1),
                                     frameSize=(-0.3, 0.3, 0, 0.03))
        cp_bar = DirectWaitBar(text="",
                               value=70,
                               range=100,
                               pos=(1.0, 0, 0.9),
                               barColor=(0, 0, 255, 1),
                               frameSize=(-0.3, 0.3, 0, 0.03),
                               frameColor=(255, 0, 0, 1))

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

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

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        nameplate = TextNode('textNode username_' + str(self.userName))
        nameplate.setText(self.userName)
        npNodePath = self.ralph.attachNewNode(nameplate)
        npNodePath.setScale(0.8)
        npNodePath.setBillboardPointEye()
        #npNodePath.setPos(1.0,0,6.0)
        npNodePath.setZ(6.5)

        bar = DirectWaitBar(value=100, scale=1.0)
        bar.setColor(255, 0, 0)
        #bar.setBarRelief()
        bar.setZ(6.0)
        bar.setBillboardPointEye()
        bar.reparentTo(self.ralph)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept("c", self.setKey, ["charge", 1])
        self.accept("c-up", self.setKey, ["charge", 0])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

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

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        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 __init__(self):
    # This code puts the standard title and instruction text on screen
    self.title = OnscreenText(text="Panda3D: Tutorial - Collision Detection",
                              style=1, fg=(1,1,1,1),
                              pos=(0.7,-0.95), scale = .07)
    self.instructions = OnscreenText(text="Mouse pointer tilts the board",
                                     pos = (-1.3, .95), fg=(1,1,1,1),
                                     align = TextNode.ALeft, scale = .05)
    
    self.accept("escape", sys.exit)        # Escape quits
    base.disableMouse()                    # Disable mouse-based camera control
    camera.setPosHpr(0, 0, 25, 0, -90, 0)  # Place the camera

    # Load the maze and place it in the scene
    self.maze = loader.loadModel("models/maze")
    self.maze.reparentTo(render)

    # Most times, you want collisions to be tested against invisible geometry
    # rather than every polygon. This is because testing against every polygon
    # in the scene is usually too slow. You can have simplified or approximate
    # geometry for the solids and still get good results.
    # 
    # Sometimes you'll want to create and position your own collision solids in
    # code, but it's often easier to have them built automatically. This can be
    # done by adding special tags into an egg file. Check maze.egg and ball.egg
    # and look for lines starting with <Collide>. The part is brackets tells
    # Panda exactly what to do. Polyset means to use the polygons in that group
    # as solids, while Sphere tells panda to make a collision sphere around them
    # Keep means to keep the polygons in the group as visable geometry (good
    # for the ball, not for the triggers), and descend means to make sure that
    # the settings are applied to any subgroups.
    # 
    # Once we have the collision tags in the models, we can get to them using
    # NodePath's find command

    # Find the collision node named wall_collide
    self.walls = self.maze.find("**/wall_collide")

    # Collision objects are sorted using BitMasks. BitMasks are ordinary numbers
    # with extra methods for working with them as binary bits. Every collision
    # solid has both a from mask and an into mask. Before Panda tests two
    # objects, it checks to make sure that the from and into collision masks
    # have at least one bit in common. That way things that shouldn't interact
    # won't. Normal model nodes have collision masks as well. By default they
    # are set to bit 20. If you want to collide against actual visable polygons,
    # set a from collide mask to include bit 20
    # 
    # For this example, we will make everything we want the ball to collide with
    # include bit 0
    self.walls.node().setIntoCollideMask(BitMask32.bit(0))
    # CollisionNodes are usually invisible but can be shown. Uncomment the next
    # line to see the collision walls
    # self.walls.show()

    # We will now find the triggers for the holes and set their masks to 0 as
    # well. We also set their names to make them easier to identify during
    # collisions
    self.loseTriggers = []
    for i in range(6):
      trigger = self.maze.find("**/hole_collide" + str(i))
      trigger.node().setIntoCollideMask(BitMask32.bit(0))
      trigger.node().setName("loseTrigger")
      self.loseTriggers.append(trigger)
      # Uncomment this line to see the triggers
      # trigger.show()

    # Ground_collide is a single polygon on the same plane as the ground in the
    # maze. We will use a ray to collide with it so that we will know exactly
    # what height to put the ball at every frame. Since this is not something
    # that we want the ball itself to collide with, it has a different
    # bitmask.
    self.mazeGround = self.maze.find("**/ground_collide")
    self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
    
    # Load the ball and attach it to the scene
    # It is on a root dummy node so that we can rotate the ball itself without
    # rotating the ray that will be attached to it
    self.ballRoot = render.attachNewNode("ballRoot")
    self.ball = loader.loadModel("models/ball")
    self.ball.reparentTo(self.ballRoot)

    # Find the collison sphere for the ball which was created in the egg file
    # Notice that it has a from collision mask of bit 0, and an into collison
    # mask of no bits. This means that the ball can only cause collisions, not
    # be collided into
    self.ballSphere = self.ball.find("**/ball")
    self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
    self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())

    # No we create a ray to start above the ball and cast down. This is to
    # Determine the height the ball should be at and the angle the floor is
    # tilting. We could have used the sphere around the ball itself, but it
    # would not be as reliable
    self.ballGroundRay = CollisionRay()     # Create the ray
    self.ballGroundRay.setOrigin(0,0,10)    # Set its origin
    self.ballGroundRay.setDirection(0,0,-1) # And its direction
    # Collision solids go in CollisionNode
    self.ballGroundCol = CollisionNode('groundRay') # Create and name the node
    self.ballGroundCol.addSolid(self.ballGroundRay) # Add the ray
    self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) # Set its bitmasks
    self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
    # Attach the node to the ballRoot so that the ray is relative to the ball
    # (it will always be 10 feet over the ball and point down)
    self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
    # Uncomment this line to see the ray
    # self.ballGroundColNp.show()

    # Finally, we create a CollisionTraverser. CollisionTraversers are what
    # do the job of calculating collisions
    self.cTrav = CollisionTraverser()
    # Collision traverservs tell collision handlers about collisions, and then
    # the handler decides what to do with the information. We are using a
    # CollisionHandlerQueue, which simply creates a list of all of the
    # collisions in a given pass. There are more sophisticated handlers like
    # one that sends events and another that tries to keep collided objects
    # apart, but the results are often better with a simple queue
    self.cHandler = CollisionHandlerQueue()
    # Now we add the collision nodes that can create a collision to the
    # traverser. The traverser will compare these to all others nodes in the
    # scene. There is a limit of 32 CollisionNodes per traverser
    # We add the collider, and the handler to use as a pair
    self.cTrav.addCollider(self.ballSphere, self.cHandler)
    self.cTrav.addCollider(self.ballGroundColNp, self.cHandler)

    # Collision traversers have a built in tool to help visualize collisions.
    # Uncomment the next line to see it.
    # self.cTrav.showCollisions(render)
    
    # This section deals with lighting for the ball. Only the ball was lit
    # because the maze has static lighting pregenerated by the modeler
    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))
    
    # This section deals with adding a specular highlight to the ball to make
    # it look shiny
    m = Material()
    m.setSpecular(Vec4(1,1,1,1))
    m.setShininess(96)
    self.ball.setMaterial(m, 1)

    # Finally, we call start for more initialization
    self.start()