Ejemplo n.º 1
0
    def __init__(self):
        self.line_dir = NodePath()

        base.cTrav = CollisionTraverser()
        self.col_handler = CollisionHandlerEvent()

        picker_node = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(picker_node)
        self.pickerRay = CollisionRay()
        picker_node.addSolid(self.pickerRay)

        plane_node = CollisionNode("base_plane")
        plane = base.render.attachNewNode(plane_node)
        self.plane_col = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        picker_node.addSolid(self.pickerRay)

        picker_node.setTag("rays", "mray")
        base.cTrav.addCollider(pickerNPos, self.col_handler)

        self.col_handler.addInPattern("%(rays)ft-into-%(type)it")
        self.col_handler.addOutPattern("%(rays)ft-out-%(type)it")
        self.col_handler.addAgainPattern("ray_again_all%("
                                         "rays"
                                         ")fh%("
                                         "type"
                                         ")ih")

        self.model = loader.loadModel("../models/chest.egg")
        self.model_node = NodePath("sdfafd")
        self.model.reparentTo(self.model_node)
        self.model_node.reparentTo(render)
        #
        #        self.text_node = TextNode("battle_text")
        #        self.text_node.setText("TEXTYTEXTYTEXTTEXT")
        #        self.text_node_path = render.attachNewNode(self.text_node)
        #        self.text_node_path.reparentTo(render)
        #        self.text_node_path.setPos(0,0,4)
        #        self.text_node_path.setHpr(0,0,0)
        #        self.text_node_path.setScale(1)
        #        #self.text_node_path.setTransparency(TransparencyAttrib.MAlpha)
        #        self.text_node.setTextColor((1,1,1,1))
        #        self.text_node.setAlign(TextNode.ALeft)

        self.placement_ghost = EditorObjects.PlacementGhost(
            0, "tower", base.object_scale)

        z = 0
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))

        taskMgr.add(self.ray_update, "updatePicker")
        taskMgr.add(self.get_mouse_plane_pos, "MousePositionOnPlane")
        taskMgr.add(self.task_mouse_press_check, "checkMousePress")

        self.input_init()

        self.pickable = None
Ejemplo n.º 2
0
    def __init__(self, node):

        Physical.__init__(self)

        self.node = node
        self.thrust = 0.0
        self.loadSpecs()

        # precalculated values for combinations of variables
        self.setCalculationConstants()

        # dynamic variables
        self.acceleration = Vec3(0.0, 0.0, 0.0)
        self.angle_of_attack = 0.0

        # state variables
        self.rudder = 0.0
        self.ailerons = 0.0
        self.elevator = 0.0

        self.ode_body = OdeBody(self.world)
        # positions and orientation are set relative to render
        self.ode_body.setPosition(self.node.getPos(render))
        self.ode_body.setQuaternion(self.node.getQuat(render))

        self.ode_mass = OdeMass()
        self.ode_mass.setBox(self.mass, 1, 1, 1)
        self.ode_body.setMass(self.ode_mass)

        self.accumulator = 0.0
        self.step_size = 0.02
        taskMgr.add(self.simulationTask,
                    "plane physics",
                    sort=-1,
                    taskChain="world")
Ejemplo n.º 3
0
 def __init__(self, showBase, camDict):
   self.showBase = showBase
   self.showBase.disableMouse()
   self.setSettings(camDict)
   self.initMouseToWorldCoordConversion()
   self.initMouseRayCollision()
   self.savedCollisionPoint = Vec3(0, 0, 0)
Ejemplo n.º 4
0
    def _forwardAndVelocityVectorForces(self, up, right, norm_v, speed):
        """ calculates torque and force resulting from deviation of the
        velocity vector from the forward vector """

        # could do with a better name for this method

        # get the projection of the normalised velocity onto the up and
        # right vectors to find relative pitch and heading angles
        p_angle = acos(up.dot(norm_v)) - pi / 2
        h_angle = acos(right.dot(norm_v)) - pi / 2

        torque_p = p_angle * self.pitch_torque_coefficient * speed
        torque_h = h_angle * self.heading_torque_coefficient * speed
        force_p = p_angle * self.pitch_force_coefficient * speed
        force_h = h_angle * self.heading_force_coefficient * speed

        return Vec3(-torque_p, 0.0, torque_h), Vec3(-force_p, 0.0, force_h)
