Exemple #1
0
    protected override void OnUpdate()
    {
        var localInput = GetSingleton <CommandTargetComponent>().targetEntity;

        if (localInput == Entity.Null)
        {
            var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
            Entities.WithNone <InputCommandData>().ForEach((Entity ent, ref PlayerComponent player) =>
            {
                if (player.PlayerId == localPlayerId)
                {
                    PostUpdateCommands.AddBuffer <InputCommandData>(ent);
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                        targetEntity = ent
                    });
                }
            });
            return;
        }

        var input = default(InputCommandData);

        input.tick   = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;
        localAngleH += Input.GetAxis("Horizontal");
        localAngleV -= Input.GetAxis("Vertical");

        input.angleH = localAngleH;
        input.angleV = localAngleV;
        input.speed  = defaultspeed;

        var inputBuffer = EntityManager.GetBuffer <InputCommandData>(localInput);

        inputBuffer.AddCommandData(input);
    }
Exemple #2
0
    protected override void OnUpdate()
    {
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach(
            (Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            Debug.Log(string.Format("Server setting connection {0} to in game",
                                    EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));


            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = MobileRTSGhostSerializerCollection.FindGhostType <PlayerSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId]
                                  .Value;
            var player = EntityManager.Instantiate(prefab);
            EntityManager.SetComponentData(player,
                                           new Player
            {
                PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });

            PostUpdateCommands.AddBuffer <PlayerInput>(player);
            PostUpdateCommands.SetComponent(reqSrc.SourceConnection,
                                            new CommandTargetComponent {
                targetEntity = player
            });

            PostUpdateCommands.AddComponent(player, new PlayerConfig {
                Civilians = 2, Archers = 1
            });

            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
Exemple #3
0
        // 更新時に呼ばれる
        protected override void OnUpdate()
        {
            Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
            {
                // ゲーム参加リクエストの受信
                PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
                UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
#if true
                // Cubeの生成
                var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
                var ghostId         = NetCodeTestGhostSerializerCollection.FindGhostType <CubeSnapshotData>();
                var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
                var player          = EntityManager.Instantiate(prefab);
                EntityManager.SetComponentData(player, new MovableCubeComponent
                {
                    PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
                });
                PostUpdateCommands.AddBuffer <CubeInput>(player);
                PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                    targetEntity = player
                });
#endif

                // ゲーム参加リクエストの破棄
                PostUpdateCommands.DestroyEntity(reqEnt);
            });
        }
Exemple #4
0
    protected override void OnUpdate()
    {
        var entities = cmdTargetGroup.ToEntityArray(Allocator.TempJob);

        if (entities.Length == 1)
        {
            var ent = entities[0];

            if (!EntityManager.HasComponent <PlayerCommandData>(ent))
            {
                PostUpdateCommands.AddBuffer <PlayerCommandData>(ent);

                var ctc = EntityManager.GetComponentData <CommandTargetComponent>(ent);
                ctc.targetEntity = ent;
                PostUpdateCommands.SetComponent(ent, ctc);
            }
            else
            {
                var cmdBuf = EntityManager.GetBuffer <PlayerCommandData>(ent);

                PlayerCommandData cmdData = default;
                cmdData.tick       = m_TimeSystem.predictTargetTick;
                cmdData.horizontal = Input.GetAxisRaw("Horizontal");
                cmdData.vertical   = Input.GetAxisRaw("Vertical");

                cmdBuf.AddCommandData(cmdData);
            }
        }
        entities.Dispose();
    }
    protected override void OnUpdate()
    {
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
            var ghostCollection = GetSingletonEntity <GhostPrefabCollectionComponent>();
            var prefab          = Entity.Null;
            var prefabs         = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection);
            for (int ghostId = 0; ghostId < prefabs.Length; ++ghostId)
            {
                if (EntityManager.HasComponent <MovableCubeComponent>(prefabs[ghostId].Value))
                {
                    prefab = prefabs[ghostId].Value;
                }
            }
            var player = EntityManager.Instantiate(prefab);
            EntityManager.SetComponentData(player, new GhostOwnerComponent {
                NetworkId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });
            PostUpdateCommands.AddBuffer <CubeInput>(player);

            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });

            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
        protected override void OnUpdate()
        {
            for (var i = 0; i < data.Length; i++)
            {
                var archetype = data.ArchetypeComponents[i].ArchetypeName;
                var entity    = data.Entities[i];

                switch (worker.WorkerType)
                {
                case WorkerUtils.UnityClient when archetype == ArchetypeConfig.CharacterArchetype:
                case WorkerUtils.UnityClient when archetype == ArchetypeConfig.CubeArchetype:
                case WorkerUtils.UnityClient when archetype == ArchetypeConfig.SpinnerArchetype:
                case WorkerUtils.UnityGameLogic when archetype == ArchetypeConfig.CharacterArchetype:
                case WorkerUtils.UnityGameLogic when archetype == ArchetypeConfig.CubeArchetype:
                case WorkerUtils.UnityGameLogic when archetype == ArchetypeConfig.SpinnerArchetype:
                    PostUpdateCommands.AddBuffer <BufferedTransform>(entity);
                    break;

                default:
                    worker.LogDispatcher.HandleLog(LogType.Error, new LogEvent(ArchetypeMappingNotFound)
                                                   .WithField(LoggingUtils.LoggerName, LoggerName)
                                                   .WithField("ArchetypeName", archetype)
                                                   .WithField("WorkerType", worker.WorkerType));
                    break;
                }
            }
        }
