public void TestEntityRemovedWhenRemovingWholeEntity()
        {
            Game game = new Game();
            EntityManager entityManager = new EntityManager(game);

            // Create compound entities.
            CompoundEntities<TestCompound> compoundEntities = new CompoundEntities<TestCompound>(entityManager);
            int eventCount = 0;
            compoundEntities.EntityRemoved += (id, entity) => { ++eventCount; };

            // Add entity with required components.
            var entityId = entityManager.CreateEntity();
            entityManager.AddComponent<TestCompoundComponentA>(entityId);
            entityManager.AddComponent<TestCompoundComponentB>(entityId);

            // Now remove entity.
            entityManager.RemoveEntity(entityId);
            entityManager.CleanUpEntities();

            Assert.AreEqual(1, eventCount);
        }
        public void TestInvalidEntityAdded()
        {
            Game game = new Game();
            EntityManager entityManager = new EntityManager(game);

            // Create compound entities.
            CompoundEntities<TestCompound> compoundEntities = new CompoundEntities<TestCompound>(entityManager);
            bool entityAdded = false;
            compoundEntities.EntityAdded += (id, entity) => { entityAdded = true; };

            // Just add one of the necessary components.
            var entityId = entityManager.CreateEntity();
            entityManager.AddComponent<TestCompoundComponentA>(entityId);

            Assert.IsFalse(entityAdded);
        }
예제 #3
0
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var scale  = transform.localScale;
        var bounds = new RectangleBounds
        {
            HalfWidthHeight = new float2(scale.x / 2.0f, scale.y / 2.0f),
        };

        dstManager.AddComponentData(entity, bounds);
        dstManager.AddComponent(entity, typeof(PaddleTag));

        dstManager.AddComponentData(entity, new MovementSpeed
        {
            Speed = MovementSpeed
        });

        dstManager.AddComponentData <Position2D>(entity, new Position2D
        {
            Value = new float2(transform.position.x, transform.position.y)
        });
        dstManager.RemoveComponent <Translation>(entity);
        dstManager.RemoveComponent <Rotation>(entity);
    }
예제 #4
0
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        dstManager.AddComponent <TurretInput>(entity);
        dstManager.AddComponentData(entity, new FireInterval {
            Value = fireInterval
        });
        dstManager.AddComponentData <FireCooldown>(entity, new FireCooldown {
            Value = fireInterval
        });
        dstManager.AddComponentData(entity, new FireSpeed {
            Value = fireSpeed
        });

        //store a reference to the entity which represents the projectile Prefab
        dstManager.AddComponentData(entity, new ProjectilePrefab {
            Reference = conversionSystem.GetPrimaryEntity(projectilePrefab)
        });

        //store the coordinates of the spawn point, so projectiles can be placed and rotated correctly when firing
        dstManager.AddComponentData(entity, new ProjectileSpawnPoint {
            LocalTranslation = projectileSpawnPoint.localPosition, LocalRotation = projectileSpawnPoint.localRotation
        });
    }
예제 #5
0
        public void AddComponent <T>(Entity entity) where T : struct, IComponentData
        {
            switch (Type)
            {
            case EntityManagerType.MOCK:
                return;

            case EntityManagerType.ENTITY_MANAGER:
                EntityManager.AddComponent <T>(entity);
                return;

            case EntityManagerType.ENTITY_COMMAND_BUFFER:
            case EntityManagerType.ENTITY_MANAGER_AND_COMMAND_BUFFER:
                EntityCommandBuffer.AddComponent <T>(entity);
                return;

            case EntityManagerType.ENTITY_COMMAND_BUFFER_CONCURRENT:
                EntityCommandBufferConcurrent.AddComponent <T>(EntityCommandBufferJobIndex, entity);
                return;
            }

            throw new NotImplementedException();
        }
    protected override void OnUpdate()
    {
        Entities.ForEach((ref StudentComponent studentComponent, ref Entity entity) =>
        {
            if (studentComponent.infectionState == StudentComponent.InfectionState.Susceptible)
            {
                studentComponent.infectionState = StudentComponent.InfectionState.Infected;
            }

            if (studentComponent.infectionState == StudentComponent.InfectionState.Infected)
            {
                //Change the colour of the sprite to red
                EntityManager.RemoveComponent(entity, typeof(RenderMesh));
                EntityManager.AddComponent(entity, typeof(RenderMesh));
                EntityManager.SetSharedComponentData(entity,
                                                     new RenderMesh
                {
                    mesh     = mesh,
                    material = redMaterial
                });
            }
        });
    }