Ejemplo n.º 5
0
 def _controlRotForce(self, control, axis, coeff, speed, rspeed,
                      max_rspeed):
     """ generic control rotation force
     control - positive or negative amount of elevator/rudder/ailerons
     axis - vector about which the torque is applied
     coeff - the conversion of the amount of the control to a rotational force
     speed - the speed of the plane
     rspeed - the current rotational speed about the axis
     max_rspeed - a cut-off for the rotational speed
     """
     if control * rspeed < max_rspeed:
         return axis * control * coeff * speed
     else:
         return Vec3(0.0, 0.0, 0.0)
Ejemplo n.º 6
0
    def addNodeDrawing(self,
                       nodeData,
                       nodeSettings,
                       loader,
                       mapNode,
                       pos=Vec3()):
        id = nodeData.get('id')
        text = nodeData.get('name')

        nodeDrawing = NodeDrawing(text, loader, mapNode, id)
        nodeDrawing.mainNode.setPos(pos)

        nodeDrawing.setSelected(nodeSettings)

        self.allDrawingData[id] = nodeDrawing
        self.setNodeDrawingHeight(nodeData, nodeDrawing)
Ejemplo n.º 7
0
    def setCalculationConstants(self):
        """pre-calculate some calculation constants from the
        flight parameters"""
        # density of air: rho = 1.2041 kg m-3
        half_rho = 0.602
        self.lift_factor = half_rho * self.wing_area

        # could modify lift_induced_drag by a factor of 1.05 to 1.15
        self.lift_induced_drag_factor = (-1.0) * self.lift_factor / \
                                        (pi*self.aspect_ratio)
        self.drag_factor_x = (-1.0) * half_rho * self.drag_area_x * \
                                                 self.drag_coef_x
        self.drag_factor_y = (-1.0) * half_rho * self.drag_area_y * \
                                                 self.drag_coef_y
        self.drag_factor_z = (-1.0) * half_rho * self.drag_area_z * \
                                                 self.drag_coef_z

        self.gravity = Vec3(0.0, 0.0, -9.81)
        self.gravityM = self.gravity * self.mass
Ejemplo n.º 8
0
    def simulationTask(self, task):
        """Update position and velocity based on aerodynamic forces."""
        delta_time = global_clock.getDt()
        self.accumulator += delta_time
        updated = False
        #print self.accumulator, delta_time
        while self.accumulator > self.step_size:
            self.accumulator -= self.step_size
            updated = True

            position = self.position()
            velocity = self.velocity()
            speed = velocity.length()
            norm_v = velocity + Vec3(0.0, 0.0, 0.0)
            norm_v.normalize()

            yawv, pitchv, rollv = self.angVelBodyHpr()

            quat = self.quat()
            forward = quat.getForward()
            up = quat.getUp()
            right = quat.getRight()

            linear_force = self._force(position, velocity, right, up, forward)

            self.ode_body.addForce(linear_force)

            # Control forces:
            elevator_af = self._controlRotForce(self.elevator,
                                                Vec3(1.0, 0.0, 0.0),
                                                self.elevator_coefficient,
                                                speed, pitchv,
                                                self.terminal_pitch)
            ailerons_af = self._controlRotForce(self.ailerons,
                                                Vec3(0.0, 1.0, 0.0),
                                                self.ailerons_coefficient,
                                                speed, rollv,
                                                self.terminal_roll)
            rudder_af = self._controlRotForce(self.rudder, Vec3(0.0, 0.0, 1.0),
                                              self.rudder_coefficient, speed,
                                              yawv, self.terminal_yaw)

            # Damping forces
            pitch_damping_avf = self._rotDamping(Vec3(1.0, 0.0, 0.0), pitchv,
                                                 self.pitch_damping)
            roll_damping_avf = self._rotDamping(Vec3(0.0, 1.0, 0.0), rollv,
                                                self.roll_damping)
            yaw_damping_avf = self._rotDamping(Vec3(0.0, 0.0, 1.0), yawv,
                                               self.yaw_damping)

            self.ode_body.addRelTorque(elevator_af + ailerons_af + rudder_af +
                                       roll_damping_avf + pitch_damping_avf +
                                       yaw_damping_avf)

            # Forces to rotate the forward vector towards the velocity vector
            # and vice versa
            fvv_torque, fvv_force = self._forwardAndVelocityVectorForces(
                up, right, norm_v, speed)
            self.ode_body.addRelTorque(fvv_torque)
            self.ode_body.addForce(fvv_force)

            if position.getZ() < 0:
                position.setZ(0)
                velocity.setZ(0)
                self.setPosition(position)
                self.setVelocity(velocity)
            self.rudder = 0.0
            self.elevator = 0.0
            self.ailerons = 0.0
            self.world.quickStep(self.step_size)
        if updated:
            self.node.setPosQuat(render, self.position(), quat)
        return task.cont