Exemple #7
0
    protected override void OnUpdate()
    {
        var localInput = GetSingleton <CommandTargetComponent>().targetEntity;

        if (localInput == Entity.Null)
        {
            var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
            Entities.WithNone <PlayerInput>().ForEach((Entity ent, ref SynchronizedCarComponent car) =>
            {
                if (car.PlayerId == localPlayerId)
                {
                    PostUpdateCommands.AddBuffer <PlayerInput>(ent);
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                        targetEntity = ent
                    });
                }
            });
            return;
        }
        var input = default(PlayerInput);

        input.tick = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;

        input.keyForwardPressed   = Convert.ToByte(Input.GetKey(SerializedFields.singleton.keyForward));
        input.keyBackwardPressed  = Convert.ToByte(Input.GetKey(SerializedFields.singleton.keyBackward));
        input.keyTurnRightPressed = Convert.ToByte(Input.GetKey(SerializedFields.singleton.keyTurnRight));
        input.keyTurnLeftPressed  = Convert.ToByte(Input.GetKey(SerializedFields.singleton.keyTurnLeft));

        var inputBuffer = EntityManager.GetBuffer <PlayerInput>(localInput);

        inputBuffer.AddCommandData(input);
    }
Exemple #8
0
    protected override void OnUpdate()
    {
        var localInputDataEntity = GetSingleton <CommandTargetComponent>().targetEntity;

        if (localInputDataEntity == Entity.Null)
        {
            var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
            Entities.WithAll <MovableComponent>().WithNone <CharacterSyncData>().ForEach((Entity ent, ref GhostOwnerComponent ghostOwner) =>
            {
                if (ghostOwner.NetworkId == localPlayerId)
                {
                    PostUpdateCommands.AddBuffer <CharacterSyncData>(ent);
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                        targetEntity = ent
                    });
                    CameraFollow.instance.CharacterEntity = ent;
                }
            });
            return;
        }

        var input = default(CharacterSyncData);

        input.Tick       = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;
        input.Horizontal = Input.GetAxis("Horizontal");
        input.Vertical   = Input.GetAxis("Vertical");
        var inputBuffer = EntityManager.GetBuffer <CharacterSyncData>(localInputDataEntity);

        inputBuffer.AddCommandData(input);
    }
Exemple #9
0
        protected override void OnUpdate()
        {
            Entities.WithNone <State>().ForEach((Entity entity, ref RegistryAsset registryAsset) =>
            {
                GameDebug.Log(World, Part.ShowLifetime, "Initializing PartOwner:{0}", entity);

                var registry      = PartRegistry.GetPartRegistry(World, registryAsset.Value);
                var categoryCount = registry.Value.GetCategoryCount();

                var buffer = PostUpdateCommands.AddBuffer <PartElement>(entity);
                for (int i = 0; i < categoryCount; i++)
                {
                    buffer.Add(PartElement.Default);
                }

                PostUpdateCommands.AddComponent(entity, State.Default);
            });

            Entities.WithNone <InputState>().ForEach((Entity entity, ref State state) =>
            {
                GameDebug.Log(World, Part.ShowLifetime, "Deinitializing PartOwner:{0}", entity);

                var partBuffer = EntityManager.GetBuffer <PartElement>(entity);
                for (int i = 0; i < partBuffer.Length; i++)
                {
                    if (partBuffer[i].PartEntity != Entity.Null)
                    {
                        PostUpdateCommands.DestroyEntity(partBuffer[i].PartEntity);
                        GameDebug.Log(Part.ShowLifetime, "   destroying part:{0}", partBuffer[i].PartEntity);
                    }
                }
                PostUpdateCommands.RemoveComponent <State>(entity);
                PostUpdateCommands.RemoveComponent <PartElement>(entity);
            });
        }
Exemple #10
0
    protected override void OnUpdate()
    {
        // Get all entities with the ReceiveRpc's component (and without the SendRpc's component),
        // and which also have a GoInGameRequest component indicating they wish to join the game.
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            // Mark that entity as in game
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));

            // Generate a controllable cube for this newly connected player with an input buffer
            // See CubeInput.cs
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = NetCubeGhostSerializerCollection.FindGhostType <CubeSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
            var player          = EntityManager.Instantiate(prefab);
            EntityManager.SetComponentData(player, new MovableCubeComponent {
                PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });

            PostUpdateCommands.AddBuffer <CubeInput>(player);
            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });

            // We don't need that request any more, destroy it.
            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
        protected override void OnUpdate()
        {
            var childrenBuffer = GetBufferFromEntity <Child>(true);

            Entities.With(canvasQuery).ForEach((Entity entity, CanvasSortOrder s0, DynamicBuffer <Child> b0) => {
                // Clear the list so that we can build a render hierarchy.
                batchedEntityList.Clear();

                var renderBatchEntity = PostUpdateCommands.CreateEntity(renderBatchArchetype);
                PostUpdateCommands.SetComponent(renderBatchEntity, new RenderGroupID {
                    Value = s0.Value
                });
                var buffer = PostUpdateCommands.AddBuffer <RenderElement>(renderBatchEntity);

                RecurseChildren(in b0, in childrenBuffer);

                buffer.ResizeUninitialized(batchedEntityList.Count);

                for (int i = 0; i < buffer.Length; i++)
                {
                    buffer[i] = new RenderElement {
                        Value = batchedEntityList[i]
                    };
                }

                PostUpdateCommands.RemoveComponent <DirtyTag>(entity);
            });
        }
