protected override void OnUpdate() { EntityQueryBuilder queryBuilder = Entities.WithAll(typeof(MoveComponent), typeof(Translation), typeof(EnemyComponent)); queryBuilder.ForEach((ref MoveComponent move, ref Translation translation, ref EnemyComponent enemyComponent) => { //move.speed += move.acc * Time.DeltaTime; translation.Value += new float3(move.dragDir * Time.DeltaTime, 0); }); queryBuilder = Entities.WithAll(typeof(MoveComponent), typeof(Translation), typeof(Rotation)); queryBuilder.ForEach((ref MoveComponent move, ref Translation translation, ref Rotation rotation) => { move.acc = move.dragDir * math.lerp(0, GameSetting.Instance.maxAccDirStep, move.dragDirLenth) * GameSetting.Instance.playerAccParam; move.speed += move.acc * Time.DeltaTime; move.speed = math.clamp(move.speed, -move.maxSpeed, move.maxSpeed); if (!move.speed.Equals(float2.zero)) { float2 nspeed = math.normalize(move.speed); float angle = nspeed.x > 0 ? math.acos(nspeed.y) : -math.acos(nspeed.y); rotation.Value = quaternion.AxisAngle(zAxis, angle); } translation.Value += new float3(move.speed * Time.DeltaTime, 0); }); }
public static void KillPlayer(Entity playerCar, EntityManager EntityManager, EntityQueryBuilder Entities, EntityCommandBuffer PostUpdateCommands) { var playerId = EntityManager.GetComponentData <SynchronizedCarComponent>(playerCar).PlayerId; DynamicBuffer <PowerupSlotElement> powerupSlots = EntityManager.GetBuffer <PowerupSlotElement>(playerCar); for (int i = 0; i < SerializedFields.singleton.numberOfPowerupSlots; i++) { powerupSlots[i] = new PowerupSlotElement { Content = PowerupSlotContent.Empty }; } EntityManager.GetBuffer <LaserPowerupSlotElement>(playerCar).Clear(); Entities.ForEach((Entity connectionEntity, ref NetworkIdComponent id) => { if (id.Value == EntityManager.GetComponentData <SynchronizedCarComponent>(playerCar).PlayerId) { for (uint i = 0; i < SerializedFields.singleton.numberOfPowerupSlots; i++) { var powerupSlotChangedRequest = PostUpdateCommands.CreateEntity(); PostUpdateCommands.AddComponent(powerupSlotChangedRequest, new PowerupSlotChangedRequest { SlotNumber = i, SlotContent = PowerupSlotContent.Empty }); PostUpdateCommands.AddComponent(powerupSlotChangedRequest, new SendRpcCommandRequestComponent { TargetConnection = connectionEntity }); } } }); var resurrectionEntity = PostUpdateCommands.CreateEntity(); PostUpdateCommands.AddComponent(resurrectionEntity, new ResurrectionComponent { CarToResurrect = playerCar, RemainingTime = SerializedFields.singleton.deathPenaltyInSeconds }); Entities.ForEach((Entity connectionEntity, ref NetworkIdComponent networkIdComponent) => { var playerDiedRequest = PostUpdateCommands.CreateEntity(); PostUpdateCommands.AddComponent(playerDiedRequest, new PlayerDiedRequest { PlayerId = playerId }); PostUpdateCommands.AddComponent(playerDiedRequest, new SendRpcCommandRequestComponent { TargetConnection = connectionEntity }); }); }
/// <summary> /// resumes all timers /// </summary> /// <param name="entities">A reference to the EntityQueryBuilder instance</param> public static void ResumeAllTimers(EntityQueryBuilder entities) { entities.ForEach((ref Timer timer) => { timer.isPaused = false; }); }
/// <summary> /// Marks a scene for unloading /// </summary> /// <param name="entityManager">Reference to the entitymanager instance</param> /// <param name="entities">A reference tot the entityquerybuilder instance named entities</param> /// <param name="sceneNumberToUnload">The index fo the scene to unload</param> /// <returns>Weather or not the scene is succesfully marked for unloading</returns> public static bool MarkSceneForUnload(EntityManager entityManager, EntityQueryBuilder entities, int sceneNumberToUnload) { NativeArray <ScenesLoaded> scenesLoaded = entityManager.GetBuffer <ScenesLoaded>(_sceneHandler).ToNativeArray(Allocator.Temp); if (!entityManager.HasComponent <Indestructable>(scenesLoaded[sceneNumberToUnload].referenceEntity)) { try { entities.ForEach((DynamicBuffer <ScenesToUnload> scenesToLoad) => { scenesToLoad.Add(new ScenesToUnload { sceneNumber = sceneNumberToUnload, doByNumber = true }); }); return(true); } catch (Exception e) { Debug.Log(e.ToString()); } } scenesLoaded.Dispose(); return(false); }
/// <summary> /// Marks a scene for unloading /// </summary> /// <param name="entityManager">Reference to the entitymanager instance</param> /// <param name="entities">A reference tot the entityquerybuilder instance named entities</param> /// <param name="sceneToUnload">The Entity with the SceneData component</param> /// <returns>Weather or not the scene is succesfully marked for unloading</returns> public static bool MarkSceneForUnload(EntityManager entityManager, EntityQueryBuilder entities, Entity sceneToUnload) { if (!entityManager.HasComponent <Indestructable>(sceneToUnload)) { try { entities.ForEach((DynamicBuffer <ScenesToUnload> scenesToLoad) => { scenesToLoad.Add(new ScenesToUnload { scene = sceneToUnload, doByNumber = false }); }); return(true); } catch (Exception e) { Debug.Log(e.ToString()); } } return(false); }
/// <summary> /// Loads the scene at the given index /// </summary> /// <param name="numberInFlow">The index of the scene you want to load</param> /// <param name="entityManager">A reference to the entitymanager instance</param> /// <param name="entities">A reference to the entityQueryBuilder instance</param> /// <returns>A bool to mark the succesfull scene loading</returns> /// <exception cref="TriedToLoadDisabledSceneException">When you try to load a disabled scene</exception> private static bool LoadFlowScene(int numberInFlow, EntityManager entityManager, EntityQueryBuilder entities) { try { bool loadedScene = false; if (_flow[numberInFlow].disabledInFlow) { throw new TriedToLoadDisabledSceneException(); } loadedScene = SceneHandlerSystem.NextScene(_flow[numberInFlow].flowScene, entityManager, entities, false); if (loadedScene) { entities.ForEach((ref FlowStatistics stats) => { stats.currentScene = numberInFlow; }); } return(loadedScene); } catch (Exception e) { Debug.Log(e.ToString()); } return(false); }
/// <summary> /// Adds a scenereference to lists of scenes to spawn a copy of it during the next scene in the OnUpdate() /// The position and offset is added to all entities in the scene /// </summary> /// <param name="sceneReference">A reference to the scene to spawn</param> /// <param name="isIndestructable">If true, there will be NO way to unload the scene</param> /// <param name="entities">The EntitiesQueryBuilder Entities</param> /// <param name="posGiven">The absolute new position of the sceneEntities</param> /// <param name="offsetGiven">The relative new position of the sceneEntities</param> /// <returns>A bool to mark the correct loading of the scene</returns> public static bool LoadSceneAsyncWithPositionAndOffset(SceneReference sceneReference, bool isIndestructable, EntityQueryBuilder entities, float2 posGiven, float2 offsetGiven) { try { entities.ForEach((DynamicBuffer <ScenesToLoad> scenesToLoad) => { scenesToLoad.Add(new ScenesToLoad { sceneReference = sceneReference, makeIndestrucktable = isIndestructable, setPos = true, setOffset = true, pos = posGiven, offset = offsetGiven }); }); return(true); } catch (Exception e) { Debug.Log(e.ToString()); return(false); } }
public void Update() { if (!_inProgress) { return; } _queryBuilder.ForEach((Entity entity, ref TComponent component, ref TMarker marker) => { if (_items.ContainsKey(entity)) { if (component.Completed) { OnItemCompleted?.Invoke(entity, ref component, ref marker); _items.Remove(entity); } } }); if (_inProgress && _items.Count == 0) { _inProgress = false; Completed = true; OnCompleted?.Invoke(this); OnReadyToRelease?.Invoke(this); } }
protected override void OnUpdate() { EntityQueryBuilder queryBuilder = Entities.WithAll(typeof(MoveComponent), typeof(EnemyComponent)); queryBuilder.ForEach((ref MoveComponent moveComponent, ref EnemyComponent enemyComponent) => { moveComponent.dragDir = rand.NextFloat2(1) - 0.5f; }); }
/// <summary> /// set the maxTime for a timer /// </summary> /// <param name="ID">The ID of the timer</param> /// <param name="entities">A reference to the EntityQueryBuilder instance</param> /// <param name="time">The max time to set the timer to</param> public static void SetMaxTime(uint ID, EntityQueryBuilder entities, float time) { entities.ForEach((ref Timer timer) => { if (timer.ID == ID) { timer.maxTime = time; } }); }
/// <summary> /// Set a new scenerefernce to spawn /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> /// <param name="sceneReference">The new scenereference to spawn</param> public static void SetSceneReference(EntityQueryBuilder entities, uint ID, SceneReference sceneReference) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.sceneReferenceToSpawn = sceneReference; } }); }
/// <summary> /// Set a new relative spawning position /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> /// <param name="newOffset">The new relative position</param> public static void SetSpawnOffset(EntityQueryBuilder entities, uint ID, float2 newOffset) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.spawnOffset = newOffset; } }); }
/// <summary> /// Resume a spawner to spawning scenes /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> public static void ResumeSpawning(EntityQueryBuilder entities, uint ID) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.isSpawningPaused = false; } }); }
/// <summary> /// Set a spawner to a new spawntype /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> /// <param name="type">The new spawntype</param> public static void SetSpawnMode(EntityQueryBuilder entities, uint ID, SpawnType type) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.spawnType = type; } }); }
/// <summary> /// Triggers both timed and manual spawners to spawn /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> public static void Trigger(EntityQueryBuilder entities, uint ID) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.isTriggered = true; } }); }
/// <summary> /// Set the spawner to spawn with or without position and/or offset /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> /// <param name="translationType">The type of translation you want to add to all entities in the scene</param> public static void SetTranslationType(EntityQueryBuilder entities, uint ID, TranslationType translationType) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.translationType = translationType; } }); }
/// <summary> /// resumes the timer /// </summary> /// <param name="ID">The ID of the timer</param> /// <param name="entities">A reference to the EntityQueryBuilder instance</param> public static void ResumeTimer(uint ID, EntityQueryBuilder entities) { entities.ForEach((ref Timer timer) => { if (timer.ID == ID) { timer.isPaused = false; } }); }
/// <summary> /// Set a new absolute spawning position /// </summary> /// <param name="entities">A reference to the entityquerybuilder instance</param> /// <param name="ID">The ID of the spawner to trigger</param> /// <param name="newPos">The new absolute position</param> public static void SetSpawnPos(EntityQueryBuilder entities, uint ID, float2 newPos) { entities.ForEach((ref Spawner spawner) => { if (spawner.ID == ID) { spawner.spawnPos = newPos; } }); }
/// <summary> /// returns weather the timer is finished or not /// </summary> /// <param name="ID">The ID of the timer</param> /// <param name="entities">A reference to the EntityQueryBuilder instance</param> /// <returns>(bool) weather or not the timer is finished</returns> public static bool IsDone(uint ID, EntityQueryBuilder entities) { bool returnValue = false; entities.ForEach((ref Timer timer) => { if (timer.ID == ID) { returnValue = timer.isMarkedDone; } }); return(returnValue); }
public static TState TryFindTransition <TTransition, TState>( EntityQueryBuilder entities, TState from, TState[] to ) where TTransition : struct, IComponentData, IStateTransition <TState> where TState : System.Enum { TState target = from; var c = System.Collections.Generic.EqualityComparer <TState> .Default; #if UNITY_EDITOR int numTransitions = 0; entities.ForEach((ref TTransition transition) => { bool match = false; for (int i = 0; i < to.Length; i++) { if (c.Equals(transition.State, to[i])) { target = to[i]; match = true; break; } } if (!match) { UnityEngine.Debug.LogError($"Invalid transition from {from} to {transition.State}, expected {to}."); } numTransitions += 1; }); if (numTransitions > 1) { UnityEngine.Debug.LogError($"Multiple transitions from {from}."); } #else entities.ForEach((ref TTransition transition) => { for (int i = 0; i < to.Length; i++) { if (c.Equals(transition.State, to[i])) { target = to[i]; break; } } } #endif return(target); }
/// <summary> /// resets all timers /// </summary> /// <param name="entities">A reference to the EntityQueryBuilder instance</param> public static void ResetAllTimers(EntityQueryBuilder entities) { entities.ForEach((ref Timer timer) => { if (timer.countType == CountType.Down) { timer.currentTime = timer.maxTime; timer.isMarkedDone = false; } else { timer.currentTime = 0; timer.isMarkedDone = false; } }); }
public static NativeArray <CellInfo> GetCellEntitiesAtRow(this EntityQueryBuilder eqb, int i) { var result = new NativeList <CellInfo>(Allocator.Temp); eqb.ForEach((Entity e, ref Cell c) => { if (c.Position.y == i) { result.Add(new CellInfo { Entity = e, Cell = c }); } }); return(result.AsArray()); }
/// <summary> /// resets the timer /// </summary> /// <param name="ID">The ID of the timer</param> /// <param name="entities">A reference to the EntityQueryBuilder instance</param> public static void ResetTimer(uint ID, EntityQueryBuilder entities) { entities.ForEach((ref Timer timer) => { if (timer.ID != ID) { return; } if (timer.countType == CountType.Down) { timer.currentTime = timer.maxTime; timer.isMarkedDone = false; } else { timer.currentTime = 0; timer.isMarkedDone = false; } }); }
public void Update() { if (_client == Entity.Null) { return; } _queryBuilder.ForEach((Entity entity, ref TComponent component, ref TMarker marker) => { if (_client == entity) { if (component.Completed) { _client = Entity.Null; Completed = true; OnCompleted?.Invoke(entity, ref component, ref marker); OnReadyToRelease?.Invoke(this); } } }); }
/// <summary> /// Adds a scenereference to lists of scenes to spawn a copy of it during the next scene in the OnUpdate() /// </summary> /// <param name="sceneReference">A reference to the scene to spawn</param> /// <param name="isIndestructable">If true, there will be NO way to unload the scene</param> /// <param name="entities">The EntitiesQueryBuilder Entities</param> /// <returns>A bool to mark the correct loading of the scene</returns> public static bool LoadSceneAsync(SceneReference sceneReference, bool isIndestructable, EntityQueryBuilder entities) { try { entities.ForEach((DynamicBuffer <ScenesToLoad> scenesToLoad) => { scenesToLoad.Add(new ScenesToLoad { sceneReference = sceneReference, makeIndestrucktable = isIndestructable, setPos = false, setOffset = false }); }); return(true); } catch (Exception e) { Debug.Log(e.ToString()); return(false); } }
public static uint GetPlayerPlacement(int playerId, uint numberOfPlayers, EntityManager EntityManager, EntityQueryBuilder Entities, ComponentSystem componentSystem) { SortedDictionary <uint, List <Entity> > carEntitiesByCrossedCheckpoints = new SortedDictionary <uint, List <Entity> >(); Entities.ForEach((Entity carEntity, ref ProgressionComponent progressionComponent) => { if (!carEntitiesByCrossedCheckpoints.ContainsKey(progressionComponent.CrossedCheckpoints)) { carEntitiesByCrossedCheckpoints.Add(progressionComponent.CrossedCheckpoints, new List <Entity>()); } carEntitiesByCrossedCheckpoints[progressionComponent.CrossedCheckpoints].Add(carEntity); }); uint skippedPlayers = 0; foreach (var pair in carEntitiesByCrossedCheckpoints) { var carEntitiesInSameSection = pair.Value; if (carEntitiesInSameSection.Exists((Entity car) => EntityManager.GetComponentData <SynchronizedCarComponent>(car).PlayerId == playerId)) { if (carEntitiesInSameSection.Count == 1) { return(numberOfPlayers - skippedPlayers); } else { NativeArray <CalculateCheckpointDistanceJob.Input> jobInput = new NativeArray <CalculateCheckpointDistanceJob.Input>(carEntitiesInSameSection.Count * 2, Allocator.TempJob); NativeArray <CalculateCheckpointDistanceJob.Output> jobOutput = new NativeArray <CalculateCheckpointDistanceJob.Output>(carEntitiesInSameSection.Count * 2, Allocator.TempJob); var crossedCheckpoints = pair.Key; var checkPointInitializationSystem = componentSystem.World.GetExistingSystem <CheckpointInitializationSystem>(); var numberOfCheckpoints = checkPointInitializationSystem.numberOfCheckpoints; var nextCheckpointEntity = checkPointInitializationSystem.checkpoints[(crossedCheckpoints + 1) % numberOfCheckpoints]; var nextCheckpointPosition = EntityManager.GetComponentData <Translation>(nextCheckpointEntity).Value; var nextCheckpointRotation = EntityManager.GetComponentData <Rotation>(nextCheckpointEntity).Value; var nextCheckpointScale = EntityManager.GetComponentData <NonUniformScale>(nextCheckpointEntity).Value; var nextNextCheckpointEntity = checkPointInitializationSystem.checkpoints[(crossedCheckpoints + 2) % numberOfCheckpoints]; var nextNextCheckpointPosition = EntityManager.GetComponentData <Translation>(nextNextCheckpointEntity).Value; var nextNextCheckpointRotation = EntityManager.GetComponentData <Rotation>(nextNextCheckpointEntity).Value; var nextNextCheckpointScale = EntityManager.GetComponentData <NonUniformScale>(nextNextCheckpointEntity).Value; for (int i = 0; i < carEntitiesInSameSection.Count; i++) { var carEntity = carEntitiesInSameSection[i]; var carPosition = EntityManager.GetComponentData <Translation>(carEntity).Value; var carRotation = EntityManager.GetComponentData <Rotation>(carEntity).Value; jobInput[2 * i + 0] = new CalculateCheckpointDistanceJob.Input { CarPosition = carPosition, CarRotation = carRotation, CheckPointPosition = nextCheckpointPosition, CheckPointRotation = nextCheckpointRotation, CheckPointSize = nextCheckpointScale }; jobInput[2 * i + 1] = new CalculateCheckpointDistanceJob.Input { CarPosition = carPosition, CarRotation = carRotation, CheckPointPosition = nextNextCheckpointPosition, CheckPointRotation = nextNextCheckpointRotation, CheckPointSize = nextNextCheckpointScale }; } var job = new CalculateCheckpointDistanceJob { input = jobInput, output = jobOutput }; JobHandle jobHandle = job.Schedule(carEntitiesInSameSection.Count * 2, 1); jobHandle.Complete(); List <PlayerDistance> playerDistancesFromNextCheckpoint = new List <PlayerDistance>(); for (int i = 0; i < carEntitiesInSameSection.Count; i++) { playerDistancesFromNextCheckpoint.Add(new PlayerDistance { PlayerId = EntityManager.GetComponentData <SynchronizedCarComponent>(carEntitiesInSameSection[i]).PlayerId, Distance = jobOutput[2 * i + 0].Distance }); } uint placement = 0; if (playerDistancesFromNextCheckpoint.Exists((element) => element.PlayerId == playerId && element.Distance == 0) && playerDistancesFromNextCheckpoint.Exists((element) => element.PlayerId != playerId && element.Distance == 0)) { List <PlayerDistance> playerDistancesFromNextNextCheckpoint = new List <PlayerDistance>(); for (int i = 0; i < playerDistancesFromNextCheckpoint.Count; i++) { if (playerDistancesFromNextCheckpoint[i].Distance == 0) { playerDistancesFromNextNextCheckpoint.Add(new PlayerDistance { PlayerId = playerDistancesFromNextCheckpoint[i].PlayerId, Distance = jobOutput[2 * i + 1].Distance }); } } skippedPlayers += Convert.ToUInt32(playerDistancesFromNextCheckpoint.Count - playerDistancesFromNextNextCheckpoint.Count); playerDistancesFromNextNextCheckpoint.Sort((lhs, rhs) => rhs.Distance.CompareTo(lhs.Distance)); // ORDER BY distance DESC; foreach (var playerDistance in playerDistancesFromNextNextCheckpoint) { if (playerDistance.PlayerId != playerId) { skippedPlayers++; } else { placement = numberOfPlayers - skippedPlayers; break; } } } else { playerDistancesFromNextCheckpoint.Sort((lhs, rhs) => rhs.Distance.CompareTo(lhs.Distance)); // ORDER BY distance DESC; foreach (var playerDistance in playerDistancesFromNextCheckpoint) { if (playerDistance.PlayerId != playerId) { skippedPlayers++; } else { placement = numberOfPlayers - skippedPlayers; break; } } } jobInput.Dispose(); jobOutput.Dispose(); return(placement); } } else { skippedPlayers += Convert.ToUInt32(carEntitiesInSameSection.Count); } } return(0); }