Ejemplo n.º 9
0
 def velocity(self):
     """ return the current velocity """
     #return self.physics_object.getVelocity()
     return Vec3(self.ode_body.getLinearVel())
Ejemplo n.º 10
0
 def initMouseRayCollision(self):
   z = 0
   self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))
Ejemplo n.º 11
0
 def setViewBasedOnNodePos(self, pos):
   camera = self.showBase.camera
   newPos = Vec3(camera.getPos())
   newPos.x = pos.x
   newPos.y = pos.y
   camera.setPos(newPos)
Ejemplo n.º 12
0
 def getDelta(self, point1, point2):
   delta = Vec3()
   if point1 is not None:
     if point1.almostEqual(point2) is False:
       delta = point2 - point1
   return delta
Ejemplo n.º 13
0
class Utils():
    LAST_ASSIGNED_ID = 0

    STARTJSON = None

    # Node
    NODE_SCALE = LVecBase3f(7, 9, 1)

    VERT_DEPTH_DIST = 20
    VERT_BREADTH_DIST = 30
    HORT_DEPTH_DIST = 25
    HORT_BREADTH_DIST = 10
    VERTICAL_DEPTH = False

    CURRENT_NODE_DATA_LIST = None

    TEXT_INPUT = None

    @staticmethod
    def convertToNodes(
            jsonData):  # Needed to be able to assign parentId(Proof?)
        # Utils.test(jsonData)
        nodeList = {}

        allNodeJsons = [copy.deepcopy(jsonData)]

        depth = 0
        while len(allNodeJsons) > 0:
            nodeJsonsInCurrentDepth = allNodeJsons
            allNodeJsons = []

            while len(nodeJsonsInCurrentDepth) > 0:
                currentJson = nodeJsonsInCurrentDepth[0]
                nodeJsonsInCurrentDepth.remove(currentJson)

                id = Utils.getIdOrAssignUnique(currentJson)
                node = Utils.getNode(currentJson, depth)
                nodeList[id] = node

                Utils.placeToParentsChildrenList(node, nodeList)

                nodeChildren = node.get('children')
                if nodeChildren is not None:
                    allNodeJsons.extend(nodeChildren)
                    for child in nodeChildren:
                        child['parentId'] = id

            depth += 1
        return nodeList

    @staticmethod
    def placeToParentsChildrenList(node, nodeList):
        parentId = node.get("parentId")
        if parentId is not None:
            nodeJsonSiblings = nodeList[parentId].get("children")
            for index, sibling in enumerate(nodeJsonSiblings):
                if sibling.get("x") is None:
                    nodeJsonSiblings.remove(sibling)
                    nodeJsonSiblings.insert(index, node)
                    nodeList[parentId]["children"] = nodeJsonSiblings
                    break

    @staticmethod
    def getNode(nodeJson, y):
        name = nodeJson.get('name')
        nodeId = nodeJson.get('id')
        parentId = nodeJson.get('parentId')
        children = nodeJson.get('children')
        node = {
            "name": name,
            "id": nodeId,
            "parentId": parentId,
            "children": children,
            "x": -1.0,
            "y": y,
            "mod": 0
        }
        return node

    @staticmethod
    def showNodes(nodeList):
        for key in nodeList:
            node = nodeList[key]
            print(
                node.get('name') + " id " + str(node.get('id')) +
                " parentId " + str(node.get('parentId')) + " x " +
                str(node.get("x")) + " y " + str(node.get("y")))

    @staticmethod
    def getIdOrAssignUnique(nodeJson):
        id = nodeJson.get('id')
        if id is None:
            Utils.LAST_ASSIGNED_ID += 1
            id = Utils.LAST_ASSIGNED_ID
            nodeJson['id'] = id
        return id

    @staticmethod
    def getUniqueId(nodeDataList, recheckLastId=False):
        Utils.LAST_ASSIGNED_ID = Utils.getLastAssignedId(
            nodeDataList, recheckLastId)
        Utils.LAST_ASSIGNED_ID += 1
        return Utils.LAST_ASSIGNED_ID

    @staticmethod
    def getLastAssignedId(nodeDataList, recheckLastId):
        highestIdAssigned = Utils.LAST_ASSIGNED_ID
        if Utils.CURRENT_NODE_DATA_LIST != nodeDataList or recheckLastId:
            Utils.CURRENT_NODE_DATA_LIST = nodeDataList
            for key in nodeDataList:
                if key >= highestIdAssigned:
                    highestIdAssigned = key

        return highestIdAssigned

    @staticmethod
    def showNode(node):
        print("name " + str(node.get("name")) + " x " + str(node.get("x")) +
              " y " + str(node.get("y")))

    @staticmethod
    def showDict(argDict):
        for key in argDict:
            print(str(key) + " " + str(argDict[key]))

    @staticmethod
    def dictLen(argDict):
        if argDict is None:
            return 0
        return len(argDict)

    @staticmethod
    def getJson(name):  # Deprecated
        jsonPath = path.abspath(path.join(__file__, "../../../assets/" + name))
        return json.load(open(jsonPath))

    @staticmethod
    def getAssetPath(fileName):
        return path.abspath(path.join(__file__, "../../../assets/" + fileName))

    @staticmethod
    def getChildren(node, nodeList):
        childrenIds = node.get("childrenIds")
        if childrenIds is None:
            return None

        children = []
        for id in childrenIds:
            children.append(nodeList[id])
        return children

    @staticmethod
    def getChildrenDict(node, nodeList):
        childrenIds = node.get("childrenIds")
        if childrenIds is None:
            return None

        children = {}
        for id in childrenIds:
            children[id] = nodeList[id]
        return children

    @staticmethod
    def createTextInput(pos, onEnterTextCb):
        Utils.TEXT_INPUT = TextInput(pos, onEnterTextCb)

    @staticmethod
    def closeTextInput():
        if Utils.TEXT_INPUT is not None:
            Utils.TEXT_INPUT.entry.destroy()
            Utils.TEXT_INPUT = None

    @staticmethod
    def getNodePosition(depth, breadth):
        if Utils.VERTICAL_DEPTH:
            x = breadth * Utils.VERT_BREADTH_DIST
            y = float(depth) * Utils.VERT_DEPTH_DIST
        else:
            y = breadth * Utils.HORT_BREADTH_DIST
            x = float(depth) * Utils.HORT_DEPTH_DIST
        z = 0  # Should be addressed later on

        return LVecBase3f(x, y, z)

    @staticmethod
    def getNodeDataPointt(nodeData):
        depth = nodeData.get("depth")
        breadth = nodeData.get("x")
        return Utils.getNodePosition(depth, breadth)

    # Have to find another way to organize functions
    @staticmethod
    def removeSelectedField(nodeId, nodeDataSettings):
        nodeSettings = nodeDataSettings.get(nodeId)
        if nodeSettings is not None:
            nodeDataSettings.pop(nodeId, None)
        return nodeDataSettings

    # Mouse helpers
    PLANE = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
    CT = CollisionTraverser()
    CHQ = CollisionHandlerQueue()
    CN = CollisionNode('mouseRay')

    NEW_CN = None
    CR = CollisionRay()

    @staticmethod
    def getMousePosition(showBase):
        Utils.initMouseFields(showBase)
        return Utils.getMouseCollisionToPlane(showBase, Utils.PLANE)

    @staticmethod
    def initMouseFields(showBase):
        if Utils.NEW_CN is None:
            Utils.NEW_CN = showBase.camera.attachNewNode(Utils.CN)
            Utils.CN.setFromCollideMask(BitMask32.bit(1))

            Utils.CN.addSolid(Utils.CR)
            Utils.CT.addCollider(Utils.NEW_CN, Utils.CHQ)

    @staticmethod
    def getMouseCollisionToPlane(showBase, plane):
        mouseWatcherNode = showBase.mouseWatcherNode
        if mouseWatcherNode.hasMouse():
            mpos = mouseWatcherNode.getMouse()

            pos3d = LPoint3()
            nearPoint = LPoint3()
            farPoint = LPoint3()
            showBase.camLens.extrude(mpos, nearPoint, farPoint)

            render = showBase.render
            camera = showBase.camera
            if plane.intersectsLine(pos3d,
                                    render.getRelativePoint(camera, nearPoint),
                                    render.getRelativePoint(camera, farPoint)):
                return pos3d
        return None

    @staticmethod
    def getDistSqr2D(point3d1, point3d2):
        dx = point3d2.x - point3d1.x
        dy = point3d2.y - point3d1.y
        return (dx * dx) + (dy * dy)

    @staticmethod
    def isInRange(sqrDist, rangeDist):
        if sqrDist < (rangeDist * rangeDist):
            return True
        return False

    @staticmethod
    def collidesRect(p1, p2, width, height):
        r1 = Rect(p1.x, p1.y, width, height)
        r2 = Rect(p2.x, p2.y, width, height)

        result = r1.collidesWith(r2)
        # print(str(result))
        return result