Exemple #12
0
    protected override void OnUpdate()
    {
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            if (connectedPlayers < GameSession.serverSession.numberOfPlayers)
            {
                PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
                var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
                var ghostId         = SerpentineGhostSerializerCollection.FindGhostType <CarStubSnapshotData>();
                var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
                var player          = PostUpdateCommands.Instantiate(prefab);

                int indexOfNextFreeSpawnLocationIndex = Random.Range(0, freeSpawnLocationIndices.Count);
                uint nextSpawnLocationIndex           = freeSpawnLocationIndices[indexOfNextFreeSpawnLocationIndex];
                freeSpawnLocationIndices.RemoveAt(indexOfNextFreeSpawnLocationIndex);

                PostUpdateCommands.SetComponent(player, new Translation {
                    Value = SerializedFields.singleton.spawnLocations[(int)nextSpawnLocationIndex].position
                });
                PostUpdateCommands.SetComponent(player, new Rotation {
                    Value = SerializedFields.singleton.spawnLocations[(int)nextSpawnLocationIndex].rotation
                });
                PostUpdateCommands.SetComponent(player, new SynchronizedCarComponent {
                    PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
                });
                PostUpdateCommands.SetComponent(player, new MissileScopeComponent {
                    TargetPlayerId = null
                });
                PostUpdateCommands.AddBuffer <PlayerInput>(player);
                PostUpdateCommands.AddBuffer <PowerupSlotElement>(player);
                PostUpdateCommands.AddBuffer <LaserPowerupSlotElement>(player);

                for (int i = 0; i < SerializedFields.singleton.numberOfPowerupSlots; i++)
                {
                    PostUpdateCommands.AppendToBuffer(player, new PowerupSlotElement {
                        Content = PowerupSlotContent.Empty
                    });
                }

                PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                    targetEntity = player
                });
                PostUpdateCommands.DestroyEntity(reqEnt);

                var raceInformationRequest = PostUpdateCommands.CreateEntity();
                PostUpdateCommands.AddComponent(raceInformationRequest, new RaceInformationRequest {
                    laps = GameSession.serverSession.laps
                });
                PostUpdateCommands.AddComponent(raceInformationRequest, new SendRpcCommandRequestComponent {
                    TargetConnection = reqSrc.SourceConnection
                });

                connectedPlayers++;
            }
        });
    }
        protected override void OnUpdate()
        {
            var deltaTime = Time.DeltaTime;

            Entities
            .WithAll <ClientToServerCommandHandler>()
            .WithNone <ClientPlayerMovementCommand>()
            .ForEach(entity => { PostUpdateCommands.AddBuffer <ClientPlayerMovementCommand>(entity); });

            Entities
            .WithAll <Player>()
            .ForEach((Entity entity, ref Player player, ref Velocity velocity, ref NetworkEntity networkEntity, ref Translation translation, ref Rotation rotation) =>
            {
                velocity.value = int2.zero;

                if (Input.GetKey(KeyCode.A))
                {
                    velocity.value.x = -1;
                }
                if (Input.GetKey(KeyCode.D))
                {
                    velocity.value.x = 1;
                }
                if (Input.GetKey(KeyCode.W))
                {
                    velocity.value.y = 1;
                }
                if (Input.GetKey(KeyCode.S))
                {
                    velocity.value.y = -1;
                }

                if (velocity.value.x == 0 && velocity.value.y == 0)
                {
                    return;
                }

                translation.Value = translation.Value + new float3(velocity.value.x, 0, velocity.value.y) * deltaTime * 5.0f;

                var tick = ClientManager.Instance.ServerTick;

                var playerMoveInput = EntityManager.GetBuffer <ClientPlayerMovementCommand>(ClientManager.Instance.ConnectionToServer.commandHandlerEntity);
                playerMoveInput.AddCommandData(new ClientPlayerMovementCommand
                {
                    playerId        = player.playerId,
                    networkEntityId = networkEntity.networkEntityId,
                    position        = translation.Value,
                    rotation        = rotation.Value.value,
                    velocity        = velocity.value,
                    Tick            = tick,
                    createdTick     = tick
                });

                //Debug.Log($"[Client] send player movement for player {player.playerId} at tick {tick}");
            });
        }