예제 #7
0
        protected override void OnUpdate()
        {
            // Get access to settings
            var settings = GetSingleton <SettingsSingleton>();

            // Get access to audio
            var flipper          = GetSingleton <Flipper>();
            var flipperSound     = flipper.FlipperAudio;
            var flipperSoundData = EntityManager.GetComponentData <AudioSource>(flipperSound);

            Entities.ForEach((Entity entity, ref FoodInstanceComponent food, ref PhysicsVelocity velocity,
                              in PhysicsMass mass, in LaunchComponent launchComponent) =>
            {
                food.isLaunched = true;

                // Add propulsion to food
                float power    = launchComponent.strength * settings.launchStrengthMultiplier;
                power          = math.pow(power, settings.launchExp);
                float3 impulse = launchComponent.direction * power;

                float t   = 1.0f - launchComponent.strength;
                t         = math.pow(t, settings.heightExp);
                t         = 1.0f - t;
                impulse.y = settings.launchHeight * t;

                velocity.ApplyLinearImpulse(mass, impulse);
                velocity.ApplyAngularImpulse(mass, m_Random.NextFloat3() * settings.launchRotateAmount);

                World.EntityManager.AddComponent <PhysicsGravityFactor>(entity);
                PhysicsGravityFactor physicsGravityFactor = new PhysicsGravityFactor();
                physicsGravityFactor.Value = 1.0f;
                World.EntityManager.SetComponentData(entity, physicsGravityFactor);

                // Play audio
                EntityManager.RemoveComponent <LaunchComponent>(entity);
                EntityManager.AddComponent <AudioSourceStart>(flipperSound);
            }).WithStructuralChanges().WithoutBurst().Run();
예제 #8
0
    protected override void OnStartRunning()
    {
        base.OnStartRunning();
        Enabled = false;

        int count = Bootstrap.settings._spawnCount;

        //spawn in a circle
        EntityManager entityManager = EntityManager;
        var           pikmin        = entityManager.CreateEntity(Bootstrap.pikminArch);
        var           pikminLook    = Bootstrap.settings._pikminLook;
        var           pikminArr     = new NativeArray <Entity>(count, Allocator.Temp);

        entityManager.Instantiate(pikmin, pikminArr);

        var   rand   = new Random(0x4564ff);
        float offset = 360.0f / count;

        for (int i = 0; i < count; i++)
        {
            float distance = rand.NextFloat(10.0f, 50.0f);
            float rad      = math.radians(i * (offset + rand.NextFloat(0.0f, 20.0f)));
            entityManager.SetComponentData(pikminArr[i], new Position {
                Value = new float3(math.cos(rad), rand.NextFloat(-1.0f, 1.0f), math.sin(rad)) * distance
            });
            entityManager.SetComponentData(pikminArr[i], new Velocity {
                Value = float3.zero
            });
            entityManager.SetComponentData(pikminArr[i], new Scale {
                Value = Bootstrap.settings._spawnScale
            });
            entityManager.AddComponent(pikminArr[i], typeof(SwarmFlockFormation));
            entityManager.AddSharedComponentData(pikminArr[i], pikminLook[(i % Bootstrap.settings._pikminLook.Count)].Value);
        }
        entityManager.DestroyEntity(pikmin);
        pikminArr.Dispose();
    }
예제 #9
0
    protected override void OnUpdate()
    {
        //Get all selected units
        using (var selectedUnits = m_selectedUnits.ToEntityArray(Allocator.TempJob))
            using (var highlights = m_highlights.ToEntityArray(Allocator.TempJob))
            {
                //TODO Find a better way to spawn highlight prefabs
                // Works right now since we know there will be at least one HighlightSpawner
                var highlight = highlights[0];
                var prefab    = EntityManager.GetComponentData <HighlightSpawner>(highlight).Prefab;

                foreach (var selectedUnit in selectedUnits)
                {
                    //Remove the component from the unit so this system doesn't continually run
                    EntityManager.RemoveComponent <Selecting>(selectedUnit);

                    //Get our prefab from our spawner and set Translation (to produce a LocalToWorld)
                    var entity = EntityManager.Instantiate(prefab);
                    EntityManager.AddComponent(entity, typeof(Highlight));

                    //For a child to sucessfully have a parent it needs:
                    // 1. LocalToWorld (either a translation or rotation)
                    // 2. LocalToParent
                    // 3. Parent
                    EntityManager.SetComponentData(entity, new Translation {
                        Value = new float3(0, -0.5f, 0)
                    });
                    var localParent = EntityManager.GetComponentData <LocalToWorld>(selectedUnit).Value;
                    EntityManager.AddComponentData(entity, new LocalToParent {
                        Value = localParent
                    });
                    EntityManager.AddComponentData(entity, new Parent {
                        Value = selectedUnit
                    });
                }
            }
    }
    //TODO: Figure out if everything in the player spawning region belongs somewhere else.
    #region Player spawning helpers

    /// <summary>
    /// Spawns in a player's mob according to their job and character information at the given coordinates.
    /// Used by systems that need to handle spawning players.
    /// </summary>
    /// <param name="coordinates">Coordinates to spawn the character at.</param>
    /// <param name="job">Job to assign to the character, if any.</param>
    /// <param name="profile">Appearance profile to use for the character.</param>
    /// <param name="station">The station this player is being spawned on.</param>
    /// <returns>The spawned entity</returns>
    public EntityUid SpawnPlayerMob(
        EntityCoordinates coordinates,
        Job?job,
        HumanoidCharacterProfile?profile,
        EntityUid?station)
    {
        var entity = EntityManager.SpawnEntity(
            _prototypeManager.Index <SpeciesPrototype>(profile?.Species ?? SpeciesManager.DefaultSpecies).Prototype,
            coordinates);

        if (job?.StartingGear != null)
        {
            var startingGear = _prototypeManager.Index <StartingGearPrototype>(job.StartingGear);
            EquipStartingGear(entity, startingGear, profile);
            if (profile != null)
            {
                EquipIdCard(entity, profile.Name, job.Prototype, station);
            }
        }

        if (profile != null)
        {
            _humanoidAppearanceSystem.UpdateFromProfile(entity, profile);
            EntityManager.GetComponent <MetaDataComponent>(entity).EntityName = profile.Name;
            if (profile.FlavorText != "" && _configurationManager.GetCVar(CCVars.FlavorText))
            {
                EntityManager.AddComponent <DetailExaminableComponent>(entity).Content = profile.FlavorText;
            }
        }

        foreach (var jobSpecial in job?.Prototype.Special ?? Array.Empty <JobSpecial>())
        {
            jobSpecial.AfterEquip(entity);
        }

        return(entity);
    }
예제 #11
0
        // Start is called before the first frame update
        void Start()
        {
            BlobAssetStore blobAsset = new BlobAssetStore();

            manager = World.DefaultGameObjectInjectionWorld.EntityManager;
            var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAsset);
            var prefab   = GameObjectConversionUtility.ConvertGameObjectHierarchy(asteroidPrefab, settings);

            for (int i = 0; i < numAsteroids; i++)
            {
                var   instance = manager.Instantiate(prefab);
                float x        = Mathf.Sin(i) * UnityEngine.Random.Range(25, 50);
                float y        = UnityEngine.Random.Range(-5, 5);
                float z        = Mathf.Cos(i) * UnityEngine.Random.Range(25, 50);
                var   position = transform.TransformPoint(new float3(x, y, z));
                manager.SetComponentData(instance, new Translation {
                    Value = position
                });

                var q = Quaternion.Euler(new Vector3(0, 0, 0));
                manager.SetComponentData(instance, new Rotation {
                    Value = new quaternion(q.x, q.y, q.z, q.w)
                });

                var scale = new float3(UnityEngine.Random.Range(5, 15),
                                       UnityEngine.Random.Range(5, 10),
                                       UnityEngine.Random.Range(5, 15));
                scale *= UnityEngine.Random.Range(1, 10);

                manager.AddComponent(instance, ComponentType.ReadWrite <NonUniformScale>());
                manager.SetComponentData(instance, new NonUniformScale {
                    Value = scale
                });
            }

            blobAsset.Dispose();
        }
