// Takes a PT_XMLHashtable from PT_XMLReader of a <shot> entry in XML and // parses it into a Shot static public Shot ParseShotXML(PT_XMLHashtable xHT) { Shot sh = new Shot(); sh.position.x = float.Parse(xHT.att("x")); sh.position.y = float.Parse(xHT.att("y")); sh.position.z = float.Parse(xHT.att("z")); sh.rotation.x = float.Parse(xHT.att("qx")); sh.rotation.y = float.Parse(xHT.att("qy")); sh.rotation.z = float.Parse(xHT.att("qz")); sh.rotation.w = float.Parse(xHT.att("qw")); sh.target.x = float.Parse(xHT.att("tx")); sh.target.y = float.Parse(xHT.att("ty")); sh.target.z = float.Parse(xHT.att("tz")); return(sh); }
static public Shot ParseShotXML(PT_XMLHashtable xHT) { Shot sh = new Shot (); sh.position.x = float.Parse(xHT.att("x")); sh.position.y = float.Parse(xHT.att("y")); sh.position.z = float.Parse(xHT.att("z")); sh.rotation.x = float.Parse(xHT.att("qx")); sh.rotation.y = float.Parse(xHT.att("qy")); sh.rotation.z = float.Parse(xHT.att("qz")); sh.rotation.w = float.Parse(xHT.att("qw")); sh.target.x = float.Parse(xHT.att("tx")); sh.target.y = float.Parse(xHT.att("ty")); sh.target.z = float.Parse(xHT.att("tz")); return (sh); }
// Строим комнату основанную на room number. Альтернативная версия BuildRoom // которая выбирает roomXML основываясь на room num public void BuildRoom(string str) { PT_XMLHashtable roomHT = null; for (int i = 0; i < roomsXML.Count; i++) { roomHT = roomsXML[i]; if (roomHT.HasAtt("num")) { if (roomHT.att("num") == str) { BuildRoom(roomHT); return; } } } Utils.tr("ERROR", "LayoutTiles.BuildRoom()", "Room not found: ", str); }
}//EnemyFactory(string sType) public void BuildRoom(string rNumStr){ PT_XMLHashtable roomHT = null; for (int i = 0; i < roomsXML.Count; i++){ PT_XMLHashtable ht = roomsXML[i]; if (ht.att("num") == rNumStr){ roomHT = ht; break; }//end of if }//end of for loop if (roomHT == null){ Utils.tr("ERROR", "LayoutTiles.BuildRoom()", "Room not found: " + rNumStr); return; }//end of if BuildRoom(roomHT); }//end of BuildRoom(string rNumStr)
private Decorator GetDecorator(PT_XMLHashtable table) { var decorator = new Decorator { Type = table.att("type") ?? "pip", Flip = (table.att("flip") == "1"), Location = { x = float.Parse(table.att("x")), y = float.Parse(table.att("y")), z = float.Parse(table.att("z")) } }; if (table.HasAtt("scale")) { decorator.Scale = float.Parse(table.att("scale")); } return(decorator); }
// Build a room from an XML <room> entry public void BuildRoom(PT_XMLHashtable room) { // Get the texture names for the floors and walls from <room> attributes string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); int bossNumber = int.Parse(room.att("boss")); // Split the room into rows of tiles based on carriage returns in the // Rooms.xml file string[] roomRows = room.text.Split('\n'); // Trim tabs from the beginnings of lines. However, we're leaving spaces // and underscores to allow for non-rectangular rooms. enemiesHolder = new GameObject("EnemiesStore").transform; for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } string type, rawType, tileTexStr; int height; float maxY = roomRows.Length - 1; gridPositions.Clear(); // These loops scan through each tile of each row of the room for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { // Set defaults height = 0; tileTexStr = floorTexStr; // Get the character representing the tile type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": // empty space case "_": // empty space // Just skip over empty space continue; case ".": // default floor // Keep type="." break; case "|": // default wall height = 1; break; default: // Anything else will be interpreted as floor type = "."; break; } // Set the texture for floor or wall based on <room> attributes GameObject toInstantiate = null; Vector3 position = new Vector3(x - 1, maxY - y - 1, 0f); if (type == ".") { gridPositions.Add(position); toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)]; } else if (type == "|") { toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)]; } if (rawType == "S") { Instantiate(exit, position, Quaternion.identity); } else if (rawType == "X") { GameObject bossTile = bossTiles[bossNumber]; GameObject e = Instantiate(bossTile, position, Quaternion.identity) as GameObject; e.GetComponent <Enemy>().HasTheKey(); } else { try { int n = int.Parse(rawType); GameObject enemyTile = minions[n]; GameObject enemy = Instantiate(enemyTile, position, Quaternion.identity) as GameObject; enemy.transform.SetParent(enemiesHolder); } catch (Exception e) { } } GameObject instance = Instantiate(toInstantiate, position, Quaternion.identity) as GameObject; } } }
//Build a room from an XML <room> entry public void BuildRoom(PT_XMLHashtable room) { //Destroy any old tiles foreach (Transform t in tileAnchor) //Clear out old tiles. You can iterate over a Transform to get its children { Destroy(t.gameObject); } //Move the Mage out of the way Mage.S.pos = Vector3.left * 1000; //HACK: This keeps the Mage from accidentally triggering OnTriggerExit() on a Portal. OnTriggerExit() is sometimes inappropriately called Mage.S.ClearInput(); //Cancel any active mouse input and drags string rNumStr = room.att("num"); //Get the texture names for the floors and walls from <room> attributes string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); //Split the room into rows of tiles based on carriage returns in the Room.xml file string[] roomRows = room.text.Split('\n'); //Trim tabs from the beginnings of lines. However, we're leaving spaces and underscores to allow for non-rectangular rooms for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } //Clear the tiles Array tiles = new Tile[100, 100]; //Arbitrary max room size is 100 x 100 //Local fields Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List <Portal> portals = new List <Portal>(); //These loops scan through each tile of each row of the room for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { //Set defaults height = 0; tileTexStr = floorTexStr; //Get the character representing the tile type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": //empty space case "_": //empty space //Just skip over empty space continue; //Skips to the next iteration of the x loop case ".": //default floor //Keep type = "." break; case "|": //default wall height = 1; break; default: //Anything else will be interpreted as a floor type = "."; break; } //Set the texture for floor or wall based on <room> attributes if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } //Instantiate a new TilePrefab go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile>(); //Set the parent Transform to tileAnchor ti.transform.parent = tileAnchor; //Set the position of the tile ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; //Add ti to the tiles 2D Array //Set the type, height, and texture of the Tile ti.type = type; ti.height = height; ti.tex = tileTexStr; //If the type is still rawType, continue to the next iteration if (rawType == type) { continue; } //Check for specific entities in the room switch (rawType) { case "X": //Starting position for the Mage if (firstRoom) { Mage.S.pos = ti.pos; //Uses the Mage singleton roomNumber = rNumStr; //Setting roomNumber now keeps any portals from moving the Mage to them in this first room firstRoom = false; } break; case "0": //Numbers are room portals (up to F in hexadecimal) case "1": //This allows portals to be placed in the Rooms.xml file case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": //Instantiate a Portal GameObject pGO = Instantiate(portalPrefab) as GameObject; Portal p = pGO.GetComponent <Portal>(); p.pos = ti.pos; p.transform.parent = tileAnchor; //Attaching this to the tileAnchor means that the Portal will be Destroyed when a new room is built p.toRoom = rawType; portals.Add(p); break; default: //Try to see if there's an Enemy for that letter Enemy en = EnemyFactory(rawType); if (en == null) { break; //If there's not one, break out } //Set up the new enemy en.pos = ti.pos; //Make en a child of tileAnchor so it's deleted when the next room is loaded en.transform.parent = tileAnchor; en.typeString = rawType; break; } } } //Position the Mage foreach (Portal p in portals) { //If p.toRoom is the same as the room number the Mage just existed, then the Mage should enter this room through this Portal. //Alternatively, if firstRoom == true and there was no X in the room (as a default Mage starting point), move the Mage to //this Portal as a backup measure (if, for instance, you want to just load room number "5") if (p.toRoom == roomNumber || firstRoom) { //If there's an X in the room, firstRoom will be set to false by the time the code gets here Mage.S.StopWalking(); //Stop any Mage movement Mage.S.pos = p.pos; //Move Mage to this Portal location //Mage maintains her facing from the previous room, so there is no need to rotate her //in order for her to enter this room facing the right direction p.justArrived = true; //Tell the Portal that Mage has just arrived firstRoom = false; //Stops a second Portal in this room from moving the Mage to it } } //Finally, assign the roomNumber roomNumber = rNumStr; }
public void BuildRoom(PT_XMLHashtable room) { //destroy old tiles foreach (Transform t in tileAnchor) { Destroy(t.gameObject); } //move the player out of the way and reset them Mage.S.pos = Vector3.left * 1000; Mage.S.ClearInput(); string rNumStr = room.att("num"); //get the texture names for the room string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); //split the room into rows string[] roomRows = room.text.Split('\n'); for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } //clear tiles array tiles = new Tile[100, 100]; //fields for later Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List <Portal> portals = new List <Portal> (); //scan through each tile for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { height = 0; tileTexStr = floorTexStr; //Get tile character type = rawType = roomRows [y] [x].ToString(); switch (rawType) { case "": //Empty case "_": //Empty continue; case ".": //default floor break; case "|": //default wall height = 1; break; default: type = "."; break; } //Set floor/wall texture if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } //instantiate a new tile go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile> (); ti.transform.parent = tileAnchor; ti.pos = new Vector3(x, maxY - y, 0); tiles [x, y] = ti; //Set tile fields ti.type = type; ti.height = height; ti.tex = tileTexStr; //if type is still rawtype, continue if (rawType == type) { continue; } //Check for specific entities switch (rawType) { case "X": if (firstRoom) { Mage.S.pos = ti.pos; roomNumber = rNumStr; firstRoom = false; } break; case "0": // These numbers are the room portals. They are hexadecimal case "1": // This allows them to be placed in the Rooms.xml file case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": GameObject pGO = Instantiate(portalPrefab) as GameObject; Portal p = pGO.GetComponent <Portal>(); p.pos = ti.pos; p.transform.parent = tileAnchor; p.toRoom = rawType; portals.Add(p); break; default: //is there an enemy Enemy en = EnemyFactory(rawType); if (en == null) { break; } en.pos = ti.pos; en.transform.parent = tileAnchor; en.typeString = rawType; break; } } } //Position the Mage foreach (Portal p in portals) { if (p.toRoom == roomNumber || firstRoom) { Mage.S.StopWalking(); Mage.S.pos = p.pos; p.justArrived = true; firstRoom = false; } } roomNumber = rNumStr; }
public void BuildLevel(PT_XMLHashtable level) { // Destroy any old Tiles foreach (Transform t in tileAnchor) { // Clear out old tiles // ^ You can iterate over a Transform to get its children Destroy(t.gameObject); } string lNumStr = level.att("num"); int x_start = int.Parse (level.att ("x_start")); int y_start = int.Parse (level.att ("y_start")); int x_goal = int.Parse (level.att ("x_goal")); int y_goal = int.Parse (level.att ("y_goal")); string[] levelRows = level.text.Split('\n'); for (int i=0; i<levelRows.Length; i++) { levelRows[i] = levelRows[i].Trim('\t'); } // Clear the tiles Array tiles = new Tile[ 100, 100 , 10 ]; // Arbitrary max room size is 100x100x10 // Declare a number of local fields that we'll use later Tile ti; string type; GameObject go; int height; int z_start = -1; int[,] map = new int[100,100]; float maxY = levelRows.Length-1; // These loops scan through each tile of each row of the room for (int y=0; y<levelRows.Length; y++) { for (int x=0; x<levelRows[y].Length; x++) { // Set defaults height = 0; // Get the character representing the tile type = levelRows [y] [x].ToString (); switch (type) { case ".": case " ": case "_": case "0": // cualquiera de estas cosas se interpreta como hueco height = 0; map[x,y] = 0; break; default:// todo lo demas sera un numero que indica la altura height = int.Parse(type); map[x,y] = height; for (int h = 0; h < height; h++) { // pintar un cubo por cada altura if (y == y_goal && x == x_goal && h == height-1){ // coincide con las coordenadas objetivo go = Instantiate (goalPrefab) as GameObject; }else{ // casilla normal go = Instantiate (tilePrefab) as GameObject; } ti = go.GetComponent<Tile> (); // Set the parent Transform to tileAnchor ti.transform.parent = tileAnchor; // Set the position of the tile ti.pos = new Vector3 (x,h,y); tiles [x, h, y] = ti; // Add ti to the tiles 2D Array // Set the type, height, and texture of the Tile ti.type = "baldosa"; } if (y == y_start && x == x_start){ z_start = height; } break; } } } Game.S.setMap (map, x_goal, y_goal, x_start, y_start, z_start ); }
public void BuildRoom(PT_XMLHashtable room) { // Destroy any old Tiles foreach (Transform t in tileAnchor) { // Clear out old tiles // ^ You can iterate over a Transform to get its children Destroy(t.gameObject); } // Move the Mage out of the way Mage.S.pos = Vector3.left * 1000; // ^ This keeps the Mage from accidentally triggering OnTriggerExit() on // a Portal. In my testing, I found that OnTriggerExit was being called // at strange times. Mage.S.ClearInput(); // Cancel any active mouse input and drags string rNumStr = room.att("num"); // Get the texture names for the floors and walls from <room> attributes string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); // Split the room into rows of tiles based on carriage returns in the // Rooms.xml file string[] roomRows = room.text.Split('\n'); // Trim tabs from the beginnings of lines. However, we're leaving spaces // and underscores to allow for non-rectangular rooms. for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } // Clear the tiles Array tiles = new Tile[100, 100]; // Arbitrary max room size is 100x100 // Declare a number of local fields that we'll use later Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List<Portal> portals = new List<Portal>(); // These loops scan through each tile of each row of the room for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { // Set defaults height = 0; tileTexStr = floorTexStr; // Get the character representing the tile type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": // empty space case "_": // empty space // Just skip over empty space continue; case ".": // default floor // Keep type="." break; case "|": // default wall height = 1; break; default: // Anything else will be interpreted as floor type = "."; break; } // Set the texture for floor or wall based on <room> attributes if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } // Instantiate a new TilePrefab go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent<Tile>(); // Set the parent Transform to tileAnchor ti.transform.parent = tileAnchor; // Set the position of the tile ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; // Add ti to the tiles 2D Array // Set the type, height, and texture of the Tile ti.type = type; ti.height = height; ti.tex = tileTexStr; // If the type is still rawType, continue to the next iteration if (rawType == type) continue; // Check for specific entities in the room switch (rawType) { // 1 case "X": // Starting position for the Mage // Mage.S.pos = ti.pos; // Uses the Mage Singleton if (firstRoom) { Mage.S.pos = ti.pos; // Uses the Mage Singleton roomNumber = rNumStr; // ^ Setting roomNumber now keeps any portals from // moving the Mage to them in this first room. firstRoom = false; } break; case "0": // Numbers are room portals (up to F in hexadecimal) case "1": // This allows portals to be placed in the Rooms.xml file case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": // Instantiate a Portal GameObject pGO = Instantiate(portalPrefab) as GameObject; Portal p = pGO.GetComponent<Portal>(); p.pos = ti.pos; p.transform.parent = tileAnchor; // ^ Attaching this to the tileAnchor means that the Portal // will be Destroyed when a new room is built p.toRoom = rawType; portals.Add(p); break; default: // Try to see if there's an Enemy for that letter Enemy en = EnemyFactory(rawType); if (en == null) break; // If there's not one, break out // Set up the new Enemy en.pos = ti.pos; // Make en a child of tileAnchor so it's deleted when the // next room is loaded. en.transform.parent = tileAnchor; en.typeString = rawType; break; } // More to come here... } } // Position the Mage foreach (Portal p in portals) { // If p.toRoom is the same as the room number the Mage just exited, // then the Mage should enter this room through this Portal // Alternatively, if firstRoom == true and there was no X in the // room (as a default Mage starting point), move the Mage to this // Portal as a backup measure (if, for instance, you want to just // load room number "5") if (p.toRoom == roomNumber || firstRoom) { // ^ If there's an X in the room, firstRoom will be set to false // by the time the code gets here Mage.S.StopWalking(); // Stop any Mage movement Mage.S.pos = p.pos; // Move _Mage to this Portal location // _Mage maintains her facing from the previous room, so there // is no need to rotate her in order for her to enter this room // facing the right direction. p.justArrived = true; // ^ Tell the Portal that Mage has just arrived. firstRoom = false; // ^ Stops a 2nd Portal in this room from moving the Mage to it } } // Finally assign the roomNumber roomNumber = rNumStr; }
public void BuildRoom(PT_XMLHashtable room) { foreach (Transform t in tileAnchor) { Destroy(t.gameObject); } Mage.S.pos = Vector3.left * 1000; Mage.S.ClearInput(); string rNumStr = room.att("num"); string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); string[] roomRows = room.text.Split('\n'); for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } tiles = new Tile [100, 100]; Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List <Portal> portals = new List <Portal>(); for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { height = 0; tileTexStr = floorTexStr; type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": case "_": continue; case ".": break; case "|": height = 1; break; default: type = "."; break; } if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile>(); ti.transform.parent = tileAnchor; ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; ti.type = type; ti.height = height; ti.tex = tileTexStr; if (rawType == type) { continue; } switch (rawType) { case "X": if (firstRoom) { Mage.S.pos = ti.pos; roomNumber = rNumStr; firstRoom = false; } break; case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": GameObject pGO = Instantiate(portalPrefab) as GameObject; Portal p = pGO.GetComponent <Portal>(); p.pos = ti.pos; p.transform.parent = tileAnchor; p.toRoom = rawType; portals.Add(p); break; default: Enemy en = EnemyFactory(rawType); if (en == null) { break; } en.pos = ti.pos; en.transform.parent = tileAnchor; en.typeString = rawType; break; } } } foreach (Portal p in portals) { if (p.toRoom == roomNumber || firstRoom) { Mage.S.StopWalking(); Mage.S.pos = p.pos; p.justArrived = true; firstRoom = false; } } roomNumber = rNumStr; }
public void BuildRoom(PT_XMLHashtable room) { // Разрушаем старые плитки foreach (Transform t in tileAnchor) { Destroy(t.gameObject); } // Двигаем мага подальше Mage.S.pos = Vector3.left * 1000; // Чтобы случайно не затригерил ничего Mage.S.ClearInput(); // Очищаем любые фигнюшки на маге string rNumStr = room.att("num"); // Выбираем текстуры для поля и для стен string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); // Делим комнату на строки, основываясь на возврат каретки в Room.xml string[] roomRows = room.text.Split('\n'); // Убираем табы, но оставляем пробелы и нижние подчеркивания для непрямоугольных комнат for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } // Очищаем массив плит tiles = new Tile[100, 100]; // Произвольный размер комнаты // Объявляем некоторые локальные поля, которые будут использоваться позже Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List <Portal> portals = new List <Portal>(); // Этот цикл сканирует в каждой строчке каждую плитку for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { // Задаём базовые значения height = 0; tileTexStr = floorTexStr; // Достаём символ, который определяет плитку type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": // Пустой пробел case "_": // Пустой пробел // Просто пропускаем continue; case ".": // Базовый пол // Сохраняем тип = "." break; case "|": // Базовая стена height = 1; break; default: // Что то другое будет рассматриваться как пол type = "."; // rawType будет какой-то финтифлюшкой, а этот тип будет похож на стену break; // таким образом автор потом различит объекты - не интерьер } // Задаём текстуру для пола или стены основываясь на аттрибутах if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } // Создаём новый TilePrefab go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile>(); // Задаём родителя ti.transform.parent = tileAnchor; // Задаём позицию ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; // Добавляем плитку в наш массив // Задаём тип, высоту и текстуру ti.type = type; ti.height = height; ti.tex = tileTexStr; // Если тип до сих пор равен rawType, идём к след. итерации if (rawType == type) { continue; } // Проверяем специфичные создания в комнате switch (rawType) { case "X": // Стартовая позиция для мага //Mage.S.pos = ti.pos; if (firstRoom) { Mage.S.pos = ti.pos; // Используем синглтон мага roomNumber = rNumStr; firstRoom = false; } break; case "0": // Номера это порталы в комнату case "1": // Позволяет распологать порталыв Rooms.xml case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": // Создаём портал GameObject pGO = Instantiate(portalPrefab) as GameObject; // Когда комната сменится, портал тоже удалится pGO.transform.parent = tileAnchor; Portal p = pGO.GetComponent <Portal>(); p.pos = ti.pos; p.toRoom = rawType; pGO.GetComponent <Collider>().isTrigger = false; pGO.GetComponent <Collider>().isTrigger = true; portals.Add(p); break; default: // Ищем есть ли враг для этой буквы Enemy en = EnemyFactory(rawType); if (en == null) { break; // Если нет подходящего, возвращаем } // Устанавливаем врага en.pos = ti.pos; // Делаем врага дитём tileAnchor так он удалится на след.комнате en.transform.parent = tileAnchor; en.typeString = rawType; break; } // Дальше лучше :) } } // Располагаем мага foreach (Portal p in portals) { if (p.toRoom == roomNumber || firstRoom) { Mage.S.StopWalking(); // Прекращаем любое движение мага Mage.S.pos = p.pos; p.justArrived = true; firstRoom = false; } } roomNumber = rNumStr; }
//Build a room from an XML <room> entry public void BuildRoom(PT_XMLHashtable room) { //Destroy any old tiles foreach (Transform t in tileAnchor) { Destroy(t.gameObject); } //Move the mage out of the way Mage.S.pos = Vector3.left * 1000; Mage.S.ClearInput(); string rNumStr = room.att("num"); //Get the texture names for the floors and walls from <room> attribute string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); //Split the room into rows of tiles based on line breaks in Rooms.xml string[] roomRows = room.text.Split('\n'); //Trim tabs from the beginnings of lines. However, we're leaving spaces and underscores to allow for non-rectangular rooms. for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } //Clear the tiles array tiles = new Tile[100, 100]; //Arbitrary max room size is 100X100 //Declare a number of local fields that we'll use later Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List <Portal> portals = new List <Portal>(); //These loops scan through each tile of each row of the room for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { //Set defaults height = 0; tileTexStr = floorTexStr; //Get the character representing the tile type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": case "_": //skip over empty space continue; case ".": // default floor //Keep type "." break; case "|": //default wall height = 1; break; default: //Anything else will be interpreted as floor break; } //Set the texture for floor or wall based on <room> attributes if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } //Instantiate a new TilePrefab go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile>(); //Set the parent Transform to tileAnchor ti.transform.parent = tileAnchor; //set the position of the tile ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; // Add ti to the tiles 2D array //Set the type, height and texture of the Tile ti.type = type; ti.height = height; ti.tex = tileTexStr; //if the type is still rawType, continue to the next iteration ////**********//if (rawType == type) //************** continue; //Check for specific entities in the room switch (rawType) { case "X": // Starting position for the Mage //Mage.S.pos = ti.pos; if (firstRoom) { Mage.S.pos = ti.pos; roomNumber = rNumStr; firstRoom = false; } break; case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": //instantiate a portal GameObject pGO = Instantiate(portalPrefab) as GameObject; Portal p = pGO.GetComponent <Portal>(); p.pos = ti.pos; p.transform.parent = tileAnchor; // attaching this to the tileAnchor means that the Portal will be destroyed when a new room is built p.toRoom = rawType; portals.Add(p); break; default: //Try to see if theres an enemy for that letter IEnemy en = EnemyFactory(rawType); if (en == null) { break; } en.pos = ti.pos; //Make en a child of tileAnchor so it's deleted when the next room is loaded en.transform.parent = tileAnchor; en.typeString = rawType; break; } } } //Position the Mage foreach (Portal p in portals) { //if p.toRoom is the same as the room number the Mage just exited //then the Mage should enter this room through this Portal //Alternatively, if firstRoom == true and there was no X in the //room (as a default Mage starting point), move the mage to this //Portal as a backup (if you start from a room different from 0 if (p.toRoom == roomNumber || firstRoom) { //if there's an X in the Room, firstRoom will be set to false Mage.S.StopWalking(); Mage.S.pos = p.pos; //move mage to this portal location //Mage maintains facing from the previous room, so there //is no need to rotate to enter this room to face the right direction p.justArrived = true; firstRoom = false; // stops the mage to move to second portal } } roomNumber = rNumStr; }
//从XML<room>入口建立一个room对象 public void BuildRoom(PT_XMLHashtable room) { //销毁旧的Tiles foreach (Transform t in tileAnchor) { Destroy(t.gameObject); } //Mage离开 //Mage.S.pos = Vector3.left * 1000; GameObject.FindWithTag("Mage").transform.position = Vector3.left * 1000; Mage.S.ClearInput(); //---------------------------------------------------------------- string rNumStr = room.att("num"); //从<room>属性获取floors和walls的文本名 string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); //基于Rooms.xml文件中返回的carriage值将room分行 string[] roomRows = room.text.Split('\n'); //从每行起始修剪制表符 for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } //清空tiles数组 tiles = new Tile[100, 100]; //一些局部变量 Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; List <Portal> portals = new List <Portal>(); //循环遍历每个room的每行中的tile for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { //设置默认值 height = 0; tileTexStr = floorTexStr; //获取代表tile的字符 type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": //跳过空格 case "_": continue; case ".": //默认floor break; case "|": //默认wall height = 1; break; default: //其他任何都作为floor type = "."; break; } //基于<room>属性设置floors和walls文本 if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } //初始化新的TilePrefab对象 go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile>(); //设置父Transform为tileAnchor ti.transform.parent = tileAnchor; //设置tile坐标 ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; //设置Tile的类型,高度和文本 ti.type = type; ti.height = height; ti.tex = tileTexStr; //如果类型是rawType,则继续下一个操作 if (rawType == type) { continue; } //检查room中指定的对象实例 switch (rawType) { //Mage的起始位置 case "X": //出错代码:Mage.S.pos = ti.pos; //报错信息:单例化无法设置 //解决措施: //GameObject.FindWithTag("Mage").transform.position = ti.pos; if (firstRoom) { //Mage.S.pos = ti.pos; GameObject.FindWithTag("Mage").transform.position = ti.pos; roomNumber = rNumStr; firstRoom = false; } break; case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "A": case "B": case "C": case "D": case "E": case "F": //实例化Portal,设置地点,归于tileAnchor下,赋通向房间的值, GameObject pGo = Instantiate(portalPrefab) as GameObject; //魔法阵的z方向需为负值,否则与地面齐平被覆盖 //产生问题:设置魔法阵后不可单击魔法门位置产生标记 //问题分析:Mage.cs内关于魔法阵识别问题,即便MouseTap()内判断 //解决方案:将魔法阵PortalPrefab_MagicCircle的tag设置为Ground,即可在MouseTap内将其归类于Ground进行识别 Portal p = pGo.GetComponent <Portal>(); p.pos = ti.pos + new Vector3(0, 0, -0.3f); p.transform.parent = tileAnchor; p.toRoom = rawType; portals.Add(p); break; default: //确认是否有Enemy对应的字母 Enemy en = EnemyFactory(rawType); if (en == null) { break; } //设置新的Enemy en.pos = ti.pos; en.transform.parent = tileAnchor; en.typeString = rawType; break; } // } } //定位Mage foreach (Portal p in portals) { //如果p.toRoom与Mage刚离开的房间号相同,则Mage应从该入口交替进入房间 //此外,若firstroom==true且房间内无X坐标,则应该让Mage移动到该入口作为备用手段 if (p.toRoom == roomNumber || firstRoom) { //若房间内没有X坐标,则将firstroom设置为false Mage.S.StopWalking(); Mage.S.pos = p.pos; //Mage保持面向先前的房间 p.justArrived = true; //通知Portal,Mage刚进入 firstRoom = false; // } } //最后分配roomNumber roomNumber = rNumStr; }
// ------------------------------------- // -------------- METODOS -------------- // ------------------------------------- /* * carga el tablero definido en el xml pasado por paramtero */ public void readLayout(string xmlText) { //Antes de hacer nada, reseteamos el tablero this.resetLayout(); xmlr = new PT_XMLReader(); xmlr.Parse(xmlText); xml = xmlr.xml["xml"][0]; //1.- Definiciones de las dimensiones PT_XMLHashtable dimensions = xml["dimensions"][0]; //1.1 - tablero this.size_x = int.Parse(dimensions ["board"][0].att("length_x")); this.size_z = int.Parse(dimensions ["board"][0].att("length_z")); this.scale = float.Parse(dimensions ["board"][0].att("scale")); //1.2 - bloque this.blockSize = float.Parse(dimensions ["block"][0].att("size")); this.blockSeparation = float.Parse(dimensions ["block"][0].att("separation")); //1.3 - cover this.coverSize = float.Parse(dimensions ["cover"][0].att("size")); //1.4 - robot this.robotHeight = float.Parse(dimensions ["robot"][0].att("height")); //2.- Celdas por defecto this.default_height = int.Parse(xml ["board"] [0].att("default_height")); this.initBoard(this.default_height, this.size_x, this.size_z); this.emptyCurrentBoard(); //3.- Definimos de las celdas PT_XMLHashList tileX = xml["board"][0]["tile"]; for (int i = 0; i < tileX.Count; i++) { int x, z; x = int.Parse(tileX[i].att("x")); z = int.Parse(tileX[i].att("z")); this.board_def[x, z].height = int.Parse(tileX[i].att("height")); string attr = (tileX[i].HasAtt("attr")) ? tileX[i].att("attr") : "none"; switch (attr) { case "goal": this.board_def[x, z].type = TileType.goal; Director.S.totalGoals++; break; default: this.board_def[x, z].type = TileType.normal; break; } this.board_def[x, z].isOn = false; //leemos movimientos. string mvto_t = (tileX[i].HasAtt("mvto")) ? tileX[i].att("mvto") : "none"; switch (mvto_t) { case "h": this.board_def[x, z].typeMvto = tipoMovimiento.horizontal; this.board_def[x, z].nSteps = int.Parse(tileX[i].att("nsteps")); this.board_def[x, z].createStates(); break; case "v": this.board_def[x, z].typeMvto = tipoMovimiento.vertical; this.board_def[x, z].nSteps = int.Parse(tileX[i].att("nsteps")); this.board_def[x, z].createStates(); break; case "f": this.board_def[x, z].typeMvto = tipoMovimiento.frente; this.board_def[x, z].nSteps = int.Parse(tileX[i].att("nsteps")); this.board_def[x, z].createStates(); break; case "none": this.board_def[x, z].typeMvto = tipoMovimiento.none; break; } //Cada celda ocupa su posicion original al comenzar el juego this.current_board[x, z] = new PairInt(x, z); } //4.- Posicion inicial del robot. PT_XMLHashtable robot = xml["robot"][0]["position"][0]; this.robotPosition = new Vector3(float.Parse(robot.att("x")), float.Parse(robot.att("y")), float.Parse(robot.att("z"))); robot = xml["robot"][0]["rotation"][0]; this.robotRotation = new Vector3(float.Parse(robot.att("x")), float.Parse(robot.att("y")), float.Parse(robot.att("z"))); //Transformamos la rotacion en el intervalo [0,360) while (this.robotRotation.y < 0) { this.robotRotation.y += 360; } while (this.robotRotation.y >= 360) { this.robotRotation.y -= 360; } }
public void BuildRoom(PT_XMLHashtable room) { string floorTexStr = room.att("floor"); string wallTexStr = room.att("wall"); string[] roomRows = room.text.Split('\n'); for (int i = 0; i < roomRows.Length; i++) { roomRows[i] = roomRows[i].Trim('\t'); } tiles = new Tile[100, 100]; Tile ti; string type, rawType, tileTexStr; GameObject go; int height; float maxY = roomRows.Length - 1; for (int y = 0; y < roomRows.Length; y++) { for (int x = 0; x < roomRows[y].Length; x++) { height = 0; tileTexStr = floorTexStr; type = rawType = roomRows[y][x].ToString(); switch (rawType) { case " ": case "_": continue; case ".": // default floor break; case "|": // default wall height = 1; break; default: type = "."; break; } if (type == ".") { tileTexStr = floorTexStr; } else if (type == "|") { tileTexStr = wallTexStr; } go = Instantiate(tilePrefab) as GameObject; ti = go.GetComponent <Tile>(); ti.transform.parent = tileAnchor; ti.pos = new Vector3(x, maxY - y, 0); tiles[x, y] = ti; ti.type = type; ti.height = height; ti.tex = tileTexStr; if (rawType == type) { continue; } switch (rawType) { case "X": Mage.S.pos = ti.pos; break; } //More here } } }