Exemple #14
0
        protected override void OnUpdate()
        {
            //Bootstraps
            Entities.With(_triggerBootstrapQuery).ForEach(entity => { PostUpdateCommands.AddBuffer <MecanimTrigger>(entity); });
            Entities.With(_floatBootstrapQuery).ForEach(entity => { PostUpdateCommands.AddBuffer <MecanimSetFloat>(entity); });
            Entities.With(_boolBootstrapQuery).ForEach(entity => { PostUpdateCommands.AddBuffer <MecanimSetBool>(entity); });
            Entities.With(_intBootstrapQuery).ForEach(entity => { PostUpdateCommands.AddBuffer <MecanimSetInteger>(entity); });

            //Universal Trigger
            Entities.ForEach((Entity entity, DynamicBuffer <MecanimTrigger> dataBuffer, Animator animator) =>
            {
                for (int i = 0; i < dataBuffer.Length; i++)
                {
                    animator.SetTrigger(dataBuffer[i].hashedParameter);
                }

                dataBuffer.Clear();
            });

            //Universal float
            Entities.ForEach((Entity entity, DynamicBuffer <MecanimSetFloat> dataBuffer, Animator animator) =>
            {
                for (int i = 0; i < dataBuffer.Length; i++)
                {
                    var dataInstance = dataBuffer[i];
                    animator.SetFloat(dataInstance.hashedParameter, dataInstance.value);
                }

                dataBuffer.Clear();
            });

            //Universal bool
            Entities.ForEach((Entity entity, DynamicBuffer <MecanimSetBool> dataBuffer, Animator animator) =>
            {
                for (int i = 0; i < dataBuffer.Length; i++)
                {
                    var dataInstance = dataBuffer[i];
                    animator.SetBool(dataInstance.hashedParameter, dataInstance.value);
                }

                dataBuffer.Clear();
            });

            //Universal int
            Entities.ForEach((Entity entity, DynamicBuffer <MecanimSetInteger> dataBuffer, Animator animator) =>
            {
                for (int i = 0; i < dataBuffer.Length; i++)
                {
                    var dataInstance = dataBuffer[i];
                    animator.SetInteger(dataInstance.hashedParameter, dataInstance.value);
                }

                dataBuffer.Clear();
            });
        }
Exemple #15
0
    protected override void OnUpdate()
    {
        Entities.WithNone <BEResourceSource>().ForEach((Entity entity, ref TriggerGather trigger) =>
        {
            PostUpdateCommands.AddBuffer <BEResourceSource>(entity);
        });

        //agrega elementos al buffer y si no hay elementos. Se quita
        Entities.WithAll <BEResourceSource>().ForEach((Entity entity, ref TriggerGather trigger) =>
        {
            var buffer = EntityManager.GetBuffer <BEResourceSource>(entity);
            buffer.Clear();
            //necesito conocer donde hay recursos.
            ResourceSourceAndEntity res;

            if (ResourceSourceManagerSystem.TryGetResourceAtHex(trigger.targetResourcePos, out res))
            {
                var type = res.resourceSource.resourceType;
                var allConectedResources = ResourceSourceManagerSystem.GetAllConectedResourcesOfType(trigger.targetResourcePos, type);
                foreach (var keyValue in allConectedResources)
                {
                    buffer.Add((BEResourceSource)keyValue.Value);
                }

                if (EntityManager.HasComponent <GroupOnGather>(entity))
                {
                    PostUpdateCommands.SetComponent <GroupOnGather>(entity, new GroupOnGather()
                    {
                        GatheringResourceType = type
                    });
                }
                else
                {
                    PostUpdateCommands.AddComponent <GroupOnGather>(entity, new GroupOnGather()
                    {
                        GatheringResourceType = type
                    });
                }
            }
            else
            {
                //NO HAY RECURSOS EN EL HEXAGONO.
                //detiene ejecucion de gather.
                //es decir no agrega el componente "GroupOnGather" que trigerrea el resto de componentes del systema de gather.
            }
        });



        //remove the component after use
        Entities.ForEach((Entity entity, ref TriggerGather trigger) =>
        {
            PostUpdateCommands.RemoveComponent <TriggerGather>(entity);
        });
    }
        protected override void OnUpdate()
        {
            Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref SpawnAvatarCommand req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
            {
                int connectionId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value;

                PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
                UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game", connectionId));

                // Delete original avatar
                Entities.ForEach((Entity ent, ref PlayerId playerId) =>
                {
                    if (playerId.playerId == connectionId)
                    {
                        PostUpdateCommands.DestroyEntity(ent);
                    }
                });

                // Setup the character avatar
                Entity ghostCollection = GetSingletonEntity <GhostPrefabCollectionComponent>();
                DynamicBuffer <GhostPrefabBuffer> ghostPrefabs = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection);
                int ghostId = GetPlayerGhostIndex(ghostPrefabs, req.avatarId, EntityManager);
                var prefab  = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection)[ghostId].Value;
                var player  = PostUpdateCommands.Instantiate(prefab);
                PostUpdateCommands.SetComponent(player, new PlayerId {
                    playerId = connectionId
                });
                PostUpdateCommands.SetComponent(player, new Translation {
                    Value = req.position
                });
                PostUpdateCommands.SetComponent(player, new Rotation {
                    Value = req.attitude
                });
                PostUpdateCommands.SetComponent(player, new GhostOwnerComponent {
                    NetworkId = connectionId
                });

                int deadPlayerId = GetPlayerGhostIndex(ghostPrefabs, PlayerPrefabComponent.DeadPlayerId, EntityManager);
                var dedPrefab    = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection)[deadPlayerId].Value;
                var dedPlayer    = PostUpdateCommands.Instantiate(dedPrefab);
                PostUpdateCommands.SetComponent(dedPrefab, new Translation {
                    Value = req.position
                });
                PostUpdateCommands.SetComponent(dedPrefab, new Rotation {
                    Value = req.attitude
                });

                PostUpdateCommands.AddBuffer <PlayerInput>(player);
                PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                    targetEntity = player
                });

                PostUpdateCommands.DestroyEntity(reqEnt);
            });
        }
    protected override void OnUpdate()
    {
        var localInput = GetSingleton <CommandTargetComponent>().targetEntity;

        if (localInput == Entity.Null)
        {
            var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
            Entities.WithAll <MovableCubeComponent>().WithNone <CubeInput>().ForEach((Entity ent, ref GhostOwnerComponent ghostOwner) =>
            {
                if (ghostOwner.NetworkId == localPlayerId)
                {
                    PostUpdateCommands.AddBuffer <CubeInput>(ent);
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                        targetEntity = ent
                    });
                }
            });
            return;
        }
        var input = default(CubeInput);

        input.Tick = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;
        if (Input.GetKey("a"))
        {
            input.horizontal -= 1;
        }
        if (Input.GetKey("d"))
        {
            input.horizontal += 1;
        }
        if (Input.GetKey("s"))
        {
            input.vertical -= 1;
        }
        if (Input.GetKey("w"))
        {
            input.vertical += 1;
        }
        if (Input.GetKey("space"))
        {
            input.up += 1;
        }
        if (Input.GetKey("escape"))
        {
            input.reset = true;
        }
        var inputBuffer = EntityManager.GetBuffer <CubeInput>(localInput);

        inputBuffer.AddCommandData(input);
    }