예제 #12
0
        /// <summary>
        ///     Attaches a player session to an entity, optionally kicking any sessions already attached to it.
        /// </summary>
        /// <param name="uid">The entity to attach the player to</param>
        /// <param name="player">The player to attach to the entity</param>
        /// <param name="force">Whether to kick any existing players from the entity</param>
        /// <param name="forceKicked">The player that was forcefully kicked, or null.</param>
        /// <returns>Whether the attach succeeded, or not.</returns>
        public bool Attach(EntityUid uid, IPlayerSession player, bool force, out IPlayerSession?forceKicked)
        {
            // Null by default.
            forceKicked = null;

            // Cannot attach to a deleted/nonexisting entity.
            if (EntityManager.Deleted(uid))
            {
                return(false);
            }

            // Check if there was a player attached to the entity already...
            if (EntityManager.TryGetComponent(uid, out ActorComponent actor))
            {
                // If we're not forcing the attach, this fails.
                if (!force)
                {
                    return(false);
                }

                // Set the event's force-kicked session before detaching it.
                forceKicked = actor.PlayerSession;

                // This detach cannot fail, as a player is attached to this entity.
                // It's important to note that detaching the player removes the component.
                RaiseLocalEvent(uid, new DetachPlayerEvent());
            }

            // We add the actor component.
            actor = EntityManager.AddComponent <ActorComponent>(uid);
            actor.PlayerSession = player;
            player.SetAttachedEntity(actor.Owner);

            // The player is fully attached now, raise an event!
            RaiseLocalEvent(uid, new PlayerAttachedEvent(actor.Owner, player, forceKicked));
            return(true);
        }
            public override void OnAddComponent(AddComponentOp op)
            {
                var entity = TryGetEntityFromEntityId(op.EntityId);

                var data = Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Serialization.Deserialize(op.Data.SchemaData.Value.GetFields(), World);

                data.DirtyBit = false;
                entityManager.AddComponentData(entity, data);
                entityManager.AddComponent(entity, ComponentType.Create <NotAuthoritative <Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Component> >());

                var update = new Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Update
                {
                };

                var updates = new List <Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Update>
                {
                    update
                };

                var updatesComponent = new Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.ReceivedUpdates
                {
                    handle = ReferenceTypeProviders.UpdatesProvider.Allocate(World)
                };

                ReferenceTypeProviders.UpdatesProvider.Set(updatesComponent.handle, updates);
                entityManager.AddComponentData(entity, updatesComponent);

                if (entityManager.HasComponent <ComponentRemoved <Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Component> >(entity))
                {
                    entityManager.RemoveComponent <ComponentRemoved <Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Component> >(entity);
                }
                else if (!entityManager.HasComponent <ComponentAdded <Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Component> >(entity))
                {
                    entityManager.AddComponent(entity, ComponentType.Create <ComponentAdded <Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents.Component> >());
                }
                else
                {
                    LogDispatcher.HandleLog(LogType.Error, new LogEvent(ReceivedDuplicateComponentAdded)
                                            .WithField(LoggingUtils.LoggerName, LoggerName)
                                            .WithField(LoggingUtils.EntityId, op.EntityId.Id)
                                            .WithField("Component", "Improbable.Gdk.Tests.ComponentsWithNoFields.ComponentWithNoFieldsWithEvents")
                                            );
                }
            }
