/// <summary> /// Создание еды /// </summary> private void _createFood() { var r = new System.Random(); for (int i = 0; i < 3; i++) { // Создание еды в свободной точке PointModel currentPoint; var x = 0; var y = 0; do { x = Random.Range(0, GameMatrix.Count); y = Random.Range(0, GameMatrix[x].Count); currentPoint = GameMatrix[x][y]; } while (currentPoint.CellState != Initialize.EnumСell.Empty); // Выбор типа еды currentPoint.Food = ((Initialize.EnumFood)r.Next(1, Enum.GetValues(typeof(Initialize.EnumFood)).Length)); // Создание ГеймОбьекта еды GameObject newGO = new GameObject("Food"); // Цвет обьекта еды switch (currentPoint.Food) { case Initialize.EnumFood.NormalFood: newGO.AddComponent <Image>().color = Color.green; break; case Initialize.EnumFood.SpoiledFood: newGO.AddComponent <Image>().color = Color.red; break; case Initialize.EnumFood.FastFood: newGO.AddComponent <Image>().color = Color.blue; break; case Initialize.EnumFood.SlowFood: newGO.AddComponent <Image>().color = Color.grey; break; case Initialize.EnumFood.SwitchFood: newGO.AddComponent <Image>().color = Color.magenta; break; } // Размер обьекта еды newGO.GetComponent <RectTransform>().sizeDelta = StateController.StartSnakeState.SnakePartSize; // Перент обьекта еды newGO.transform.SetParent(StateController.StartSnakeState.TSnakeParent); // Позиция обьекта еды newGO.transform.position = currentPoint.Position; // Добавление в PointModel обьекта еды currentPoint.CellGO = newGO; currentPoint.CellState = Initialize.EnumСell.Food; // Добавление в list с координатами "еды" (обьекта еды) FoodCoods.Add(new MatrixIdModel() { x = x, y = y }); } }
void RandomFillMap() { if (useRandomSeedActual) { seed = Time.time.ToString(); // Debug.Log("++++++++ " + seed.GetHashCode()); } System.Random pseudoRandom = new System.Random(seed.GetHashCode()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { map[x, y] = 1; } else { map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercent) ? 1 : 0; } } } }
PhaseHandler.RowPosition GetRandomTargetRow(ActionPhase actionPhase = null) { print("selecting a random target row"); if (actionPhase == null) { actionPhase = this; } Array values = Enum.GetValues(typeof(PhaseHandler.RowPosition)); System.Random random = new System.Random(); PhaseHandler.RowPosition randomTargetRow = (PhaseHandler.RowPosition)values.GetValue(random.Next(values.Length)); var targetPlayer = actionPhase.GetTargetPlayer(randomTargetRow); print("validating whether the randomly chosen target is valid"); if (actionPhase.CanPlayerAttack(targetPlayer)) { print($"got valid random target row: {randomTargetRow} (player {targetPlayer.playerName})"); return(randomTargetRow); } else { // this is ugly since it will only work for 2 rows but its okay for our usecase now print($"got invalid target row: {randomTargetRow}, therefore choosing the other one"); return(randomTargetRow == PhaseHandler.RowPosition.Front ? PhaseHandler.RowPosition.Back : PhaseHandler.RowPosition.Front); } }
/// <summary> /// Randomly returns a trail type /// </summary> /// <returns>The randomly selected type of trail that this object will draw behind it</returns> private TrailType getRandomTrailType() { var r = new System.Random(); int trailSelection = r.Next() % Enum.GetNames(typeof(TrailType)).Length; switch (trailSelection) { case 5: return(TrailType.edgyShadow); case 4: return(TrailType.basic); case 3: return(TrailType.iceMagic); case 2: return(TrailType.sithLord); case 1: return(TrailType.archimedeanSprial); case 0: default: return(TrailType.rainbow); } }
private void GenerateEnemy(Vector3 position, Quaternion rotation, RoadEntityData entityData) { entityData.entityType = EntityType.Enemy; var random = new System.Random(DateTime.Now.Millisecond); var randomEnemyCount = random.Next(0, countOfRoads); random = new System.Random(DateTime.Now.Millisecond); var randomEnemyType = random.Next(0, enemies.Count); Transform enemy; var enemyType = enemies[randomEnemyType].GetComponentInChildren <Enemy.Opponents.Enemy>().enemyType; entityData.enemyType = enemyType; entityData.roadCount = randomEnemyCount; for (var i = 0; i <= randomEnemyCount; i++) { enemy = Instantiate(enemies[randomEnemyType], position, rotation, enemysHolder).transform; enemy.position += enemy.right * roadOffsets[i]; var yOffset = enemy.GetComponentInChildren <Enemy.Opponents.Enemy>()?.enemyType == EnemyType.Fly ? .5f : 0; entityData.height = yOffset; enemy.position += enemy.up * yOffset; // NEW enemy.forward = -enemy.forward; } AddData(entityData); }
public void OnTriggerEnter(Collider thingICollidedWith) { if (thingICollidedWith.transform.root == playersVehicle.transform) { Health health = Traverse.Create(playeractor).Field("h").GetValue() as Health; if (health.currentHealth > 10) { playeractor.health.Damage(birdDamage, new Vector3(0, 0, 0), Health.DamageTypes.Impact, birdActor, "Bird Strike"); } Debug.Log("Bird Strike!!"); squawk.Play(); BaseFailure fail = getRandomFailure(); System.Random rand = new System.Random(); double chance = rand.NextDouble(); if (fail.failureName.Contains("Engine Failure") && chance <= engineFailureRate) { fail.runFailure(); } else { Debug.Log($"Is {chance} <= {fail.failureRate * failureRateMultiplier}?"); if (chance <= fail.failureRate * failureRateMultiplier) { Debug.Log($"Triggering failure {fail.failureName}"); fail.runFailure(null, true); } } } }
public FloorLayout[] GenerateAllFloors(int towerNumber, int numberFloors) { Random.InitState(towerNumber); System.Random dungeonRandom = new System.Random(towerNumber); var floors = new FloorLayout[numberFloors]; try { for (var i = 0; i < numberFloors; i++) { if (i == 0) { floors[i] = GenerateBasement(); } else { floors[i] = GenerateFloor(i, dungeonRandom); } } } catch (Exception e) { Debug.LogError(e); #if UNITY_EDITOR Debug.LogError("There was an error generating the floor definition. Leaving play mode."); UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif } return(floors); }
//random Fill map with 0, resource1, resource2 private void RandomFillMap(int[,] map, int resource1, int resource2, string seed) { System.Random pseudoRandom = new System.Random(seed.GetHashCode()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { //resource1 || resource2 //map[x, y] = 1; map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercent1 * 100 / (randomFillPercent1 + randomFillPercent2)) ? resource1 : resource2; } else { int randomInt = pseudoRandom.Next(0, 100); if (randomInt > (randomFillPercent1 + randomFillPercent2)) { map[x, y] = 0; } else if (randomInt < randomFillPercent1) { map[x, y] = resource1; } else { map[x, y] = resource2; } //map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercent) ? 1 : 0; } } } }
private static Ingredient[] GenerateRandomRecipe(int numIngredients) { var recipe = new Ingredient[numIngredients]; for (int j = 0; j < numIngredients; j++) //otherwise the whole array initializes to value 0 of Ingredient, and then that ingredient is filtered out of all recipes by the duplicates filter { recipe[j] = Ingredient.NOT_AN_INGREDIENT; } var i = 0; if ((Ingredient)GameInfo.ThemeIngredient == Ingredient.NOT_AN_INGREDIENT) { GameInfo.ThemeIngredient = Random.Range(0, (int)Ingredient.NOT_AN_INGREDIENT); } recipe[i++] = (Ingredient)GameInfo.ThemeIngredient; for (; i < numIngredients; i++) { var ing = Ingredient.NOT_AN_INGREDIENT; int pos = 0; while (pos > -1) //no duplicate ingredients in recipes { ing = (Ingredient)UnityEngine.Random.Range(0, (int)Ingredient.NOT_AN_INGREDIENT); pos = Array.IndexOf(recipe, ing); } recipe[i] = ing; } var rnd = new System.Random(); recipe = recipe.OrderBy(x => rnd.Next()).ToArray(); return(recipe); }
IEnumerator scramble() { Debug.LogFormat("[Broken Binary #{0}] Picked up word is " + word, _moduleID); yield return(null); char[] array = ordered.ToCharArray(); disordered = ordered; while (disordered == ordered) { System.Random rng = new System.Random(); int n = array.Length; while (n > 1) { n--; int k = rng.Next(n + 1); var value = array[k]; array[k] = array[n]; array[n] = value; } string scram = new string(array); disordered = scram; } Debug.LogFormat("[Broken Binary #{0}] Left button is spelling " + word[Int32.Parse(disordered[0].ToString())], _moduleID); Debug.LogFormat("[Broken Binary #{0}] Middle button is spelling " + word[Int32.Parse(disordered[1].ToString())], _moduleID); Debug.LogFormat("[Broken Binary #{0}] Right button is spelling " + word[Int32.Parse(disordered[2].ToString())], _moduleID); Debug.LogFormat("[Broken Binary #{0}] Top button is spelling " + word[Int32.Parse(disordered[3].ToString())], _moduleID); Debug.LogFormat("[Broken Binary #{0}] Bottom button is spelling " + word[Int32.Parse(disordered[4].ToString())], _moduleID); Start(); }
void RandomFillMap() { if (useRandomSeed) { randy = new Random(); seed = Time.time.ToString(); seed = Random.Range(Int32.MinValue, Int32.MaxValue).ToString(); } System.Random pseudoRandom = new System.Random(seed.GetHashCode()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { map[x, y] = 1; } else { map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercent)? 1: 0; } } } }
private void HandleGameEnded() { if (FLogger.Ready) { FLogger.LogEvent( Firebase.Analytics.FirebaseAnalytics.EventLevelEnd, GetLevelName(), score.ToString() ); } var random = new System.Random(); if (random.Next(4) == 0) { PlayAd(); } float timeElapsed = Time.time - startTime; this.finished = true; if (StateToFlag || StateToFlag || StateToCapital) { StateText.GetComponent <TextMeshProUGUI>().text = ""; StateFlag.GetComponent <Image>().enabled = false; } GameObject.Find("text").GetComponent <CrazyTextEffect>().SetTimeElapsed((int)timeElapsed); GameObject.Find("text").GetComponent <CrazyTextEffect>().SetScore(score); GameObject.Find("text").GetComponent <CrazyTextEffect>().play = true; BackButton.SetActive(true); BackButton.transform.GetChild(0).GetComponent <TextMeshProUGUI>().enabled = true; SoundController.PlayFinish(); }
void RandomFillMap() { if (useRandomSeed) { seed = Time.time.ToString(); } System.Random pseudoRandom = new System.Random(seed.GetHashCode()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { map[x, y] = 1; } else { if (pseudoRandom.Next(0, 100) < randomFillPercent) { map[x, y] = 1; } else { map[x, y] = 0; floorNum++; } } } } }
/** randSizeDungeon Method * This is the random size of the map * We can multiply by 100 cause of the size of our prefab rooms **/ private void RandSizeDungeon(int seed) { System.Random prng = new System.Random(seed); sizeMap.x = prng.Next(min, max) * 100; sizeMap.y = prng.Next(min, max) * 100; }
public static void Rearrange <T>(List <T> items) { if (items.Count <= 1) { return; } System.Random _random = new System.Random(); T last = items[items.Count - 1]; int n = items.Count; for (int i = 0; i < n; i++) { int r = i + _random.Next(n - i); T t = items[r]; items[r] = items[i]; items[i] = t; } if (items[0].Equals(last)) { int r = _random.Next(1, items.Count); T t = items[r]; items[r] = items[0]; items[0] = t; } }
public static Vector2 insideUnitCircle(this System.Random self) { float radius = (float)self.NextDouble(); float angle = (float)self.NextDouble() * Mathf.PI * 2; return(new Vector2(Mathf.Cos(angle) * radius, Mathf.Sin(angle) * radius)); }
// Start is called before the first frame update void Start() { // You get the Rigidbody component you attach to the GameObject m_Rigidbody2D = GetComponent <Rigidbody2D>(); m_CircleCollider2D = GetComponent <CircleCollider2D>(); m_SpriteRenderer = GetComponent <SpriteRenderer>(); sprites = Resources.LoadAll <Sprite>("Sprites/asteroid"); // This starts at first mode (nothing happening yet) m_ModeSwitching = ModeSwitching.Impulse; // Initialising floats angle = Random.Range(0, 2 * Mathf.PI); magnitude = Random.Range(MinImpulseForce, MaxImpulseForce); // Initialising the force which is used on GameObject in various ways direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)); // Apply impulse force to get game object moving if (m_ModeSwitching == ModeSwitching.Impulse) { m_Rigidbody2D.AddForce(direction * magnitude, ForceMode2D.Impulse); } // Use System.Random.Next() to generate an integer from 0 to 4 System.Random rnd = new System.Random(); spriteSelected = rnd.Next(0, 4); m_SpriteRenderer.sprite = sprites[spriteSelected]; Vector2 spriteHalfSize = m_SpriteRenderer.sprite.bounds.extents; m_CircleCollider2D.radius = spriteHalfSize.x > spriteHalfSize.y ? spriteHalfSize.x : spriteHalfSize.y; }
void CreatSourceRdm(int _percentage) { if (GraphDone == true) { System.Random Random = new System.Random(); int SourceCount = Mathf.FloorToInt(TenVertex.Count * (_percentage * 0.01f)); qIndex = 0; if (Sources != null && Sources.Count != 0) { foreach (var tv in TenVertex) { if (tv.GetState() != 0) { tv.SetState(0, 0); } } Sources = new List <int>(SourceCount); } else { Sources = new List <int>(SourceCount); } for (int i = 0; i <= SourceCount; i++) { int _source = Random.Next(0, TenVertex.Count); Sources.Add(_source); TenVertex[_source].SetState(1); _queue.Enqueue(_source); } } }
public void TurnOnAll() { if (GraphDone == true && GrowSpread == false && GrowDirect == false) { if (displayed == false) { System.Random rdm = new System.Random(); foreach (var tv in TenVertex) { int substate = rdm.Next(0, 3); tv.SetState(2, substate); } displayed = true; //turnOnAllBtn.GetComponent<ButtonImageHandler>().SetTexture(true); } else { foreach (var tv in TenVertex) { tv.SetState(0); } displayed = false; //turnOnAllBtn.GetComponent<ButtonImageHandler>().SetTexture(false); } } }
public Color GetColor(ETypeObject type, int clicks) { if (clicks < 0) { return(ERROR_COLOR); } var res = from ccd in ClicksData where ccd.ObjectType == type && ccd.MinClicksCount <= clicks && ccd.MaxClicksCount > clicks select ccd; var selectedItems = new List <ClickColorData>(res); if (selectedItems.Count == 0) { return(ERROR_COLOR); } if (selectedItems.Count == 1) { return(selectedItems[0].ColorObject); } System.Random rnd = new System.Random(); return(selectedItems[rnd.Next(0, selectedItems.Count)].ColorObject); }
static string RandomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new System.Random(); return(new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray())); }
private void RenderWorld(World world) { var rng = new System.Random(); for (var w = 0; w < world.W; w++) { for (var e = 0; e < world.E; e++) { var hex = world[w, e]; if (hex != null) { var tile = Instantiate(HexModels[(int)hex.Type], this.transform, true); tile.tag = "Tile"; tile.transform.position = new TileVector(w, e).ToVector3() + ModelExtensions.Up * TileHeightOffset; tile.transform.localScale *= TileScale; tile.transform.rotation = ((CardinalDirection)rng.Next(6)).GetBearingRotation(); _hexInstances.Add(tile); if (hex.Type == HexType.Objective) { tile.GetComponent <DObjective>().setHex(hex); } /* if(hex.Type == HexType.Deploy) * { * //tile.GetComponent<Renderer>().material.color = Color.red; * //tile.GetComponent<Renderer>().material.color = hex.Owner.Colour * } * // Debug.Log(tile.ToString() + w + e);*/ } } } }
//Gets seed for generating map void RandomFillMap() { int randomTime = Random.Range(1, 60); if (randomSeed) { seed = System.DateTime.Now.AddSeconds(Time.time + randomTime).ToString(); } System.Random Randoms = new System.Random(seed.GetHashCode()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (Randoms.Next(0, 100) < fillPercent) { map[x, y] = 1; } else { map[x, y] = 0; } } } }
void RandomFillMap() { pseudoRandom = new System.Random(seed.GetHashCode()); for (int x = 0; x < columns + 2; x++) { for (int y = 0; y < rows + 2; y++) { if (x == 0 || x == columns + 1 || y == 0 || y == rows + 1) { map[x, y] = new Tile(x, y, TileValue.OuterWall); } else { if (pseudoRandom.Next(0, 100) < wallsFillPercent) { map[x, y] = new Tile(x, y, TileValue.Obstacle); } else { map[x, y] = new Tile(x, y, TileValue.Floor); } } } } }
/// <summary> /// Performs Fisher-Yates Shuffle with Circular Check /// </summary> private void ShuffleQuestions() { if (Questions.Count <= 1) { return; } Question lastQuestion = Questions[Questions.Count - 1]; System.Random rng = new System.Random(); int n = Questions.Count; while (n > 1) { n--; int k = rng.Next(n + 1); Question value = Questions[k]; Questions[k] = Questions[n]; Questions[n] = value; } if (lastQuestion == Questions[0]) { int k = rng.Next(1, Questions.Count); Question value = Questions[k]; Questions[k] = Questions[0]; Questions[0] = value; } _needsShuffling = false; }
public static MyEnum.ArmyDoctrines chooseDoctrine(Nation player) { //for now it is just random - later give AI prefences based on its general military strategy //Make sure to check if all doctrines have been acquired before calling Array values = Enum.GetValues(typeof(MyEnum.ArmyDoctrines)); System.Random random = new System.Random(); bool flag = false; MyEnum.ArmyDoctrines randomDoct = (MyEnum.ArmyDoctrines)values.GetValue(random.Next(values.Length)); // Debug.Log("Randomly Chosen Doctrine: " + randomDoct); while (flag == false) { if (player.landForces.hasDoctrine(randomDoct)) { randomDoct = (MyEnum.ArmyDoctrines)values.GetValue(random.Next(values.Length)); continue; } else { flag = true; } } return(randomDoct); }
// ------------------------------------- void Awake() { rnd = new System.Random((useSeed) ? randomSeed : Random.Range(int.MinValue, int.MaxValue)); pause = startPaused; CalcBoardSize(); CalcBoard(); StartCoroutine(UpdateBoard()); }
private System.Random GetRandom() { if (_random == null) { _random = new System.Random(Seed); } return(_random); }
protected override void onModelLoaded(GameObject obj) { base.onModelLoaded(obj); PlayBornAnimation(); System.Random counter = new System.Random((Time.renderedFrameCount + InstanceID).GetHashCode()); mRes.cryInternal = counter.Next(mRes.cryInternal - (int)(mRes.cryInternal * 0.5), mRes.cryInternal + (int)(mRes.cryInternal * 0.5)); }
// origin: https://stackoverflow.com/questions/1064901/random-number-between-2-double-numbers private static float GetRandomNumber(float minimum, float maximum, System.Random rand = null) { if (rand == null) { rand = new System.Random(); } return((float)rand.NextDouble() * (maximum - minimum) + minimum); }
public TerrainData Generate(int seed) { System.Random rng = new System.Random(seed); TerrainData data = new TerrainData(m_width, m_height); _generateNoise(rng, data); _circleCull(data); _smoothMap(rng, data); _findAreas(data); _removeSmallAreas(data); _placeTerrainObjects(data.GetArea(0), rng); return data; }
void BoardSetup() { if (useRandomSeed) { seed = Random.Range (0, 1000000000).ToString (); } pseudoRandom = new System.Random (seed.GetHashCode ()); boardHolder = new GameObject ("Maze").transform; boardHolder.tag = "Labyrinth"; allTiles = new Tile[columns, rows]; for (int x = -1; x < columns+1 ; x++) { for (int y = -1; y < rows+1 ; y++) { GameObject instance = Instantiate (wand, new Vector3 (x * groesse, 0f, y * groesse), Quaternion.Euler (0, 0, 0)) as GameObject; instance.transform.SetParent (boardHolder); if (x != -1 && y != -1 && x < columns && y < rows) { //Rand wird ignoriert! allTiles [x, y] = new Tile (instance, x, y); if (x % 2 == 0 && y % 2 != 0) { wandTiles.Add (allTiles [x, y]); allTiles[x,y].teil.name= "Wand/Distinct: "+ allTiles[x,y].distinct; //DestroyImmediate(allTiles[x,y].teil); } else if (x % 2 != 0 && y % 2 == 0) { wandTiles.Add (allTiles [x, y]); allTiles[x,y].teil.name= "Wand/Distinct: "+ allTiles[x,y].distinct; //DestroyImmediate(allTiles[x,y].teil); } else if(x%2 == 0 && y%2 == 0){ raumListe.Add(allTiles [x, y]); allTiles [x, y].distinct = zellenNummer; distinctList.Add (new List<Tile> ()); //Neue Liste für Tiles mit Distinct = Zellennummer wird erstellt distinctList[zellenNummer].Add (allTiles [x, y]); //Der Liste wird das Tile mit seinem Distinct hinzugefügt. zellenNummer++; allTiles[x,y].teil.name= "Raum/Distinct: "+ allTiles[x,y].distinct; } else allTiles[x,y].teil.name= "Unpassierbar"; } } } }
/** Returns randomly selected points on the specified nodes with each point being separated by \a clearanceRadius from each other. * Selecting points ON the nodes only works for TriangleMeshNode (used by Recast Graph and Navmesh Graph) and GridNode (used by GridGraph). * For other node types, only the positions of the nodes will be used. * * clearanceRadius will be reduced if no valid points can be found. */ public static List<Vector3> GetPointsOnNodes (List<GraphNode> nodes, int count, float clearanceRadius = 0) { if (nodes == null) throw new ArgumentNullException ("nodes"); if (nodes.Count == 0) throw new ArgumentException ("no nodes passed"); var rnd = new System.Random(); var pts = ListPool<Vector3>.Claim(count); // Square clearanceRadius *= clearanceRadius; if (nodes[0] is TriangleMeshNode || nodes[0] is GridNode) { //Assume all nodes are triangle nodes or grid nodes var accs = ListPool<float>.Claim(nodes.Count); float tot = 0; for (var i=0;i<nodes.Count;i++) { var tnode = nodes[i] as TriangleMeshNode; if (tnode != null) { float a = Math.Abs(Polygon.TriangleArea(tnode.GetVertex(0), tnode.GetVertex(1), tnode.GetVertex(2))); tot += a; accs.Add (tot); } else { var gnode = nodes[i] as GridNode; if (gnode != null) { var gg = GridNode.GetGridGraph (gnode.GraphIndex); var a = gg.nodeSize*gg.nodeSize; tot += a; accs.Add (tot); } else { accs.Add(tot); } } } for (var i=0;i<count;i++) { //Pick point var testCount = 0; var testLimit = 10; var worked = false; while (!worked) { worked = true; //If no valid points can be found, progressively lower the clearance radius until such a point is found if (testCount >= testLimit) { clearanceRadius *= 0.8f; testLimit += 10; if (testLimit > 100) clearanceRadius = 0; } var tg = (float)rnd.NextDouble()*tot; var v = accs.BinarySearch(tg); if (v < 0) v = ~v; if (v >= nodes.Count) { // This shouldn't happen, due to NextDouble being smaller than 1... but I don't trust floating point arithmetic. worked = false; continue; } var node = nodes[v] as TriangleMeshNode; Vector3 p; if (node != null) { // Find a random point inside the triangle float v1; float v2; do { v1 = (float)rnd.NextDouble(); v2 = (float)rnd.NextDouble(); } while (v1+v2 > 1); p = ((Vector3)(node.GetVertex(1)-node.GetVertex(0)))*v1 + ((Vector3)(node.GetVertex(2)-node.GetVertex(0)))*v2 + (Vector3)node.GetVertex(0); } else { var gnode = nodes[v] as GridNode; if (gnode != null) { var gg = GridNode.GetGridGraph (gnode.GraphIndex); var v1 = (float)rnd.NextDouble(); var v2 = (float)rnd.NextDouble(); p = (Vector3)gnode.position + new Vector3(v1 - 0.5f, 0, v2 - 0.5f) * gg.nodeSize; } else { //Point nodes have no area, so we break directly instead pts.Add ((Vector3)nodes[v].position); break; } } // Test if it is some distance away from the other points if (clearanceRadius > 0) { for (var j=0;j<pts.Count;j++) { if ((pts[j]-p).sqrMagnitude < clearanceRadius) { worked = false; break; } } } if (worked) { pts.Add (p); break; } else { testCount++; } } } ListPool<float>.Release(accs); } else { for (var i=0;i<count;i++) { pts.Add ((Vector3)nodes[rnd.Next (nodes.Count)].position); } } return pts; }
// Use this for initialization void Start() { cockAS = GetComponent<AudioSource> (); rand = new System.Random (); // Debug.Log ("start"); anim = GetComponent<Animator> (); cockWalkSound (); goa = GameObject.Find ("Girlfriend"); speed = Constant.normalspeed; moveflag = true; falling = false; initialdir(); }
// Use this for initialization void Start() { AS = GetComponent<AudioSource> (); girlfriend = GameObject.Find("Girlfriend"); dirlight = GameObject.Find ("Directional light"); roachking = GameObject.Find("RoachKing"); myui = GameObject.Find("Canvas"); timeCounter = 120; timeShow = 120; rand = new System.Random (); roachking.SetActive (false); //roachking.SendMessage("setactive"); ///////////////////Game Desgin//////////////////// gameStartTime = Time.time; StartCoroutine ("spark", 20); StartCoroutine ("cockraochKingShowUp"); // StartCoroutine("gdM1"); // StartCoroutine("gdM2"); // // StartCoroutine("gdRoutineFloor"); // StartCoroutine("gdRoutineWall"); // // StartCoroutine("gdC1"); // StartCoroutine("gdC2"); // // StartCoroutine("gdCu1"); // StartCoroutine("gdCu2"); InvokeRepeating("gdM1", gdM1Begin, gdM1RepeatRate); InvokeRepeating ("gdM2", gdM2Begin, gdM2RepeatRate); InvokeRepeating("gdRoutineFloor", gdRoutineBegin, gdRoutineFRepeatRate); InvokeRepeating ("gdRoutineWall", gdRoutineBegin, gdRoutineWRepeatRate); InvokeRepeating ("gdC1", gdC1Begin, gdC1RepeatRate); InvokeRepeating ("gdC2", gdC2Begin, gdC2RepeatRate); InvokeRepeating ("gdCu1", gdCu1Begin, gdCu1RepeatRate); InvokeRepeating ("gdCu2", gdCu2Begin, gdCu2RepeatRate); //////////////////////// ///////////////////////// }