Exemple #18
0
    protected override void OnUpdate()
    {
        if (!init)
        {
            var random          = new Unity.Mathematics.Random(853);
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = whalesGhostSerializerCollection.FindGhostType <BoidSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;

            for (int i = 0; i < Bootstrap.Instance.boidCount; ++i)
            {
                var boid = EntityManager.Instantiate(prefab);

                EntityManager.SetComponentData(boid, new Translation {
                    Value = random.NextFloat3(1f)
                });
                EntityManager.SetComponentData(boid, new Rotation {
                    Value = quaternion.identity
                });
                EntityManager.SetComponentData(boid, new Velocity {
                    Value = random.NextFloat3Direction() * Bootstrap.Param.initSpeed
                });
                EntityManager.SetComponentData(boid, new Acceleration {
                    Value = float3.zero
                });
                EntityManager.AddBuffer <NeighborsEntityBuffer>(boid);
            }
            init = true;
        }

        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(string.Format("Server setting connection {0} to in game", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();

            var playerGhostId = whalesGhostSerializerCollection.FindGhostType <WhaleSnapshotData>();
            var playerPrefab  = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[playerGhostId].Value;
            var player        = EntityManager.Instantiate(playerPrefab);
            EntityManager.SetComponentData(player, new PlayerComponent {
                PlayerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value
            });
            PostUpdateCommands.AddBuffer <InputCommandData>(player);

            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });
            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
Exemple #19
0
    public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
    {
        var available = reader.AvailableBytes;

        reader.GetBytes(temp, available);

        var entity = PostUpdateCommands.CreateEntity();

        PostUpdateCommands.AddComponent(entity, new ServerStateCommand());
        var buffer      = PostUpdateCommands.AddBuffer <SerializedServerState>(entity).Reinterpret <byte>();
        var nativearray = new NativeArray <byte>(temp, Allocator.Temp);

        buffer.AddRange(nativearray);
        nativearray.Dispose();
    }
Exemple #20
0
    protected override void OnUpdate()
    {
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach(
            (Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game",
                                                EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));

            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = SelfDev_NetcodeGhostSerializerCollection.FindGhostType <PlayerSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
            var playerEntity    = EntityManager.Instantiate(prefab);

            int playerId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value;
            EntityManager.AddComponentData(playerEntity, new MovableCubeComponent {
                PlayerId = playerId
            });
            PostUpdateCommands.AddBuffer <CubeInput>(playerEntity);

            EntityManager.AddComponentData(playerEntity, new MainPlayerData {
                teamID = playerId
            });
            TeamData teamData = new TeamData()
            {
                teamID = playerId
            };

            bool up = (playerId % 2) == 0;
            EntityManager.SetComponentData(playerEntity, new Translation {
                Value = up ?
                        new float3(0f, 0f, POS) : new float3(0f, 0f, -POS)
            });

            AddExtraBlock(playerEntity, 1f, teamData, playerId);
            AddExtraBlock(playerEntity, 2f, teamData, playerId);
            AddExtraBlock(playerEntity, -1f, teamData, playerId);
            AddExtraBlock(playerEntity, -2f, teamData, playerId);

            Debug.Log($"Creating input buffer {playerEntity}");

            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = playerEntity
            });

            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