예제 #14
0
    void SpawnTree(Vector3 pos)
    {
        Entity entity = entityManager.Instantiate(treeEntityPrefab);

        entityManager.SetComponentData(entity, new AgeComponent {
            Value = 0
        });
        // entityManager.SetComponentData(entity, new NonUniformScale { Value = new float3(1, 6, 1) });

        entityManager.SetComponentData(entity, new Translation {
            Value = new float3(pos.x, pos.y, pos.z)
        });

        entityManager.AddComponent(entity, typeof(SeedSpawnPoint));
        entityManager.SetComponentData(entity, new SeedSpawnPoint {
            Value = new float3(UnityEngine.Random.Range(-4, 4), 0, UnityEngine.Random.Range(-4, 4))
        });

        RenderMesh tempMesh = World.Active.EntityManager.GetSharedComponentData <RenderMesh>(entity);

        entityManager.SetSharedComponentData(entity, new RenderMesh {
            mesh = Settings.Stage1Prefab(), material = tempMesh.material
        });
    }
예제 #15
0
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var srcRigComponent  = SourceRigPrefab.GetComponent <RigComponent>();
        var dstRigComponent  = GetComponent <RigComponent>();
        var srcRigPrefab     = conversionSystem.TryGetPrimaryEntity(SourceRigPrefab);
        var srcRigDefinition = dstManager.GetComponentData <Rig>(srcRigPrefab);

        StringHash binding   = RemapLocalToRoot.transform.name;
        var        overrides = new Unity.Animation.RigRemapUtils.OffsetOverrides(1, Allocator.Temp);

        overrides.AddTranslationOffsetOverride(binding, new RigTranslationOffset {
            Rotation = quaternion.identity, Scale = 1f, Space = RigRemapSpace.LocalToRoot
        });
        overrides.AddRotationOffsetOverride(binding, new RigRotationOffset {
            PreRotation = quaternion.identity, PostRotation = quaternion.identity, Space = RigRemapSpace.LocalToRoot
        });

        var setup = new RigRemapSetup
        {
            SrcClip = SourceClip.ToDenseClip(),
            SrcRig  = srcRigDefinition.Value,

            // Automatically create a remap table based on matching rig component properties. This example uses two hierarchies that are
            // different but have matching transform names. For this specific case, we use the BindingHashUtils.HashName delegate instead
            // of the default HashFullPath strategy in order to find matching entries. Given we are remapping the srcRig (TerraFormerLOD1) to
            // a sub rig part (HandRigLOD0) we override the remapping offsets of the RightHand transform to perform operations in
            // LocalToRoot space (lines 29-32) in order to displace the hand at the wanted position/rotation.
            RemapTable = Unity.Animation.Hybrid.RigRemapUtils.CreateRemapTable(
                srcRigComponent, dstRigComponent, Unity.Animation.RigRemapUtils.ChannelFilter.All, overrides, BindingHashUtils.HashName
                )
        };

        dstManager.AddComponentData(entity, setup);

        dstManager.AddComponent <DeltaTime>(entity);
    }
    private void CreateNewGameObjects(SimAssetBank.Lookup simAssetBank)
    {
        Entities
        .WithAll <BindedViewType_GameObject>()
        .WithNone <BindedGameObjectTag>()
        .WithoutBurst()
        .WithStructuralChanges()
        .ForEach((Entity viewEntity, in SimAssetId id, in BindedSimEntity simEntity) =>
        {
            EntityManager.AddComponent <BindedGameObjectTag>(viewEntity);

            SimAsset simAsset = simAssetBank.GetSimAsset(id);

            if (simAsset.BindedViewPrefab != null)
            {
                GameObject viewGO = Object.Instantiate(simAsset.BindedViewPrefab);

                var bindedSimEntityManaged = viewGO.GetOrAddComponent <BindedSimEntityManaged>();
                bindedSimEntityManaged.Register(simEntity);

                EntityManager.AddComponentObject(viewEntity, bindedSimEntityManaged);
                EntityManager.AddComponentObject(viewEntity, viewGO.transform);
            }
        }).Run();
예제 #17
0
    protected override void OnUpdate()
    {
        var gameData = GetSingleton <GameState>();

        Logger.Log("In Sphere Destruction System");
        Entities
        .WithAll <DestroyedTag, SphereTag>()
        .WithoutBurst()
        .ForEach((Entity entity) =>
        {
            Logger.Log("Increasing score");
            gameData.score++;
            SetSingleton(gameData);

            EntityManager.AddComponent(shakeTarget, typeof(ActivatedTag));
            EntityManager.AddComponent(uiUpdateTarget, typeof(ActivatedTag));

            EntityManager.AddComponentData(EntityManager.CreateEntity(), new SoundRequest {
                Value = SoundType.Success
            });

            EntityManager.DestroyEntity(entity);
        }).WithStructuralChanges().Run();
    }
예제 #18
0
    protected override void OnUpdate()
    {
        EntityManager.DestroyEntity(GetSingletonEntity <BallSpawnerSystemController>());
        // 如果球出界了就会执行GameOver的System操作
        // 在创建时先实现实体,然后等待一秒后去掉GetReady并且给球一个速度
        Job.WithoutBurst().WithCode(() =>
        {
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[2].Value; // 初始化球
            var ball            = EntityManager.Instantiate(prefab);
            EntityManager.AddComponent <ThePong>(ball);                                                                // 添加标识,方便以后删除
            EntityManager.SetComponentData <Translation>(ball, new Translation {
                Value = new float3(0f, 0f, 0f)
            });
            Thread.Sleep(2000);
            EntityManager.SetComponentData(ball, new PhysicsVelocity
            {
                Linear  = new float3(math.radians(10f), math.radians(10f), 0f),
                Angular = new float3(0f, 0f, 0f)
            });

            EntityManager.CreateEntity(typeof(BallCheckSystemController));
        }).Run();
    }
예제 #19
0
        protected override void ConvertComponent(UnityEngine.UI.Selectable unityComponent, Entity entity, RectTransformToEntity rectTransformToEntity, Dictionary <UnityEngine.Object, Entity> assetToEntity, EntityManager commandBuffer)
        {
            commandBuffer.AddComponent(entity, typeof(DotsUI.Input.Selectable));
            var    colors = unityComponent.colors;
            Entity target;

            if (!rectTransformToEntity.TryGetValue(unityComponent.targetGraphic?.rectTransform, out target))
            {
                target = entity;
            }
            commandBuffer.AddComponentData(entity, new DotsUI.Input.SelectableColor()
            {
                Normal         = colors.normalColor.ToFloat4(),
                Hover          = colors.highlightedColor.ToFloat4(),
                Pressed        = colors.pressedColor.ToFloat4(),
                Selected       = colors.selectedColor.ToFloat4(),
                Disabled       = colors.disabledColor.ToFloat4(),
                TransitionTime = colors.fadeDuration,
                Target         = target
            });
            commandBuffer.AddComponentData(entity, new DotsUI.Input.PointerInputReceiver {
                ListenerTypes = DotsUI.Input.PointerEventType.SelectableGroup
            });
        }
예제 #20
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (!m_DestroyedQuery.IsEmptyIgnoreFilter || !m_NewQuery.IsEmptyIgnoreFilter)
        {
            EntityManager.AddComponent <CompanionGameObjectUpdateTransformSystemState>(m_NewQuery);
            EntityManager.RemoveComponent <CompanionGameObjectUpdateTransformSystemState>(m_DestroyedQuery);

            m_Entities.Dispose();
            m_Entities = m_ExistingQuery.ToEntityArray(Allocator.Persistent);

            var transforms = new Transform[m_Entities.Length];
            for (int i = 0; i < m_Entities.Length; i++)
            {
                transforms[i] = EntityManager.GetComponentObject <CompanionLink>(m_Entities[i]).transform;
            }
            m_TransformAccessArray.SetTransforms(transforms);
        }

        return(new CopyTransformJob
        {
            localToWorld = GetComponentDataFromEntity <LocalToWorld>(),
            entities = m_Entities
        }.Schedule(m_TransformAccessArray, inputDeps));
    }
    protected override void OnUpdate()
    {
        if (Input.GetButtonDown("Jump"))
        {
            CreateEntities();
        }

        secondCounter += Time.DeltaTime;
        if (secondCounter >= 0.04166f)
        {
            toUpdate = true;
        }

        if (toUpdate)
        {
            toUpdate      = false;
            secondCounter = 0f;
            for (int i = 0; i < renderMeshFrames.Count - 1; i++)
            {
                //Get all entities with this frame??
                query.SetSharedComponentFilter(renderMeshFrames[i]);
                //Store entities
                NativeArray <Entity> arrAnim1 = query.ToEntityArray(Allocator.TempJob);
                //Modify RenderMesh to next frame
                entityManager.SetSharedComponentData(query, renderMeshFrames[i + 1]);
                //Add Tag
                entityManager.AddComponent <ChangedFrameTag>(arrAnim1);
                //Dispose
                arrAnim1.Dispose();
            }
            query.SetSharedComponentFilter(renderMeshFrames[renderMeshFrames.Count - 1]);
            entityManager.SetSharedComponentData(query, renderMeshFrames[0]);

            entityManager.RemoveComponent <ChangedFrameTag>(frameTagQuery);
        }
    }