Ejemplo n.º 14
0
    def __init__(self):
        base.cTrav = CollisionTraverser()
        self.col_handler = CollisionHandlerEvent()

        self.selected = -1
        self.selected_node = None
        self.selecteds = []
        self.multi_select = False
        self.multi_selecting = False
        self.select_box = NodePath()

        picker_node = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(picker_node)
        self.pickerRay = CollisionRay()
        picker_node.addSolid(self.pickerRay)

        plane_node = CollisionNode("base_plane")
        plane = base.render.attachNewNode(plane_node)
        self.plane_col = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        picker_node.addSolid(self.pickerRay)

        picker_node.setTag("rays", "mray")
        base.cTrav.addCollider(pickerNPos, self.col_handler)

        self.col_handler.addInPattern("%(rays)ft-into-%(type)it")
        self.col_handler.addOutPattern("%(rays)ft-out-%(type)it")

        self.col_handler.addAgainPattern("ray_again_all%("
                                         "rays"
                                         ")fh%("
                                         "type"
                                         ")ih")

        self.DO = DirectObject()

        self.DO.accept('mray-into-army', self.col_in_object)
        self.DO.accept('mray-out-army', self.col_out_object)
        self.DO.accept('mray-into-battle', self.col_in_object)
        self.DO.accept('mray-out-battle', self.col_out_object)
        self.DO.accept('mray-into-tower', self.col_in_object)
        self.DO.accept('mray-out-tower', self.col_out_object)

        self.DO.accept('ray_again_all', self.col_against_object)

        if base.client == False:
            self.col_handler.addInPattern("%(player)ft-into-%(player)it")
            self.col_handler.addInPattern("%(type)ft-into-%(type)it")
            self.DO.accept('army-into-battle', self.col_army_against_battle)
            self.DO.accept('army-into-tower', self.col_army_against_tower)
            self.DO.accept('1-into-2', self.col_p1_into_p2)

        self.pickable = None

        self.DO.accept('mouse1', self.mouse_click, ["down"])
        self.DO.accept('mouse1-up', self.mouse_click, ["up"])
        self.DO.accept('mouse3-up', self.mouse_order)

        taskMgr.add(self.ray_update, "updatePicker")
        taskMgr.add(self.task_select_check, "updatePicker")
        taskMgr.add(self.get_mouse_plane_pos, "MousePositionOnPlane")

        z = 0
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))

        self.model = loader.loadModel("models/chest.egg")
        self.model.reparentTo(render)
        self.model.hide()
        cm = CardMaker("blah")
        cm.setFrame(-100, 100, -100, 100)
        pnode = render.attachNewNode(cm.generate())  #.lookAt(0, 0, -1)
        pnode.hide()
