예제 #1
0
class FreeBLiTZ(ShowBase):
    def __init__(self):
        from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser
        from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4
        ShowBase.__init__(self)

        self.sky = self.loader.loadModel('models/sky-sphere')
        self.sky.reparentTo(self.render)
        self.stage = self.loader.loadModel('models/test-collide')
        self.stage.reparentTo(self.render)
        self.floor = self.stage.findAllMatches('**/=CollideType=floor')
        self.floor.setCollideMask(FLOOR_MASK)
        self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle')
        if self.obstacles:
            self.obstacles.setCollideMask(OBSTACLE_MASK)
        self.zones = self.stage.findAllMatches('**/=CollideType=zone')
        if self.zones:
            self.zones.setCollideMask(ZONE_MASK)
        self.create_stanchions()

        # Character rig, which allows camera to follow character
        self.char_rig = self.stage.attachNewNode('char_rig')

        self.active_char = Character('mainchar', self.char_rig)

        self.cam.reparentTo(self.char_rig)
        self.cam.setPos(0.5, -3, 1.5)
        self.cam.lookAt(0.5, 0, 1.5)

        self.light = DirectionalLight('dlight')
        self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0))
        self.lightNP = self.stage.attachNewNode(self.light)
        self.lightNP.setHpr(-75, -45, 0)
        self.stage.setLight(self.lightNP)

        self.amblight = AmbientLight('amblight')
        self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0))
        self.amblightNP = self.stage.attachNewNode(self.amblight)
        self.stage.setLight(self.amblightNP)

        self.accept('w', self.active_char.begin_forward)
        self.accept('a', self.active_char.begin_left)
        self.accept('s', self.active_char.begin_backward)
        self.accept('d', self.active_char.begin_right)
        self.accept('w-up', self.active_char.end_forward)
        self.accept('a-up', self.active_char.end_left)
        self.accept('s-up', self.active_char.end_backward)
        self.accept('d-up', self.active_char.end_right)
        self.taskMgr.add(self.active_char.MoveTask, 'MoveTask')

        self.look = False
        self.prev_pos = None
        self.accept('mouse2', self.begin_look)
        self.accept('mouse2-up', self.end_look)
        self.accept('mouse3', self.active_char.begin_spin)
        self.accept('mouse3-up', self.active_char.end_spin)
        self.taskMgr.add(self.MouseTask, 'MouseTask')

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(self.active_char.actor_from_floor,
                                       self.char_rig)
        self.wall_handler = CollisionHandlerPusher()
        self.wall_handler.addCollider(self.active_char.actor_from_obstacle,
                                      self.char_rig)
        self.zone_handler = CollisionHandlerEvent()
        self.zone_handler.addInPattern('%fn-into')
        self.zone_handler.addOutPattern('%fn-out')

        def foo(entry):
            print 'You are in the zone'

        def bar(entry):
            print 'You are not in the zone'

        self.accept('blockchar_zone-into', foo)
        self.accept('blockchar_zone-out', bar)
        self.cTrav = CollisionTraverser('main traverser')
        self.cTrav.setRespectPrevTransform(True)
        self.cTrav.addCollider(self.active_char.actor_from_floor,
                               self.floor_handler)
        self.cTrav.addCollider(self.active_char.actor_from_obstacle,
                               self.wall_handler)
        self.cTrav.addCollider(self.active_char.actor_from_zone,
                               self.zone_handler)
        #self.cTrav.showCollisions(self.stage)

    def create_stanchions(self):
        from pandac.PandaModules import GeomVertexReader, CollisionNode, CollisionTube
        self.stanchions = self.stage.findAllMatches('**/=Stanchion')
        for stanchion in self.stanchions:
            geomnode = stanchion.node()
            radius = float(stanchion.getTag('Stanchion'))
            geom = geomnode.getGeom(0)
            vdata = geom.getVertexData()
            for gp in range(geom.getNumPrimitives()):
                vreader = GeomVertexReader(vdata, 'vertex')
                prim = geom.getPrimitive(gp)
                prim = prim.decompose()
                for p in range(prim.getNumPrimitives()):
                    start = prim.getPrimitiveStart(p)
                    end = prim.getPrimitiveEnd(p)
                    vertices = []
                    for v in range(start, end):
                        vi = prim.getVertex(v)
                        vreader.setRow(vi)
                        vertex = vreader.getData3f()
                        vertices.append(vertex)
                    vertices.append(vertices[0])
                    for i in range(1, len(vertices)):
                        a, b = vertices[i - 1], vertices[i]
                        stanchion_np = stanchion.attachNewNode(
                            CollisionNode('stanchion'))
                        print 'creating cyl with radius %f from %s to %s' % (
                            radius, a, b)
                        stanchion_np.node().addSolid(
                            CollisionTube(a[0], a[1], a[2], b[0], b[1], b[2],
                                          radius))
                        stanchion_np.node().setFromCollideMask(OBSTACLE_MASK)
            geomnode.removeAllGeoms()

    def begin_look(self):
        self.look = True

    def end_look(self):
        self.look = False
        self.prev_pos = None

    def MouseTask(self, task):
        if self.mouseWatcherNode.hasMouse():
            (x, y) = self.mouseWatcherNode.getMouse()
            if self.prev_pos:
                if self.look or self.active_char.spinning:
                    h_diff = (x - self.prev_pos[0]) * 180
                    p_diff = (y - self.prev_pos[1]) * 90
                    new_h = clamp_deg_sign(self.char_rig.getH() - h_diff)
                    self.char_rig.setH(new_h)
                    self.cam.setP(self.cam.getP() + p_diff)
                    self.active_char.spin(new_h)
            self.prev_pos = (x, y)
        return task.cont