예제 #22
0
        /// <summary>
        /// Add a fixed array to the entity
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="length"></param>
        /// <typeparam name="T"></typeparam>
        protected void AddFixedArray <T>(Entity entity, int length)
            where T : struct
        {
            var typeIndex = TypeManager.GetTypeIndex <T>();

            void LocalCreateFixedArray()
            {
                EntityManager.AddComponent(entity, ComponentType.FixedArray(typeof(T), length));
            }

            if (EntityManager.HasComponent(entity, ComponentType.FromTypeIndex(typeIndex)))
            {
                var fixedArray = EntityManager.GetFixedArray <T>(entity);
                if (fixedArray.Length != length)
                {
                    EntityManager.RemoveComponent(entity, ComponentType.FromTypeIndex(typeIndex));
                    LocalCreateFixedArray();
                }
            }
            else
            {
                LocalCreateFixedArray();
            }
        }
예제 #23
0
        public void ToggleFollow()
        {
            var entities = GetEntityQuery(ComponentType.ReadOnly <Selected>(), ComponentType.ReadOnly <Translation>()).ToEntityArray(Allocator.TempJob);

            if (entities.Length == 1)
            {
                Entity entity = entities[0];
                if (EntityManager.HasComponent <Followed>(entity))
                {
                    Unfollow();
                }
                else
                {
                    Unfollow();
                    EntityManager.AddComponent <Followed>(entity);
                }
            }
            else
            {
                Unfollow();
            }

            entities.Dispose();
        }