Ejemplo n.º 15
0
    def __init__(self, framework, *args, **kwargs):
        self.bullets = []
        self.environment = {}
        self.colliders = {}
        self.task_manager = []
        self.bullet_colliders = []
        self.remove_bullet_indices = []

        super().__init__(*args, **kwargs)
        self.f = framework
        self.controller = Controller(self.f.accept, self)
        self.f.set_background_color(0.2, 0.2, 0.2, 0.6)

        if settings.ALLOW_FILTERS:
            self.filter = CommonFilters(self.f.win, self.f.cam)
            self.filter.set_bloom(mintrigger=0.99, size="small")
            # self.filter.set_blur_sharpen(amount=0.99)

        self.base_node = NodePath("base")
        self.base_node.reparent_to(self.f.render)

        # floor
        self.plane = self.create_model(settings.egg / "plane",
                                       self.base_node,
                                       "ground-zero",
                                       color=(1, 1, 1, 1))
        self.create_model(settings.egg / "house_01",
                          self.base_node,
                          "house-01",
                          position=(20, 50, 0),
                          scale=1.5)
        self.create_model(settings.egg / "house_02",
                          self.base_node,
                          "house-02",
                          position=(-50, 10, 0),
                          scale=1.5)

        self.sun_light_model = self.create_model("models/misc/sphere",
                                                 self.base_node,
                                                 "sun",
                                                 position=(0, -150, 250),
                                                 scale=5.0,
                                                 color=(1, 1, 1, 1),
                                                 _store=False)

        tank = self.create_model(settings.egg / "tank",
                                 self.base_node,
                                 "player",
                                 scale=3.0,
                                 position=(0.0, 0.0, 1e-3))
        gun = self.create_model("models/misc/sphere",
                                tank,
                                "player-gun",
                                position=(0.0, 4.5, 1.755),
                                scale=0.1,
                                _store=False)
        self.tank = Tank(tank, gun, framework=self.f)
        self._tank = self.tank.tank

        enemy = self.create_model(settings.egg / "enemy",
                                  self.base_node,
                                  "enemy",
                                  scale=0.8,
                                  position=(-80.0, 80.0, 1e-3))
        self.enemy = EnemyTank(enemy, None, framework=self.f)

        # point light for shadows
        sun_light = PointLight("sun-light")
        sun_light.set_color((0.4, 0.4, 0.4, 1))
        self.sun_light_node = self.base_node.attach_new_node(sun_light)
        self.sun_light_node.reparent_to(self.sun_light_model)
        self.redistribute_light(self.sun_light_node)
        self.plane.set_light(self.sun_light_node)

        # daylight
        if settings.ALLOW_DAYLIGHT:
            day_light = DirectionalLight("day-light")
            day_light.set_color((1, 1, 1, 1))
            self.daylight_node = self.f.render.attach_new_node(day_light)
            self.daylight_node.set_p(-20)
            self.daylight_node.set_h(10)
            self.daylight_node.reparent_to(self.sun_light_model)
            self.redistribute_light(self.daylight_node)

        # shadows
        if settings.ALLOW_SHADOWS:
            sun_light.set_shadow_caster(True, 2048, 2048)
            self.f.render.set_shader_auto()

        # 3rd person camera lock
        if settings.TRD_PERSON_CAM:
            self.f.camera.reparent_to(self.tank.tank)
            self.f.cam.set_pos(0, -25, 10)
            self.f.cam.lookAt(self.tank.tank)
            self.f.cam.setP(self.f.camera.getP() - 20)

        if settings.ALLOW_AMBIENT:
            amblight = AmbientLight("ambient-light")
            amblight.set_color((0.2, 0.2, 0.2, 1))
            self.amblight_node = self.f.render.attach_new_node(amblight)
            self.redistribute_light(self.amblight_node)

        # colliders
        tank_collider = self.environment["player"].attachNewNode(
            CollisionNode('player-collider'))
        tank_collider.node().addSolid(
            CollisionBox(Point3(-1.5, -3, 0), Point3(1.5, 3, 2.25)))
        self.colliders['player-collider'] = tank_collider

        enemy_collider = self.environment["enemy"].attachNewNode(
            CollisionNode('enemy-collider'))
        enemy_collider.node().addSolid(
            CollisionBox(Point3(-6.5, -13.5, 0), Point3(6.5, 13, 10)))
        self.colliders['enemy-collider'] = enemy_collider

        house_01_collider = self.environment["house-01"].attachNewNode(
            CollisionNode('house-01-collider'))
        house_01_collider.node().addSolid(
            CollisionBox(Point3(0, 2, 0), Point3(14.5, 16, 17)))
        self.colliders['house-01'] = house_01_collider

        house_02_collider = self.environment["house-02"].attachNewNode(
            CollisionNode('house-02-collider'))
        house_02_collider.node().addSolid(
            CollisionBox(Point3(0, 0, 0), Point3(21, 27, 37)))
        self.colliders['house-02'] = house_02_collider

        floor_collider = self.environment["ground-zero"].attachNewNode(
            CollisionNode('ground-zero-collider'))
        floor_collider.node().addSolid(
            CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))))
        self.colliders['ground-zero-collider'] = floor_collider

        self.f.pusher.addCollider(tank_collider, self.environment["player"])
        self.f.cTrav.addCollider(tank_collider, self.f.pusher)

        # show.hide all colliders
        if settings.SHOW_COLLIDERS:
            for key, value in self.colliders.items():
                logger.info(f"collider for {key} is visible")
                value.show()
                self.f.cTrav.showCollisions(self.f.render)

        # uppdate
        self.f.cHandler.addInPattern('%fn')
        self.f.accept('bullet-collider', self.handle_collision)

        self.task_manager.append(self.f.task_mgr.add(self.update))
        self.task_manager.append(self.f.task_mgr.add(self.update_bullets))
