// TODO: move to MapGrid.cs implementation. public Vector3 GetWorldPosition(MapGrid pos) { return new Vector3( (Mathf.Clamp(pos.x, 0, gridXNum - 1) + 0.5f) * MapGrid.Width, 0.0f, (Mathf.Clamp(pos.z, 0, gridZNum - 1) + 0.5f) * MapGrid.Height); }
public Map(int Width, int Height) { this.Width = Width; this.Height = Height; Defaults(); Grid = new MapGrid(this); }
public Map(int Width , int Height , int BuildingNumber , int CitizenNumber , int ZombiePerc) { this.BuildingNumber = BuildingNumber; this.CitizenNumber = CitizenNumber; this.Width = Width; this.Height = Height; this.ZombiePercentage = ZombiePerc; Grid = new MapGrid(this); Defaults(); }
public void WalkTo(Vector3 _dst, PathFinished _delegate = null) { MapGrid gridOriginSrc = entity.Grid; MapGrid gridOriginDst = new MapGrid(_dst); // 如果起始点是阻挡,检测方向是否为走出阻挡的方向 MapGrid gridRealSrc = gridOriginSrc; if ((MapNav[gridRealSrc.x, gridRealSrc.z] & entity.TileType) == 0) { if (MapNav.GetNearestValidGrid(gridOriginDst, gridOriginSrc, out gridRealSrc, entity.TileType, 1) == false) { StopPath(); return; } } MapGrid gridRealDst; if (MapNav.GetNearestValidGrid(gridRealSrc, gridOriginDst, out gridRealDst, entity.TileType) == false) { StopPath(); return; } // 正在走着 if (path.Count > 0 && path[path.Count - 1] == gridRealDst) { pathFinished = null; pathFinished += _delegate; return; } path = MapNav.GetPath(gridRealSrc, gridRealDst, entity.TileType); if (path.Count == 0) { StopPath(); return; } //src = entity.Position; if (gridRealDst == gridOriginDst) dst = _dst; else dst = MapNav.GetWorldPosition(gridRealDst); move.targetArrived -= this.onTargetArrived; move.targetArrived += this.onTargetArrived; pathFinished = null; pathFinished += _delegate; // 路径第一个节点为起始点,放弃,从第二个节点开始 path.RemoveAt(0); onTargetArrived(); }
void IUtilityCommand.Run(Utility utility, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = utility.ModData; grid = Game.ModData.Manifest.Get<MapGrid>(); file = new IniFile(File.Open(args[1], FileMode.Open)); foreach (var section in file.Sections) { var sequence = section.GetValue("Sequence", string.Empty); if (!string.IsNullOrEmpty(sequence)) ImportInfantrySequences(section, sequence); var foundation = section.GetValue("Foundation", string.Empty); if (!string.IsNullOrEmpty(foundation)) ImportBuildingSequences(section); } }
/*private void TryAttackSlot(RaycastHit hit, SoldierAttack attack) { * throw new NotImplementedException(); * }*/ internal void HandleCover() { if (animations) { // TODO: Cover check doesn't work in all directions if (MapGrid.OnlyGround(curPositionSlot)) { curCoverHeight = 0; animations.StopAnimation("Crouch"); } else if (MapGrid.OnlyLowCover(curPositionSlot)) { curCoverHeight = 1; animations.RunAnimation("Crouch"); } else { curCoverHeight = 2; animations.StopAnimation("Crouch"); } } }
private bool IsInArea(MapGrid mc) { if (mc == null) { return(false); } if (mc.PrevOwner == this.player || mc.Owner == this.player) { return(true); } if (this.IsMinYOK(mc) && this.IsMaxYOK(mc) && this.IsMinXOK(mc) && this.IsMaxXOK(mc)) { return(true); } else { return(false); } }
private void BuildWorldMap() { MapGrid.Add(new SquareDesert()); MapGrid.Add(new SquareDesert()); MapGrid.Add(new SquareDesert()); MapGrid.Add(new SquareDesert()); MapGrid.Add(new SquareMountain()); MapGrid.Add(new SquareMountain()); MapGrid.Add(new SquareMountain()); MapGrid.Add(new SquareMountain()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); MapGrid.Add(new SquarePrairie()); }
void CreateHole() { if (Size <= 0) { return; } for (int i = 0; i <= Size; i++) { int WallID = -1; if (i == 0) { MapGrid.CreateLeftShareHole(new Int2(StartUnit + i, Layer), ref WallID); } else if (i == Size) { MapGrid.CreateRightShareHole(new Int2(StartUnit + i, Layer), ref WallID); } else { MapGrid.CreateHole(new Int2(StartUnit + i, Layer), ref WallID); } if (WallID != -1) { Life m = CM.GetLifeM(WallID, LifeMType.WALL); if (m is IggWall) { (m as IggWall).SetWallDead(); } } } }
public PelletTurret(Texture2D upgrade1, Texture2D upgrade2, Texture2D upgrade3, Texture2D bulletTexture, Texture2D platformTexture, int xPos, int yPos, IProjectileHandler handler, List <Enemy> enemies) { this.Textures = new List <Texture2D>() { upgrade1 }; this._bulletTexture = bulletTexture; //Settings this.Name = "PELLET"; this.Price = 600; this._shootSpeed = 20; this.Upgrade1Price = 1000; this.Upgrade2Price = 2500; this._shootsAir = true; this._shootsGround = true; this.Damage = Settings.TowerDefenseSettings.TURRET_DAMAGES[0]; this.ShootRate = Settings.TowerDefenseSettings.TURRET_FIRE_RATES[3]; this.Range = Settings.TowerDefenseSettings.TURRET_RANGES[2]; this.UpgradeLevel = 1; this._upgrade1 = upgrade1; this._upgrade2 = upgrade2; this._upgrade3 = upgrade3; this.XPos = xPos; this.YPos = yPos; this._handler = handler; var position = MapGrid.GetPosition(XPos, YPos); _animatedSprite = new AnimatedSprite(new Vector2(1, 1), position, position, 0, 200, Textures, new int[] { 1000 }); this._enemies = enemies; this._platformTexture = platformTexture; }
void Start() { mapGrid = GetComponent <MapGrid>(); tilePool = new ObjectPool(tilePrefab, transform); Square[][] matrix = mapGrid.GetGridMatrix(); int columns = AppConfig.COLUMN_SIZE; int rows = AppConfig.ROW_SIZE; for (int c = 0; c < columns; c++) { for (int r = 0; r < rows; r++) { TileView tile = tilePool.GetInstance().GetComponent <TileView>(); // Position in pixels: Vector2 position = Utility.GetPositionInPixel(c, r); tile.Initialize(matrix[c][r], position); tile.gameObject.SetActive(true); } } }
private bool IsGridMoved(Vector2 point, float size) { int row_s = Mathf.CeilToInt((point.y - size - MapGrid.Origin().y) / MapGrid.Size()); int row_e = Mathf.CeilToInt((point.y + size - MapGrid.Origin().y) / MapGrid.Size()); int col_s = Mathf.CeilToInt((point.x - size - MapGrid.Origin().x) / MapGrid.Size()); int col_e = Mathf.CeilToInt((point.x + size - MapGrid.Origin().x) / MapGrid.Size()); if (row_s <= 0 || row_e > MapGrid.MaxRow() || col_s <= 0 || col_e > MapGrid.MaxCol()) { return(false); } bool res = true; for (int i = row_s; i < row_e + 1; i++) { for (int j = col_s; j < col_e + 1; j++) { res = res && mapGrids[i][j].isMoved; } } return(res); }
/// <summary> /// 严格检查两点之间是否通畅 /// </summary> /// <returns><c>true</c>, if path clear was lined, <c>false</c> otherwise.</returns> /// <param name="vecSrc">Vec source.</param> /// <param name="vecDst">Vec dst.</param> public bool LinePathClear(Vector3 vecSrc, Vector3 vecDst, TileType validType = TileType.TileType_Walk) { MapGrid dstPt = new MapGrid(vecDst); Vector3 dir = vecDst - vecSrc; dir.Normalize(); dir *= ShortestMoveDst; Vector3 curPos = vecSrc; MapGrid curPt = new MapGrid() { x = 0, z = 0 }; for (; (vecDst - curPos).magnitude > ShortestMoveDst; curPos += dir) { if (curPt != new MapGrid(curPos)) { curPt = new MapGrid(curPos); } else { continue; } if ((this[curPt.x, curPt.z] & validType) == 0) { return(false); } if (curPt == dstPt) { break; } } return(true); }
/// <summary> /// 在源点和目标点之间,找个有效的可到达点。搜寻范围在dst ~ (dst-radius)内 /// </summary> /// <returns>The nearest valid grid.</returns> /// <param name="src">Source.</param> /// <param name="dst">Dst.</param> /// <param name="validType">Valid type.</param> /// <param name="radius">Grid Radius.</param> public bool GetNearestValidGrid(MapGrid src, MapGrid dst, out MapGrid ptOut, TileType validType, int gridRadius = -1) { ptOut = dst; while ((this[ptOut.x, ptOut.z] & validType) == 0) { ptOut = GetNearestGrid(src, ptOut); if (ptOut == src) { break; } if (gridRadius > 0) { gridRadius--; if (gridRadius == 0) { break; } } } return((this[ptOut.x, ptOut.z] & validType) != 0); }
private bool IsDestinationBlocked(Vector3 destination) { //should already remove self grid block, so don't need to check whether grid is change //that means if unit alread inside a grid is blocked, then it is blocked by other unit // COORD c1 = MapGrid.GetTileCoord (_owner.transform.position.x, _owner.transform.position.z); COORD c2 = MapGrid.GetTileCoord(destination.x, destination.z); // if(c1.IsEqual(c2)) // { // return false; // } if (_game.mapGrid.IsBlock(c2.x, c2.z)) { return(true); } else { return(false); } }
public override void BeforeDead() { base.BeforeDead(); int wood = m_Attr.Wood; if (wood > 0) { Vector3 pos = MapGrid.GetMG(m_Attr.Pos).pos; pos += new Vector3(0, 0.5f, 1.2f);//此处y控制深度, z控制高度 DropResource.Drop(ResourceType.Wood, wood, pos); CmCarbon.SetAddWinWood(wood); } int stone = m_Attr.Stone; if (stone > 0) { Debug.Log("get stone:" + stone + "," + this); } int steel = m_Attr.Steel; if (steel > 0) { Debug.Log("get steel:" + steel + "," + this); } List <Life> listRAW = new List <Life>(); CM.SearchLifeMListInBoat(ref listRAW, LifeMType.SOLDIER, LifeMCamp.ATTACK); foreach (var item in listRAW) { Role r = item as Role; r.ChangeTarget(ChangeTargetReason.ClearOtherTarget, this); } EventCenter.AntiRegisterHooks(NDEventType.StatusCG, SetStatus); Destroy(); }
public override void hunt() { /* if(stunTurns >= 1){ * stunTurns -= 1; * actions -= 2; * if(stunTurns <= 0){ * stunEffect.SetActive(false); * } * return; * }*/ NodeController moveTarget = findMoveNode("attack", "melee"); //in case for some reason cant find any reason to attack. shouldnt happen but if for some reason does wont end in eternal loop if (moveTarget == null) { //actions -= 2; return; } if (!isInMeleeRange(moveTarget)) { //BadGuyWalking(); NodeController currentPos = currentNode.GetComponent <NodeController>(); List <GameObject> distance = MapGrid.getPath(currentNode, moveTarget.x, moveTarget.y); //if(distance.Count <= moveRange+1 && distance.Count != 0){ checkpunch = true; hurtClosest(); sounds.playSound("punch");} startMoving(currentPos.x, currentPos.y, moveTarget.x, moveTarget.y); state = "moving"; //actions -= 2; } else { //BadGuyPunchDontMove(); hurtClosest(); //sounds.playSound("punch"); //actions -= 2; } //counting = true; //counter = 0; }
protected void JoinMap(int SceneID, Int2 Start, ShapeType Info) { if (Info == null) { return; } List <Int2> l = new List <Int2>(); for (int layer = 0; layer < Info.height; layer++) { for (int unit = 0; unit < Info.width; unit++) { if (Info.GetShapeValue(layer, unit) == 1) { for (int i = 0; i <= MapGrid.m_UnitRoomGridNum; i++) { l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + i, Start.Layer + layer)); } /*l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 0, Start.Layer + layer)); * l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 1, Start.Layer + layer)); * l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 2, Start.Layer + layer)); * l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 3, Start.Layer + layer)); * l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 4, Start.Layer + layer)); * l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 5, Start.Layer + layer));*/ } } } // foreach (Int2 Pos in l) { MapGrid Gird = MapGrid.GetMG(Pos); if (Gird != null) { Gird.JoinBuild(m_SceneID); } } }
/// <summary> /// finds closest grid on list of grids /// </summary> /// <param name="sta">starting grid</param> /// <param name="grd">list of grids to search for</param> /// <param name="mg">mapgrid to work with</param> /// <returns></returns> public Grid FindNearestGrid(Grid sta, List <Grid> grd, MapGrid mg) { if (sta == null || grd == null || mg == null || grd.Count <= 0) { return(null); } if (grd.Count == 1) { return(grd[0]); } Vector2[] pattern = { new Vector2(-1, 0), new Vector2(0, 1), new Vector2(1, 0), new Vector2(0, -1) }; List <Grid> usedGrid = new List <Grid>(); Grid found = null; List <Grid> outerGrid = new List <Grid>(); outerGrid.Add(pathGrid[(int)sta.getIndex().x, (int)sta.getIndex().y]); for (int i = 0; i < nearestGridLimit && found == null; i++) { found = expandGridFind(outerGrid, pathGrid, usedGrid, pattern, grd, mg); } resetGrid(usedGrid); return(found); }
/// <summary> /// 保持方向一致 /// </summary> private static void GetNASHoldDir(ref MapGrid l, ref MapGrid r, DIR dir, ref MapGrid m) { if (dir == DIR.LEFT) { if (l != null) { l = l.GetNextAttackStation(dir); } m = l; } else if (dir == DIR.RIGHT) { if (r != null) { r = r.GetNextAttackStation(dir); } m = r; } else { m = null; } }
// Update is called once per frame public void Update() { if (_hasPath) { COORD currentCoord = MapGrid.GetTileCoord(_unit.transform.position.x, _unit.transform.position.z); COORD targetCoord = MapGrid.GetTileCoord(_targetTileCenter.x, _targetTileCenter.z); if (currentCoord.IsEqual(targetCoord)) { _hasPath = false; } /* * foreach(MapAStar.NODE node in _path.nodes) * { * if(tileCoord.x == node.x && tileCoord.z == node.z) * { * _hasPath = false; * break; * } * } */ } }
//获取洞的最底下一个点 public static MapGrid GetHoleBottom(MapGrid m) { if (m == null) { return(null); } if (m.Type != GridType.GRID_HOLE && m.Type != GridType.GRID_HOLESTAIR) { return(m); } else { if (m.Down == null) { Debug.Log("船型数据异常,请调查原因"); return(null); } else { return(GetHoleBottom(m.Down)); } } }
private void Awake() { var monsterPools = statsHolder.FindObjectByType <MonsterStats>(); _blockManager = GetComponentInChildren <MapBlockManager>(); _mapGrid = GetComponentInChildren <MapGrid>(); _gameInputManager = GetComponentInChildren <GameInputManager>(); _gameInteractorCtrl = GetComponentInChildren <InGameUICtrl>(); _poolManager = GetComponentInChildren <PoolManager>(); _gameUnitManager = GetComponentInChildren <GameUnitManager>(); _levelDesignManager = GetComponentInChildren <LevelDesignManager>(); _headView = GetComponentInChildren <HeaderView>(); _mapBlockBottomView = GetComponentInChildren <MapBlockBottomView>(); _mapGrid.SetUp(); _gameInputManager.SetUp(_mapGrid, _blockManager); _gameUnitManager.SetUp(_blockManager, _mapGrid, poolingTheme.total); _levelDesignManager.Init(_gameUnitManager, _blockManager, _mapGrid, monsterPools); _gameInteractorCtrl.SetUp(_gameInputManager, _gameUnitManager, _levelDesignManager, _mapGrid, _blockManager, poolingTheme, statsHolder); }
public IEnumerator CustomSeed() { ProceduralGeneration.SetSeed("Test"); ProceduralGeneration.GenerateMap(m_mapGrid); GameObject mapGridObject2 = GameObject.Instantiate(m_mapGridPrefab, Vector2.zero, Quaternion.identity); MapGrid mapGrid2 = mapGridObject2.GetComponent <MapGrid>(); ProceduralGeneration.GenerateMap(mapGrid2); for (int x = 0; x < m_mapGrid.GetWidth(); x++) { for (int y = 0; y < m_mapGrid.GetHeight(); y++) { Assert.True(m_mapGrid.m_grid[x][y].GetTileType() == mapGrid2.m_grid[x][y].GetTileType()); } } GameObject.Destroy(mapGridObject2); yield return(null); }
//创建地图 public static void CreateMap(List <Int3> SizeList, List <Int2> Hole, List <Int2> AttackPos) { ClearMap(); List <StairInfo> lStair = new List <StairInfo>(); CmCarbon.GetStairInfo(ref lStair); //设置地图大小 MapSize.SetMapSize(SizeList); //创建格子 MapGrid.CreateMapGrid(SizeList); //创建洞 MapGrid.CreateHole(Hole); //用户楼梯 MapGrid.CreateStair(lStair); //预设攻击位 MapGrid.SetAttackGrid(AttackPos); GetGridList(); GetStairsList(); m_IsLoadMap = true; }
public static List <Coord> GetPath(Coord A, Coord B, MapGrid map, bool isVisualize) { List <Coord> path = new List <Coord>(); map.ResetMap(); if (isVisualize) { SearchVisualizerView.current.Reset(); } Square start = map.GetGridMatrix()[A.col][A.row]; Square target = map.GetGridMatrix()[B.col][B.row]; float visualizeDelay = 0f; if (isVisualize) { SearchVisualizerView.current.VisualizeVisit(start, visualizeDelay); } DFS(path, start, target, map, isVisualize, visualizeDelay); return(path); }
//public int LoadResourceUnit(int ruindex) //{ // Model m = GlobalSettings.Instance.Model; // ResourceUnit ru = m.GetResourceUnit(ruindex); // if (ru == null) // { // return -1; // } // mTrees.Clear(); // for (int i = 0; i < ru.Trees.Count; i++) // { // if (!ru.Tree(i).IsDead()) // { // mTrees.Add(new MutableTuple<Tree, float>(ru.Tree(i), 0.0)); // } // } // return mTrees.Count; //} //private int Load(string filter, Model model) //{ // TreeWrapper tw = new TreeWrapper(); // mTrees.Clear(); // AllTreeIterator at = new AllTreeIterator(model); // if (String.IsNullOrEmpty(filter)) // { // for (Tree t = at.MoveNextLiving(); t != null; t = at.MoveNextLiving()) // { // if (!t.IsDead()) // { // mTrees.Add(new MutableTuple<Tree, float>(t, 0.0)); // } // } // } // else // { // Expression expr = new Expression(filter, tw); // expr.EnableIncrementalSum(); // Debug.WriteLine("filtering with " + filter); // for (Tree t = at.MoveNextLiving(); t != null; t = at.MoveNextLiving()) // { // tw.Tree = t; // if (!t.IsDead() && expr.Execute(model.GlobalSettings) == 0.0) // { // mTrees.Add(new MutableTuple<Tree, float>(t, 0.0)); // } // } // } // return mTrees.Count; //} public static void KillSaplings(MapGrid standGrid, Model model, int key) { //MapGridWrapper *wrap = qobject_cast<MapGridWrapper*>(map_grid_object.toQObject()); //if (!wrap) { // context().throwError("loadFromMap called with invalid map object!"); // return; //} //loadFromMap(wrap.map(), key); RectangleF boundingBox = standGrid.GetBoundingBox(key); GridWindowEnumerator <float> runner = new(model.Landscape.LightGrid, boundingBox); while (runner.MoveNext()) { if (standGrid.GetStandIDFromLightCoordinate(runner.GetCellPosition()) == key) { SaplingCell?saplingCell = model.Landscape.GetSaplingCell(runner.GetCellPosition(), true, out ResourceUnit ru); if (saplingCell != null) { ru.ClearSaplings(saplingCell, true); } } } }
/// specify removal fractions /// @param SWDFrac 0: no change, 1: remove all of standing woody debris /// @param DWDfrac 0: no change, 1: remove all of downled woody debris /// @param litterFrac 0: no change, 1: remove all of soil litter /// @param soilFrac 0: no change, 1: remove all of soil organic matter public static void RemoveCarbon(MapGrid standGrid, int key, float standingWoodyFraction, float downWoodFraction, float litterFraction, float soilFraction) { if ((standingWoodyFraction < 0.0F) || (standingWoodyFraction > 1.0F) || (downWoodFraction < 0.0F) || (downWoodFraction > 1.0F) || (soilFraction < 0.0F) || (soilFraction > 1.0F) || (litterFraction > 0.0F && litterFraction > 1.0F)) { throw new ArgumentException("removeSoilCarbon called with one or more invalid parameters."); } IList <MutableTuple <ResourceUnit, float> > ruAreas = standGrid.GetResourceUnitAreaFractions(key); //float totalArea = 0.0F; for (int areaIndex = 0; areaIndex < ruAreas.Count; ++areaIndex) { ResourceUnit ru = ruAreas[areaIndex].Item1; if (ru.Soil == null) { throw new NotSupportedException("Soil is not enabled on resource unit. Down wood, litter, and soil carbon cannot be removed."); } float areaFactor = ruAreas[areaIndex].Item2; // 0..1 //totalArea += areaFactor; // swd if (standingWoodyFraction > 0.0F) { if (ru.Snags == null) { throw new NotSupportedException("Snags are not enabled on resource unit. Standing woody carbon cannot be removed."); } ru.Snags.RemoveCarbon(standingWoodyFraction * areaFactor); } // soil pools ru.Soil.RemoveBiomassFractions(downWoodFraction * areaFactor, litterFraction * areaFactor, soilFraction * areaFactor); // Debug.WriteLine(ru.index() + area_factor; } //Debug.WriteLine("total area " + totalArea + " of " + standGrid.GetArea(key)); }
public bool CheckRangeAttackTarget(Life target, Vector3 pos, float radus) { Building buildlife = target as Building; if (buildlife != null) { BuildInfo info = CmCarbon.GetBuildInfo(buildlife.m_Core.m_DataID); for (int i = 0; i < info.m_Shape.height; i++) { for (int j = 0; j < info.m_Shape.width * MapGrid.m_UnitRoomGridNum; j++) { MapGrid bg = MapGrid.GetMG(i + info.m_cy, j + info.m_cx); Vector3 tbpos = bg.WorldPos; float bdis = Vector2.Distance(new Vector2(tbpos.x, tbpos.y), new Vector2(pos.x, pos.y)); if (bdis <= radus) { return(true); } bdis = Vector2.Distance(new Vector2(tbpos.x, tbpos.y + 3f), new Vector2(pos.x, pos.y)); if (bdis <= radus) { return(true); } } } return(false); } MapGrid g = target.GetMapGrid(); Vector3 tpos = g.WorldPos; float dis = Vector2.Distance(new Vector2(tpos.x, tpos.y), new Vector2(pos.x, pos.y)); if (dis <= radus) { return(true); } return(false); }
public IEnumerator RandomSeed() { ProceduralGeneration.GenerateRandomSeed(); ProceduralGeneration.GenerateMap(m_mapGrid); string seed1 = ProceduralGeneration.GetSeed(); GameObject mapGridObject2 = GameObject.Instantiate(m_mapGridPrefab, Vector2.zero, Quaternion.identity); MapGrid mapGrid2 = mapGridObject2.GetComponent <MapGrid>(); ProceduralGeneration.GenerateRandomSeed(); ProceduralGeneration.GenerateMap(mapGrid2); string seed2 = ProceduralGeneration.GetSeed(); Assert.True(seed1 != seed2); bool isIdentical = true; for (int x = 0; x < m_mapGrid.GetWidth() && isIdentical; x++) { for (int y = 0; y < m_mapGrid.GetHeight() && isIdentical; y++) { if (m_mapGrid.m_grid[x][y].GetTileType() != mapGrid2.m_grid[x][y].GetTileType()) { isIdentical = false; } } } Assert.True(isIdentical == false); GameObject.Destroy(mapGridObject2); yield return(null); }
public void SetBorn(Int2 BornPos, int deep) { MapPos = BornPos; m_AttackStation = MapPos; m_NAttackStation = MapPos; m_NGrid = BornPos; RankDeep = deep; // MapGrid m = MapGrid.GetMG(MapPos); if (m != null) { if (MapM.AskForMapGridDeep(m_SceneID, m, deep, RoleParent.m_Core.m_Camp, DIR.LEFT, SEARCHAGT.SAGTY_POLL, ref BornPos, ref deep)) { m = MapGrid.GetMG(BornPos); RankDeep = deep; MapCheckStations.RoleStation(m_SceneID, m, new StationsInfo(RoleParent.m_Attr as RoleAttribute, RankDeep, RoleParent.m_Core.m_Camp, DIR.LEFT, GridSpace.Space_DOWN)); } } }
/// <summary> /// 创建宠物 /// </summary> private SummonPet CreatePet(int PetDataID, MapGrid StartGrid) { SummonpetInfo info = SummonM.GetSummonPetInfo(PetDataID); SummonPet pet = new SummonPet(); pet.CreateSkin(BattleEnvironmentM.GetLifeMBornNode(true), info.m_modeltype, info.m_modeltype.ToString(), AnimatorState.Empty, true); //IGameRole i = GameRoleFactory.Create(BattleEnvironmentM.GetLifeMBornNode(true), info.m_modeltype, info.m_modeltype.ToString(), AnimatorState.Empty); GameObject go = pet.RoleSkinCom.tRoot.gameObject; Vector3 pos = Vector3.zero; string posname = ""; LifeObj lo = go.AddComponent <LifeObj>(); pet.SetSummonPetLife(info, pet.RoleSkinCom.ProPerty, LifeEnvironment.Combat); pet.SetLifeCore(new LifeMCore(PetDataID, true, LifeMType.SUMMONPET, Camp, MoveState.Walk)); pet.SetSkin(); pet.SetBornPos(StartGrid.GridPos, 0); lo.SetLife(pet, pet.RoleSkinCom.ProPerty); go.transform.parent = BattleEnvironmentM.GetLifeMBornNode(true); Vector3 start = StartGrid.WorldPos; start.z = Camera.main.transform.position.z; go.transform.position = start; return(pet); }
void IUtilityCommand.Run(Utility utility, string[] args) { // HACK: The engine code assumes that Game.modData is set. Game.ModData = utility.ModData; grid = Game.ModData.Manifest.Get <MapGrid>(); file = new IniFile(File.Open(args[1], FileMode.Open)); foreach (var section in file.Sections) { var sequence = section.GetValue("Sequence", string.Empty); if (!string.IsNullOrEmpty(sequence)) { ImportInfantrySequences(section, sequence); } var foundation = section.GetValue("Foundation", string.Empty); if (!string.IsNullOrEmpty(foundation)) { ImportBuildingSequences(section); } } }
public AirlockClient(IPAddress address, int destport, int srcport) { Network = new NetworkClient(new UDPConnection(address, destport, srcport)); NetDefinitions netDefs = new NetDefinitions(); netDefs.LoadEntityTypes(); WorldContent = new IncomingSyncPool(netDefs, (ushort)AirlockServer.SyncPoolID.WorldContent); ReturnContent = new OutgoingSyncPool(netDefs, (ushort)AirlockServer.SyncPoolID.ReturnContent); ClientContent = new IncomingSyncPool(netDefs, (ushort)AirlockServer.SyncPoolID.ClientContent); ClientContent.LinkedPools.Add(WorldContent); Network.Attach(WorldContent); Network.Attach(ReturnContent); Network.Attach(ClientContent); Network.SetState(NetworkClient.ConnectionState.Open); LocalPlayer = new LocalPlayer(); ReturnContent.AddEntity(LocalPlayer); Inputs = new ClientInputs(); Grid = new MapGrid(); }
// Use this for initialization void Start() { Map = new MapGrid[8, 6]; int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 6; j++) { Coordinate target_location = new Coordinate(i, j); GameObject target_grid = GameObject.Find(target_location.toString()); if (target_grid.GetComponent <Grid>() == null) { Debug.Log("MapGrid Initialization Error: Cant find target Grid."); } if (target_location != target_grid.GetComponent <Grid>().getLocaiotn()) { Debug.Log("MapGrid Initialization Error: MapGrid and Gird location dismatch."); } Map[i, j] = new MapGrid(target_location, target_grid, true); } } //setGridsState(new Coordinate[5]{new Coordinate(0, 0),new Coordinate(1,0),new Coordinate(2,0),new Coordinate(3,0),new Coordinate(4,0)}, GridState.Selected); }
public PathNode(int _index, int _parentIndex, float _g, float _h, MapNav mapNav) { index = _index; parentIndex = _parentIndex; g = _g; h = _h; f = g + h; grid = new MapGrid(){x = index % mapNav.gridXNum, z = index / mapNav.gridXNum}; position = mapNav.GetWorldPosition(grid); }
public List<MapGrid> GetPath(Vector3 fromPosition, Vector3 toPosition, TileType validType) { var from = new MapGrid(fromPosition); var to = new MapGrid(toPosition); return GetPath(from.x, from.z, to.x, to.z, validType); }
//get the reference list to target MapGrids private MapGrid[] getMapGrids(Coordinate[] target_locations) { int length = target_locations.Length; MapGrid[] target_mapgrids = new MapGrid[length]; int i; for (i=0; i<length; i++) { target_mapgrids[i] = getMapGrid(target_locations[i]); } return target_mapgrids; }
public static MapGrid GenerateMap(string filePath, int cellWidth, int cellHeight) { Bitmap image = new Bitmap(filePath); int imageHeight = image.Height; int imageWidth = image.Width; int columnCount = image.Width / cellWidth; int rowCount = image.Height / cellHeight; MapGrid grid = new MapGrid(); grid.CellWidth = cellWidth; grid.CellHeight = cellHeight; grid.ColumnCount = columnCount; grid.RowCount = rowCount; for (int row = 0; row < rowCount; row++) { for (int col = 0; col < columnCount; col++) { int posX = col * cellWidth; int posY = row * cellHeight; try { Bitmap cellImage = new Bitmap(cellWidth, cellHeight,image.PixelFormat); if ((row != (rowCount - 1)) && (col != (columnCount - 1))) { // loop down a row for(int i =0; i < cellHeight; i++) { for(int j=0; j < cellWidth; j++) { var pixelColor = image.GetPixel(posX + j, posY + i); cellImage.SetPixel(j, i, pixelColor); } } } else { int cellEdgeHeight = cellHeight; int cellEdgeWidth = cellWidth; if (row == (rowCount - 1)) { cellEdgeHeight = imageHeight - (row * cellHeight); } if (col == (columnCount - 1)) { cellEdgeWidth = imageWidth - (col * cellWidth); } } var cellAverage = ImageLibraryGenerator.GetAverageColorFromBitmap(cellImage); grid.AddCell(new MapCell(posX, posY, cellAverage.ToString(), cellAverage)); } catch (Exception e) { throw new Exception(e.Message); } } } return grid; }
/// <summary> /// 严格检查两点之间是否通畅 /// </summary> /// <returns><c>true</c>, if path clear was lined, <c>false</c> otherwise.</returns> /// <param name="vecSrc">Vec source.</param> /// <param name="vecDst">Vec dst.</param> public bool LinePathClear(Vector3 vecSrc, Vector3 vecDst, TileType validType = TileType.TileType_Walk) { MapGrid dstPt = new MapGrid(vecDst); Vector3 dir = vecDst - vecSrc; dir.Normalize(); dir *= ShortestMoveDst; Vector3 curPos = vecSrc; MapGrid curPt = new MapGrid(){x=0, z=0}; for(; (vecDst - curPos).magnitude > ShortestMoveDst; curPos += dir) { if(curPt != new MapGrid(curPos)) { curPt = new MapGrid(curPos); } else { continue; } if((this[curPt.x, curPt.z] & validType) == 0) { return false; } if(curPt == dstPt) break; } return true; }
/// <summary> /// 导出NPC摆放信息 /// </summary> /// <param name="path"></param> /// <returns></returns> private bool ExportNpc(string path) { var host = Target.transform.parent; var npc = host.GetComponentsInChildren<NpcEditor>(); var db = Table.Query<table.TableNpc>().ToDictionary(i => i.id); var error = from i in npc let id = (uint)i.baseId where db.ContainsKey(id) == false select i; if (error.Any()) { Debug.LogError("NPC表格中找不到对应id的NPC:\n" + string.Join("\n", (from i in error select string.Format("{0}\t{1}", i.baseId, i.transform.GetPath())).ToArray())); return false; } var json = NGUIJson.jsonEncode(new Hashtable() { {"npcs", System.Array.ConvertAll(npc, i => { var grid = new MapGrid(i.transform.localPosition); return new Hashtable() { {"id", i.baseId}, {"name", string.IsNullOrEmpty(i.alias) ? db[(uint)i.baseId].name : i.alias}, {"x", grid.x}, {"y", grid.z}, {"angle", (int)i.transform.localRotation.eulerAngles.y}, {"relivetime", i.relivetime}, {"rate", Mathf.Clamp(i.rate, 0, 100)}, }; }) }, }); //Debug.Log(json); File.WriteAllText(path, json, new System.Text.UTF8Encoding(false)); return true; }
public void OnSceneGUI() { MapNav mapNav = Target; float y = 0.1f; if (curProcessType == ProcessType.None) return; if (curProcessType == ProcessType.Set || curProcessType == ProcessType.Clear) { Plane groundPlane = new Plane(Vector3.up, Vector3.zero); float rayDistance; Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (groundPlane.Raycast(ray, out rayDistance)) { Vector3 hitPoint = ray.GetPoint(rayDistance); if (hitPoint.x >= 0.0f && hitPoint.x <= mapNav.gridXNum * MapGrid.Width && hitPoint.z >= 0.0f && hitPoint.z <= mapNav.gridZNum * MapGrid.Height) { Handles.color = Color.black; float _radius = radius * 0.5f; Handles.DrawPolyLine(new Vector3[] { new Vector3(hitPoint.x - _radius * MapGrid.Width, y, hitPoint.z - _radius * MapGrid.Height), new Vector3(hitPoint.x - _radius * MapGrid.Width, y, hitPoint.z + _radius * MapGrid.Height), new Vector3(hitPoint.x + _radius * MapGrid.Width, y, hitPoint.z + _radius * MapGrid.Height), new Vector3(hitPoint.x + _radius * MapGrid.Width, y, hitPoint.z - _radius * MapGrid.Height), new Vector3(hitPoint.x - _radius * MapGrid.Width, y, hitPoint.z - _radius * MapGrid.Height) }); if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag) { var grid = new MapGrid(hitPoint); for (int _z = grid.z - Mathf.RoundToInt(_radius); _z <= grid.z + Mathf.RoundToInt(_radius); ++_z) { if (_z < 0) continue; if (_z > mapNav.gridZNum - 1) continue; for (int _x = grid.x - Mathf.RoundToInt(_radius); _x <= grid.x + Mathf.RoundToInt(_radius); ++_x) { if (_x < 0) continue; if (_x > mapNav.gridXNum - 1) continue; Vector3 position = mapNav.GetWorldPosition(new MapGrid() {x = _x, z = _z }); if (Mathf.Abs(position.x - hitPoint.x) <= _radius * MapGrid.Width && Mathf.Abs(position.z - hitPoint.z) <= _radius * MapGrid.Height) { switch (curProcessType) { case ProcessType.Set: mapNav[_x, _z] |= curTileType; break; case ProcessType.Clear: mapNav[_x, _z] &= ~curTileType; break; default: throw new System.NotImplementedException(); } } } } } } } } else if (curProcessType == ProcessType.FindPath) { if (Event.current.type == EventType.MouseDown) { Plane groundPlane = new Plane(Vector3.up, Vector3.zero); float rayDistance; Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (groundPlane.Raycast(ray, out rayDistance)) { Vector3 hitPoint = ray.GetPoint(rayDistance); if (hitPoint.x >= 0.0f && hitPoint.x <= mapNav.gridXNum * MapGrid.Width && hitPoint.z >= 0.0f && hitPoint.z <= mapNav.gridZNum * MapGrid.Height) { if (bSampleStart) vecStart = hitPoint; else vecEnd = hitPoint; bSampleStart = !bSampleStart; MapGrid gridEnd; if (mapNav.GetNearestValidGrid(new MapGrid(vecStart), new MapGrid(vecEnd), out gridEnd, TileType.TileType_Walk)) path = mapNav.GetPath(new MapGrid(vecStart), gridEnd, TileType.TileType_Walk); else path.Clear(); } } } Handles.color = Color.red; Handles.CubeCap(0, vecStart, new Quaternion(0, 0, 0, 1), 0.1f); Handles.color = Color.blue; Handles.CubeCap(0, vecEnd, new Quaternion(0, 0, 0, 1), 0.1f); if (path.Count > 0) { Handles.color = Color.black; Vector3 lastPoint = vecStart; lastPoint.y = y; foreach (MapGrid grid in path) { Vector3 curPoint = mapNav.GetWorldPosition(grid); curPoint.y = y; Handles.color = Color.black; Handles.DrawLine(lastPoint, curPoint); lastPoint = curPoint; Handles.color = Color.cyan; Handles.CubeCap(0, curPoint, new Quaternion(0, 0, 0, 1), 0.1f); } } } HandleUtility.Repaint(); switch (Event.current.type) { case EventType.MouseUp: case EventType.MouseDown: case EventType.MouseDrag: case EventType.MouseMove: Event.current.Use(); break; } }
public bool LinePathClear(MapGrid gridSrc, MapGrid gridDst, TileType validType = TileType.TileType_Walk) { return LinePathClear(GetWorldPosition(gridSrc), GetWorldPosition(gridDst), validType); }
void Update() { if (Layout && uiMapTexture.gameObject.activeSelf && MainRole.Instance != null) { Layout = false; var relativePos = new Vector2(MainRole.Instance.entity.Position.x / mapSize.x, MainRole.Instance.entity.Position.z / mapSize.y); // 地图位置更新 material.mainTextureOffset = new Vector2( Mathf.Clamp(relativePos.x - 0.5f * relativeExtent.x, 0.0f, 1.0f - relativeExtent.x), Mathf.Clamp(relativePos.y - 0.5f * relativeExtent.y, 0.0f, 1.0f - relativeExtent.y)); material.mainTextureScale = relativeExtent; // force update if (uiMapTexture.panel != null) { uiMapTexture.panel.RemoveWidget(uiMapTexture); uiMapTexture.panel = null; } // 主角图标位置更新 LayoutFlag(MainRole.Instance.entity, uiFlagMainRole); var pos = new MapGrid(MainRole.Instance.transform.position); uiMapGrid.text = string.Format("{0},{1}", pos.x, pos.z); } // 主角图标显隐 uiFlagMainRole.gameObject.SetActive(MainRole.Instance != null); // 主角图标旋转 if (MainRole.Instance != null) uiFlagMainRole.transform.localRotation = Quaternion.Euler(0, 180, MainRole.Instance.transform.localRotation.eulerAngles.y); foreach (var f in flags) LayoutFlag(f.Key, f.Value); }
/// <summary> /// 两点间要是超过最大路径距离,就切分路段 /// </summary> /// <param name="grid1">Grid1.</param> /// <param name="grid2">Grid2.</param> /// <param name="path">Path.</param> private void SplitBlockLineEx(MapGrid grid1, MapGrid grid2, out List<MapGrid> path) { path = new List<MapGrid>(); if(grid1.x == grid2.x && grid1.z == grid2.z) return; path = new List<MapGrid>(); path.Clear(); Vector3 vecSrc = GetWorldPosition(grid1); Vector3 vecDst = GetWorldPosition(grid2); Vector3 dir = vecDst - vecSrc; float fLength = dir.magnitude; if(fLength < ShortestMoveDst) return; dir.Normalize(); dir *= ShortestMoveDst; Vector3 curPos = vecSrc; MapGrid curPt = grid1; path.Add(grid1); for(;;) { curPos += dir; if (new MapGrid(curPos) == curPt) continue; curPt = new MapGrid(curPos); // 已经是最后一个节点,退出 if(curPt == grid2) { if(path[path.Count-1] != grid2) path.Add(grid2); break; } // 大于一段路的最大长度,加入变换点 if(path.Count > 0) { if((GetWorldPosition(curPt) - GetWorldPosition(path[path.Count-1])).magnitude >= MaxPathLen) { path.Add(curPt); } } } return; }
// Use this for initialization void Start() { Map = new MapGrid[8, 6]; int i, j; for (i=0; i<8; i++) { for(j=0; j<6; j++) { Coordinate target_location = new Coordinate(i, j); GameObject target_grid = GameObject.Find(target_location.toString()); if(target_grid.GetComponent<Grid>()==null) Debug.Log("MapGrid Initialization Error: Cant find target Grid."); if(target_location!=target_grid.GetComponent<Grid>().getLocation()) Debug.Log("MapGrid Initialization Error: MapGrid and Gird location dismatch."); Map[i, j] = new MapGrid(target_location, target_grid, true); } } //setGridsState(new Coordinate[5]{new Coordinate(0, 0),new Coordinate(1,0),new Coordinate(2,0),new Coordinate(3,0),new Coordinate(4,0)}, GridState.Selected); }
//set the state of grids at multipple target loactions, MapGrid, list private void setGridsState(MapGrid[] target_mapgrids, GridState[] target_states) { int length = target_mapgrids.Length; int i; for (i=0; i<length; i++) { target_mapgrids[i].grid.GetComponent<Grid> ().setState (target_states[i]); } }
/// <summary> /// 在源点和目标点之间,找个有效的可到达点。搜寻范围在dst ~ (dst-radius)内 /// </summary> /// <returns>The nearest valid grid.</returns> /// <param name="src">Source.</param> /// <param name="dst">Dst.</param> /// <param name="validType">Valid type.</param> /// <param name="radius">Grid Radius.</param> public bool GetNearestValidGrid(MapGrid src, MapGrid dst, out MapGrid ptOut, TileType validType, int gridRadius = -1) { ptOut = dst; while((this[ptOut.x, ptOut.z] & validType) == 0) { ptOut = GetNearestGrid(src, ptOut); if(ptOut == src) break; if(gridRadius > 0) { gridRadius --; if(gridRadius == 0) break; } } return (this[ptOut.x, ptOut.z] & validType) != 0; }
/// <summary> /// 沿着指向源点的方向,把目标点前移一段距离 /// </summary> /// <returns>The nearest grid.</returns> /// <param name="src">Source.</param> /// <param name="dst">Dst.</param> /// <param name="mindis">gridnum.</param> public MapGrid GetNearestGrid(MapGrid src, MapGrid dst, int gridnum=1) { MapGrid ptOut = src; if(src == dst) return ptOut; Vector3 vecDir = this.GetWorldPosition(src) - this.GetWorldPosition(dst); vecDir.Normalize(); Vector3 vecOut = this.GetWorldPosition(dst) + gridnum * MapGrid.Width * vecDir; ptOut = new MapGrid(vecOut); return ptOut; }
public List<MapGrid> GetPath(MapGrid fromPos, MapGrid toPos, TileType validType) { return GetPath(fromPos.x, fromPos.z, toPos.x, toPos.z, validType); }
// Use this for initialization void Start() { _grid = GetComponent<MapGrid> (); }
/// <summary> /// 严格检查两点是否可达,若不可达,则修正目标点为最远可达点 /// </summary> /// <returns><c>true</c> if this instance is path reached the specified vecSrc vecDst validType; otherwise, <c>false</c>.</returns> /// <param name="vecSrc">Vec source.</param> /// <param name="vecDst">Vec dst.</param> /// <param name="validType">Valid type.</param> public bool IsPathReached(Vector3 vecSrc, Vector3 vecOriginDst ,out Vector3 vecDst, TileType validType = TileType.TileType_Walk) { MapGrid ptSrc = new MapGrid(vecSrc); MapGrid ptDst = new MapGrid(vecOriginDst); Vector3 dir = vecOriginDst - vecSrc; float length = dir.magnitude; dir.Normalize(); dir *= ShortestMoveDst; Vector3 vecCur = vecSrc; MapGrid ptCur = new MapGrid(){x=0, z=0}; vecDst = vecCur; // 如果起始点是阻挡,检测方向是否为走出阻挡的方向 if((this[ptSrc.x, ptSrc.z] & validType) == 0) { Vector3 vecForward = vecSrc + dir * MapGrid.Width; MapGrid ptForward = new MapGrid(vecSrc + dir * MapGrid.Width); if(ptForward == ptSrc || (this[ptForward.x, ptForward.z] & validType) == 0) return false; } int i = 0; for(; (vecOriginDst - vecCur).magnitude > ShortestMoveDst; vecCur += dir) { if (ptCur != new MapGrid(vecCur)) { ptCur = new MapGrid(vecCur); // 遇到阻挡,不考虑起始点的阻挡,有可能会走进去 if((ptCur != ptSrc) && (this[ptCur.x, ptCur.z] & validType) == 0) { // 回退一小格,免得和阻挡格子太接近 if(i <= 1) vecDst = vecSrc; else vecDst -= dir; break; } // 到达目标点 if(ptCur == ptDst) { vecDst = vecOriginDst; break; } } vecDst = vecCur; i++; } return (vecDst - vecSrc).magnitude > ShortestMoveDst; }