Exemple #21
0
        protected override void OnUpdate()
        {
            _gameInput.Update(Time.DeltaTime);

            // 只会执行一次
            if (Keyboard.current.escapeKey.wasPressedThisFrame)
            {
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible   = true;
            }

            if (Keyboard.current.f12Key.wasPressedThisFrame)
            {
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible   = false;
            }

            var localPlayer = GetSingleton <CommandTargetComponent>().Target;

            if (localPlayer == Entity.Null)
            {
                // 找到LocalPlayer
                Entities.ForEach((Entity ent, ref GhostOwnerComponent playerIdComponent) =>
                {
                    if (playerIdComponent.Value != GetSingleton <NetworkIdComponent>().Value)
                    {
                        return;
                    }
                    // 把localPlayer与Session 关联 , 并添加InputBuffer到PLocalPlayerS很伤
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(),
                                                    new CommandTargetComponent()
                    {
                        Target = ent
                    });
                    PostUpdateCommands.AddBuffer <InputCommand>(ent);
                    PostUpdateCommands.AddComponent(ent, new LocalPlayerComponent());
                    Debug.Log($"关联LocalPlayer.");
                });
                return;
            }

            var input = _gameInput.GetInputCommand();

            input.Tick = World.GetExistingSystem <TickSimulationSystemGroup>().ServerTick;
            var inputBuffer = EntityManager.GetBuffer <InputCommand>(localPlayer);

            inputBuffer.AddCommandData(input);
        }
Exemple #22
0
        // 1フレーム毎に呼ばれる
        protected override void OnUpdate()
        {
            // localInputの取得
            var localInput = GetSingleton <CommandTargetComponent>().targetEntity;

            if (localInput == Entity.Null)
            {
                var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
                Entities.WithNone <CubeInput>().ForEach((Entity ent, ref MovableCubeComponent cube) =>
                {
                    if (cube.PlayerId == localPlayerId)
                    {
                        PostUpdateCommands.AddBuffer <CubeInput>(ent);
                        PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                            targetEntity = ent
                        });
                    }
                });
                return;
            }

            // キー入力データの生成
            var input = default(CubeInput);

            input.tick = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;
            if (Input.GetKey("a"))
            {
                input.horizontal -= 1;
            }
            if (Input.GetKey("d"))
            {
                input.horizontal += 1;
            }
            if (Input.GetKey("s"))
            {
                input.vertical -= 1;
            }
            if (Input.GetKey("w"))
            {
                input.vertical += 1;
            }

            // サーバーに送信
            var inputBuffer = EntityManager.GetBuffer <CubeInput>(localInput);

            inputBuffer.AddCommandData(input);
        }
        protected override void BeginScene(float2 targetSize)
        {
            Entities
            .With(groupRemoveGlyphHtml)
            .ForEach((Entity e, DynamicBuffer <TintedGlyphHTML> glyph) =>
            {
                ReleaseTintedGlyphs(wrapper, e);
                PostUpdateCommands.RemoveComponent <TintedGlyphHTML>(e);
                PostUpdateCommands.RemoveComponent <TintedGlyphIndex>(e);
            });

            Entities
            .With(groupRemoveTextBitmap)
            .ForEach((Entity e, DynamicBuffer <TextBitmapHTML> glyph) =>
            {
                PostUpdateCommands.RemoveComponent <TextBitmapHTML>(e);
            });

            Entities
            .With(groupAddTextBitmap)
            .ForEach((Entity e, ref Text2DStyleBitmapFont text) =>
            {
                PostUpdateCommands.AddComponent(e, new TintedGlyphIndex()
                {
                    index = 0
                });
                DynamicBuffer <TintedGlyphHTML> tintedGlyphBuffer = PostUpdateCommands.AddBuffer <TintedGlyphHTML>(e);
                DynamicBuffer <TextBitmapHTML> textBuffer         = PostUpdateCommands.AddBuffer <TextBitmapHTML>(e);
            });

            //TODO: See if we need to optimize this
            Entities
            .With(groupInitializeBuffer)
            .ForEach((Entity e, ref TintedGlyphIndex index) =>
            {
                if (EntityManager.HasComponent <GlyphPrivateBuffer>(e))
                {
                    int length = EntityManager.GetBuffer <GlyphPrivateBuffer>(e).Length;
                    DynamicBuffer <TintedGlyphHTML> tintedGlyphBuffer = EntityManager.GetBuffer <TintedGlyphHTML>(e);
                    DynamicBuffer <TextBitmapHTML> textBuffer         = EntityManager.GetBuffer <TextBitmapHTML>(e);
                    tintedGlyphBuffer.ResizeUninitialized(length);
                    textBuffer.ResizeUninitialized(length);
                }
            });

            BeginSceneNative(wrapper, targetSize.x, targetSize.y);
        }
 protected override void OnUpdate()
 {
     for (int i = 0; i < data.Length; ++i)
     {
         // Need to split this out into server / client / whatever
         var transform    = data.Transform[i];
         var defaultToSet = new TransformToSet
         {
             Position    = transform.Location.ToUnityVector3() + worker.Origin,
             Velocity    = transform.Velocity.ToUnityVector3(),
             Orientation = transform.Rotation.ToUnityQuaternion()
         };
         var defaultToSend = new TransformToSend
         {
             Position    = transform.Location.ToUnityVector3() - worker.Origin,
             Velocity    = transform.Velocity.ToUnityVector3(),
             Orientation = transform.Rotation.ToUnityQuaternion()
         };
         var previousTransform = new DefferedUpdateTransform
         {
             Transform = transform
         };
         var ticksSinceLastUpdate = new TicksSinceLastTransformUpdate
         {
             NumberOfTicks = 0
         };
         var lastTransform = new LastTransformSentData
         {
             // could set this to the max time if we want to immediately send something
             TimeSinceLastUpdate = 0.0f,
             Transform           = transform
         };
         var lastPosition = new LastPositionSentData
         {
             // could set this to the max time if we want to immediately send something
             TimeSinceLastUpdate = 0.0f,
             Position            = data.Position[i]
         };
         PostUpdateCommands.AddComponent(data.Entity[i], defaultToSet);
         PostUpdateCommands.AddComponent(data.Entity[i], defaultToSend);
         PostUpdateCommands.AddComponent(data.Entity[i], previousTransform);
         PostUpdateCommands.AddComponent(data.Entity[i], ticksSinceLastUpdate);
         PostUpdateCommands.AddComponent(data.Entity[i], lastPosition);
         PostUpdateCommands.AddComponent(data.Entity[i], lastTransform);
         PostUpdateCommands.AddBuffer <BufferedTransform>(data.Entity[i]);
     }
 }