예제 #24
0
        protected override void OnUpdate()
        {
            Entities.WithStructuralChanges().WithAll <FactionTag>().ForEach((Entity entity, ref Faction faction) =>
            {
                var factionMember = new FactionMember {
                    factionEntity = entity
                };
                m_aiQuery.SetSharedComponentFilter(factionMember);
                m_playerQuery.SetSharedComponentFilter(factionMember);

                if (faction.playerPrefab != Entity.Null && !m_playerQuery.IsEmpty)
                {
                    var newPlayerShip = EntityManager.Instantiate(faction.playerPrefab);
                    AddSharedComponentDataToLinkedGroup(newPlayerShip, factionMember);
                    SpawnPlayer(newPlayerShip);
                    faction.remainingReinforcements--;
                }

                {
                    int spawnCount    = m_aiQuery.CalculateEntityCount();
                    var newShipPrefab = EntityManager.Instantiate(faction.aiPrefab);
                    EntityManager.AddComponent <NewFleetTag>(newShipPrefab);
                    AddSharedComponentDataToLinkedGroup(newShipPrefab, factionMember);
                    var newShips = EntityManager.Instantiate(newShipPrefab, spawnCount, Allocator.TempJob);
                    EntityManager.DestroyEntity(newShipPrefab);
                    SpawnAi(newShips);
                    newShips.Dispose();
                    faction.remainingReinforcements -= spawnCount;
                }

                m_aiQuery.ResetFilter();
                m_playerQuery.ResetFilter();
            }).Run();

            EntityManager.RemoveComponent <NewFleetTag>(m_aiQuery);
        }