Ejemplo n.º 16
0
	def __init__(self):
		ShowBase.__init__(self)
		self.disableMouse()
		self.camera.setPos(40, -100, 160)
		self.camera.lookAt(40,-44.5,0)
		self.rows, self.cols = 9, 8
		#Start tile & end tile
		self.start, self.end = (0, 0), (8, 7)
		self.cellSize = 10
		#Plane used for intersection of mouseLine
		#To get coords of mouse
		self.mousePlane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
		#No click has been made
		self.mousePressed = False
		self.displayTextObject = None
		#Holds the model for all tiles
		self.tiles = []
		for row in xrange(self.rows):
			self.tiles += [[0]*self.cols]
		#Holds the texture for the grass tiles
		self.grass = loader.loadTexture("models/textures/sponge.jpg")
		#Holds the models for all the towers
		self.towerModels = []
		for row in xrange(self.rows):
			self.towerModels += [[0]*self.cols]
		#Holds the G value of each tile for pathing
		self.tileNodes = []
		for row in xrange(self.rows):
			self.tileNodes += [[0]*self.cols]
		for row in xrange(self.rows):
			for col in xrange(self.cols):
				self.tileNodes[row][col] = Tile(self)
		#Holds the towers in a 2d array
		self.towers = []
		for row in xrange(self.rows):
			self.towers += [[0]*self.cols]
		self.board = [
						['s', 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0,'e']
					 ]
		self.drawBoard()
		self.drawBoardLines()
		self.drawBackground()
		
		#Stores all center points of each tile
		self.midPoints= []
		startX = 5 #X Coordinate of first Square's center
		startY = -5 #Y Coordinate of first Square's center
		for row in xrange(self.rows):
			self.midPoints += [[Point3(0,0,0)]*self.cols]
		for row in xrange(self.rows):
			for col in xrange(self.cols):
				self.midPoints[row][col] = Point3(
											startX+col*self.cellSize,
											startY-row*self.cellSize,
											0)
		self.createPath(self.start, self.end)
		