Exemple #25
0
        protected override void OnUpdate()
        {
            var localInput = GetSingleton <CommandTargetComponent>().targetEntity;

            // Debug.Log("");
            if (localInput == Entity.Null)
            {
                var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
                Entities
                .WithNone <Player.PlayerInput>()
                .ForEach((Entity entity, ref MovablePlayerComponent comp) =>
                {
                    if (comp.PlayerId == localPlayerId)
                    {
                        PostUpdateCommands.AddBuffer <Player.PlayerInput>(entity);
                        PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                            targetEntity = entity
                        });
                    }
                });
                return;
            }


            var input = default(Player.PlayerInput);

            input.tick = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;


            var up    = UnityEngine.Input.GetKey(KeyCode.W);
            var left  = UnityEngine.Input.GetKey(KeyCode.A);
            var down  = UnityEngine.Input.GetKey(KeyCode.S);
            var right = UnityEngine.Input.GetKey(KeyCode.D);
            var space = UnityEngine.Input.GetKey(KeyCode.Space);

            input.Up    = up;
            input.Left  = left;
            input.Right = right;
            input.Down  = down;
            input.Shoot = space;


            var inputBuffer = EntityManager.GetBuffer <Player.PlayerInput>(localInput);

            inputBuffer.AddCommandData(input);
        }
Exemple #26
0
    protected override void OnUpdate()
    {
        var localInput = GetSingleton <CommandTargetComponent>().targetEntity;

        if (localInput == Entity.Null)
        {
            var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
            Entities.WithNone <QbitInput>().ForEach((Entity ent, ref QbitDataComponent qbit) =>
            {
                if (qbit.PlayerId == localPlayerId)
                {
                    PostUpdateCommands.AddBuffer <QbitInput>(ent);
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                        targetEntity = ent
                    });
                }
            });
            return;
        }
        var input = default(QbitInput);

        input.tick = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;
        if (Input.GetKey("a"))
        {
            input.horizontal -= 1;
        }
        if (Input.GetKey("d"))
        {
            input.horizontal += 1;
        }
        if (Input.GetKey("s"))
        {
            input.vertical -= 1;
        }
        if (Input.GetKey("w"))
        {
            input.vertical += 1;
        }
        if (Input.GetKey("space"))
        {
            input.spacebarSpecial = 1;
        }
        var inputBuffer = EntityManager.GetBuffer <QbitInput>(localInput);

        inputBuffer.AddCommandData(input);
    }
Exemple #27
0
    protected override void OnUpdate()
    {
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(String.Format("El server establecio la conexion {0} ", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
#if true
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = ProyectoNetcodeGhostSerializerCollection.FindGhostType <SphereSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
            var player          = EntityManager.Instantiate(prefab);

            EntityManager.SetComponentData(player, new PlayerData
            {
                playerId      = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value,
                maxHealth     = 100,
                currentHealth = 100,
                death         = false,
                auto          = false,
                autoSpawn     = true,
                dest          = new float3(0f, 1f, 30f),
                dest2         = new float3(0f, 1f, -30f),
                killedBy      = Entity.Null,
                hudEntity     = Entity.Null
            });


            //Posiciones aleatorias
            float x = 0;
            float y = 1;
            float z = 0;
            EntityManager.SetComponentData(player, new Unity.Transforms.Translation {
                Value = new float3(x, y, z)
            });

            PostUpdateCommands.AddBuffer <PlayerInput>(player);
            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });
#endif


            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }
