def move_to_point(self, tx, ty): self.target_x = tx self.target_y = ty dist = float( TCalc.dist_to_point(self.node_path.getX(), self.node_path.getY(), tx, ty)) print dist #time = dist/speed #print dist/speed #print time*speed,dist try: self.sq_army_move.pause() self.intvl_army_move = None except: print "no sequence" if dist > 1: self.intvl_army_move = self.node_path.posInterval( dist / self.speed, Point3(self.target_x, self.target_y, 0), startPos=Point3(self.node_path.getX(), self.node_path.getY(), 0)) self.sq_army_move = Sequence(self.intvl_army_move) self.sq_army_move.start() else: try: self.sq_army_move.finish() except: print "no sequence"
def __init__(self, bat_np, t, x, y, col): rate = 2 z = 20 scale = 12 scale_up = 15 text_node = TextNode("battle_text") text_node.setText(t) text_node_path = bat_np.attachNewNode(text_node) text_node_path.reparentTo(render) text_node_path.setPos(x, y, 0) text_node_path.setHpr(0, -90, 0) text_node_path.setScale(scale) text_node_path.setTransparency(TransparencyAttrib.MAlpha) text_node.setTextColor(col) text_node.setAlign(TextNode.ACenter) node_scl_up = text_node_path.scaleInterval( rate, Point3(scale_up, scale_up, scale_up)) node_z_up = text_node_path.posInterval(rate, Point3(x, y, z * 2)) node_z_up2 = text_node_path.posInterval(rate, Point3(x, y, z * 2)) node_fade_down = text_node_path.colorScaleInterval( rate, (col[0], col[1], col[2], 0)) node_func_death = Func(self.destroy) t_para = Parallel(node_scl_up, node_z_up, node_fade_down) t_seq = Sequence(t_para, node_func_death) t_seq.start() self.tnp = text_node_path
def _updateHovered(self, task): """ Updates the position of the Highlighter selector based on mouse position. Only updates if the value should change. Should not call every frame unless the user can shake his/her mouse really fast between tiles. """ if base.mouseWatcherNode.hasMouse(): # If mouse is in the window: # Draw a line from the point on screen through the camera to the # imaginary plane and check for intersections: mPos = base.mouseWatcherNode.getMouse() pos3D = Point3() # Output stored here. nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mPos, nearPoint, farPoint) # Create a line # Check for intersection: if self._groundPlane.intersectsLine( pos3D, render.getRelativePoint(base.cam, nearPoint), render.getRelativePoint(base.cam, farPoint)): highlCoords = Point2D(int(pos3D.x), int(pos3D.y)) # Ensure the calculated position is a valid tile: if self._hoveredCoord != highlCoords and\ self._tileMap.isFloor(highlCoords): self._hoveredCoord = highlCoords self._highlightTiles() elif self._hoveredCoord != None and\ not self._tileMap.isFloor(highlCoords): self._hoveredCoord = None self._highlightTiles() return task.cont
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
def __init__(self, tileMap): self._tileMap = tileMap self._groundPlane = Plane(Point3(0, 0, 1), Point3(0, 0, 1)) self._hoveredCoord = None # The coordinates we are hovering over. self._highlightMode = None # Targeter reference self._highlightModeParams = None # Targeter params dict self._highlightedTiles = list() # List of tile highlighted by pointer. self._previewTiles = list() # List of tiles highlighted by preview. # Perform mouse raycasting every frame: taskMgr.add(self._updateHovered, "mouseScanning")
def get_mouse_plane_pos(self, task): if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() self.pos3d = Point3() nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mpos, nearPoint, farPoint) if self.plane.intersectsLine( self.pos3d, render.getRelativePoint(camera, nearPoint), render.getRelativePoint(camera, farPoint)): #print "Mouse ray intersects ground plane at ", self.pos3d self.model.setPos(render, self.pos3d) return task.again
def getMouseCollisionToPlane(self, plane): mouseWatcherNode = self.showBase.mouseWatcherNode if mouseWatcherNode.hasMouse(): mpos = mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() self.showBase.camLens.extrude(mpos, nearPoint, farPoint) render = self.showBase.render camera = self.showBase.camera if plane.intersectsLine(pos3d, render.getRelativePoint(camera, nearPoint), render.getRelativePoint(camera, farPoint)): return pos3d return None
def create_counter(self): new_army = Army(self.player, "Infantry", self.node_path.getX(), self.node_path.getY(), 1) base.armies.append(new_army) new_army.state = "new" new_army.army_fight_col.setTag("state", "new") intvl_exit = new_army.node_path.posInterval( 2, Point3(self.x, self.y - 24, 0), startPos=Point3(self.x, self.y, 0)) def army_ready(): new_army.state = "normal" new_army.army_fight_col.setTag("state", "normal") func_armyready = Func(army_ready) sq_army_move = Sequence(intvl_exit, func_armyready) sq_army_move.start()
def camInterval(self, cam, actor): inc = cam.getX(), cam.getY() + 10, cam.getZ() #print(inc) #maybe a list of numbers-- an array for x, y, z, a method (manX, manY, manZ) man = manipulate by +- int, ret that array which will be used #as the Point3 args. if args are NaN/0/null, just ret the xyz arr. will be used to get the last position args for after the sequence finalizes. intervalOne = cam.posInterval(4.0, Point3(inc)) camSequence = Sequence(intervalOne) camSequence.append(Func(self.loadButtons, actor)) #print(camSequence.__len__()) camSequence.start()
def die(self): if base.single_player == False and base.client == False: base.net_manager.server_messager("army_kill", [self.my_id]) self.state = "dead" self.army_fight_col.removeNode() self.node_col.removeNode() rate = 4 intvl_shrink = self.model.scaleInterval(rate, Point3(0, 0, 0)) func_destroy = Func(self.destroy) self.sq_die = Sequence(intvl_shrink, func_destroy) self.sq_die.start() base.battles[self.battle].recenter() base.battles[self.battle].shrink() if self.selected: i = base.col_manager.selecteds.index(self) del base.col_manager.selecteds[i]
def initMouseRayCollision(self): z = 0 self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))
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
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()
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))
def turn_start(self): rate = 0.5 army_scl_up = self.model.scaleInterval(rate, Point3(1.5, 1.5, 1.5)) army_scl_down = self.model.scaleInterval(rate, Point3(1, 1, 1)) self.sq_army_bat = Sequence(army_scl_up, army_scl_down) self.sq_army_bat.loop()