from pandac.PandaModules import Vec3

import math
from math import sqrt

wallRayNP = render.attachNewNode(CollisionNode("wall ray collision node"))
wallRayNP.node().addSolid(CollisionRay(0,0,0,0,1,0))
wallRayNP.node().setIntoCollideMask(BitMask32.allOff())
wallRayNP.node().setFromCollideMask(BitMask32.allOn() & ~GeomNode.getDefaultCollideMask())
wallRayNP.node().setFromCollideMask(wallRayNP.node().getFromCollideMask() & ~BitMask32.bit(1))
#wallRayNP.show()

collisionHandler = CollisionHandlerQueue()
collisionTraverser = CollisionTraverser("pathfinder's collisionTraverser")
collisionTraverser.addCollider(wallRayNP, collisionHandler)
collisionTraverser.setRespectPrevTransform(True)

class PathFinder():
    
##    def __init__(self, position, ID = -1):
##        NodePath.__init__(self, "Waypoint")
##        self.position = position
##        self.texture = loader.loadTexture("textures/blue.jpg")
##        self.costToThisNode = 0
##        self.visited = False
##        self.neighbors = []
##        self.ID = ID
##        self.previousWaypoint = None

    @classmethod
    def AStar(self, source, target, waypoints):
예제 #3
0
파일: main.py 프로젝트: gomtuu/FreeBLiTZ
class FreeBLiTZ(ShowBase):

    def __init__(self):
        from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser
        from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4
        ShowBase.__init__(self)

        self.sky = self.loader.loadModel('models/sky-sphere')
        self.sky.reparentTo(self.render)
        self.stage = self.loader.loadModel('models/test-collide')
        self.stage.reparentTo(self.render)
        self.floor = self.stage.findAllMatches('**/=CollideType=floor')
        self.floor.setCollideMask(FLOOR_MASK)
        self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle')
        if self.obstacles:
            self.obstacles.setCollideMask(OBSTACLE_MASK)
        self.zones = self.stage.findAllMatches('**/=CollideType=zone')
        if self.zones:
            self.zones.setCollideMask(ZONE_MASK)
        self.create_stanchions()

        # Character rig, which allows camera to follow character
        self.char_rig = self.stage.attachNewNode('char_rig')

        self.active_char = Character('mainchar', self.char_rig)

        self.cam.reparentTo(self.char_rig)
        self.cam.setPos(0.5, -3, 1.5)
        self.cam.lookAt(0.5, 0, 1.5)

        self.light = DirectionalLight('dlight')
        self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0))
        self.lightNP = self.stage.attachNewNode(self.light)
        self.lightNP.setHpr(-75, -45, 0)
        self.stage.setLight(self.lightNP)

        self.amblight = AmbientLight('amblight')
        self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0))
        self.amblightNP = self.stage.attachNewNode(self.amblight)
        self.stage.setLight(self.amblightNP)

        self.accept('w', self.active_char.begin_forward)
        self.accept('a', self.active_char.begin_left)
        self.accept('s', self.active_char.begin_backward)
        self.accept('d', self.active_char.begin_right)
        self.accept('w-up', self.active_char.end_forward)
        self.accept('a-up', self.active_char.end_left)
        self.accept('s-up', self.active_char.end_backward)
        self.accept('d-up', self.active_char.end_right)
        self.taskMgr.add(self.active_char.MoveTask, 'MoveTask')

        self.look = False
        self.prev_pos = None
        self.accept('mouse2', self.begin_look)
        self.accept('mouse2-up', self.end_look)
        self.accept('mouse3', self.active_char.begin_spin)
        self.accept('mouse3-up', self.active_char.end_spin)
        self.taskMgr.add(self.MouseTask, 'MouseTask')

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(self.active_char.actor_from_floor, self.char_rig)
        self.wall_handler = CollisionHandlerPusher()
        self.wall_handler.addCollider(self.active_char.actor_from_obstacle, self.char_rig)
        self.zone_handler = CollisionHandlerEvent()
        self.zone_handler.addInPattern('%fn-into')
        self.zone_handler.addOutPattern('%fn-out')
        def foo(entry):
            print 'You are in the zone'
        def bar(entry):
            print 'You are not in the zone'
        self.accept('blockchar_zone-into', foo)
        self.accept('blockchar_zone-out', bar)
        self.cTrav = CollisionTraverser('main traverser')
        self.cTrav.setRespectPrevTransform(True)
        self.cTrav.addCollider(self.active_char.actor_from_floor, self.floor_handler)
        self.cTrav.addCollider(self.active_char.actor_from_obstacle, self.wall_handler)
        self.cTrav.addCollider(self.active_char.actor_from_zone, self.zone_handler)
        #self.cTrav.showCollisions(self.stage)

    def create_stanchions(self):
        from pandac.PandaModules import GeomVertexReader, CollisionNode, CollisionTube
        self.stanchions = self.stage.findAllMatches('**/=Stanchion')
        for stanchion in self.stanchions:
            geomnode = stanchion.node()
            radius = float(stanchion.getTag('Stanchion'))
            geom = geomnode.getGeom(0)
            vdata = geom.getVertexData()
            for gp in range(geom.getNumPrimitives()):
                vreader = GeomVertexReader(vdata, 'vertex')
                prim = geom.getPrimitive(gp)
                prim = prim.decompose()
                for p in range(prim.getNumPrimitives()):
                    start = prim.getPrimitiveStart(p)
                    end = prim.getPrimitiveEnd(p)
                    vertices = []
                    for v in range(start, end):
                        vi = prim.getVertex(v)
                        vreader.setRow(vi)
                        vertex = vreader.getData3f()
                        vertices.append(vertex)
                    vertices.append(vertices[0])
                    for i in range(1, len(vertices)):
                        a, b =  vertices[i-1], vertices[i]
                        stanchion_np = stanchion.attachNewNode(CollisionNode('stanchion'))
                        print 'creating cyl with radius %f from %s to %s' % (radius, a, b)
                        stanchion_np.node().addSolid(CollisionTube(a[0], a[1], a[2], b[0], b[1], b[2], radius))
                        stanchion_np.node().setFromCollideMask(OBSTACLE_MASK)
            geomnode.removeAllGeoms()

    def begin_look(self):
        self.look = True

    def end_look(self):
        self.look = False
        self.prev_pos = None

    def MouseTask(self, task):
        if self.mouseWatcherNode.hasMouse():
            (x, y) = self.mouseWatcherNode.getMouse()
            if self.prev_pos:
                if self.look or self.active_char.spinning:
                    h_diff = (x - self.prev_pos[0]) * 180
                    p_diff = (y - self.prev_pos[1]) * 90
                    new_h = clamp_deg_sign(self.char_rig.getH() - h_diff)
                    self.char_rig.setH(new_h)
                    self.cam.setP(self.cam.getP() + p_diff)
                    self.active_char.spin(new_h)
            self.prev_pos = (x, y)
        return task.cont
