void Awake() { connectedRoads = new List<Road>(); roadMgr = FindObjectOfType<RoadManager>(); highlighter = gameObject.AddComponent<Highlighter>(); gameObject.name = string.Format("Node{0}", gameObject.GetInstanceID()); }
void Awake() { if (s_instance == null) { s_instance = this; } else { if (s_instance!=this) { Destroy(gameObject); } } }
// Use this for initialization void Awake() { score = 0; playerController = GameObject.Find("Player").GetComponent<PlayerController>(); roadManager = GameObject.Find("RoadManager").GetComponent<RoadManager>(); spawner = GameObject.Find("Spawner").GetComponent<Spawner>(); scoreText = GameObject.Find("ScoreText").GetComponent<Text>(); restartText = GameObject.Find("ScoreCanvas").transform.GetChild(1).GetComponent<Text>(); restartText.enabled = false; }
void Start() { AudioSource[] sources = GetComponents<AudioSource>(); mainSong = sources[0]; time = 0; waveStartTime = restDuration; waveCounter = 1; countdown = GameObject.Find("GameStuff").GetComponent<Countdown>(); countdown.SetCountdownDuration(countdownDuration); roadManager = GameObject.Find("RoadManager").GetComponent<RoadManager>(); lastPlayerNode = roadManager.playerNode; status = Status.Rest; initFov = Camera.main.fov; StartCoroutine(StartSongDelay(5)); }
void Start() { AudioSource[] sources = GetComponents<AudioSource>(); engineSound = sources[2]; engineStart = sources[3]; roadManager = GameObject.Find("RoadManager").GetComponent<RoadManager>(); ship = transform.FindChild("Ship"); time = 0; direction = transform.forward * speed; offset = 0; basePosition = new Vector3(0, 0, 0); tiltTime = 0; initSpeed = speed; speed = initSpeed / 1.5f; engineStart.Play(); engineSound.loop = true; engineSound.Play(); }
public override void Awake() { StageController.Instance = this; var go = GameObject.Find("GameRoot"); RoadManager roadManager = null; if (go != null) { roadManager = go.GetComponent <RoadManager>(); if (roadManager != null) { // init ink from roadManager UpdateInk(roadManager.Ink); } } // handle clear event this.UpdateAsObservable() .Where(_ => this.unityChan.transform.position.x >= this.stageClearPoint.position.x) .First() .Subscribe(_ => { this.IsCleared = true; // after 2s Observable.Timer(TimeSpan.FromSeconds(2f)) .Subscribe(__ => { AppController.Instance.SetResult(this.Coin, this.Damage, roadManager.UsedInk); Application.LoadLevel("Result"); }); }); this.Coin = 0; base.Awake(); }
// Start is called before the first frame update void Start() { _resourceManager = FindObjectOfType <ResourceManager>(); if (OilExtractor.ExtractedOilSlick.type == OilSlickType.Land) { OilVehicle = OilTruck; LoadedOilCapacity = 100f; } else { OilVehicle = OilTanker; LoadedOilCapacity = 1_000f; } //OilVehicle.SetActive(true); //OilVehicle.transform.position = OilExtractor.DockingArea.transform.position; City.RegisterTradeRoute(this); OilExtractor.RegisterTradeRoute(this); _roadManager = OilExtractor.ExtractedOilSlick.type == OilSlickType.Land ? GameObject.FindGameObjectWithTag("TruckRoadManager").GetComponent <RoadManager>() : GameObject.FindGameObjectWithTag("SeaLaneManager").GetComponent <RoadManager>(); _roadManager.GenerateTradeRoutePath(this); }
public void SpawnVehicle() { if (!bIsSpawner) { return; } if (DijkstraTable.Table.Count == 0) { DijkstraTable = RoadManager.CalculatePathTable(this); } Connection selectedRoad = Roads[0]; GameObject vehicleObject = Instantiate(Resources.Load("TestVehiclePrefab") as GameObject); Vehicle veh = vehicleObject.GetComponent <Vehicle>(); veh.StartIntersectionPoint = this; while (veh.Route.Count <= 2) { veh.EndIntersectionPoint = RoadManager.GetRandomOtherIntersectionPoint(this); veh.Route = RoadManager.CalculateRoute(DijkstraTable, veh.StartIntersectionPoint, veh.EndIntersectionPoint); } veh.ConvertRouteToPath(); }
public void RoadManagerTestsGetStatusWithoutNeighbor() { var results = RoadManager.GetRoadNeighborStatus(new Vector3(27, 0, 27), _grid, null); Assert.AreEqual(0, results); }
private void checkBox1_CheckedChanged(object sender, EventArgs e) { RoadManager.setContinuousCreationMode(checkBox1.Checked); }
void Awake() { _Instance = this; }
public void RoadManagerTestsGetStatusNeighbourUpRight() { var result = RoadManager.GetRoadNeighboursStatus(new Vector3(3, 0, 3), grid, null); Assert.AreEqual((int)Direction.Up | (int)Direction.Right, result); }
public void RoadManagerTestsGetStatusNoNeighbours() { var result = RoadManager.GetRoadNeighboursStatus(new Vector3(27, 0, 27), grid, null); Assert.AreEqual(0, result); }
public void RoadManagerTestsGetStatusNeighbourDownUpLeftRight() { var result = RoadManager.GetRoadNeighboursStatus(new Vector3(6, 0, 6), grid, null); Assert.AreEqual((int)Direction.Up | (int)Direction.Down | (int)Direction.Left | (int)Direction.Right, result); }
public void RoadManagerTestsGetStatusNeighborIsDownRight() { var results = RoadManager.GetRoadNeighborStatus(new Vector3(3, 0, 9), _grid, null); Assert.AreEqual((int)Direction.Down | (int)Direction.Right, results); }
void DFSNextRoad(Vector2Int currTile) //get the next block to go { RoadManager roadManager = MapManager.GetInstance().GetRoadManager(); if (roadManager == null) { return; } List <Vector2Int> neighbourRoads = new List <Vector2Int>(); //check up first, if never visited and theres a tile there add it Vector2Int newGridoffsetPos = currTile + new Vector2Int(0, 1); if (roadManager.CheckMapAvailability(newGridoffsetPos) && !m_VistedRoads.ContainsKey(newGridoffsetPos)) { neighbourRoads.Add(newGridoffsetPos); } //check down newGridoffsetPos = currTile + new Vector2Int(0, -1); if (roadManager.CheckMapAvailability(newGridoffsetPos) && !m_VistedRoads.ContainsKey(newGridoffsetPos)) { neighbourRoads.Add(newGridoffsetPos); } //check right newGridoffsetPos = currTile + new Vector2Int(1, 0); if (roadManager.CheckMapAvailability(newGridoffsetPos) && !m_VistedRoads.ContainsKey(newGridoffsetPos)) { neighbourRoads.Add(newGridoffsetPos); } //check left newGridoffsetPos = currTile + new Vector2Int(-1, 0); if (roadManager.CheckMapAvailability(newGridoffsetPos) && !m_VistedRoads.ContainsKey(newGridoffsetPos)) { neighbourRoads.Add(newGridoffsetPos); } if (neighbourRoads.Count == 0) //if theres nothing { //look into the queue to see if theres any other previous roads //if queue is empty, reset the position to NPC current tile and reset the visited list if (m_RoadsQueue.Count == 0) { m_VistedRoads.Clear(); DFSNextRoad(m_CurrentTile); } else { int lastAddedIndex = m_RoadsQueue.Count - 1; Vector2Int prev = m_RoadsQueue[lastAddedIndex]; m_RoadsQueue.RemoveAt(lastAddedIndex); //remove the last element added InitNextTile(prev); } } else //go to next neighbouring tile { m_RoadsQueue.Add(m_CurrentTile); int randomNeighbourIndex = Random.Range(0, neighbourRoads.Count); InitNextTile(neighbourRoads[randomNeighbourIndex]); } }
private void button4_Click(object sender, EventArgs e) { RoadManager.maskSelectedRoadTerrain(); }
private void button5_Click(object sender, EventArgs e) { RoadManager.smoothSelectedRoadTerrain(); }
private void button3_Click(object sender, EventArgs e) { RoadManager.snapSelectedRoadToTerrain(); }
private void button2_Click(object sender, EventArgs e) { RoadManager.collapseSelectedPoints(); }
private void button1_Click(object sender, EventArgs e) { RoadManager.splitSelectedPoints(); }
private void checkBox2_CheckedChanged(object sender, EventArgs e) { RoadManager.setSnapToPrimeMode(checkBox2.Checked); }
public void RoadManagerTestsGetStatusNeighborIsOnTheLeft() { var results = RoadManager.GetRoadNeighborStatus(new Vector3(18, 0, 6), _grid, null); Assert.AreEqual((int)Direction.Left, results); }
public void RoadManagerTestsGetStatusNeighborIsUp() { var results = RoadManager.GetRoadNeighborStatus(new Vector3(6, 0, 0), _grid, null); Assert.AreEqual((int)Direction.Up, results); }
private static int showRoadNowNum = 0;//当前显示到的路径的长度 void Awake() { instance = this; roadMaker = new GeneralRoadMaker(); }
public NetInfoLane(NetInfo.Lane lane, RoadManager.VehicleType vehicleTypes, SpecialLaneType specialLaneType = SpecialLaneType.None) : this(vehicleTypes, specialLaneType) { CopyAttributes(lane); }
// Start is called before the first frame update void Start() { roadSpawner = GetComponent <RoadManager>(); }
public void RoadManagerTestsGetNeighboursRight() { var result = RoadManager.GetRoadNeighboursForPosition(grid, new Vector3Int(0, 0, 6)); Assert.IsTrue(result.ContainsKey(new Vector3Int(3, 0, 6))); }
private void Spawn() { RoadManager.NumberOfVehicles++; RoadManager.GetRandomIntersectionPoint().SpawnVehicle(); }
public void RoadManagerTestsGetStatusNeighbourDownLeft() { var result = RoadManager.GetRoadNeighboursStatus(new Vector3(15, 0, 9), grid, null); Assert.AreEqual((int)Direction.Down | (int)Direction.Left, result); }
public NetInfoLane(RoadManager.VehicleType vehicleTypes, SpecialLaneType specialLaneType = SpecialLaneType.None) { this.m_allowedVehicleTypes = vehicleTypes; this.m_specialLaneType = specialLaneType; }
private void OnEnable() { roadManager = GameObject.FindObjectOfType <RoadManager>(); }
private void readConnection(JsonTextReader reader, JsonSerializer serializer, RoadManager roads, List <Node> nodes, out Node start, out Vector3 startTangent, out Vector3 startOffset) { start = null; startTangent = new Vector3(float.NaN, float.NaN, float.NaN); startOffset = new Vector3(float.NaN, float.NaN, float.NaN); if (reader.Read()) { if (reader.TokenType == JsonToken.StartObject) { int depth = reader.Depth; do { if (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { switch ((string)reader.Value) { case Constants.TAG_SEGMENT_CONNECTION_NODE: { int nodeID = reader.ReadAsInt32() ?? -1; start = nodes[nodeID]; } break; case Constants.TAG_SEGMENT_CONNECTION_TANGENT: { if (reader.Read()) { startTangent = serializer.Deserialize <Vector3D>(reader); } } break; case Constants.TAG_SEGMENT_CONNECTION_OFFSET: { if (reader.Read()) { startOffset = serializer.Deserialize <Vector3D>(reader); } } break; } } } } while (reader.Depth > depth); } } }
/**********************************************************************************/ // функция генерирует внутренности блока // // порядок генерации объектов: // - Здания // - Дороги // - Генерируемое окружение /**********************************************************************************/ void GenerateBlockContent(GameObject block, BlockDescriptor descriptor, int x, int y) { // определяемся с ограничениями на соединение дорог RoadManager.GetInstance().SetRoadRulesToBlock(descriptor, x, y); // обновляем карту занятых и свободных клеток descriptor.UpdateFreeSpaceMap(SizeOfBlocks); // определяем тип блока для генерации Base.BLOCK_TYPE blockToGenerate = GetBlockTypeToGenerate(); // олучаем настройки для данного блока из библиотеки блоков BlockSettings settingsForGeneration = BlockLibrary.GetInstance().GetBlockSettings(blockToGenerate); // устанавливаем здания // для это выбираем его(их) из имеющейся коллекции List <GameObject> toInstantiateCollection = GetBuildingToInstance(settingsForGeneration); foreach (GameObject toInstantiate in toInstantiateCollection) { // получаем контроллер у объекта шаблона, он нам потребуется для определения размеров здания BuildingController bcOfPattern = toInstantiate.GetComponent <BuildingController>(); // пробуем установить здание в блок bool success = false; int attempts = 10; while (!success && attempts > 0) { int xBuildingSize = bcOfPattern.XBuildingSize; int yBuildingSize = bcOfPattern.YBuildingSize; int xCorToPlace = Random.Range(0, (descriptor.xSize * SizeOfBlocks) - xBuildingSize + 1); int yCorToPlace = Random.Range(0, (descriptor.ySize * SizeOfBlocks) - yBuildingSize + 1); bool isPossible = true; // проверяем тушку здания for (int xCorToCheck = xCorToPlace; xCorToCheck < xCorToPlace + xBuildingSize; xCorToCheck++) { for (int yCorToCheck = yCorToPlace; yCorToCheck < yCorToPlace + yBuildingSize; yCorToCheck++) { if (descriptor.FreeSpaceMap[xCorToCheck, yCorToCheck] != true) { isPossible = false; } } } // проверяем точку выхода из здания if (isPossible) { Point roadPoint = new Point(xCorToPlace, yCorToPlace) + bcOfPattern.RoadPoint; if (roadPoint.x < 0 || roadPoint.y < 0 || roadPoint.x >= SizeOfBlocks || roadPoint.y >= SizeOfBlocks) { isPossible = false; } else { if (descriptor.FreeSpaceMap[roadPoint.x, roadPoint.y] != true) { isPossible = false; } } } // если получилось подобрать координаты, устанавливаем новое здание в позицию и выходим из цикла if (isPossible) { // правильные координаты будут выставлены несколькими шагами дальше через localPosition GameObject instance = Instantiate(toInstantiate, new Vector3(0.0f, 0.0f, 0.0f), Quaternion.identity) as GameObject; // устанавливаем в родителя instance.transform.SetParent(block.transform); instance.transform.localPosition = new Vector3((float)(xCorToPlace + xBuildingSize / 2) * SizeOfCell, (float)(yCorToPlace + yBuildingSize / 2) * SizeOfCell, 0.0f); // сохраняем ссылку на все сгенерированные здания descriptor.Buildings.Add(instance); // обновляем карту свободных клеток в блоке descriptor.UpdateFreeSpaceMap(SizeOfBlocks); success = true; } // уменьшаем оставшееся кол-во попыток attempts--; } } // достраиваем дороги RoadManager.GetInstance().BuildRoadInBlock(descriptor, x, y, SizeOfBlocks); // генерируем прочие декоротивные и не только объекты GenerateBlockEnviroment(block, descriptor, settingsForGeneration, SizeOfBlocks); }
void roadWidthSlider_ValueChanged(object sender, EventArgs e) { RoadManager.changeSelectedRoadWidth((float)roadWidthSlider.NumericValue); RoadManager.rebuildSelectedRoadVisuals(); }
/**********************************************************************************/ // функция ответсвенная за генерацию блоков // /**********************************************************************************/ void GenerateBlocks(int xSize, int ySize) { // проверяем соответствие размера карты и блоков, они должны быть кратными if (MapSizeX % SizeOfBlocks != 0 || MapSizeY % SizeOfBlocks != 0) { Debug.LogError("MapGenerator::GenerateBlocks size of map or size of blocks is wrong!"); return; } // шанс использования предопределённого блока // вынести в настройки (?) // ! НА ТЕКУЩИЙ МОМЕНТ ФУНКЦИОНАЛ ОТКЛЮЧЁН ! // требуется коллекция предопределённых блоков для использования float chanseOfSpecialBloks = -0.1f; int xMapSizeInBlocks = MapSizeX / SizeOfBlocks; int yMapSizeInBlocks = MapSizeY / SizeOfBlocks; // проходимся по всей карте и заполняем её блоками for (int x = 0; x < xMapSizeInBlocks; x++) { for (int y = 0; y < yMapSizeInBlocks; y++) { // определяем, используем ли мы специальный блок или генерируемый float chanse = Random.Range(0.0f, 1.0f); bool isGenerated = false; GameObject toInstantiate = null; // выбираем блок для "постройки" if (chanse <= chanseOfSpecialBloks) { int attempts = 5; bool succsecc = false; while (attempts > 0 && !succsecc) { toInstantiate = BaseBlockCollection[Random.Range(0, BaseBlockCollection.Length)]; succsecc = RoadManager.GetInstance().IsBlockOk(toInstantiate, x, y); attempts--; } // если не получилось выбрать блок - переключаемся на генерацию if (!succsecc) { toInstantiate = EmptyBlock; isGenerated = true; } } // генерируем блок, для этого используется пустая болванка else { toInstantiate = EmptyBlock; isGenerated = true; } // проверяем возможность установки // если нет - уходим на следующую итерацию BlockDescriptor descriptor = toInstantiate.GetComponent <BlockDescriptor>(); if (!IsPositionFree(x, y, descriptor)) { continue; } // создаём новый экземпляр блока GameObject instance = Instantiate(toInstantiate, new Vector3((float)x * SizeOfCell * SizeOfBlocks, (float)y * SizeOfCell * SizeOfBlocks, 0.0f), Quaternion.identity) as GameObject; // устанавливаем в родителя instance.transform.SetParent(BuildingCollector.transform); // выполняем окончательную установку и настройку блока bool res = PlaceBlockAtPosition(instance, x, y); if (res == false) { Debug.LogError("Somothing is wrong with block place!"); } BlockDescriptor instDescriptor = instance.GetComponent <BlockDescriptor>(); if (isGenerated) { // генерируем внутярнку блока // объекты, дороги GenerateBlockContent(instance, instDescriptor, x, y); } else { instDescriptor.UpdateFreeSpaceMap(SizeOfBlocks); // обновляем правила дорог RoadManager.GetInstance().UpdateRulesForBlock(x, y, instDescriptor.RoadConnections); } PathFinder.GetInstance().ApplyBlockMapData(x, y, instDescriptor); } } }
private IEnumerable <Segment> readSegments(JsonTextReader reader, RoadManager roads, JsonSerializer serializer, List <Node> nodes, List <SegmentDescription> descriptions) { if (reader.Read()) { // start array if (reader.TokenType == JsonToken.StartArray) { do { if (reader.Read()) // inside node { if (reader.TokenType == JsonToken.StartObject) { Node start = null, end = null; Vector3 startTangent = Vector3.zero, endTangent = Vector3.zero; Vector3 startOffset = Vector3.zero, endOffset = Vector3.zero; SegmentDescription description = null; int depth = reader.Depth; do { if (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { switch ((string)reader.Value) { case Constants.TAG_SEGMENT_START: readConnection(reader, serializer, roads, nodes, out start, out startTangent, out startOffset); break; case Constants.TAG_SEGMENT_END: readConnection(reader, serializer, roads, nodes, out end, out endTangent, out endOffset); break; case Constants.TAG_SEGMENT_DESCRIPTION: description = descriptions[reader.ReadAsInt32() ?? -1]; break; } } } } while (reader.Depth > depth); if (start != null && end != null) { var seg = roads.CreateSegment(start, end, description); seg.Start.Tangent = startTangent; seg.End.Tangent = endTangent; seg.Start.Offset = startOffset; seg.End.Offset = endOffset; yield return(seg); } else { throw new FormatException("expected start AND end connections for segment"); } } } } while (reader.TokenType != JsonToken.EndArray); } } }