예제 #25
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_RemoveAttackingGroup.CalculateLength() > 0)
            {
                EntityManager.RemoveComponent(m_RemoveAttackingGroup, ComponentType.ReadWrite <AttackDuration>());
                EntityManager.RemoveComponent(m_RemoveAttackingGroup, ComponentType.ReadWrite <Attacking>());
            }

            EntityManager.AddComponent(m_AddAttackingGroup, ComponentType.ReadWrite <Attacking>());

            var addAttackDurationGroupLength = m_AddAttackDurationGroup.CalculateLength();

            if (addAttackDurationGroupLength > 0)
            {
                var entityArray         = new NativeArray <Entity>(addAttackDurationGroupLength, Allocator.TempJob);
                var attackDurationArray = new NativeArray <AttackDuration>(addAttackDurationGroupLength, Allocator.TempJob);
                var commandBufferSystem = World.GetExistingManager <BeginSimulationEntityCommandBufferSystem>();

                inputDeps = new ConsolidateAttackDurationJob
                {
                    EntityArray         = entityArray,
                    AttackDurationArray = attackDurationArray,
                }.Schedule(this);

                inputDeps = new AddAttackDurationJob
                {
                    EntityArray         = entityArray,
                    AttackDurationArray = attackDurationArray,
                    CommandBuffer       = commandBufferSystem.CreateCommandBuffer().ToConcurrent()
                }.Schedule(addAttackDurationGroupLength, 64, inputDeps);

                commandBufferSystem.AddJobHandleForProducer(inputDeps);
            }

            return(inputDeps);
        }
        private void InitComponentsAgent(Entity entity, float3 position)
        {
            EntityManager.AddComponent(entity, typeof(SyncPositionFromNavAgentComponent));

            EntityManager.AddComponentData(entity, new AgentPathInfoComponent {
                goes     = false,
                startPos = position,
                endPos   = position + new float3(0, 0, -Settings.LINE_HEIGTH),
            });


            var navAgentDefauult = EntityManager.GetComponentData <NavAgentComponent>(entity);
            var navAgent         = new NavAgentComponent(
                position,
                Quaternion.identity,
                navAgentDefauult.stoppingDistance,
                navAgentDefauult.moveSpeed,
                navAgentDefauult.acceleration,
                navAgentDefauult.rotationSpeed,
                navAgentDefauult.areaMask
                );

            EntityManager.SetComponentData(entity, navAgent);
        }
예제 #27
0
        public static void SetupRoomRendering(this EntityManager em, Entity room)
        {
            em.SetComponentData(room, new LocalToWorld
            {
                Value = float4x4.identity
            });

            var mesh     = new Mesh();
            var material = Object.Instantiate(HybridLevel.Material);

            material.color = Color.HSVToRGB(UnityEngine.Random.value, 0.125f, 1f);

            mesh.MarkDynamic();

            em.SetSharedComponentData(room, new RenderMesh
            {
                mesh           = mesh,
                material       = material,
                castShadows    = ShadowCastingMode.Off,
                receiveShadows = true
            });

            em.AddComponent <DirtyMesh>(room);
        }
예제 #28
0
        void AddImpact(Collision2D collision, State.Overlap state)
        {
            var collidingEntity = collision.gameObject.GetComponent <GameObjectEntity>();

            if (!collidingEntity)
            {
                return;
            }

            if (!em.HasComponent <CollidedWithGround>(collidingEntity.Entity))
            {
                em.AddComponent(collidingEntity.Entity, typeof(CollidedWithGround));
            }

            var impactComponent = new Impact {
                State       = state,
                OtherEntity = groundEntity,
                Collision   = new CollisionData(collision)
            };

            em.SetComponentData <CollidedWithGround>(collidingEntity.Entity, new CollidedWithGround {
                Impact = impactComponent
            });
        }
예제 #29
0
    private void PlaySound(SoundManager soundManager, SoundType soundType)
    {
        switch (soundType)
        {
        case SoundType.Input:
            EntityManager.AddComponent <AudioSourceStart>(soundManager.InputAS);
            break;

        case SoundType.Success:
            EntityManager.AddComponent <AudioSourceStart>(soundManager.SuccessAS);
            break;

        case SoundType.Highscore:
            EntityManager.AddComponent <AudioSourceStart>(soundManager.HighscoreAS);
            break;

        case SoundType.End:
            EntityManager.AddComponent <AudioSourceStart>(soundManager.EndAS);
            break;

        default:
            break;
        }
    }