Exemple #28
0
        private void SpawnHearts()
        {
            var gameState          = GetSingleton <GameStateData>();
            var heartManager       = GetSingleton <HeartManager>();
            var heartManagerEntity = GetSingletonEntity <HeartManager>();

            gameState.Hearts = heartManager.NoOfHearts;
            SetSingleton(gameState);

            var camEntity   = GetSingletonEntity <Camera>();
            var camTr       = EntityManager.GetComponentData <Translation>(camEntity);
            var cam         = GetSingleton <Camera>();
            var top         = cam.fov - 0.5f;
            var right       = top * cam.aspect;
            var heartAnchor = new float3(right + camTr.Value.x, top + camTr.Value.y, 0);

            var heartBuffer = PostUpdateCommands.AddBuffer <Heart>(heartManagerEntity);

            for (var i = 0; i < gameState.Hearts; i++)
            {
                var translation = new Translation
                {
                    Value = heartAnchor
                };

                var heartBackground = PostUpdateCommands.Instantiate(heartManager.HeartBackgroundPrefab);
                var heart           = PostUpdateCommands.Instantiate(heartManager.HeartPrefab);

                PostUpdateCommands.SetComponent(heartBackground, translation);
                PostUpdateCommands.SetComponent(heart, translation);

                PostUpdateCommands.AddComponent(heartBackground, typeof(HeartBackground));

                heartBuffer.Add(new Heart()
                {
                    Value = heart
                });

                heartAnchor.x--;
            }

            m_NoOfHearts = gameState.Hearts;
        }
        protected override void OnUpdate()
        {
            var spawnZoneEntity = GetSingletonEntity <SpawnZone>();
            DynamicBuffer <SpawnPoint> spawnPoints = EntityManager.GetBuffer <SpawnPoint>(spawnZoneEntity);

            Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref JoinGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
            {
                int connectionId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value;

                PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
                UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game", connectionId));

                // Setup the character avatar
                Entity ghostCollection = GetSingletonEntity <GhostPrefabCollectionComponent>();
                DynamicBuffer <GhostPrefabBuffer> ghostPrefabs = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection);
                int ghostId = SpawnPlayerAvatarSystem.GetPlayerGhostIndex(ghostPrefabs, PlayerPrefabComponent.AliveCharacterId, EntityManager);
                var prefab  = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection)[ghostId].Value;
                var player  = PostUpdateCommands.Instantiate(prefab);
                PostUpdateCommands.SetComponent(player, new PlayerId {
                    playerId = connectionId
                });
                PostUpdateCommands.SetComponent(player, new GhostOwnerComponent {
                    NetworkId = connectionId
                });

                float3 spawnTranslation  = spawnPoints[connectionId % spawnPoints.Length].position;
                quaternion spawnRotation = spawnPoints[connectionId % spawnPoints.Length].attitude;
                float verticalRotation   = ((Quaternion)spawnRotation).eulerAngles.y;
                PostUpdateCommands.SetComponent(player, new Translation {
                    Value = spawnTranslation
                });
                PostUpdateCommands.SetComponent(player, new Rotation {
                    Value = spawnRotation
                });

                PostUpdateCommands.AddBuffer <PlayerInput>(player);
                PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                    targetEntity = player
                });

                PostUpdateCommands.DestroyEntity(reqEnt);
            });
        }
    protected override void OnUpdate()
    {
        //UnityEngine.Debug.Log("Server Updata");
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            if (connectedPlayers < GameSession.serverSession.numberOfPlayers)
            {
                PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
                var sourceConnectionNetworkId = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value;
                UnityEngine.Debug.Log(String.Format("Server setting connection {0} to in game", sourceConnectionNetworkId));
                var ghostCollection = GetSingletonEntity <GhostPrefabCollectionComponent>();
                var prefab          = Entity.Null;
                var prefabs         = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection);
                for (int ghostId = 0; ghostId < prefabs.Length; ++ghostId)
                {
                    if (EntityManager.HasComponent <CharacterTag>(prefabs[ghostId].Value))
                    {
                        prefab = prefabs[ghostId].Value;
                    }
                }
                // 随机生成位置索引
                int indexOfNextFreeSpawnLocationIndex = Random.Range(0, freeSpawnLocationIndices.Count);
                uint nextSpawnLocationIndex           = freeSpawnLocationIndices[indexOfNextFreeSpawnLocationIndex];
                freeSpawnLocationIndices.RemoveAt(indexOfNextFreeSpawnLocationIndex);

                var player = EntityManager.Instantiate(prefab);
                EntityManager.SetComponentData(player, new MovableComponent()
                {
                    Speed = 1f
                });
                EntityManager.SetComponentData(player, new GhostOwnerComponent {
                    NetworkId = sourceConnectionNetworkId
                });
                PostUpdateCommands.AddBuffer <CharacterSyncData>(player);

                PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                    targetEntity = player
                });

                PostUpdateCommands.DestroyEntity(reqEnt);
            }
        });
    }