#Board Information
		#Towers
		self.arrowTowerModel = loader.loadModel(
			"models/towers/arrowTowerFolder/arrowTower")
		self.fireTowerModel = loader.loadModel(
			"models/towers/fireTowerFolder/fireTower")
		self.iceTowerModel = loader.loadModel(
			"models/towers/iceTowerFolder/iceTower")

#Main Menu
		self.mainFrame = DirectFrame(frameColor=(0, 0, 0, 1),
		                      frameSize=(-2, 2, -2, 2),
		                      pos=(0, 0, 0))
		instructionsText = "   Stefan Dasbach's Tower Defense\n\n\n"+\
							"Monsters move accross the screen\n" +\
							"from the green square to the red\nsquare."+\
							" Choose and build from among a \nrange" +\
							" of towers including Arrow, Fire,\nand" +\
							" Ice. Waves of monsters come in \n10 and" +\
							" will spawn every 15 seconds. You\ncan" +\
							" only build towers when creeps are\nnot" +\
							" alive.\n\nPress 'P' to play!"
		self.instructionsNode = OnscreenText(
									text=instructionsText,
									pos = (-0.9, 0.55),
									scale = (0.1),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
									frame = (1, 0, 0, 1),
									align = TextNode.ALeft
												)
		# self.fireProjectileModel = loader.loadModel(
		# 	"models/projectiles/fireProjectileFolder/fireProjectile")
		# self.iceProjectileModel = loader.loadModel(
		# "models/projectiles/iceProjectileFolder/iceProjectile")
		# 
		# self.iceProjectileModel.setScale(0.03,0.03,0.03)
		# self.iceProjectileModel.setPos(12,-5,0)
		# # self.iceProjectileModel.lookAt(15, -5, 0)
		# self.iceProjectileModel.reparentTo(self.render)
		
#Level information
		self.level = 1
		self.gold = 20
		self.lives = 20
		self.totalHp = 0
		self.arrowTowerCost = 10
		self.fireTowerCost = 25
		self.iceTowerCost = 30
		#Building period, True at beginning of game
		self.buildTime = True
		#Spawning/killing of creeps period, False at beginning
		self.fireTime = False
		self.displayGameInfoNode = None
		self.displayGameInfoNode1 = None
		
#Spawn Creeps
		self.numberOfCreeps = 10
		#Time for building
		self.waveTime = 15
		self.creeps = []
		self.hasSpawnedWave = False
		#Delay between spawning of each creep
		self.delayTime = 0
		self.interval = 0
		self.buildTimeDuration = 0
		self.alreadyInitedGame = False
		self.accept("p", self.initGame)