private void FillGrid(int seed) { UnityEngine.Random.State originalState = UnityEngine.Random.state; UnityEngine.Random.InitState(seed); FillGrid(); UnityEngine.Random.state = originalState; }
void OnEnable() { var timerModule = GetComponentInParent <Timer>(); if (!timerModule) { Debug.LogError("No timer component found!", this); } // Use the serial number as a seed value for random number generation int seed = timerModule.SerialNumber.GetHashCode(); UnityEngine.Random.InitState(seed); _randomState = UnityEngine.Random.state; _sequence.Clear(); var connection = GetComponentInParent <Connection <Message> >(); if (connection) { Debug.Log(string.Format("Got connection {0}", connection)); connection.ReceiveMessage += OnReceiveMessage; } else { Debug.LogWarning("There is no connection component.", this); } GenerateRandomIndicesMap(); // first random generated color AddRandomColor(); }
void AddRandomColor() { // load random state UnityEngine.Random.state = _randomState; // generate random color Color[] colors = (Color[])Enum.GetValues(typeof(Color)); Color color = colors[UnityEngine.Random.Range(0, colors.Length)]; _sequence.Add(color); _currentIndex = 0; // store new random state _randomState = UnityEngine.Random.state; SendMessageUpwards("Send", new Message { Module = GetComponent <ModuleIdentifier>().Name, Text = color.ToString() }); #if (UNITY_EDITOR) Debug.LogFormat(this, "Sequence = {0}", string.Join(", ", _sequence.ConvertAll(c => c.ToString()).ToArray())); var timer = GetComponentInParent <Timer>(); Converter <Color, string> converter = c => GetExpectedColor(c, timer.SerialNumberHasVowel, timer.Strikes).ToString(); Debug.LogFormat(this, "Sequence to play = {0}", string.Join(", ", _sequence.ConvertAll(converter).ToArray())); #endif }
private bool GetChance() { UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState(Time.frameCount); UnityEngine.Random.state = state; return(UnityEngine.Random.Range(0f, 1f) <= this.chanceForSecondaryConsume); }
public void GenerateCoins() { UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState(0); int num = 0; int num2 = 0; foreach (World world in worlds) { foreach (Pack pack in world.packs) { int num3 = 0; foreach (Level level in pack.levels) { level.GenerateCoins(ELSingleton <XmlSettings> .Instance.coinsInLevelsConfig[num], num3); num3++; } num2++; if (num2 >= ELSingleton <XmlSettings> .Instance.coinsInLevelsConfig[num].packs) { num2 = 0; num++; num = Math.Min(num, ELSingleton <XmlSettings> .Instance.coinsInLevelsConfig.Count - 1); } } } UnityEngine.Random.state = state; }
private Rect LegacyGetRandomBodyRect(Vector2 aInitialPos, Ferr2DT_SegmentDescription aDesc) { #if UNITY_5_4_OR_NEWER UnityEngine.Random.State tSeed = default(UnityEngine.Random.State); #else int tSeed = 0; #endif if (randomByWorldCoordinates) { #if UNITY_5_4_OR_NEWER tSeed = UnityEngine.Random.state; UnityEngine.Random.InitState((int)(aInitialPos.x + aInitialPos.y)); #else tSeed = UnityEngine.Random.seed; UnityEngine.Random.seed = (int)(aInitialPos.x + aInitialPos.y); #endif } Rect body = TerrainMaterial.ToUV(aDesc.body[UnityEngine.Random.Range(0, aDesc.body.Length)]); if (randomByWorldCoordinates) { #if UNITY_5_4_OR_NEWER UnityEngine.Random.state = tSeed; #else UnityEngine.Random.seed = tSeed; #endif } return(body); }
// Token: 0x06000A28 RID: 2600 RVA: 0x00049964 File Offset: 0x00047B64 private void UpdateEnvironment(long sec, Heightmap.Biome biome) { string environmentOverride = this.GetEnvironmentOverride(); if (!string.IsNullOrEmpty(environmentOverride)) { this.m_environmentPeriod = -1L; this.m_currentBiome = this.GetBiome(); this.QueueEnvironment(environmentOverride); return; } long num = sec / this.m_environmentDuration; if (this.m_environmentPeriod != num || this.m_currentBiome != biome) { this.m_environmentPeriod = num; this.m_currentBiome = biome; UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState((int)num); List <EnvEntry> availableEnvironments = this.GetAvailableEnvironments(biome); if (availableEnvironments != null && availableEnvironments.Count > 0) { EnvSetup env = this.SelectWeightedEnvironment(availableEnvironments); this.QueueEnvironment(env); } UnityEngine.Random.state = state; } }
void OnEnable() { var timerModule = GetComponentInParent <Timer>(); if (!timerModule) { Debug.LogError("No timer component found!", this); } // Use the serial number as a seed value for random number generation int seed = timerModule.SerialNumber.GetHashCode(); UnityEngine.Random.InitState(seed); _randomState = UnityEngine.Random.state; var connection = GetComponentInParent <Connection <Message> >(); if (connection) { Debug.Log(string.Format("Got connection {0}", connection)); connection.ReceiveMessage += OnReceiveMessage; } else { Debug.LogWarning("There is no connection component.", this); } _symbolTable = new Sprite[ColumnCount, RowCount]; GenerateColumns(); GenerateShownSymbols(); }
static public int constructor(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.Random.State o; o = new UnityEngine.Random.State(); pushValue(l, true); pushValue(l, o); return(2); } catch (Exception e) { return(error(l, e)); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif }
public string Serialize(int _playerIdx) { playerIdx = _playerIdx; rngState = UnityEngine.Random.state; var json = JsonUtility.ToJson(this); return(json); }
public static Color getRandomColor(int randomSeed) { UnityEngine.Random.State currState = UnityEngine.Random.state; UnityEngine.Random.InitState(randomSeed); Color colToReturn = UnityEngine.Random.ColorHSV(); UnityEngine.Random.state = currState; return(colToReturn); }
// Token: 0x06000E56 RID: 3670 RVA: 0x000668AC File Offset: 0x00064AAC private float GetGrowTime() { UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState((int)((ulong)this.m_nview.GetZDO().m_uid.id + (ulong)this.m_nview.GetZDO().m_uid.userID)); float value = UnityEngine.Random.value; UnityEngine.Random.state = state; return(Mathf.Lerp(this.m_growTime, this.m_growTimeMax, value)); }
void IState <State> .CopyFrom(State other) { this.entityId = other.entityId; this.tick = other.tick; this.randomState = other.randomState; this.points.CopyFrom(other.points); this.units.CopyFrom(other.units); this.pointComponents.CopyFrom(other.pointComponents); this.unitComponents.CopyFrom(other.unitComponents); }
static public int constructor(IntPtr l) { try { UnityEngine.Random.State o; o = new UnityEngine.Random.State(); pushValue(l, true); pushValue(l, o); return(2); } catch (Exception e) { return(error(l, e)); } }
static int set_state(IntPtr L) { try { UnityEngine.Random.State arg0 = (UnityEngine.Random.State)ToLua.CheckObject(L, 2, typeof(UnityEngine.Random.State)); UnityEngine.Random.state = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int set_stateter(IntPtr L) { try { UnityEngine.Random.State arg0 = StackTraits<UnityEngine.Random.State>.Check(L, 1); UnityEngine.Random.state = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } }
// Token: 0x06000ECB RID: 3787 RVA: 0x00069A74 File Offset: 0x00067C74 private RuneStone.RandomRuneText GetRandomText() { if (this.m_randomTexts.Count == 0) { return(null); } Vector3 position = base.transform.position; int seed = (int)position.x * (int)position.z; UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState(seed); RuneStone.RandomRuneText result = this.m_randomTexts[UnityEngine.Random.Range(0, this.m_randomTexts.Count)]; UnityEngine.Random.state = state; return(result); }
/// <summary> /// Inserts random values into the hashgrid. /// </summary> public static void InitializeHashGrid(int seed) { UnityEngine.Random.State currentState = UnityEngine.Random.state; _hashGrid = new HexHash[HashGridSize * HashGridSize]; UnityEngine.Random.InitState(seed); for (int i = 0; i < _hashGrid.Length; i++) { _hashGrid[i] = HexHash.Create(); } // Random generator need to restore its previous status // in order to avoid all random event to be exactly the same UnityEngine.Random.state = currentState; }
public ResourceDepositManager.ResourceDeposit CreateFromPosition(Vector3 pos) { Vector2i indexFrom = ResourceDepositManager.GetIndexFrom(pos); UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState((int)(new Vector2((float)indexFrom.x, (float)indexFrom.y)).Seed(World.Seed + World.Salt)); ResourceDepositManager.ResourceDeposit resourceDeposit = new ResourceDepositManager.ResourceDeposit() { origin = new Vector3((float)(indexFrom.x * 20), 0f, (float)(indexFrom.y * 20)) }; if (UnityEngine.Random.Range(0f, 1f) < 0.5f) { resourceDeposit.Add(ItemManager.FindItemDefinition("stones"), 1f, 100, 1f, ResourceDepositManager.ResourceDeposit.surveySpawnType.ITEM, false); } else if (0 == 0) { resourceDeposit.Add(ItemManager.FindItemDefinition("stones"), 1f, UnityEngine.Random.Range(30000, 100000), UnityEngine.Random.Range(0.3f, 0.5f), ResourceDepositManager.ResourceDeposit.surveySpawnType.ITEM, false); float single = 0f; single = (!World.Procedural ? 0.1f : (TerrainMeta.BiomeMap.GetBiome(pos, 2) > 0.5f ? 1f : 0f) * 0.25f); if (UnityEngine.Random.Range(0f, 1f) >= 1f - single) { resourceDeposit.Add(ItemManager.FindItemDefinition("metal.ore"), 1f, UnityEngine.Random.Range(10000, 100000), UnityEngine.Random.Range(2f, 4f), ResourceDepositManager.ResourceDeposit.surveySpawnType.ITEM, false); } float single1 = 0f; single1 = (!World.Procedural ? 0.1f : (TerrainMeta.BiomeMap.GetBiome(pos, 1) > 0.5f ? 1f : 0f) * (0.25f + 0.25f * (TerrainMeta.TopologyMap.GetTopology(pos, 8) ? 1f : 0f) + 0.25f * (TerrainMeta.TopologyMap.GetTopology(pos, 1) ? 1f : 0f))); if (UnityEngine.Random.Range(0f, 1f) >= 1f - single1) { resourceDeposit.Add(ItemManager.FindItemDefinition("sulfur.ore"), 1f, UnityEngine.Random.Range(10000, 100000), UnityEngine.Random.Range(4f, 4f), ResourceDepositManager.ResourceDeposit.surveySpawnType.ITEM, false); } float single2 = 0f; if (!World.Procedural) { single2 += 0.15f; } else if (TerrainMeta.BiomeMap.GetBiome(pos, 8) > 0.5f || TerrainMeta.BiomeMap.GetBiome(pos, 4) > 0.5f) { single2 += 0.25f; } if (UnityEngine.Random.Range(0f, 1f) >= 1f - single2) { resourceDeposit.Add(ItemManager.FindItemDefinition("hq.metal.ore"), 1f, UnityEngine.Random.Range(5000, 10000), UnityEngine.Random.Range(30f, 50f), ResourceDepositManager.ResourceDeposit.surveySpawnType.ITEM, false); } } this._deposits.Add(indexFrom, resourceDeposit); Interface.CallHook("OnResourceDepositCreated", resourceDeposit); UnityEngine.Random.state = state; return(resourceDeposit); }
void Logic() { for (int idxTrader = 0; idxTrader < 8; idxTrader++) { m_velocity[idxTrader] = Mathf.PerlinNoise(Time.fixedTime * 0.05f + idxTrader * 200f, 0.1f) + 0.1f; m_inventory[idxTrader][idxTrader].amount += m_velocity[idxTrader] * 0.05f; UnityEngine.Random.State prevRandState = UnityEngine.Random.state; UnityEngine.Random.InitState(1111111); for (int idxResource = 0; idxResource < 8; idxResource++) { Mathf.PerlinNoise(idxTrader * 100.0f, idxResource * 2.0f + 0.1f * Time.time * (0.5f + UnityEngine.Random.Range(0f, 1f))); } UnityEngine.Random.state = prevRandState; } }
private void LegacyAddSegment(List <Vector2> aSegment, bool aLeftInner, bool aRightInner, List <float> aScale, List <CutOverrides> aCutOverrides, bool aClosed, bool aSmooth, Ferr2DT_TerrainDirection aDir = Ferr2DT_TerrainDirection.None) { Ferr2DT_SegmentDescription desc; if (aDir != Ferr2DT_TerrainDirection.None) { desc = TerrainMaterial.GetDescriptor(aDir); } else { desc = GetDescription(aSegment); } #if UNITY_5_4_OR_NEWER UnityEngine.Random.State tSeed = UnityEngine.Random.state; #else int tSeed = UnityEngine.Random.seed; #endif Rect body = TerrainMaterial.ToUV(desc.body[0]); float bodyWidth = body.width * unitsPerUV.x; #if UNITY_5_4_OR_NEWER UnityEngine.Random.InitState((int)(aSegment[0].x * 100000 + aSegment[0].y * 10000)); #else UnityEngine.Random.seed = (int)(aSegment[0].x * 100000 + aSegment[0].y * 10000); #endif Vector2 capLeftSlideDir = (aSegment[1] - aSegment[0]); Vector2 capRightSlideDir = (aSegment[aSegment.Count - 2] - aSegment[aSegment.Count - 1]); capLeftSlideDir.Normalize(); capRightSlideDir.Normalize(); aSegment[0] -= capLeftSlideDir * desc.capOffset; aSegment[aSegment.Count - 1] -= capRightSlideDir * desc.capOffset; LegacyCreateBody(desc, aSegment, aScale, aCutOverrides, bodyWidth, Mathf.Max(2, splitCount + 2), aClosed); if (!aClosed) { LegacyAddCap(aSegment, desc, aLeftInner, -1, aScale[0], aSmooth); LegacyAddCap(aSegment, desc, aRightInner, 1, aScale[aScale.Count - 1], aSmooth); } #if UNITY_5_4_OR_NEWER UnityEngine.Random.state = tSeed; #else UnityEngine.Random.seed = tSeed; #endif }
// Token: 0x06000A4B RID: 2635 RVA: 0x0004A900 File Offset: 0x00048B00 private void UpdateWind(long timeSec, float dt) { if (this.m_debugWind) { float f = 0.017453292f * this.m_debugWindAngle; Vector3 dir = new Vector3(Mathf.Sin(f), 0f, Mathf.Cos(f)); this.SetTargetWind(dir, this.m_debugWindIntensity); } else { EnvSetup currentEnvironment = this.GetCurrentEnvironment(); if (currentEnvironment != null) { UnityEngine.Random.State state = UnityEngine.Random.state; float f2 = 0f; float num = 0.5f; this.AddWindOctave(timeSec, 1, ref f2, ref num); this.AddWindOctave(timeSec, 2, ref f2, ref num); this.AddWindOctave(timeSec, 4, ref f2, ref num); this.AddWindOctave(timeSec, 8, ref f2, ref num); UnityEngine.Random.state = state; Vector3 dir2 = new Vector3(Mathf.Sin(f2), 0f, Mathf.Cos(f2)); num = Mathf.Lerp(currentEnvironment.m_windMin, currentEnvironment.m_windMax, num); if (Player.m_localPlayer) { float magnitude = Player.m_localPlayer.transform.position.magnitude; if (magnitude > 10500f - this.m_edgeOfWorldWidth) { float num2 = Utils.LerpStep(10500f - this.m_edgeOfWorldWidth, 10500f, magnitude); num2 = 1f - Mathf.Pow(1f - num2, 2f); dir2 = Player.m_localPlayer.transform.position.normalized; num = Mathf.Lerp(num, 1f, num2); } else { Ship localShip = Ship.GetLocalShip(); if (localShip && localShip.IsWindControllActive()) { dir2 = localShip.transform.forward; } } } this.SetTargetWind(dir2, num); } } this.UpdateWindTransition(dt); }
public static int constructor(IntPtr l) { int result; try { UnityEngine.Random.State state = default(UnityEngine.Random.State); LuaObject.pushValue(l, true); LuaObject.pushValue(l, state); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return(result); }
private void UpdateRandomPart(int newSeed) { UnityEngine.Random.State state = UnityEngine.Random.state; this.randomSeed = newSeed; UnityEngine.Random.InitState(this.randomSeed); BasePart.PartTier partTier = (BasePart.PartTier)UnityEngine.Random.Range(0, 4); List <BasePart> allTierParts = CustomizationManager.GetAllTierParts(partTier, (partTier != BasePart.PartTier.Regular) ? CustomizationManager.PartFlags.Craftable : CustomizationManager.PartFlags.None); if (allTierParts.Count > 0) { int index = UnityEngine.Random.Range(0, allTierParts.Count); this.CurrentFavorite = allTierParts[index]; } if (this.OnPartAcquired != null) { this.OnPartAcquired(); } UnityEngine.Random.state = state; }
// Token: 0x06001045 RID: 4165 RVA: 0x00072AAC File Offset: 0x00070CAC private WorldGenerator(World world) { this.m_world = world; this.m_version = this.m_world.m_worldGenVersion; this.VersionSetup(this.m_version); UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState(this.m_world.m_seed); this.m_offset0 = (float)UnityEngine.Random.Range(-10000, 10000); this.m_offset1 = (float)UnityEngine.Random.Range(-10000, 10000); this.m_offset2 = (float)UnityEngine.Random.Range(-10000, 10000); this.m_offset3 = (float)UnityEngine.Random.Range(-10000, 10000); this.m_riverSeed = UnityEngine.Random.Range(int.MinValue, int.MaxValue); this.m_streamSeed = UnityEngine.Random.Range(int.MinValue, int.MaxValue); this.m_offset4 = (float)UnityEngine.Random.Range(-10000, 10000); if (!this.m_world.m_menu) { this.Pregenerate(); } UnityEngine.Random.state = state; }
// Token: 0x06000E61 RID: 3681 RVA: 0x00066CD0 File Offset: 0x00064ED0 private void RegeneratePoints(Vector2Int centerGrid, int gridWith) { this.m_currentCenterGrid = centerGrid; UnityEngine.Random.State state = UnityEngine.Random.state; this.m_points.Clear(); for (int i = centerGrid.y - gridWith; i <= centerGrid.y + gridWith; i++) { for (int j = centerGrid.x - gridWith; j <= centerGrid.x + gridWith; j++) { UnityEngine.Random.InitState(j + i * 100); Vector3 gridPos = this.GetGridPos(new Vector2Int(j, i)); for (int k = 0; k < this.m_amount; k++) { Vector3 item = new Vector3(UnityEngine.Random.Range(gridPos.x - this.m_gridSize, gridPos.x + this.m_gridSize), UnityEngine.Random.Range(gridPos.z - this.m_gridSize, gridPos.z + this.m_gridSize)); this.m_points.Add(item); } } } UnityEngine.Random.state = state; }
Vector3 miss(Quaternion forwardRot, Vector3 forward, float missDistance, float missAngle) { if (missDistance < 0) { UnityEngine.Random.State oldState = UnityEngine.Random.state; // Becomes deterministic for a quick little bit: UnityEngine.Random.InitState((int)((long)(parentPlayerMove.GetComponent <SyncPlayer>().playerTime * 10000.0) % 2000000000)); Vector3 direction = -missDistance * UnityEngine.Random.insideUnitCircle * maxMissAngle * Mathf.PI / 180.0f * UnityEngine.Random.Range(0.5f, 1f); // This is here because the accuracy, is on average less when using a cone to do inaccuracy. This increases the amount of shots that are more accurate. In the future it could just use tan, or maybe tan with this. UnityEngine.Random.state = oldState; // As to maintain randomness otherwise.. not really necessary direction.z = 1.0f; return(Quaternion.LookRotation(forward) * Quaternion.LookRotation(direction.normalized) * Vector3.forward); } else { Vector3 direction = new Vector3(Mathf.Cos(missAngle), Mathf.Sin(missAngle), 0) * Mathf.Tan(missDistance * Mathf.PI / 180.0f); // If miss distance is under 90 degrees, this will be under 1. direction.z = 1.0f; return(Quaternion.LookRotation(forward) * Quaternion.LookRotation(direction.normalized) * Vector3.forward); } }
void Start() { thisTransform = transform; mesh = GetComponent <MeshFilter>().mesh; tris = mesh.triangles; verts = mesh.vertices; normals = mesh.normals; Vector3 corner1 = verts[0]; Vector3 corner2 = verts[0]; foreach (Vector3 vert in verts) { corner1 = Vector3.Min(corner1, vert); corner2 = Vector3.Max(corner2, vert); } o = new Octree(new Box(corner1, corner2)); for (int i = 0; i < tris.Length / 3; i++) { o.AddTriangle(i); } randState = UnityEngine.Random.state; }
// Token: 0x06001053 RID: 4179 RVA: 0x000730D0 File Offset: 0x000712D0 private List <WorldGenerator.River> PlaceRivers() { UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState(this.m_riverSeed); DateTime now = DateTime.Now; List <WorldGenerator.River> list = new List <WorldGenerator.River>(); List <Vector2> list2 = new List <Vector2>(this.m_lakes); while (list2.Count > 1) { Vector2 vector = list2[0]; int num = this.FindRandomRiverEnd(list, this.m_lakes, vector, 2000f, 0.4f, 128f); if (num == -1 && !this.HaveRiver(list, vector)) { num = this.FindRandomRiverEnd(list, this.m_lakes, vector, 5000f, 0.4f, 128f); } if (num != -1) { WorldGenerator.River river = new WorldGenerator.River(); river.p0 = vector; river.p1 = this.m_lakes[num]; river.center = (river.p0 + river.p1) * 0.5f; river.widthMax = UnityEngine.Random.Range(60f, 100f); river.widthMin = UnityEngine.Random.Range(60f, river.widthMax); float num2 = Vector2.Distance(river.p0, river.p1); river.curveWidth = num2 / 15f; river.curveWavelength = num2 / 20f; list.Add(river); } else { list2.RemoveAt(0); } } this.RenderRivers(list); DateTime.Now - now; UnityEngine.Random.state = state; return(list); }
/// <summary> /// Returns a random float number between min [inclusive] and max [inclusive]. /// </summary> /// <param name="min">The minimum [inclusive] number to allow in the range.</param> /// <param name="max">The maximum [inclusive] number to allow in the range.</param> /// <returns>Returns a random float number provided between the range.</returns> public unsafe float Range(float min, float max) { // Backup our original state UnityEngine.Random.State backupState = UnityEngine.Random.state; // Cast our state struct into Unity engine's state struct to set our random state. var genState = state; UnityEngine.Random.state = *((UnityEngine.Random.State *) & genState); // Generate a random number now. float result = UnityEngine.Random.Range(min, max); // Cast UnityEngine's new state back to our struct. var genState2 = UnityEngine.Random.state; state = *((State *)&genState2); // Restore our random state and return it. UnityEngine.Random.state = backupState; return(result); }
// To keep looking at the poi until new command, set duration to -1 public void LookAtPoiDirectly( Vector3 poi, float duration=-1, float headLatency=0.075f ) { eyeAndHeadAnimator.LookAtSpecificThing( poi, headLatency: headLatency ); nextChangePOITime = (duration >= 0) ? (Time.time + duration) : -1; state = State.LookingAtPoiDirectly; }
// To keep looking at the player until new command, set duration to -1 public void LookAtPlayer(float duration=-1, float headLatency=0.075f) { UpdateCameraTransformIfNecessary(); if ( playerLeftEyeXform != null && playerRightEyeXform != null ) eyeAndHeadAnimator.LookAtFace( playerLeftEyeXform, playerRightEyeXform, headLatency ); else eyeAndHeadAnimator.LookAtFace( playerEyeCenterXform, headLatency ); nextChangePOITime = (duration >= 0) ? (Time.time + duration) : -1; targetPOI = null; timeOutsideOfAwarenessZone = 0; state = State.LookingAtPlayer; }
public void LookAroundIdly() { if ( state == State.LookingAtPlayer ) stareBackDeadtime = Random.Range(10.0f, 30.0f); targetPOI = ChooseNextHeadTargetPOI(); if ( targetPOI != null ) eyeAndHeadAnimator.LookAtAreaAround( targetPOI ); else eyeAndHeadAnimator.LookAtAreaAround(ChooseNextHeadTargetPoint()); nextChangePOITime = Time.time + Random.Range(Mathf.Min(minLookTime, maxLookTime), Mathf.Max(minLookTime, maxLookTime)); state = State.LookingAroundIdly; }
public void GrabPlayer(Player player) { if (player.IsKnockedOut()) { PlayerHasBeenKnockedOut(); } else { _animator.Play("Shake"); } _player = player; _state = State.Grabbed; _player.AddChaser(this); _player.PushPlayer(_rigidbody.velocity, 60); _rigidbody.velocity = Vector3.zero; _rigidbody.constraints = RigidbodyConstraints.FreezeAll; SoundManager.Instance.PlayGrabbedEffect(); gameObject.SetLayerRecursively(_grabLayer); }
void OnExplosionFinished(bool success) { if (settings.Callback != null) { if (!success) { settings.Callback(timer.ElapsedMilliseconds, ExplosionState.ExplosionStarted); OnExplosionStarted(); } settings.Callback(timer.ElapsedMilliseconds, ExplosionState.ExplosionFinished); } state = State.None; queue.OnExplosionFinished(settings.id); }
/// <summary> /// callback from queue, do not call this unles you know what you are doing! /// </summary> public void StartExplosionFromQueue(Vector3 pos, int id, OnExplosion callback) { ExploderUtils.Assert(state == State.None, "Wrong state: " + state); mainCentroid = pos; explosionID = id; state = State.Preprocess; ExplosionCallback = callback; #if DBG processingTime = 0.0f; preProcessingTime = 0.0f; postProcessingTime = 0.0f; postProcessingTimeEnd = 0.0f; isolatingIslandsTime = 0.0f; #endif }
void OnExplosionFinished(bool success) { if (ExplosionCallback != null) { if (!success) { ExplosionCallback(timer.ElapsedMilliseconds, ExplosionState.ExplosionStarted); OnExplosionStarted(); } ExplosionCallback(timer.ElapsedMilliseconds, ExplosionState.ExplosionFinished); } state = State.None; queue.OnExplosionFinished(explosionID); }
public IEnumerator FallRecovery(Vector3 fallDirection) { _animator.Play("FellDown"); //_defaultMesh.SetActive(false); //_stunnedMesh.SetActive(true); _state = State.Fall; gameObject.SetLayerRecursively(_stunnedLayer); var inputDirection = fallDirection.normalized; _rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation; _rigidbody.velocity = inputDirection * 40f; yield return new WaitForSeconds(.5f); _rigidbody.velocity = Vector3.zero;; yield return new WaitForSeconds(3.5f); transform.DOShakePosition(.5f, Vector3.one.SetY(0f), 40); yield return new WaitForSeconds(.5f); _fallRecoveryRoutine = null; _state = State.Run; gameObject.SetLayerRecursively(_defaultLayer); // TODO: Walk animation _animator.Play("Walk"); //_defaultMesh.SetActive(true); //_stunnedMesh.SetActive(false); }
public void Start() { MaxSpeed = Random.Range(8, 14); _state = State.Run; _playerMove = FindObjectOfType<Move>().gameObject; _rigidbody = GetComponent<Rigidbody>(); _defaultLayer = gameObject.layer; _grabLayer = LayerMask.NameToLayer("Chaser-Grab"); _stunnedLayer = LayerMask.NameToLayer("Chaser-Stun"); _grabStamina = GrabStaminaMax; _cameraInput = Camera.main.GetComponent<CameraInput>(); _animator = GetComponentInChildren<Animator>(); _animator.Play("Walk"); _defaultMesh = transform.FindChild("Mesh").gameObject; //_stunnedMesh = transform.FindChild("Mesh-Stunned").gameObject; //_defaultMesh.SetActive(true); //_stunnedMesh.SetActive(false); }
public IEnumerator ChargeInDirection(Vector3 targetDirection) { _animator.Play("Dive"); var inputVector = (targetDirection).normalized; var playerForce = (inputVector * Acceleration * 2f * Time.smoothDeltaTime); var currentVelocity = _rigidbody.velocity.SetY(0); // Apply friction currentVelocity = ApplyFriction(currentVelocity, Friction, Time.smoothDeltaTime); if (currentVelocity.magnitude > MaxChargeSpeed) { currentVelocity = currentVelocity.normalized * MaxChargeSpeed; } else { currentVelocity = currentVelocity + playerForce; } _rigidbody.velocity = currentVelocity; yield return new WaitForSeconds(.5f); _chargeInDirectionRoutine = null; if (_state != State.Grabbed) { _animator.Play("Walk"); _state = State.Run; } }
void FixedUpdate() { if (_state == State.Grabbed || _state == State.Fall) { return; } var playerPosition = GetRelativePlayerPosition(); const float chargeDistance = 10f; var shouldCharge = playerPosition.sqrMagnitude < Mathf.Pow(chargeDistance, 2f); shouldCharge = shouldCharge && _state != State.Charge; if (shouldCharge) { _state = State.Charge; } if (_state == State.Run) { FollowPlayer(playerPosition); LookAtPlayer(playerPosition); } if (_state == State.Charge && _chargeInDirectionRoutine == null) { _chargeInDirectionRoutine = ChargeInDirection(playerPosition); StartCoroutine(_chargeInDirectionRoutine); } }
void LookAwayFromPlayer() { stareBackDeadtime = Random.Range(5.0f, 10.0f); bool isPlayerOnMyLeft = eyeAndHeadAnimator.headParentXform.InverseTransformPoint( playerEyeCenterXform.position ).x < 0; Vector3 awayPoint = eyeAndHeadAnimator.headParentXform.TransformPoint( eyeAndHeadAnimator.GetOwnEyeCenter() + 10 * (Quaternion.Euler(0, isPlayerOnMyLeft ? 50 : -50, 0 ) * Vector3.forward)); eyeAndHeadAnimator.LookAtAreaAround( awayPoint ); nextChangePOITime = Time.time + Random.Range(Mathf.Min(minLookTime, maxLookTime), Mathf.Max(minLookTime, maxLookTime)); state = State.LookingAwayFromPlayer; }
void Update() { long cuttingTime = 0; switch (state) { case State.None: break; case State.Preprocess: { timer.Reset(); timer.Start(); #if DBG var watch = new Stopwatch(); watch.Start(); #endif // get mesh data from game object in radius var readyToCut = Preprocess(); #if DBG watch.Stop(); preProcessingTime = watch.ElapsedMilliseconds; processingFrames = 0; #endif // nothing to explode if (!readyToCut) { #if DBG ExploderUtils.Log("Nothing to explode " + settings.Position); #endif OnExplosionFinished(false); } else { // continue to cutter, don't wait to another frame state = State.ProcessCutter; goto case State.ProcessCutter; } } break; case State.ProcessCutter: { #if DBG processingFrames++; var watch = new Stopwatch(); watch.Start(); #endif // process main cutter var cuttingFinished = ProcessCutter(out cuttingTime); #if DBG watch.Stop(); processingTime += watch.ElapsedMilliseconds; #endif if (cuttingFinished) { poolIdx = 0; postList = new List<CutMesh>(meshSet); // continue to next state if the cutter is finished if (splitMeshIslands) { #if DBG isolatingIslandsFrames = 0; isolatingIslandsTime = 0.0f; #endif islands = new List<CutMesh>(meshSet.Count); state = State.IsolateMeshIslands; goto case State.IsolateMeshIslands; } state = State.PostprocessInit; goto case State.PostprocessInit; } } break; case State.IsolateMeshIslands: { #if DBG var watchPost = new Stopwatch(); watchPost.Start(); #endif var isolatingFinished = IsolateMeshIslands(ref cuttingTime); #if DBG watchPost.Stop(); isolatingIslandsFrames++; isolatingIslandsTime += watchPost.ElapsedMilliseconds; #endif if (isolatingFinished) { // goto next state state = State.PostprocessInit; goto case State.PostprocessInit; } } break; case State.PostprocessInit: { InitPostprocess(); state = State.Postprocess; goto case State.Postprocess; } case State.Postprocess: { #if DBG var watchPost = new Stopwatch(); watchPost.Start(); #endif if (Postprocess(cuttingTime)) { timer.Stop(); } #if DBG watchPost.Stop(); postProcessingTime += watchPost.ElapsedMilliseconds; #endif } break; } #if DBG if (Input.GetKeyDown(KeyCode.M)) { settings.MeshColliders = !settings.MeshColliders; } #endif }
private void Awake() { // init cutter cutter = new Core.MeshCutter(); cutter.Init(512, 512); UnityEngine.Random.seed = System.DateTime.Now.Millisecond; settings= new ExploderSettings(this); var use2d = settings.Use2DCollision; // init pool FragmentPool.Instance.Allocate(settings.FragmentPoolSize, settings.MeshColliders, use2d, settings.FragmentPrefab); FragmentPool.Instance.SetDeactivateOptions(settings.DeactivateOptions, settings.FadeoutOptions, settings.DeactivateTimeout); FragmentPool.Instance.SetExplodableFragments(settings.ExplodeFragments, settings.DontUseTag); FragmentPool.Instance.SetFragmentPhysicsOptions(settings.FragmentOptions, use2d); FragmentPool.Instance.SetSFXOptions(settings.SFXOptions); timer = new Stopwatch(); // init queue queue = new ExploderQueue(this); if (settings.ExplodeSelf) { if (settings.DontUseTag) { gameObject.AddComponent<Explodable>(); } else { gameObject.tag = "Exploder"; } } state = State.DryRun; PreAllocateBuffers(); state = State.None; if (settings.SFXOptions.ExplosionSoundClip) { audioSource = gameObject.GetComponent<AudioSource>(); if (!audioSource) { audioSource = gameObject.AddComponent<AudioSource>(); } } }