예제 #30
0
    private void DoSpawn(EntityManager manager, Entity prefab, int x, int z)
    {
        var entity = manager.Instantiate(prefab);

        manager.SetComponentData(entity, new Translation()
        {
            Value = new float3(x, 0.75f, z)
        });
        manager.AddComponent <LbReachCell>(entity);
        manager.AddComponent <LbRat>(entity);
        manager.AddComponentData(entity, new LbMovementSpeed()
        {
            Value = 4.0f
        });
        manager.AddComponentData(entity, new LbDistanceToTarget()
        {
            Value = 1.0f
        });
        manager.AddComponentData(entity, new LbRotationSpeed()
        {
            Value = 1.0f
        });


        switch (RandomGenerator.NextInt(4))
        {
        case 0:
            manager.AddComponent <LbNorthDirection>(entity);
            break;

        case 1:
            manager.AddComponent <LbSouthDirection>(entity);
            break;

        case 2:
            manager.AddComponent <LbEastDirection>(entity);
            break;

        default:
            manager.AddComponent <LbWestDirection>(entity);
            break;
        }
    }
예제 #31
0
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            dstManager.AddComponent <Monster>(entity);
            dstManager.AddComponent <Position>(entity);
            dstManager.AddComponent <TilesInView>(entity);
            dstManager.AddComponent <Energy>(entity);
            dstManager.AddComponent <Prefab>(entity);
            dstManager.AddComponent <Actor>(entity);

            dstManager.AddComponent <Collidable>(entity);

            dstManager.AddComponentData <ViewRange>(entity, _viewRange);
            dstManager.AddComponentData <Speed>(entity, _speed);
            dstManager.AddComponentData <Name>(entity, name);
            dstManager.AddComponentData <Health>(entity, _health);

            dstManager.AddComponentData <Renderable>(entity, new Renderable
            {
                bgColor = Color.black,
                fgColor = _color,
                glyph   = CodePage437.ToCP437(_glyph)
            });
        }
예제 #32
0
    public void Convert(Entity entity, EntityManager entityManager, GameObjectConversionSystem conversionSystem)
    {
        entityManager.AddComponent(entity, typeof(JumpHeight));
        entityManager.AddComponent(entity, typeof(Heading));
        entityManager.AddComponent(entity, typeof(ColAngle));
        entityManager.AddComponent(entity, typeof(JumpForce));
        entityManager.AddComponent(entity, typeof(OnGround));
        entityManager.AddComponent(entity, typeof(MovementAcceleration));


        entityManager.SetComponentData(entity, new MovementAcceleration {
            AccelerationDuration = 1.5f, MaxSpeed = movementSpeed
        });
        entityManager.SetComponentData(entity, new JumpHeight {
            Value = jumpHeight
        });
        entityManager.SetComponentData(entity, new ColAngle {
            Value = -1
        });
    }
        public void TestValidEntityWithOptionalCompAdded()
        {
            Game game = new Game();
            EntityManager entityManager = new EntityManager(game);

            // Create compound entities.
            CompoundEntities<TestCompoundWithOneOptionalComp> compoundEntities =
                new CompoundEntities<TestCompoundWithOneOptionalComp>(entityManager);
            bool entityAdded = false;
            compoundEntities.EntityAdded += (id, entity) => { entityAdded = true; };

            // Just add one of the components which is the necessary one.
            var entityId = entityManager.CreateEntity();
            entityManager.AddComponent<TestCompoundComponentA>(entityId);

            Assert.IsTrue(entityAdded);
        }
        public void TestValidEntityWithOptionalCompAddedTriggerEventOnlyOnce()
        {
            Game game = new Game();
            EntityManager entityManager = new EntityManager(game);

            // Create compound entities.
            CompoundEntities<TestCompoundWithOneOptionalComp> compoundEntities =
                new CompoundEntities<TestCompoundWithOneOptionalComp>(entityManager);
            int entityAddedEvent = 0;
            compoundEntities.EntityAdded += (id, entity) => { ++entityAddedEvent; };

            // Just add one of the components which is the necessary one.
            var entityId = entityManager.CreateEntity();
            entityManager.AddComponent<TestCompoundComponentA>(entityId);
            entityManager.AddComponent<TestCompoundComponentB>(entityId);

            Assert.AreEqual(1, entityAddedEvent);
        }
        public void TestValidEntityAddedWithComponentField()
        {
            Game game = new Game();
            EntityManager entityManager = new EntityManager(game);

            // Create compound entities.
            CompoundEntities<TestCompoundWithField> compoundEntities =
                new CompoundEntities<TestCompoundWithField>(entityManager);
            bool entityAdded = false;
            compoundEntities.EntityAdded += (id, entity) => { entityAdded = true; };

            // Add entity with correct components.
            var entityId = entityManager.CreateEntity();
            entityManager.AddComponent<TestCompoundComponentA>(entityId);

            Assert.IsTrue(entityAdded);
        }