예제 #4
0
파일: game.py 프로젝트: elbixos/panda3D
class ArcadeFlightGame(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.debug = False
        self.maxdistance = 400
        self.statusLabel = self.makeStatusLabel(0)
        self.collisionLabel = self.makeStatusLabel(1)

        self.player = AlliedFlanker(self.loader, self.render, self.taskMgr)
        self.world = GameWorld(1024, self.loader, self.render, self.camera)

        self.taskMgr.add(self.updateTask, "update")
        self.keyboardSetup()

        # performance and map to player so can't fly beyond visible terrain
        self.player.setMaxHeight(self.maxdistance)

        if self.debug == False:
            self.camLens.setFar(self.maxdistance)
        else:
            base.oobe()

        self.camLens.setFov(60)
        self.setupCollisions()
        self.textCounter = 0

    def makeStatusLabel(self, i):
        """ Create a status label at the top-left of the screen,
        Parameter 'i' is the row number """
        return OnscreenText(style=2, fg=(.5,1,.5,1), pos=(-1.3,0.92-(.08 * i)), \
                               align=TextNode.ALeft, scale = .08, mayChange = 1)

    def keyboardSetup(self):
        self.keyMap = {"left":0, "right":0, "climb":0, "fall":0, \
                        "accelerate":0, "decelerate":0, "fire":0}
        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["accelerate", 1])
        self.accept("a-up", self.setKey, ["accelerate", 0])
        self.accept("z", self.setKey, ["decelerate", 1])
        self.accept("z-up", self.setKey, ["decelerate", 0])
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_down", self.setKey, ["climb", 1])
        self.accept("arrow_down-up", self.setKey, ["climb", 0])
        self.accept("arrow_up", self.setKey, ["fall", 1])
        self.accept("arrow_up-up", self.setKey, ["fall", 0])
        self.accept("space", self.setKey, ["fire", 1])
        self.accept("space-up", self.setKey, ["fire", 0])
        base.disableMouse()  # or updateCamera will fail!

    def setKey(self, key, value):
        """ Used by keyboard setup """
        self.keyMap[key] = value

    def setupCollisions(self):
        self.collTrav = CollisionTraverser()

        # rapid collisions detected using below plus FLUID pos
        self.collTrav.setRespectPrevTransform(True)

        self.playerGroundSphere = CollisionSphere(0, 1.5, -1.5, 1.5)
        self.playerGroundCol = CollisionNode('playerSphere')
        self.playerGroundCol.addSolid(self.playerGroundSphere)

        # bitmasks
        self.playerGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.playerGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.world.setGroundMask(BitMask32.bit(0))
        self.world.setWaterMask(BitMask32.bit(0))

        # and done
        self.playerGroundColNp = self.player.attach(self.playerGroundCol)
        self.playerGroundHandler = CollisionHandlerQueue()
        self.collTrav.addCollider(self.playerGroundColNp,
                                  self.playerGroundHandler)

        # DEBUG as per video:
        if (self.debug == True):
            self.playerGroundColNp.show()
            self.collTrav.showCollisions(self.render)

    def updateTask(self, task):
        """ Gets added to the task manager, updates the player, deals with inputs,
        collisions, game logic etc. """
        self.player.calculate()
        self.actionInput()
        validMove = self.player.move(self.world.getSize())

        # lets not be doing this every frame...
        if validMove == False and self.textCounter > 30:
            self.statusLabel.setText("STATUS: MAP END; TURN AROUND")
        elif self.textCounter > 30:
            self.statusLabel.setText("STATUS: OK")
        if self.textCounter > 30:
            self.textCounter = 0
        else:
            self.textCounter = self.textCounter + 1
        self.updateCamera()

        self.collTrav.traverse(self.render)
        for i in range(self.playerGroundHandler.getNumEntries()):
            entry = self.playerGroundHandler.getEntry(i)
            if (self.debug == True):
                self.collisionLabel.setText("DEAD:" +
                                            str(globalClock.getFrameTime()))
            self.player.die()
        return Task.cont

    def actionInput(self):
        """ Used by updateTask to process keyboard input """
        if (self.keyMap["climb"] != 0):
            self.player.climb()
        elif (self.keyMap["fall"] != 0):
            self.player.dive()
        else:
            self.player.unwindVertical()

        if (self.keyMap["left"] != 0):
            self.player.bankLeft()
        elif (self.keyMap["right"] != 0):
            self.player.bankRight()
        else:
            self.player.unwindHorizontal()

        if (self.keyMap["accelerate"] != 0):
            self.player.accelerate()
        elif (self.keyMap["decelerate"] != 0):
            self.player.brake()

    def updateCamera(self):
        self.player.lookAtMe(self.camera)