public override void _Ready() { // Get nodes _joystick = GetParent().GetNode("CanvasLayer/Joystick").GetChild <JoystickButton>(0); _playerSprite = GetNode <Sprite>("PlayerSprite"); _inventory = GetParent().GetNode <Inventory>("CanvasLayer/Inventory"); _debugOverlay = GetParent().GetNode <DebugOverlay>("CanvasLayer/DebugOverlay"); _audioPlayer = GetNode <AudioStreamPlayer>("AudioPlayer"); _itemTooltip = (ItemTooltip)GD.Load <PackedScene>("res://ItemTooltip.tscn").Instance(); GetParent().GetNode("CanvasLayer").AddChild(_itemTooltip); _gathering = GetParent <Gathering>(); _footstepPlayer = GetNode <AudioStreamPlayer>("FootstepPlayer"); _miscPlayer = GetNode <AudioStreamPlayer>("MiscPlayer"); // Load assets _runForwards = GD.Load <Texture>("res://textures/Player_run_forwards.png"); _runBackwards = GD.Load <Texture>("res://textures/Player_run_backwards.png"); _runRight = GD.Load <Texture>("res://textures/Player_run_right.png"); _runForwardsNormal = GD.Load <Texture>("res://textures/normal/Player_run_forwards_n.png"); _runBackwardsNormal = GD.Load <Texture>("res://textures/normal/Player_run_backwards_n.png"); _runRightNormal = GD.Load <Texture>("res://textures/normal/Player_run_right_n.png"); _forestSong = GD.Load <AudioStreamOGGVorbis>("res://audio/music/enchanted_forest_longer.ogg"); // Load footstep sounds into an array for (int i = 0; i < _footstepSounds.Length; i++) { string terrainType = string.Empty; int indexOffset = 0; if (i < 4) { terrainType = "dirt"; } else if (i >= 4 && i < 8) { terrainType = "grass"; indexOffset = 4; } else if (i >= 8) { terrainType = "stone"; indexOffset = 8; } _footstepSounds[i] = GD.Load <AudioStream>("res://audio/sfx/footstep/" + terrainType + "_" + (i - indexOffset + 1).ToString() + ".wav"); } // Load magic pop sounds for (int i = 0; i < _magicPopSounds.Length; i++) { _magicPopSounds[i] = GD.Load <AudioStream>("res://audio/sfx/magic/magic_pop_open_0" + (i + 1).ToString() + ".wav"); } // Other setup Timer spriteAnimTimer = GetNode <Timer>("SpriteAnimateTimer"); spriteAnimTimer.WaitTime = 1f / _SpriteFPS; spriteAnimTimer.Connect("timeout", this, nameof(AnimateSprite)); _invItems.AddRange(new Item.ItemStack[] { new Item.ItemStack(Items.BRIMSTONE, 1), new Item.ItemStack(Items.FLY_AGARIC, 3), new Item.ItemStack(Items.ELDERBERRIES, 5), new Item.ItemStack(Items.AQUA_FORTIS, 1), new Item.ItemStack(Items.HOLLY_BERRIES, 3), new Item.ItemStack(Items.AQUA_VITAE, 1) }); GetParent().GetNode <Inventory>("CanvasLayer/Inventory").UpdateSlots(_invItems); _debugOverlay.TrackProperty(nameof(_inventory.Scale), _inventory, "Inventory Scale"); _debugOverlay.TrackFunc(nameof(FloorPositionString), this, "Player Position"); _inventory.Connect("ItemSlotSelected", this, nameof(InventorySlotSelected)); _audioPlayer.Stream = _forestSong; _audioPlayer.VolumeDb = -25f; _audioPlayer.Play(); }
private Scene3D(Game game, Func <Viewport> getViewport, InputMessageBuffer inputMessageBuffer, int randomSeed, bool isDiagnosticScene, MapFile mapFile, string mapPath) { Camera = new Camera(getViewport); SelectionGui = new SelectionGui(); DebugOverlay = new DebugOverlay(this, game.ContentManager); Random = new Random(randomSeed); if (mapFile != null) { MapFile = mapFile; Terrain = AddDisposable(new Terrain.Terrain(mapFile, game.AssetStore.LoadContext)); WaterAreas = AddDisposable(new WaterAreaCollection(mapFile.PolygonTriggers, mapFile.StandingWaterAreas, mapFile.StandingWaveAreas, game.AssetStore.LoadContext)); Navigation = new Navigation.Navigation(mapFile.BlendTileData, Terrain.HeightMap); } if (mapPath != null) { var mapCache = game.AssetStore.MapCaches.GetByName(mapPath.ToLower()); if (mapCache == null) { mapCache = game.AssetStore.MapCaches.GetByName(Path.Combine(game.UserDataFolder, mapPath).ToLower()); } if (mapCache == null) { throw new Exception($"Failed to load MapCache \"{mapPath}\""); } MapCache = mapCache; } RegisterInputHandler(_cameraInputMessageHandler = new CameraInputMessageHandler(), inputMessageBuffer); if (!isDiagnosticScene) { RegisterInputHandler(new SelectionMessageHandler(game.Selection), inputMessageBuffer); RegisterInputHandler(_orderGeneratorInputHandler = new OrderGeneratorInputHandler(game.OrderGenerator), inputMessageBuffer); RegisterInputHandler(_debugMessageHandler = new DebugMessageHandler(DebugOverlay), inputMessageBuffer); } _particleSystemManager = AddDisposable(new ParticleSystemManager(game.AssetStore.LoadContext)); Radar = new Radar(this, game.AssetStore, MapCache); GameContext = new GameContext( game.AssetStore.LoadContext, game.Audio, _particleSystemManager, new ObjectCreationListManager(), Terrain, Navigation, Radar); GameObjects = AddDisposable( new GameObjectCollection( GameContext, game.CivilianPlayer, Navigation)); GameContext.GameObjects = GameObjects; _orderGeneratorSystem = game.OrderGenerator; }
public override void Simulate() { // Do fall damage stufftw if (Velocity.z < 0) { takeFallDamage = true; previousZVelocity = Velocity.z; } else if (takeFallDamage && Velocity.z == 0) { takeFallDamage = false; TakeDmg(); } EyePosLocal = Vector3.Up * (EyeHeight * Pawn.Scale); UpdateBBox(); EyePosLocal += TraceOffset; EyeRot = Input.Rotation; RestoreGroundPos(); //Velocity += BaseVelocity * ( 1 + Time.Delta * 0.5f ); //BaseVelocity = Vector3.Zero; //Rot = Rotation.LookAt( Input.Rotation.Forward.WithZ( 0 ), Vector3.Up ); if (Unstuck.TestAndFix()) { return; } // Check Stuck // Unstuck - or return if stuck // Set Ground Entity to null if falling faster then 250 // store water level to compare later // if not on ground, store fall velocity // player->UpdateStepSound( player->m_pSurfaceData, mv->GetAbsOrigin(), mv->m_vecVelocity ) // RunLadderMode CheckLadder(); Swimming = Pawn.WaterLevel.Fraction > 0.6f; // // Start Gravity // if (!Swimming && !IsTouchingLadder) { Velocity -= new Vector3(0, 0, Gravity * 0.5f) * Time.Delta; Velocity += new Vector3(0, 0, BaseVelocity.z) * Time.Delta; BaseVelocity = BaseVelocity.WithZ(0); } /* * if (player->m_flWaterJumpTime) * { * WaterJump(); * TryPlayerMove(); * // See if we are still in water? * CheckWater(); * return; * } */ // if ( underwater ) do underwater movement if (AutoJump ? Input.Down(InputButton.Jump) : Input.Pressed(InputButton.Jump)) { CheckJumpButton(); } // Fricion is handled before we add in any base velocity. That way, if we are on a conveyor, // we don't slow when standing still, relative to the conveyor. bool bStartOnGround = GroundEntity != null; //bool bDropSound = false; if (bStartOnGround) { //if ( Velocity.z < FallSoundZ ) bDropSound = true; Velocity = Velocity.WithZ(0); //player->m_Local.m_flFallVelocity = 0.0f; if (GroundEntity != null) { ApplyFriction(GroundFriction * SurfaceFriction); } } // // Work out wish velocity.. just take input, rotate it to view, clamp to -1, 1 // WishVelocity = new Vector3(Input.Forward, Input.Left, 0); var inSpeed = WishVelocity.Length.Clamp(0, 1); WishVelocity *= Input.Rotation; if (!Swimming && !IsTouchingLadder) { WishVelocity = WishVelocity.WithZ(0); } WishVelocity = WishVelocity.Normal * inSpeed; WishVelocity *= GetWishSpeed(); Duck.PreTick(); bool bStayOnGround = false; if (AttachedBalloons > 0) { ClearGroundEntity(); Velocity = Velocity.WithZ(1 * AttachedBalloons * BalloonVelocity); AirMove(); } else if (Swimming) { ApplyFriction(1); WaterMove(); } else if (IsTouchingLadder) { LadderMove(); } else if (GroundEntity != null) { bStayOnGround = true; WalkMove(); } else { AirMove(); } CategorizePosition(bStayOnGround); // FinishGravity if (!Swimming && !IsTouchingLadder) { Velocity -= new Vector3(0, 0, Gravity * 0.5f) * Time.Delta; } if (GroundEntity != null) { Velocity = Velocity.WithZ(0); } // CheckFalling(); // fall damage etc // Land Sound // Swim Sounds SaveGroundPos(); if (Debug) { DebugOverlay.Box(Position + TraceOffset, mins, maxs, Color.Red); DebugOverlay.Box(Position, mins, maxs, Color.Blue); var lineOffset = 0; if (Host.IsServer) { lineOffset = 10; } DebugOverlay.ScreenText(lineOffset + 0, $" Position: {Position}"); DebugOverlay.ScreenText(lineOffset + 1, $" Velocity: {Velocity}"); DebugOverlay.ScreenText(lineOffset + 2, $" BaseVelocity: {BaseVelocity}"); DebugOverlay.ScreenText(lineOffset + 3, $" GroundEntity: {GroundEntity} [{GroundEntity?.Velocity}]"); DebugOverlay.ScreenText(lineOffset + 4, $" SurfaceFriction: {SurfaceFriction}"); DebugOverlay.ScreenText(lineOffset + 5, $" WishVelocity: {WishVelocity}"); } }
public void Init(DebugOverlay debugOverlay) { m_DebugOverlay = debugOverlay != null ? debugOverlay : DebugOverlay.instance; Resize(m_DebugOverlay.width, m_DebugOverlay.height); Clear(); }
private Scene3D(Game game, Func <Viewport> getViewport, InputMessageBuffer inputMessageBuffer, int randomSeed, bool isDiagnosticScene, MapFile mapFile, string mapPath) { Game = game; PlayerManager = new PlayerManager(); PartitionCellManager = new PartitionCellManager(game); Camera = new Camera(getViewport); SelectionGui = new SelectionGui(); DebugOverlay = new DebugOverlay(this, game.ContentManager); Random = new Random(randomSeed); if (mapFile != null) { MapFile = mapFile; Terrain = AddDisposable(new Terrain.Terrain(mapFile, game.AssetStore.LoadContext)); WaterAreas = AddDisposable(new WaterAreaCollection(mapFile.PolygonTriggers, mapFile.StandingWaterAreas, mapFile.StandingWaveAreas, game.AssetStore.LoadContext)); Navigation = new Navigation.Navigation(mapFile.BlendTileData, Terrain.HeightMap); } RegisterInputHandler(_cameraInputMessageHandler = new CameraInputMessageHandler(), inputMessageBuffer); if (!isDiagnosticScene) { RegisterInputHandler(new SelectionMessageHandler(game.Selection), inputMessageBuffer); RegisterInputHandler(_orderGeneratorInputHandler = new OrderGeneratorInputHandler(game.OrderGenerator), inputMessageBuffer); RegisterInputHandler(_debugMessageHandler = new DebugMessageHandler(DebugOverlay), inputMessageBuffer); } ParticleSystemManager = AddDisposable(new ParticleSystemManager(game.AssetStore.LoadContext)); Radar = new Radar(this, game.AssetStore, mapPath); if (mapFile != null) { var borderWidth = mapFile.HeightMapData.BorderWidth * HeightMap.HorizontalScale; var width = mapFile.HeightMapData.Width * HeightMap.HorizontalScale; var height = mapFile.HeightMapData.Height * HeightMap.HorizontalScale; Quadtree = new Quadtree <GameObject>(new RectangleF(-borderWidth, -borderWidth, width, height)); } GameContext = new GameContext( game.AssetStore.LoadContext, game.Audio, ParticleSystemManager, new ObjectCreationListManager(), Terrain, Navigation, Radar, Quadtree, this); GameObjects = AddDisposable(new GameObjectCollection(GameContext)); GameContext.GameObjects = GameObjects; _orderGeneratorSystem = game.OrderGenerator; }
public static void AddDebugCommand(string commandName, Action <string[]> worker) { DebugOverlay.AddCommand(commandName, worker); }
public static void UpdateDebugRace() { DebugOverlay.UpdateDebugRace(); }
// This is for drawing 2D elements which depend on the Scene3D, e.g tooltips and health bars. internal void Render(DrawingContext2D drawingContext) { SelectionGui.Draw(drawingContext, Camera); DebugOverlay.Draw(drawingContext, Camera); }
public void TickUpdate() { if (m_ShowStats < 1) { return; } long ticks = m_StopWatch.ElapsedTicks; float frameDurationMs = (ticks - m_LastFrameTicks) * 1000 / (float)m_StopWatchFreq; m_LastFrameTicks = ticks; DebugOverlay.SetColor(Color.yellow); DebugOverlay.SetOrigin(0, 0); DebugOverlay.Write(1, 0, "FPS:{0,6:###.##}", 1.0f / Time.deltaTime); fpsHistory[Time.frameCount % fpsHistory.Length] = 1.0f / Time.deltaTime; DebugOverlay.DrawGraph(1, 1, 9, 1.5f, fpsHistory, Time.frameCount % fpsHistory.Length, Color.green); DebugOverlay.Write(30, 0, "Open console (F12) and type: \"showstats\" to toggle graphs"); if (m_ShowStats < 2) { return; } DebugOverlay.Write(0, 4, "Hello, {0,-5} world!", Time.frameCount % 100 < 50 ? "Happy" : "Evil"); DebugOverlay.Write(0, 5, "FrameNo: {0,7}", Time.frameCount); DebugOverlay.Write(0, 6, "MonoHeap:{0,7} kb", (int)(UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong() / 1024)); /// Graphing difference between deltaTime and actual passed time float fps = Time.deltaTime * 1000.0f; var idx = Time.frameCount % fpsArray[0].Length;; fpsArray[0][idx] = -Mathf.Min(0, frameDurationMs - fps); fpsArray[1][idx] = Mathf.Max(0, frameDurationMs - fps); float variance, mean, min, max; CalcStatistics(fpsArray[0], out mean, out variance, out min, out max); // Draw histogram over time differences DebugOverlay.DrawHist(20, 10, 20, 3, fpsArray, Time.frameCount, colors, max); DebugOverlay.SetColor(new Color(1.0f, 0.3f, 0.0f)); DebugOverlay.Write(20, 14, "{0,4:#.###} ({1,4:##.#} +/- {2,4:#.##})", frameDurationMs - fps, mean, Mathf.Sqrt(variance)); DebugOverlay.DrawGraph(45, 10, 40, 3, fpsArray, Time.frameCount, colors, max); /// Graphing frametime var idx2 = Time.frameCount % frameTimeArray.Length; frameTimeArray[idx2] = frameDurationMs; CalcStatistics(frameTimeArray, out mean, out variance, out min, out max); DebugOverlay.DrawHist(20, 15, 20, 3, frameTimeArray, Time.frameCount, Color.red, max); // Draw legend float scale = 18.0f - 3.0f / max * 16.6667f; DebugOverlay.DrawLine(20, scale, 40, scale, Color.black); DebugOverlay.Write(20, 18, "{0,5} ({1} +/- {2})", frameDurationMs, mean, Mathf.Sqrt(variance)); DebugOverlay.DrawGraph(45, 15, 40, 3, frameTimeArray, Time.frameCount, Color.red, max); // Draw some lines to help visualize framerate fluctuations float ratio = (float)DebugOverlay.Height / DebugOverlay.Width * Screen.width / Screen.height; float time = (float)Time.frameCount / 60.0f; for (var i = 0; i < 10; i++) { DebugOverlay.DrawLine(60, 20, 60 + Mathf.Sin(Mathf.PI * 0.2f * i + time) * 8.0f, 20 + Mathf.Cos(Mathf.PI * 0.2f * i + time) * 8.0f * ratio, Color.black); } }
protected override void Update(Entity abilityEntity, CharacterAbility charAbility, Ability_Movement.Settings settings) { Profiler.BeginSample("Movement_Update"); var time = m_world.worldTime; var command = EntityManager.GetComponentObject <UserCommandComponent>(charAbility.character).command; var characterPredictedState = EntityManager.GetComponentObject <CharacterPredictedState>(charAbility.character); var health = EntityManager.GetComponentObject <HealthState>(charAbility.character); var newPhase = CharacterPredictedState.StateData.LocoState.MaxValue; var phaseDuration = time.DurationSinceTick(characterPredictedState.State.locoStartTick); var isOnGround = characterPredictedState.State.IsOnGround(); var isMoveWanted = command.moveMagnitude != 0.0f; if (health.health <= 0) { newPhase = CharacterPredictedState.StateData.LocoState.Dead; } else { // Ground movement if (isOnGround) { if (isMoveWanted) { newPhase = CharacterPredictedState.StateData.LocoState.GroundMove; } else { newPhase = CharacterPredictedState.StateData.LocoState.Stand; } } // Jump if (isOnGround) { characterPredictedState.State.jumpCount = 0; } if (command.jump && isOnGround) { characterPredictedState.State.jumpCount = 1; newPhase = CharacterPredictedState.StateData.LocoState.Jump; } if (command.jump && characterPredictedState.State.locoState == CharacterPredictedState.StateData.LocoState.InAir && characterPredictedState.State.jumpCount < 2) { characterPredictedState.State.jumpCount = characterPredictedState.State.jumpCount + 1; characterPredictedState.State.velocity.y = 0; newPhase = CharacterPredictedState.StateData.LocoState.DoubleJump; } if (characterPredictedState.State.locoState == CharacterPredictedState.StateData.LocoState.Jump || characterPredictedState.State.locoState == CharacterPredictedState.StateData.LocoState.DoubleJump) { if (phaseDuration >= Game.config.jumpAscentDuration) { newPhase = CharacterPredictedState.StateData.LocoState.InAir; } } } // Set phase start tick if phase has changed if (newPhase != CharacterPredictedState.StateData.LocoState.MaxValue && newPhase != characterPredictedState.State.locoState) { characterPredictedState.State.locoState = newPhase; characterPredictedState.State.locoStartTick = time.tick; } if (debugCharacterMove.IntValue > 0) { // Only show for one player if (lastUsedFrame < Time.frameCount) { lastUsedFrame = Time.frameCount; int o = Time.frameCount % movehist_x.Length; movehist_x[o] = characterPredictedState.State.position.x % 10.0f; movehist_y[o] = characterPredictedState.State.position.y % 10.0f; movehist_z[o] = characterPredictedState.State.position.z % 10.0f; DebugOverlay.DrawGraph(4, 4, 10, 5, movehist_x, o, Color.red, 10.0f); DebugOverlay.DrawGraph(4, 12, 10, 5, movehist_y, o, Color.green, 10.0f); DebugOverlay.DrawGraph(4, 20, 10, 5, movehist_z, o, Color.blue, 10.0f); } } if (time.tick != characterPredictedState.State.tick + 1) { GameDebug.LogError("Update tick invalid. Game tick:" + time.tick + " but current state is at tick:" + characterPredictedState.State.tick); } characterPredictedState.State.tick = time.tick; // Apply damange impulse from previus frame if (time.tick == characterPredictedState.State.damageTick + 1) { characterPredictedState.State.velocity += characterPredictedState.State.damageDirection * characterPredictedState.State.damageImpulse; characterPredictedState.State.locoState = CharacterPredictedState.StateData.LocoState.InAir; characterPredictedState.State.locoStartTick = time.tick; } var moveQuery = EntityManager.GetComponentObject <CharacterMoveQuery>(charAbility.character); // Simple adjust of height while on platform if (characterPredictedState.State.locoState == CharacterPredictedState.StateData.LocoState.Stand && characterPredictedState.groundCollider != null && characterPredictedState.groundCollider.gameObject.layer == m_platformLayer) { if (characterPredictedState.altitude < moveQuery.settings.skinWidth - 0.01f) { var platform = characterPredictedState.groundCollider; var posY = platform.transform.position.y + moveQuery.settings.skinWidth; characterPredictedState.State.position.y = posY; } } // Calculate movement and move character var deltaPos = Vector3.zero; CalculateMovement(ref time, characterPredictedState, ref command, ref deltaPos); // Setup movement query moveQuery.collisionLayer = characterPredictedState.teamId == 0 ? m_charCollisionALayer : m_charCollisionBLayer; moveQuery.moveQueryStart = characterPredictedState.State.position; moveQuery.moveQueryEnd = moveQuery.moveQueryStart + (float3)deltaPos; Profiler.EndSample(); }
protected override void Update(Entity entity, CharBehaviour charBehavior, DefaultCharBehaviourController.InternalState internalState, DefaultCharBehaviourController.PredictedState predictedState) { if (internalState.initialized == 0) { Activate(internalState.abilityMovement); internalState.initialized = 1; EntityManager.SetComponentData(entity, internalState); } var command = EntityManager.GetComponentObject <UserCommandComponent>(charBehavior.character).command; var healthState = EntityManager.GetComponentObject <HealthState>(charBehavior.character); if (healthState.health <= 0 && predictedState.dead == 0) { if (predictedState.activeAbility != DefaultCharBehaviourController.Ability.None) { var behavior = internalState.GetAbilityBehavior(predictedState.activeAbility); Deactivate(behavior); } Deactivate(internalState.abilityMovement); Activate(internalState.abilityDead); predictedState.dead = 1; EntityManager.SetComponentData(entity, predictedState); } if (predictedState.dead == 1) { return; } // Check for abilities done if (predictedState.activeAbility != DefaultCharBehaviourController.Ability.None) { var activeBehavior = internalState.GetAbilityBehavior(predictedState.activeAbility); var abilityCtrl = EntityManager.GetComponentData <AbilityControl>(activeBehavior); if (abilityCtrl.behaviorState != AbilityControl.State.Active) { // GameDebug.Log("Behavior done:" + activeBehavior); Deactivate(activeBehavior); predictedState.activeAbility = DefaultCharBehaviourController.Ability.None; } } if (IsRequestingActive(ref internalState, DefaultCharBehaviourController.Ability.PrimFire)) { AttempActivate(ref internalState, ref predictedState, DefaultCharBehaviourController.Ability.PrimFire, false); } else if (command.secondaryFire) { AttempActivate(ref internalState, ref predictedState, DefaultCharBehaviourController.Ability.SecFire, false); } else if (command.melee) { var force = predictedState.activeAbility == DefaultCharBehaviourController.Ability.Sprint; AttempActivate(ref internalState, ref predictedState, DefaultCharBehaviourController.Ability.Melee, force); } else if (command.sprint) { AttempActivate(ref internalState, ref predictedState, DefaultCharBehaviourController.Ability.Sprint, false); } else if (command.emote != CharacterEmote.None) { if (command.moveMagnitude == 0) { AttempActivate(ref internalState, ref predictedState, DefaultCharBehaviourController.Ability.Emote, false); } } EntityManager.SetComponentData(entity, predictedState); if (DefaultCharBehaviourController.ShowInfo.IntValue > 0) { int x = 1; int y = 2; DebugOverlay.Write(x, y++, "Ability controller"); DebugOverlay.Write(x, y++, " Active ability:" + predictedState.activeAbility); DebugOverlay.Write(x, y++, " dead:" + predictedState.dead); } }
/// <summary> /// Call at the point of judgement. Will switch stream to new difficulty as soon as possible (next new combo). /// </summary> /// <param name="newDifficulty">The new stream difficulty.</param> /// <returns>The time at which the switch will take place. -1 on failure.</returns> public virtual int SetActiveStream(Difficulty newDifficulty, bool instant = false) { Difficulty oldActiveStream = ActiveStream; if (ActiveStream == newDifficulty || (Clock.AudioTime > 0 && Clock.AudioTime < nextStreamChange)) { return(-1); //already switching stream } pList <HitObject> oldStreamObjects = ActiveStreamObjects; if (oldActiveStream == Difficulty.None || instant) { //loading a new stream. ActiveStream = newDifficulty; ProcessFrom = 0; ProcessTo = -1; return(0); } if (StreamHitObjects[(int)newDifficulty] == null) { return(-1); //no difficulty is mapped for the target stream. } int switchTime = Clock.AudioTime + DifficultyManager.PreEmpt; if (oldStreamObjects != null) { if (nextPossibleSwitchTime < switchTime) { //need to find a new switch time. removeBeforeObjectIndex = 0; if (beatmap.StreamSwitchPoints != null) { bool foundPoint = false; int c = beatmap.StreamSwitchPoints.Count; for (int i = 0; i < c; i++) { if (beatmap.StreamSwitchPoints[i] > switchTime) { switchTime = beatmap.StreamSwitchPoints[i]; foundPoint = true; break; } } if (!foundPoint) { //exhausted all stream switch points. nextPossibleSwitchTime = int.MaxValue; return(-1); } } //find a good point to stream switch. this will be mapper set later. for (int i = ProcessFrom; i < oldStreamObjects.Count; i++) { if (oldStreamObjects[i].NewCombo && oldStreamObjects[i].StartTime > switchTime) { removeBeforeObjectIndex = i; switchTime = i > 0 ? oldStreamObjects[i - 1].EndTime : oldStreamObjects[i].StartTime; break; } } nextPossibleSwitchTime = switchTime; } if (removeBeforeObjectIndex == 0) { //failed to find a suitable stream switch point. nextPossibleSwitchTime = int.MaxValue; return(-1); } switchTime = nextPossibleSwitchTime; int judgementStart = (int)(switchTime - Player.Beatmap.beatLengthAt(Clock.AudioTime) * 8); //check we are close enough to the switch time to actually judge this if (newDifficulty > oldActiveStream && Clock.AudioTime < judgementStart) { #if FULL_DEBUG DebugOverlay.AddLine("Waiting for next judgement section starting at " + judgementStart + "..."); #endif return(-1); } nextPossibleSwitchTime = 0; ActiveStream = newDifficulty; pList <HitObject> newStreamObjects = ActiveStreamObjects; SpriteManager newSpriteManager = ActiveStreamSpriteManager; for (int i = ProcessFrom; i < removeBeforeObjectIndex; i++) { newSpriteManager.Add(oldStreamObjects[i]); } if (removeBeforeObjectIndex - ProcessFrom > 0) { int removeBeforeIndex = 0; for (int i = 0; i < newStreamObjects.Count; i++) { HitObject h = newStreamObjects[i]; if (h.StartTime > switchTime && h.NewCombo) { removeBeforeIndex = i; break; } h.Sprites.ForEach(s => { s.Transformations.Clear(); s.Alpha = 0; }); h.Dispose(); } newStreamObjects.RemoveRange(0, removeBeforeIndex); newStreamObjects.InsertRange(0, oldStreamObjects.GetRange(ProcessFrom, removeBeforeObjectIndex - ProcessFrom)); } } ProcessFrom = 0; ProcessTo = -1; nextStreamChange = switchTime; return(switchTime); }
private void StepMove() { var vecPos = Position; var vecVel = Velocity; // // First try walking straight to where they want to go. // TryPlayerMove(); // // mv now contains where they ended up if they tried to walk straight there. // Save those results for use later. // var vecDownPos = Position; var vecDownVel = Velocity; // // Reset original values to try some other things. // Position = vecPos; Velocity = vecVel; // Only step up as high as we have headroom to do so. var trace = TraceBBox(Position, Position + Vector3.Up * (StepSize + DistEpsilon)); if (!trace.StartedSolid) { Position = trace.EndPos; } TryPlayerMove(); trace = TraceBBox(Position, Position + Vector3.Down * (StepSize + DistEpsilon * 2)); if (trace.Normal.z < GroundNormalZ) { if (Debug) { DebugOverlay.Text(vecDownPos, "step down", 2.0f); } Position = vecDownPos; Velocity = vecDownVel.WithZ(0); // out step height return; } if (!trace.StartedSolid) { Position = trace.EndPos; } var vecUpPos = Position; float flDownDist = (vecDownPos.x - vecPos.x) * (vecDownPos.x - vecPos.x) + (vecDownPos.y - vecPos.y) * (vecDownPos.y - vecPos.y); float flUpDist = (vecUpPos.x - vecPos.x) * (vecUpPos.x - vecPos.x) + (vecUpPos.y - vecPos.y) * (vecUpPos.y - vecPos.y); if (flDownDist > flUpDist) { Position = vecDownPos; Velocity = vecDownVel; } else { // copy z value from slide move Velocity = Velocity.WithZ(vecDownVel.z); } // out step height }
private void DrawDebugShit() { DebugOverlay.ScreenText(new Vector2(100, 100), $"Current trigger state: {CurrentTriggerType}"); }
public void Update() { if (focus != Application.isFocused) { focus = Application.isFocused; if (soundMute.IntValue == -1) { m_MasterVolume.MoveTo(focus ? 1.0f : 0.0f, 0.5f); } } var masterVolume = m_MasterVolume.GetValue(); if (soundMute.IntValue == 0) { masterVolume = 0.0f; DebugOverlay.Write(Color.red, DebugOverlay.Width - 10, 2, "{0}", "AUDIO MUTED"); } else if (soundMute.IntValue == 1) { masterVolume = 1.0f; DebugOverlay.Write(Color.green, DebugOverlay.Width - 10, 2, "{0}", "AUDIO PLAYING"); } m_AudioMixer.SetFloat("MasterVolume", DecibelFromAmplitude(Mathf.Clamp(soundMasterVol.FloatValue, 0.0f, 1.0f) * masterVolume)); m_AudioMixer.SetFloat("MusicVolume", DecibelFromAmplitude(Mathf.Clamp(soundMusicVol.FloatValue, 0.0f, 1.0f))); m_AudioMixer.SetFloat("SFXVolume", DecibelFromAmplitude(Mathf.Clamp(soundSFXVol.FloatValue, 0.0f, 1.0f))); m_AudioMixer.SetFloat("MenuVolume", DecibelFromAmplitude(Mathf.Clamp(soundMenuVol.FloatValue, 0.0f, 1.0f))); // Update running sounds int count = 0; foreach (var e in m_Emitters) { if (!e.playing) { continue; } if (e.source == null) { // Could happen if parent was killed. Not good, but fixable: GameDebug.LogWarning("Soundemitter had its audiosource destroyed. Making a new."); e.source = MakeAudioSource(); e.repeatCount = 0; } if (e.fadeToKill.IsMoving()) { e.source.volume = AmplitudeFromDecibel(e.soundDef.volume) * e.fadeToKill.GetValue(); } else if (e.fadeToKill.GetValue() == 0.0f) { // kill no matter what e.Kill(); } if (e.source.isPlaying) { count++; continue; } if (e.repeatCount > 1) { e.repeatCount--; StartEmitter(e); continue; } // Reset for reuse e.playing = false; e.source.transform.parent = m_SourceHolder.transform; e.source.enabled = true; e.source.gameObject.SetActive(true); e.source.transform.position = Vector3.zero; e.fadeToKill.SetValue(1.0f); } if (soundDebug.IntValue > 0) { DebugOverlay.Write(30, 1, "Mixer: {0} {1}", m_AudioMixer.GetInstanceID(), Game.game.audioMixer.GetInstanceID()); int ii = 4; foreach (var o in GameObject.FindObjectsOfType <AudioMixerGroup>()) { DebugOverlay.Write(30, ii++, "group: {0} {1}", o.name, o.GetInstanceID()); } DebugOverlay.Write(1, 1, "Num audios {0}", count); for (int i = 0, c = m_Emitters.Length; i < c; ++i) { var e = m_Emitters[i]; DebugOverlay.Write(1, 3 + i, "Emitter {0:##} {1} {2} {3}", i, e.playing ? e.soundDef.name : "<n/a>", e.source.gameObject.activeInHierarchy ? "act":"nact", e.playing ? "Mixer: " + e.source.outputAudioMixerGroup.audioMixer.GetInstanceID() : ""); } if (m_CurrentListener == null) { DebugOverlay.Write(DebugOverlay.Width / 2 - 5, DebugOverlay.Height, "No AudioListener?"); return; } for (int i = 0, c = m_Emitters.Length; i < c; ++i) { var e = m_Emitters[i]; if (!e.playing) { continue; } var s = e.source.spatialBlend; Vector3 locpos = m_CurrentListener.transform.InverseTransformPoint(e.source.transform.position); float x = Mathf.Lerp(e.source.panStereo * 10.0f, Mathf.Clamp(locpos.x, -10, 10), s);; float z = Mathf.Lerp(-10.0f, Mathf.Clamp(locpos.z, -10, 10), s); DebugOverlay.Write(Color.Lerp(Color.green, Color.blue, s), DebugOverlay.Width / 2 + x, DebugOverlay.Height / 2 - z, "{0} ({1:##.#})", e.soundDef.name, locpos.magnitude); } } }
public void OnPrePhysicsStep() { if (!IsServer) { return; } var selfBody = PhysicsBody; if (!selfBody.IsValid()) { return; } var body = selfBody.SelfOrParent; if (!body.IsValid()) { return; } var dt = Time.Delta; body.DragEnabled = false; var rotation = selfBody.Rotation; accelerateDirection = currentInput.throttle.Clamp(-1, 1) * (1.0f - currentInput.breaking); TurnDirection = TurnDirection.LerpTo(currentInput.turning.Clamp(-1, 1), 1.0f - MathF.Pow(0.001f, dt)); airRoll = airRoll.LerpTo(currentInput.roll.Clamp(-1, 1), 1.0f - MathF.Pow(0.0001f, dt)); airTilt = airTilt.LerpTo(currentInput.tilt.Clamp(-1, 1), 1.0f - MathF.Pow(0.0001f, dt)); float targetTilt = 0; float targetLean = 0; var localVelocity = rotation.Inverse * body.Velocity; if (backWheelsOnGround || frontWheelsOnGround) { var forwardSpeed = MathF.Abs(localVelocity.x); var speedFraction = MathF.Min(forwardSpeed / 500.0f, 1); targetTilt = accelerateDirection.Clamp(-1.0f, 1.0f); targetLean = speedFraction * TurnDirection; } AccelerationTilt = AccelerationTilt.LerpTo(targetTilt, 1.0f - MathF.Pow(0.01f, dt)); TurnLean = TurnLean.LerpTo(targetLean, 1.0f - MathF.Pow(0.01f, dt)); if (backWheelsOnGround) { var forwardSpeed = MathF.Abs(localVelocity.x); var speedFactor = 1.0f - (forwardSpeed / 5000.0f).Clamp(0.0f, 1.0f); var acceleration = speedFactor * (accelerateDirection < 0.0f ? car_accelspeed * 0.5f : car_accelspeed) * accelerateDirection * dt; var impulse = rotation * new Vector3(acceleration, 0, 0); body.Velocity += impulse; } RaycastWheels(rotation, true, out frontWheelsOnGround, out backWheelsOnGround, dt); var onGround = frontWheelsOnGround || backWheelsOnGround; var fullyGrounded = (frontWheelsOnGround && backWheelsOnGround); Grounded = onGround; if (fullyGrounded) { body.Velocity += Map.Physics.Gravity * dt; } body.GravityScale = fullyGrounded ? 0 : 1; bool canAirControl = false; var v = rotation * localVelocity.WithZ(0); var vDelta = MathF.Pow((v.Length / 1000.0f).Clamp(0, 1), 5.0f).Clamp(0, 1); if (vDelta < 0.01f) { vDelta = 0; } if (debug_car) { DebugOverlay.Line(body.MassCenter, body.MassCenter + rotation.Forward.Normal * 100, Color.White, 0, false); DebugOverlay.Line(body.MassCenter, body.MassCenter + v.Normal * 100, Color.Green, 0, false); } var angle = (rotation.Forward.Normal * MathF.Sign(localVelocity.x)).Normal.Dot(v.Normal).Clamp(0.0f, 1.0f); angle = angle.LerpTo(1.0f, 1.0f - vDelta); grip = grip.LerpTo(angle, 1.0f - MathF.Pow(0.001f, dt)); if (debug_car) { DebugOverlay.ScreenText(new Vector2(200, 200), $"{grip}"); } var angularDamping = 0.0f; angularDamping = angularDamping.LerpTo(5.0f, grip); body.LinearDamping = 0.0f; body.AngularDamping = fullyGrounded ? angularDamping : 0.5f; if (onGround) { localVelocity = rotation.Inverse * body.Velocity; WheelSpeed = localVelocity.x; var turnAmount = frontWheelsOnGround ? (MathF.Sign(localVelocity.x) * 25.0f * CalculateTurnFactor(TurnDirection, MathF.Abs(localVelocity.x)) * dt) : 0.0f; body.AngularVelocity += rotation * new Vector3(0, 0, turnAmount); airRoll = 0; airTilt = 0; var forwardGrip = 0.1f; forwardGrip = forwardGrip.LerpTo(0.9f, currentInput.breaking); body.Velocity = VelocityDamping(Velocity, rotation, new Vector3(forwardGrip, grip, 0), dt); } else { var s = selfBody.Position + (rotation * selfBody.LocalMassCenter); var tr = Trace.Ray(s, s + rotation.Down * 50) .Ignore(this) .Run(); if (debug_car) { DebugOverlay.Line(tr.StartPosition, tr.EndPosition, tr.Hit ? Color.Red : Color.Green); } canAirControl = !tr.Hit; } if (canAirControl && (airRoll != 0 || airTilt != 0)) { var offset = 50 * Scale; var s = selfBody.Position + (rotation * selfBody.LocalMassCenter) + (rotation.Right * airRoll * offset) + (rotation.Down * (10 * Scale)); var tr = Trace.Ray(s, s + rotation.Up * (25 * Scale)) .Ignore(this) .Run(); if (debug_car) { DebugOverlay.Line(tr.StartPosition, tr.EndPosition); } bool dampen = false; if (currentInput.roll.Clamp(-1, 1) != 0) { var force = tr.Hit ? 400.0f : 100.0f; var roll = tr.Hit ? currentInput.roll.Clamp(-1, 1) : airRoll; body.ApplyForceAt(selfBody.MassCenter + rotation.Left * (offset * roll), (rotation.Down * roll) * (roll * (body.Mass * force))); if (debug_car) { DebugOverlay.Sphere(selfBody.MassCenter + rotation.Left * (offset * roll), 8, Color.Red); } dampen = true; } if (!tr.Hit && currentInput.tilt.Clamp(-1, 1) != 0) { var force = 200.0f; body.ApplyForceAt(selfBody.MassCenter + rotation.Forward * (offset * airTilt), (rotation.Down * airTilt) * (airTilt * (body.Mass * force))); if (debug_car) { DebugOverlay.Sphere(selfBody.MassCenter + rotation.Forward * (offset * airTilt), 8, Color.Green); } dampen = true; } if (dampen) { body.AngularVelocity = VelocityDamping(body.AngularVelocity, rotation, 0.95f, dt); } } localVelocity = rotation.Inverse * body.Velocity; MovementSpeed = localVelocity.x; }
public static void AddDebugInformation(Func <string> worker) { DebugOverlay.AddInformation(worker); }
protected override void Update(Entity abilityEntity, CharBehaviour charAbility, AbilityControl abilityCtrl, Ability_Movement.Settings settings) { if (abilityCtrl.active == 0) { if (abilityCtrl.behaviorState != AbilityControl.State.Idle) { abilityCtrl.behaviorState = AbilityControl.State.Idle; EntityManager.SetComponentData(abilityEntity, abilityCtrl); } return; } // Movement is always active (unless canceled) abilityCtrl.behaviorState = AbilityControl.State.Active; EntityManager.SetComponentData(abilityEntity, abilityCtrl); var time = m_world.worldTime; var command = EntityManager.GetComponentData <UserCommandComponentData>(charAbility.character).command; var predictedState = EntityManager.GetComponentData <CharacterPredictedData>(charAbility.character); var character = EntityManager.GetComponentObject <Character>(charAbility.character); var newPhase = CharacterPredictedData.LocoState.MaxValue; var phaseDuration = time.DurationSinceTick(predictedState.locoStartTick); var isOnGround = predictedState.IsOnGround(); var isMoveWanted = command.moveMagnitude != 0.0f; // Ground movement if (isOnGround) { if (isMoveWanted) { newPhase = CharacterPredictedData.LocoState.GroundMove; } else { newPhase = CharacterPredictedData.LocoState.Stand; } } // Jump if (isOnGround) { predictedState.jumpCount = 0; } if (command.buttons.IsSet(UserCommand.Button.Jump) && isOnGround) { predictedState.jumpCount = 1; newPhase = CharacterPredictedData.LocoState.Jump; } if (command.buttons.IsSet(UserCommand.Button.Jump) && predictedState.locoState == CharacterPredictedData.LocoState.InAir && predictedState.jumpCount < 2) { predictedState.jumpCount = predictedState.jumpCount + 1; predictedState.velocity.y = 0; newPhase = CharacterPredictedData.LocoState.DoubleJump; } if (predictedState.locoState == CharacterPredictedData.LocoState.Jump || predictedState.locoState == CharacterPredictedData.LocoState.DoubleJump) { if (phaseDuration >= Game.config.jumpAscentDuration) { newPhase = CharacterPredictedData.LocoState.InAir; } } // Set phase start tick if phase has changed if (newPhase != CharacterPredictedData.LocoState.MaxValue && newPhase != predictedState.locoState) { predictedState.locoState = newPhase; predictedState.locoStartTick = time.tick; } if (debugCharacterMove.IntValue > 0) { // Only show for one player if (lastUsedFrame < Time.frameCount) { lastUsedFrame = Time.frameCount; int o = Time.frameCount % movehist_x.Length; movehist_x[o] = predictedState.position.x % 10.0f; movehist_y[o] = predictedState.position.y % 10.0f; movehist_z[o] = predictedState.position.z % 10.0f; DebugOverlay.DrawGraph(4, 4, 10, 5, movehist_x, o, Color.red, 10.0f); DebugOverlay.DrawGraph(4, 12, 10, 5, movehist_y, o, Color.green, 10.0f); DebugOverlay.DrawGraph(4, 20, 10, 5, movehist_z, o, Color.blue, 10.0f); } } if (time.tick != predictedState.tick + 1) { GameDebug.Log("Update tick invalid. Game tick:" + time.tick + " but current state is at tick:" + predictedState.tick); } predictedState.tick = time.tick; // Apply damange impulse from previus frame if (time.tick == predictedState.damageTick + 1) { predictedState.velocity += predictedState.damageDirection * predictedState.damageImpulse; predictedState.locoState = CharacterPredictedData.LocoState.InAir; predictedState.locoStartTick = time.tick; } var moveQuery = EntityManager.GetComponentObject <CharacterMoveQuery>(charAbility.character); // Simple adjust of height while on platform if (predictedState.locoState == CharacterPredictedData.LocoState.Stand && character.groundCollider != null && character.groundCollider.gameObject.layer == m_platformLayer) { if (character.altitude < moveQuery.settings.skinWidth - 0.01f) { var platform = character.groundCollider; var posY = platform.transform.position.y + moveQuery.settings.skinWidth; predictedState.position.y = posY; } } // Calculate movement and move character var deltaPos = Vector3.zero; CalculateMovement(ref time, ref predictedState, ref command, ref deltaPos); // Setup movement query moveQuery.collisionLayer = character.teamId == 0 ? m_charCollisionALayer : m_charCollisionBLayer; moveQuery.moveQueryStart = predictedState.position; moveQuery.moveQueryEnd = moveQuery.moveQueryStart + (float3)deltaPos; EntityManager.SetComponentData(charAbility.character, predictedState); }
public void Init() { instance = this; }
private void Start() { debugOverlay = FindObjectOfType <DebugOverlay>(); }
protected override void OnUpdate() { var cameraArray = Group.GetComponentArray <Camera>(); var playerCameraArray = Group.GetComponentArray <PlayerCamera>(); for (var i = 0; i < cameraArray.Length; i++) { var camera = cameraArray[i]; var playerCamera = playerCameraArray[i]; var settings = playerCamera.cameraSettings; var enabled = settings.isEnabled; var isActive = camera.gameObject.activeSelf; if (!enabled) { if (isActive) { Game.game.PopCamera(camera); camera.gameObject.SetActive(false); } continue; } if (!isActive) { camera.gameObject.SetActive(true); Game.game.PushCamera(camera); } camera.fieldOfView = settings.fieldOfView; if (debugCameraDetach.IntValue == 0) { // Normal movement camera.transform.position = settings.position; camera.transform.rotation = settings.rotation; } else if (debugCameraDetach.IntValue == 1) { // Move char but still camera } if (debugCameraDetach.ChangeCheck()) { // Block normal input Game.Input.SetBlock(Game.Input.Blocker.Debug, debugCameraDetach.IntValue == 2); } if (debugCameraDetach.IntValue == 2 && !Console.IsOpen()) { var eu = camera.transform.localEulerAngles; if (eu.x > 180.0f) { eu.x -= 360.0f; } eu.x = Mathf.Clamp(eu.x, -70.0f, 70.0f); eu += new Vector3(-Input.GetAxisRaw("Mouse Y"), Input.GetAxisRaw("Mouse X"), 0); float invertY = Game.configInvertY.IntValue > 0 ? 1.0f : -1.0f; eu += Time.deltaTime * (new Vector3(-invertY * Input.GetAxisRaw("RightStickY") * InputSystem.s_JoystickLookSensitivity.y, Input.GetAxisRaw("RightStickX") * InputSystem.s_JoystickLookSensitivity.x, 0)); camera.transform.localEulerAngles = eu; m_DetachedMoveSpeed += Input.GetAxisRaw("Mouse ScrollWheel"); float verticalMove = (Input.GetKey(KeyCode.R) ? 1.0f : 0.0f) + (Input.GetKey(KeyCode.F) ? -1.0f : 0.0f); verticalMove += Input.GetAxisRaw("Trigger"); camera.transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal"), verticalMove, Input.GetAxisRaw("Vertical")) * Time.deltaTime * m_DetachedMoveSpeed); } if (debugCameraMove.IntValue > 0) { // Only show for one player if (lastUsedFrame < Time.frameCount) { lastUsedFrame = Time.frameCount; int o = Time.frameCount % movehist_x.Length; var rot = camera.transform.localEulerAngles; movehist_x[o] = rot.x % 90.0f; movehist_y[o] = rot.y % 90.0f; movehist_z[o] = rot.z % 90.0f; DebugOverlay.DrawGraph(4, 4, 10, 5, movehist_x, o, Color.red, 10.0f); DebugOverlay.DrawGraph(4, 12, 10, 5, movehist_y, o, Color.green, 10.0f); DebugOverlay.DrawGraph(4, 20, 10, 5, movehist_z, o, Color.blue, 10.0f); } } } }
void OnCollisionEnter(Collision collision) { // Play snowball impact sound // // @NOTE(sdsmith): Must use AudioSource.PlayClipAtpoint so the clip // persists after the destruction of the object. If we ere using an // AudioSource component, the clip would stop playing once that // component was destroyed. AudioClip impactClip = AudioClips.GetRand(AudioClips.snowballImpacts); AudioSource.PlayClipAtPoint(impactClip, transform.position); if (collision.gameObject.name == "Mountain") { // @NOTE(sdsmith): @PERFORMANCE(sdsmith): Note that 'Destroy' // delayed at least until the end of the frame update cycle. If we // hit the terrain, we know we don't need to do any additional // collision calculations. // // @TODO(sdsmith): This breaks Network manager when we take the advice // of the above comment and end the function here. Who knows. // - 2017-02-27 Destroy(this.gameObject); } // @DEBUG(sdsmith): Update debug overlay DebugOverlay.AddAttr("snowball collision count", (++nonTerrainCollisionCount).ToString()); Transform hitTransform = collision.transform; // If we hit something, lets resolve the hit if (hitTransform != null) { // Debug.Log ("HIT: " + collision.gameObject.name); Health h = hitTransform.GetComponent <Health>(); // check if the things parent has a Health object while (h == null && hitTransform.parent) { hitTransform = hitTransform.parent; h = hitTransform.GetComponent <Health>(); } // The thing we hit has a health component // Tell the thing we hit to take damage if (h != null) { PhotonView pv = h.GetComponent <PhotonView>(); if (pv == null) { Debug.Log("PlayerShooting: PhotonView is null"); } else { //get the thing that was hit PhotonPlayer target = pv.owner; // Get teams PunTeams.Team ourTeam = PhotonNetwork.player.GetTeam(); PunTeams.Team theirTeam = PunTeams.Team.none; // default objects to no team // Check if the target object has an owner // @NOTE(sdsmith): PhotonView.owner is null for scene objects // https://doc-api.photonengine.com/en/pun/current/class_photon_view.html#ad696cb93fb9835d633b9def970650edc if (target != null) { // Target has an owner (not a scene object), set its team theirTeam = target.GetTeam(); } if (ourTeam != theirTeam) { // Not targeting same team pv.RPC("TakeDamage", PhotonTargets.AllBuffered, damage, throwerViewID); // Play hit sound if our local client threw the snowball PhotonView throwerPV = PhotonView.Find(throwerViewID); if (throwerPV && Util.localPlayer == throwerPV.gameObject) { throwerPV.gameObject.GetComponent <PlayerController>().PlayHitNotification(); } } else { // Targeting same team } } } Destroy(this.gameObject); } }
public OpenKhGame(OpenKhGameStartup startup) { _startup = startup; GlobalSettings = new Dictionary <string, string>(); TryAddSetting("WorldId", startup.InitialMap); TryAddSetting("PlaceId", startup.InitialPlace); //TryAddSetting("SpawnId", ); TryAddSetting("SpawnScriptMap", startup.InitialSpawnScriptMap); TryAddSetting("SpawnScriptBtl", startup.InitialSpawnScriptBtl); TryAddSetting("SpawnScriptEvt", startup.InitialSpawnScriptEvt); var contentPath = startup.ContentPath ?? Config.DataPath; _dataContent = CreateDataContent(contentPath, Config.IdxFilePath, Config.ImgFilePath); _dataContent = new MultipleDataContent(new ModDataContent(), _dataContent); if (Kernel.IsReMixFileHasHdAssetHeader(_dataContent, "fm")) { Log.Info("ReMIX files with HD asset header detected"); _dataContent = new HdAssetContent(_dataContent); } _dataContent = new SafeDataContent(_dataContent); _kernel = new Kernel(_dataContent); if (startup.InitialState != 0) { _kernel.LoadSaveData(Config.LastSave); } var resolutionWidth = GetResolutionWidth(); var resolutionHeight = GetResolutionHeight(); Log.Info("Internal game resolution set to {0}x{1}", resolutionWidth, resolutionHeight); graphics = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = (int)Math.Round(resolutionWidth * Config.ResolutionBoost), PreferredBackBufferHeight = (int)Math.Round(resolutionHeight * Config.ResolutionBoost), IsFullScreen = Config.IsFullScreen, }; Content.RootDirectory = "Content"; IsMouseVisible = true; archiveManager = new ArchiveManager(_dataContent); inputManager = new InputManager(); _debugOverlay = new DebugOverlay(this); Config.OnConfigurationChange += () => { var resolutionWidth = GetResolutionWidth(); var resolutionHeight = GetResolutionHeight(); var backBufferWidth = (int)Math.Round(resolutionWidth * Config.ResolutionBoost); var backBufferHeight = (int)Math.Round(resolutionHeight * Config.ResolutionBoost); if (graphics.PreferredBackBufferWidth != backBufferWidth || graphics.PreferredBackBufferHeight != backBufferHeight || graphics.IsFullScreen != Config.IsFullScreen) { graphics.PreferredBackBufferWidth = backBufferWidth; graphics.PreferredBackBufferHeight = backBufferHeight; graphics.IsFullScreen = Config.IsFullScreen; _isResolutionChanged = true; Log.Info($"Internal game resolution set to {resolutionWidth}x{resolutionHeight}"); } }; }
public override void OnPlayerControlTick(TankPlayer player, bool allowDebug) { float throttle = Input.Forward; float steering = Input.Left * (throttle >= 0 ? 1 : -1) * TurnSpeed; var moveDelta = Rotation.Forward * throttle * MoveSpeed; // Corner world position var frontLeft = moveDelta + Position + Rotation * (extents * new Vector3(1, 1, 0.5f)); var frontRight = moveDelta + Position + Rotation * (extents * new Vector3(1, -1, 0.5f)); var backLeft = moveDelta + Position + Rotation * (extents * new Vector3(-1, 1, 0.5f)); var backRight = moveDelta + Position + Rotation * extents * new Vector3(-1, -1, 0.5f); var center = moveDelta + Position + extents * new Vector3(0, 0, 0.5f); // Base world directions var frontDir = Rotation.Forward; var leftDir = Rotation.Left; var backDir = Rotation.Backward; var rightDir = Rotation.Right; var frontLeftDir = (frontDir + leftDir).Normal; var frontRightDir = (frontDir + rightDir).Normal; var backLeftDir = (backDir + leftDir).Normal; var backRightDir = (backDir + rightDir).Normal; float testDistance = 2 * MoveSpeed; if (allowDebug) { /*DebugOverlay.Axis(frontLeft, Rotation); * DebugOverlay.Axis(frontRight, Rotation); * DebugOverlay.Axis(backLeft, Rotation); * DebugOverlay.Axis(backRight, Rotation);*/ DebugOverlay.Sphere(frontLeft, testDistance, Color.Red); DebugOverlay.Sphere(frontRight, testDistance, Color.Red); DebugOverlay.Sphere(backLeft, testDistance, Color.Red); DebugOverlay.Sphere(backRight, testDistance, Color.Red); } var cornerResults = new TraceResult[12]; cornerResults[0] = Trace.Ray(frontLeft, frontLeft + frontDir * testDistance).Run(); // Forward cornerResults[1] = Trace.Ray(frontLeft, frontLeft + leftDir * testDistance).Run(); // Side cornerResults[2] = Trace.Ray(frontLeft, frontLeft + frontRightDir * testDistance).Run(); // Diagonal inward cornerResults[3] = Trace.Ray(frontRight, frontRight + frontDir * testDistance).Run(); cornerResults[4] = Trace.Ray(frontRight, frontRight + rightDir * testDistance).Run(); cornerResults[5] = Trace.Ray(frontRight, frontRight + frontLeftDir * testDistance).Run(); cornerResults[6] = Trace.Ray(backLeft, backLeft + backDir * testDistance).Run(); cornerResults[7] = Trace.Ray(backLeft, backLeft + leftDir * testDistance).Run(); cornerResults[8] = Trace.Ray(backLeft, backLeft + backRightDir * testDistance).Run(); cornerResults[9] = Trace.Ray(backRight, backRight + backDir * testDistance).Run(); cornerResults[10] = Trace.Ray(backRight, backRight + rightDir * testDistance).Run(); cornerResults[11] = Trace.Ray(backRight, backRight + backLeftDir * testDistance).Run(); // Turn off movement and don't collide if both front or back corners are colliding (but only if pushing against an axis-aligned wall) bool noMove = (cornerResults[0].Hit && cornerResults[3].Hit) || (cornerResults[6].Hit && cornerResults[9].Hit); float yaw = Rotation.Yaw(); noMove &= yaw.SnapToGrid(90).AlmostEqual(yaw, 2); if (noMove) { moveDelta = 0; } for (int i = 0; i < cornerResults.Length; i++) { var result = cornerResults[i]; if (!result.Hit) { if (allowDebug) { DebugOverlay.Line(result.StartPos, result.StartPos + result.Direction * testDistance * 8, Color.Green, 0, false); } continue; } if (i % 3 != 0 && cornerResults[i - (i % 3)].Hit) // Skip the side and diagonal tests if the primary one already hit { if (allowDebug) { DebugOverlay.Line(result.StartPos, result.StartPos + result.Direction * testDistance * 8, Color.Yellow, 0, false); } continue; } if (i % 3 == 0 && noMove) { continue; } if (allowDebug) { DebugOverlay.Line(result.StartPos, result.StartPos + result.Direction * testDistance * 8, Color.Red, 0, false); } Position += result.Normal * (testDistance - result.Distance); float torque = Vector3.Cross(result.StartPos - center, result.Normal).z *Time.Delta; Rotation *= Rotation.FromYaw(torque); if (allowDebug) { DebugOverlay.Line(result.EndPos, result.EndPos + result.Normal * MathF.Abs(torque) * 50, Color.Blue, 0, false); } } var edgeResults = new TraceResult[8]; edgeResults[0] = Trace.Ray(frontLeft, frontRight).Run(); edgeResults[2] = Trace.Ray(backLeft, backRight).Run(); edgeResults[4] = Trace.Ray(frontLeft, backLeft).Run(); edgeResults[6] = Trace.Ray(frontRight, backRight).Run(); for (int i = 0; i < edgeResults.Length; i += 2) { var result = edgeResults[i]; if (result.Hit) // Only run the partner trace if the first one on that edge hits { if (i == 0) { edgeResults[i + 1] = Trace.Ray(frontRight, frontLeft).Run(); } else if (i == 2) { edgeResults[i + 1] = Trace.Ray(backRight, backLeft).Run(); } else if (i == 4) { edgeResults[i + 1] = Trace.Ray(backLeft, frontLeft).Run(); } else if (i == 6) { edgeResults[i + 1] = Trace.Ray(backRight, frontRight).Run(); } } else { continue; } if (allowDebug) { DebugOverlay.Line(result.StartPos, result.EndPos, 0, false); } Vector3 correctionDir = Vector3.Zero; if (i == 0) { correctionDir = frontDir; } else if (i == 2) { correctionDir = backDir; } else if (i == 4) { correctionDir = leftDir; } else if (i == 6) { correctionDir = rightDir; } float distance = Vector3.DistanceBetween(result.EndPos, edgeResults[i + 1].EndPos); float angle = Vector3.GetAngle(result.EndPos - result.StartPos, result.Normal) - 90; float correction = distance * 0.5f * MathF.Sin(2 * angle.DegreeToRadian()); // How much to push out of the corner, finds the altitude of a right triangle Position -= correctionDir * correction; var avgPos = (result.EndPos + edgeResults[i + 1].EndPos) * 0.5f; float torque = Vector3.Cross(avgPos - center, -correctionDir).z *Time.Delta; Rotation *= Rotation.FromYaw(torque); if (allowDebug) { DebugOverlay.Line(avgPos, avgPos - correctionDir * MathF.Abs(torque) * 50, Color.Cyan, 0, false); DebugOverlay.Line(result.EndPos, edgeResults[i + 1].EndPos, Color.Red, 0, false); DebugOverlay.Line(result.EndPos, result.EndPos + correctionDir * correction * 10, Color.Green, 0, false); DebugOverlay.Line(edgeResults[i + 1].EndPos, edgeResults[i + 1].EndPos + correctionDir * correction * 10, Color.Green, 0, false); } } moveDelta = moveDelta.WithZ(0); Position += moveDelta; Rotation *= Rotation.FromYaw(steering); }
// Checks if a specific debug overlay is enabled public bool IsDebugOverlayEnabled(DebugOverlay overlay) { return(debugLayer.debugOverlay == overlay); }
public void OnFrame() { var pos = WorldPos; var right = Rot.Right * 4; var forward = Rot.Forward * 4; var up = Rot.Up * 50; var offset = Time.Now * 2.0f; var offsetz = Time.Now * 0.1f; var mode = (int)((Time.Now * 0.3f) % 5); switch (mode) { case 0: { DebugOverlay.Text(pos, "Perlin"); break; } case 1: { DebugOverlay.Text(pos, "SparseConvolution"); break; } case 2: { DebugOverlay.Text(pos, "SparseConvolutionNormalized"); break; } case 3: { DebugOverlay.Text(pos, "Turbulence"); break; } case 4: { DebugOverlay.Text(pos, "Fractal"); break; } } var size = 100; pos -= right * size * 0.5f; pos -= forward * size * 0.5f; for (float x = 0; x < size; x++) { for (float y = 0; y < size; y++) { float val = 0; switch (mode) { case 0: { val = Noise.Perlin(x * 0.1f + offset, y * 0.1f, offsetz) * 0.5f; break; } case 1: { val = Noise.SparseConvolution(x * 0.1f + offset, y * 0.1f, offsetz) * 0.5f; break; } case 2: { val = Noise.SparseConvolutionNormalized(x * 0.1f + offset, y * 0.1f, offsetz) * 0.5f; break; } case 3: { val = Noise.Turbulence(2, x * 0.1f + offset, y * 0.1f, offsetz) * 0.5f; break; } case 4: { val = Noise.Fractal(2, x * 0.1f + offset, y * 0.1f, offsetz) * 0.5f; break; } } var start = pos + x * right + y * forward; DebugOverlay.Line(start, start + up * val, Color.Lerp(Color.Red, Color.Green, (val + 1.0f) / 2.0f)); } } }
void DrawStats() { int y = 2; Overlay.Managed.Write(2, y++, " tick rate: {0}", Game.serverTickRate.IntValue); Overlay.Managed.Write(2, y++, " entities: {0}", m_NetworkServer.NumEntities); Overlay.Managed.Write(2, y++, " sim : {0:0.0} / {1:0.0} / {2:0.0} ({3:0.0})", m_ServerSimTime.min, m_ServerSimTime.min, m_ServerSimTime.max, m_ServerSimTime.stdDeviation); int totalSnapshots = 0; foreach (var c in m_NetworkServer.GetConnections()) { totalSnapshots += c.Value.counters.snapshotsOut; } snapsPerFrame[Time.frameCount % snapsPerFrame.Length] = (totalSnapshots - totalSnapshotsLastFrame); totalSnapshotsLastFrame = totalSnapshots; DebugOverlay.DrawHist(2, 10, 60, 5, snapsPerFrame, Time.frameCount % snapsPerFrame.Length, new Color(0.5f, 0.5f, 1.0f)); //for(var i = 0; i < counters.) //DebugOverlay.Write(2, y++, " entities: {0}", counters.numEntities); /* * * DebugOverlay.Write(2, y++, "^FF0 lat : {0:0.0} / {1:0.0} / {2:0.0}", m_Latency.min, m_Latency.average, m_Latency.max); * DebugOverlay.Write(2, y++, "^0FF rtt : {0:0.0} / {1:0.0} / {2:0.0}", m_RTT.min, m_RTT.average, m_RTT.max); * DebugOverlay.Write(2, y++, "^0F0 cmdq : {0:0.0} / {1:0.0} / {2:0.0}", m_CMDQ.min, m_CMDQ.average, m_CMDQ.max); * DebugOverlay.Write(2, y++, "^F0F intp : {0:0.0} / {1:0.0} / {2:0.0}", m_Interp.min, m_Interp.average, m_Interp.max); * * var samplesPerSecond = 1.0f / m_StatsDeltaTime.average; * * y++; * DebugOverlay.Write(2, y++, "^00F bps (in): {0:00.0} ({1})", m_BytesIn.graph.average * samplesPerSecond, m_NetworkClient.updateRate); * DebugOverlay.Write(2, y++, "^F00 bps (out): {0:00.0}", m_BytesOut.graph.average * samplesPerSecond); * DebugOverlay.Write(2, y++, " pps (in): {0:00.0}", m_PackagesIn.graph.average * samplesPerSecond); * DebugOverlay.Write(2, y++, " pps (out): {0:00.0}", m_PackagesOut.graph.average * samplesPerSecond); * DebugOverlay.Write(2, y++, " pl% (in): {0:00.0}", m_PackageLossPctIn.average); * DebugOverlay.Write(2, y++, " pl% (out): {0:00.0}", m_PackageLossPctOut.average); * * y++; * DebugOverlay.Write(2, y++, " upd_srate: {0:00.0} ({1})", m_SnapshotsIn.graph.average * samplesPerSecond, m_NetworkClient.updateSendRate); * DebugOverlay.Write(2, y++, " cmd_srate: {0:00.0} ({1})", m_CommandsOut.graph.average * samplesPerSecond, m_NetworkClient.commandSendRate); * DebugOverlay.Write(2, y++, " ev (in): {0:00.0}", m_EventsIn.graph.average * samplesPerSecond); * DebugOverlay.Write(2, y++, " ev (out): {0:00.0}", m_EventsOut.graph.average * samplesPerSecond); * * var startIndex = m_BytesIn.graph.GetData().HeadIndex; * var graphY = 5; * * DebugOverlay.DrawGraph(38, graphY, 60, 5, m_Latency.GetData().GetArray(), startIndex, Color.yellow, 100); * DebugOverlay.DrawGraph(38, graphY, 60, 5, m_RTT.GetData().GetArray(), startIndex, Color.cyan, 100); * DebugOverlay.DrawGraph(38, graphY, 60, 5, m_CMDQ.GetData().GetArray(), startIndex, Color.green, 10); * DebugOverlay.DrawGraph(38, graphY, 60, 5, m_Interp.GetData().GetArray(), startIndex, Color.magenta, 100); * DebugOverlay.DrawHist(38, graphY, 60, 5, m_HardCatchup.GetArray(), startIndex, Color.red, 100); * * m_2GraphData[0] = m_BytesIn.graph.GetData().GetArray(); * m_2GraphData[1] = m_BytesOut.graph.GetData().GetArray(); * * graphY += 7; * DebugOverlay.DrawGraph(38, graphY, 60, 5, m_2GraphData, startIndex, m_BytesGraphColors); * * graphY += 6; * DebugOverlay.DrawHist(38, graphY++, 60, 1, m_SnapshotsIn.graph.GetData().GetArray(), startIndex, Color.blue, 5.0f); * DebugOverlay.DrawHist(38, graphY++, 60, 1, m_CommandsOut.graph.GetData().GetArray(), startIndex, Color.red, 5.0f); * DebugOverlay.DrawHist(38, graphY++, 60, 1, m_EventsIn.graph.GetData().GetArray(), startIndex, Color.yellow, 5.0f); * DebugOverlay.DrawHist(38, graphY++, 60, 1, m_EventsOut.graph.GetData().GetArray(), startIndex, Color.green, 5.0f); */ }
protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera camera, CullingResults cullingResult) { SetCameraRenderTarget(cmd); DebugOverlay.Render(camera.camera.cameraType, cmd); }
public void RequestDebugOverlay(DebugOverlay mode) { debugOverlay = mode; }
public static void DebugText(this object any, int line = 0, int duration = 0) { DebugOverlay.ScreenText(line, any.ToString(), duration); }