Search Unity

Question v1.0.12: How to properly predictive spawn bullet for a machine gun

Discussion in 'NetCode for ECS' started by Occuros, Jul 11, 2023.

  1. Occuros

    Occuros

    Joined:
    Sep 4, 2018
    Posts:
    300
    Predictively spawning bullets currently create multiple predicted ghosts for one bullet (these collide with each other and are subsequently destroyed).

    We have the following setup:

    We have an input-gathering system (inside thePredictedSimulationSystemGroup), in that system, a gun component sets its `isShooting` boolean ghost field to true if a button is pressed.

    In a subsequent GunHandlingSystem (Also in the PredictedSimulationSystemGroup), we check for the `IsShooting` is set to true, and if the weapon cooldown (also ghost field) is 0, we spawn the next bullet.

    Before we spawn the bullet we check the `IsFirstTimeFullyPredictingTick` of the NetworkTime, to prevent multiple spawns during rollback and resimulation.

    But it doesn't seem to work, the client has multiple bullets spawning for just one server bullet.

    What is missing to have this work properly in netcode?
     
  2. NikiWalker

    NikiWalker

    Unity Technologies

    Joined:
    May 18, 2021
    Posts:
    313
    Hey Occuros!

    Can you post code for this please? IsFirstTimeFullyPredictingTick should do it, but there may be a bug elsewhere.
    One other idea is to replace the bool isShooting flag with a byte isShootingId, then store the id in the bullet. This also helps you write a "perfect" predicted spawn classification system.
     
  3. CMarastoni

    CMarastoni

    Unity Technologies

    Joined:
    Mar 18, 2020
    Posts:
    894
    Why the input gather is running inside the Prediction loop? This should not be the case. This should be done outside, otherwise any logic break apart (because of input data rollback and playback)
     
  4. Occuros

    Occuros

    Joined:
    Sep 4, 2018
    Posts:
    300
    Sorry that might have not been clear, Input gathering is not from the individual clients, a better name would be an "InputApplySystem", it's a system that takes the gathered input from all clients and executes logic from it. (Handling positions of the hands and head, button presses etc.)

    If that use-case should be supported I can see to make a minimal replication repo where I can showcase the issue.
     
  5. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    315
    I use the byte isShootingId approach which I can strongly recommend, especially when mutliple bullets can be spawned. This has two advantages: You can specify a bullet ID which can be used for a customized GhostSpawnClassificationSystem on the client side for example but also for other bullet identifying issues. Additionally you can control the exact amount of bullets to be spawned. There is no chance of getting a bullet more or less when properly implemented.
     
    NikiWalker and Occuros like this.
  6. Occuros

    Occuros

    Joined:
    Sep 4, 2018
    Posts:
    300

    Thank you for the hint!

    Could you elaborate on the isShootingId approach? Would that be a ghost field as well? Does that byte increment every frame, every time a bullet should be shot?

    I couldn't find a sample in the ECS samples repro which used that technique.
     
  7. Occuros

    Occuros

    Joined:
    Sep 4, 2018
    Posts:
    300
  8. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    315
    I did not found that approach in a sample, but it seems quite appropriate when trying to figure out a solution for firing multiple bullets predictively. I can show how I implemented the approach while still other variations may be possible. Also there are some pitfalls to be handled here which mades the logic overall a bit more complicated, but I mention them all.

    First the stated field has to be part of the ICommandData struct which is transferred from client to server. It should be sufficient to be a byte field except when extremly high fire rates are required like firing one or two hundred bullets per second. After reaching a value of 255, it overflows and resets to zero again, so it reuses bullet IDs. But because bullets are only short-lived, this should not be an issue but have to be kept in mind.
    Code (CSharp):
    1.  
    2. public struct UnitInput : ICommandData
    3. {
    4.   // ...
    5.  
    6.   /// <summary>
    7.   /// Gets or sets the projectile ID which are issued up to.
    8.   /// An issued projectile is directed to be fired imminently or may have been fired already.
    9.   /// </summary>
    10.   /// <remarks>
    11.   /// Examples:
    12.   /// When the <see cref="UnitAttackShooting.IssuedProjectileId" /> is 12 and the <see cref="IssuingProjectileId" /> is also
    13.   /// 12 then no shots should be fired.
    14.   /// When the <see cref="UnitAttackShooting.IssuedProjectileId" /> is 17 and the <see cref="IssuingProjectileId" /> is also
    15.   /// 22 then 5 shots should be fired.
    16.   /// The first first fired projectile has the ID 18 then, the second ID is 19 and so on.
    17.   /// </remarks>
    18.   public byte IssuingProjectileId;
    19.  
    20.   /// <summary>
    21.   /// Gets or sets the currently used weapon firing mode.
    22.   /// </summary>
    23.   public WeaponFiringMode CurrentFiringMode;
    24. }
    When required to really have a short-lived unique ID of the bullet the bullet ID/projectile ID has to be combined with another ID corresponding to the shooter. In my project I combine the ID of the character/unit with it to get that short-lived unique ID.

    Then an ECS component is required which will have two fields based on the stated field for counting already fired bullets and keep track of the issued ones. This component data is transferred from server to client, at least to clients which are predicting shots.
    Code (CSharp):
    1. /// <summary>
    2. /// Contains attacking relevant data.
    3. /// </summary>
    4. [GhostComponent]
    5. public struct UnitAttacking : IComponentData
    6. {
    7.   /// <summary>
    8.   /// Gets or sets the shooting part of the attacking.
    9.   /// </summary>
    10.   [GhostField(Composite = true)]
    11.   public UnitAttackShooting Shooting;
    12. }
    13.  
    14. /// <summary>
    15. /// Contains predicted attacking relevant data.
    16. /// </summary>
    17. [GhostComponent(PrefabType = GhostPrefabType.PredictedClient, OwnerSendType = SendToOwnerType.None)]
    18. public struct UnitPredictedAttacking : IComponentData
    19. {
    20.   /// <summary>
    21.   /// Gets or sets the shooting part of the attacking.
    22.   /// </summary>
    23.   public UnitAttackShooting Shooting;
    24. }
    25.  
    Code (CSharp):
    1. /// <summary>
    2. /// Shooting relevant data about an attack.
    3. /// </summary>
    4. /// <remarks>The struct is used as part of an ECS component.</remarks>
    5. public struct UnitAttackShooting
    6. {
    7.   // ...
    8.  
    9.   /// <summary>
    10.   /// Gets or sets the the projectile which has effectively has been fired last.
    11.   /// </summary>
    12.   [GhostField]
    13.   public byte FiredProjectileId;
    14.  
    15.   /// <summary>
    16.   /// Gets or sets the ID of the last issued projectile.
    17.   /// An issued projectile is directed to be fired imminently or may have been fired already.
    18.   /// </summary>
    19.   [GhostField]
    20.   public byte IssuedProjectileId;
    21.  
    22.   /// <summary>
    23.   /// Gets or sets the tick index at which the next projectile can be shot.
    24.   /// </summary>
    25.   [GhostField]
    26.   public uint NextProjectileReadyTick;
    27.  
    28.   /// <summary>
    29.   /// Gets or sets the firing mode used for the ongoing attack.
    30.   /// When no attack is ongoing the mode has no effect and can freely be changed.
    31.   /// </summary>
    32.   [GhostField]
    33.   public WeaponFiringMode FiringMode;
    34.  
    35.   /// <summary>
    36.   /// Gets whether a shooting is currently executed.
    37.   /// </summary>
    38.   public bool IsShooting
    39.   {
    40.     get => this.FiredProjectileId != this.IssuedProjectileId;
    41.   }
    42.  
    43.   /// <summary>
    44.   /// Calculates the difference between the current <see cref="FiredProjectileId"/> and the current <see cref="IssuedProjectileId"/>.
    45.   /// </summary>
    46.   /// <returns>A value between -127 and 128 showing whether projectiles are added or removed.</returns>
    47.   /// <remarks>
    48.   /// Normally the value is zero or negative, because more projectiles are issued than fired.
    49.   /// </remarks>
    50.   public int CalculateDifferenceFiredToIssuedProjectileId()
    51.   {
    52.     return this.CalculateDifferenceToIssuedProjectileId(this.FiredProjectileId);
    53.   }
    54.  
    55.   /// <summary>
    56.   /// Calculates the difference between the specified projectile ID and the current <see cref="IssuedProjectileId"/>.
    57.   /// </summary>
    58.   /// <param name="projectileId">The projectile ID to calculate the difference to.</param>
    59.   /// <returns>A value between -127 and 128 showing whether projectiles are added or removed.</returns>
    60.   public int CalculateDifferenceToIssuedProjectileId(int projectileId)
    61.   {
    62.     // The byte value range is split in half to determine either increase or decrement of the projectile count
    63.     int lowerThreshold;
    64.     int upperThreshold;
    65.  
    66.     unchecked
    67.     {
    68.       lowerThreshold = this.IssuedProjectileId - 128;
    69.       upperThreshold = this.IssuedProjectileId + 128;
    70.     }
    71.  
    72.     if (projectileId > upperThreshold)
    73.     {
    74.       return -math.abs((this.IssuedProjectileId + 256) - projectileId);
    75.     }
    76.     else if (projectileId <= lowerThreshold) // <= to ensure that the range is always -127 to 128 (same behavior as  > upperThreshold)
    77.     {
    78.       return math.abs((projectileId + 256) - this.IssuedProjectileId);
    79.     }
    80.     else
    81.     {
    82.       return projectileId - this.IssuedProjectileId;
    83.     }
    84.   }
    85.  
    86.   /// <summary>
    87.   /// Returns whether a new projectile can be fired.
    88.   /// </summary>
    89.   /// <param name="serverTickIndex">Current server tick index.</param>
    90.   /// <returns>True when a new projectile can be fired.</returns>
    91.   public bool IsProjectileReady(uint serverTickIndex)
    92.   {
    93.     return this.FiredProjectileId == this.IssuedProjectileId
    94.       && serverTickIndex >= this.NextProjectileReadyTick;
    95.   }
    96.  
    97.   /// <summary>
    98.   /// Increments the fired projectile ID.
    99.   /// </summary>
    100.   /// <returns>The new fired projectile ID.</returns>
    101.   public byte IncrementFiredProjectileId()
    102.   {
    103.     unchecked
    104.     {
    105.       this.FiredProjectileId = (byte)(this.FiredProjectileId + 1);
    106.       return this.FiredProjectileId;
    107.     }
    108.   }
    109.  
    110.   /// <summary>
    111.   /// Increments the issued projectile ID.
    112.   /// </summary>
    113.   /// <param name="increment">Value to increment.</param>
    114.   public void IncrementIssuedProjectileId(int increment = 1)
    115.   {
    116.     this.IssuedProjectileId = this.DetermineIncrementedIssuedProjectileId(increment);
    117.   }
    118.  
    119.   /// <summary>
    120.   /// Determines the incremented projectile ID using the specified increment value.
    121.   /// </summary>
    122.   /// <param name="increment">Value to increment.</param>
    123.   /// <returns>
    124.   /// Calculated projectile ID.
    125.   /// </returns>
    126.   public byte DetermineIncrementedIssuedProjectileId(int increment = 1)
    127.   {
    128.     unchecked
    129.     {
    130.       return (byte)(this.IssuedProjectileId + increment);
    131.     }
    132.   }
    133. }
    So, that was the data definition part. Now the data has to be read and write accordingly. Somewhere in the input system, the "IssuingProjectileId" has to be increased. There may be some ready to fire conditions before, but when shooting the issuing bullet count has to be increased. It may still overflow, but the determination/calculation methods above take care about this.
    Code (CSharp):
    1. byte newIssuingProjectileId;
    2. UnitAttackShooting currentUnitAttackShooting = ...;
    3. // ...
    4. newIssuingProjectileId = currentUnitAttackShooting.DetermineIncrementedIssuedProjectileId(effectiveAddedProjectileCount);
    5.  
    It is possible to add multiple bullets at ones OR add single bullet after single bullet, depending on player inputs and game logic. It is is important that the "newIssuingProjectileId" which is send as ICommandData is consistently tracked and send. This means when the ID is increased it has to send the same increased value frame after frame even when no more bullets are fired. I hold the "newIssuingProjectileId" in a separate field. But because of this it may in theory happen that the value is getting out of sync with the "IssuedProjectileId" coming from the server. Some logic for adjustment of the "newIssuingProjectileId" on the client-side may be required then.

    Some important note about the "currentUnitAttackShooting" variable and where the value has to came from. Because the GhostInputSystemGroup run before the Prediction Loop, the value may have been reset on the client due client-side rollback when new snapshot from server arrived. Then the "IssuedProjectileId" is NOT the predicted one which will cause wrong incrementings to the "IssuingProjectileId". I circumvented that problem with having two variations of the shooting component "UnitAttacking" and "UnitPredictedAttacking" like already shown above.

    The field "Shooting" of the "UnitPredictedAttacking" is copied from the "UnitAttacking" in a specific ECS system on the client-side running right after the Prediction Loop, so the client can access this predicted values in the Input System even when data is rollbacked.

    So now the bullet ID/projectile ID data can be processed in the Prediction Loop in a ECS system for handling the spawn of the bullet entities. This is straight forward and looks like this:
    Code (CSharp):
    1. /// <summary>
    2. /// System for spawning and processing shots.
    3. /// </summary>
    4. [BurstCompile]
    5. [UpdateInGroup(typeof(PredictedFixedStepSimulationSystemGroup))]
    6. [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation | WorldSystemFilterFlags.ClientSimulation)]
    7. public unsafe partial struct ShootingProcessorSystem : ISystem
    8. {
    9.   // ...
    10.  
    11.   /// <inheritdoc />
    12.   [BurstCompile]
    13.   public void OnUpdate(ref SystemState state)
    14.   {
    15.     if (!NetcodeUtilities.TryGetNetworkTime(SystemAPI.GetSingleton<NetworkTime>(), out var networkTime))
    16.     {
    17.       return;
    18.     }
    19.  
    20.     // ...
    21.     this._processShotsJob.NetworkTime = networkTime;
    22.     state.Dependency = this._processShotsJob.ScheduleByRef(this._processShotsQuery, state.Dependency);
    23.   }
    24.  
    25.   [BurstCompile]
    26.   private partial struct ProcessShotsJob : IJobEntity
    27.   {
    28.     // ...
    29.  
    30.     [ReadOnly]
    31.     public NetworkTime NetworkTime;
    32.  
    33.     [BurstCompile]
    34.     public void Execute(ShootingAspect shootingAspect)
    35.     {
    36.       // ...
    37.  
    38.       ref var weaponDefinition = ref this.WeaponDefinitionPoolReference.Reference.Value.Definitions[shootingAspect.UnitWieldedWeaponRef.ValueRO.Fixed.WeaponClassId];
    39.       this.InitiateAndContinueAttacks(ref shootingAspect, ref weaponDefinition);
    40.       this.ExecuteAttacks(ref shootingAspect, ref weaponDefinition);
    41.     }
    42.  
    43.     [BurstCompile]
    44.     private void InitiateAndContinueAttacks(
    45.       ref ShootingAspect shootingAspect, ref WeaponDefinition weaponDefinition)
    46.     {
    47.       var serverTickIndex = this.NetworkTime.ServerTick.TickIndexForValidTick;
    48.  
    49.       ref UnitAttackShooting unitAttackShooting = ref shootingAspect.UnitAttackingRef.ValueRW.Shooting;
    50.       ref var unitWieldedWeapon = ref shootingAspect.UnitWieldedWeaponRef.ValueRW;
    51.       ref UnitInput weaponInput = ref shootingAspect.UnitWieldedWeaponRef.ValueRW.Input;
    52.  
    53.       if (unitAttackShooting.IssuedProjectileId != weaponInput.IssuingProjectileId)
    54.       {
    55.         if (weaponDefinition.AvailableFiringModes.Has(weaponInput.CurrentFiringMode))
    56.         {
    57.           // Validate data before applying
    58.           if (unitAttackShooting.IsProjectileReady(serverTickIndex)
    59.               && unitWieldedWeapon.IsAttackReady(serverTickIndex)
    60.               && shootingAspect.UnitMotionRef.ValueRO.CanAttack)
    61.           {
    62.             var minimumBurstProjectileCount = weaponInput.CurrentFiringMode.DetermineMinimumBurstProjectileCount();
    63.             var maximumRemainingProjectileCount = (int)unitWieldedWeapon.Dynamic.LoadedRemainingProjectileCount;
    64.             var projectileDifferenceCount = unitAttackShooting.CalculateDifferenceToIssuedProjectileId(weaponInput.IssuingProjectileId);
    65.  
    66.             if (maximumRemainingProjectileCount != projectileDifferenceCount
    67.                 && minimumBurstProjectileCount != projectileDifferenceCount)
    68.             {
    69.               if (this.NetworkTime.IsFirstTimeFullyPredictingTick)
    70.               {
    71.                 Log.To(this.JobLogger).Warning(
    72.                   "[T={ServerTickValue}/{WorldName}] Invalid projectile count to fire weapon '{WeaponName}' ({WeaponClassId}) for unit with ID {UnitId} with mode '{FiringMode}', because {IssuedProjectileCount} projectiles are issued while {RequiredProjectileCount} projectiles are required for the mode. Projectile count adjusted and continued.",
    73.                   serverTickIndex, this.WorldName, weaponDefinition.Name, weaponDefinition.WeaponClassId, shootingAspect.PureUnitRef.ValueRO.UnitId,
    74.                   WeaponFiringModeBurst.Texts[(int)weaponInput.CurrentFiringMode], projectileDifferenceCount, minimumBurstProjectileCount);
    75.               }
    76.  
    77.               projectileDifferenceCount = minimumBurstProjectileCount;
    78.             }
    79.  
    80.             var effectiveBurstProjectileCount = (byte)math.min(projectileDifferenceCount, maximumRemainingProjectileCount);
    81.  
    82.             unitAttackShooting.FiringMode = weaponInput.CurrentFiringMode;
    83.             unitAttackShooting.IncrementIssuedProjectileId(effectiveBurstProjectileCount);
    84.           }
    85.           else if (unitAttackShooting.IsShooting && unitAttackShooting.FiringMode == WeaponFiringMode.Automatic)
    86.           {
    87.             var projectileDifferenceCount = unitAttackShooting.CalculateDifferenceToIssuedProjectileId(weaponInput.IssuingProjectileId);
    88.  
    89.             // Only on automatic fire the issued projectile count may be increased during attack
    90.             if (projectileDifferenceCount > 0)
    91.             {
    92.               unitAttackShooting.IssuedProjectileId = weaponInput.IssuingProjectileId;
    93.             }
    94.           }
    95.         }
    96.         else
    97.         {
    98.           if (this.NetworkTime.IsFirstTimeFullyPredictingTick)
    99.           {
    100.             Log.To(this.JobLogger).Warning(
    101.               "[T={ServerTickValue}/{WorldName}] Cannot fire weapon '{WeaponName}' ({WeaponClassId}) for unit with ID {UnitId} with firing mode '{FiringMode}', because mode is not available.",
    102.               serverTickIndex, this.WorldName, weaponDefinition.Name, weaponDefinition.WeaponClassId, shootingAspect.PureUnitRef.ValueRO.UnitId,
    103.               WeaponFiringModeBurst.Texts[(int)weaponInput.CurrentFiringMode]);
    104.           }
    105.         }
    106.       }
    107.     }
    108.  
    109.     [BurstCompile]
    110.     private void ExecuteAttacks(
    111.       ref ShootingAspect shootingAspect, ref WeaponDefinition weaponDefinition)
    112.     {
    113.       ref UnitAttackShooting unitAttackShooting = ref shootingAspect.UnitAttackingRef.ValueRW.Shooting;
    114.       ref var wieldedWeaponDynamicBlock = ref shootingAspect.UnitWieldedWeaponRef.ValueRW.Dynamic;
    115.  
    116.       if (unitAttackShooting.IsShooting)
    117.       {
    118.         var serverTickIndex = this.NetworkTime.ServerTick.TickIndexForValidTick;
    119.  
    120.         // Check for out of ammunition
    121.         if (wieldedWeaponDynamicBlock.LoadedRemainingProjectileCount == 0)
    122.         {
    123.           // Reset the issued projectiles to the fired once, this ends the burst
    124.           unitAttackShooting.IssuedProjectileId = unitAttackShooting.FiredProjectileId;
    125.  
    126.           // Also activate cooldown
    127.           wieldedWeaponDynamicBlock.NextAttackReadyTick = serverTickIndex + weaponDefinition.ImmediateGunDefinition.BurstCooldownTicks;
    128.         }
    129.         else if (shootingAspect.UnitMotionRef.ValueRO.CanAttack && serverTickIndex >= unitAttackShooting.NextProjectileReadyTick)
    130.         {
    131.           var projectileId = unitAttackShooting.IncrementFiredProjectileId();
    132.  
    133.           // Checks whether this predicted server tick is predicted for the very first time (on server always true, because every tick is processed only once)
    134.           // Spawning attack ghost entities and calculating result is only required to be executed once per unique server tick (spawning new ghost entities!)
    135.           if (this.NetworkTime.IsFirstTimeFullyPredictingTick)
    136.           {
    137.             // Spawn the shot entity
    138.             var shotEntity = this.SpawnShot(ref shootingAspect, serverTickIndex, projectileId, out var pureImmediateShot);
    139.  
    140.             // Do additional handling of the shot like processing impact and so on
    141.             // ...
    142.           }
    143.  
    144.           wieldedWeaponDynamicBlock.LoadedRemainingProjectileCount--;
    145.  
    146.           unitAttackShooting.NextProjectileReadyTick = serverTickIndex + weaponDefinition.ImmediateGunDefinition.ProjectileCooldownTicks;
    147.  
    148.           // When the last shot has been fired activate cooldown
    149.           if (!unitAttackShooting.IsShooting)
    150.           {
    151.             // This appoints that the attack is on cooldown (but also used for weapon switch and reload)
    152.             wieldedWeaponDynamicBlock.NextAttackReadyTick = serverTickIndex + weaponDefinition.ImmediateGunDefinition.BurstCooldownTicks;
    153.           }
    154.         }
    155.       }
    156.     }
    157.   }
    158. }
     
    Last edited: Jul 12, 2023
    NikiWalker, Occuros and CMarastoni like this.
  9. Occuros

    Occuros

    Joined:
    Sep 4, 2018
    Posts:
    300
    Thank you for sharing all the details of your systems and implementation, will try to replicate this and see if it can resolve the multiple bullet spawn issue on the client side.

    That being said, it looks like a lot of logic is required for something very common in many multiplayer experiences.

    Are there any improvements planned to predictive spawning in netcode, to make this kind of process less laborious @CMarastoni?
     
  10. CMarastoni

    CMarastoni

    Unity Technologies

    Joined:
    Mar 18, 2020
    Posts:
    894
    Just to mention, we implement a similar mechanics for this in our HelloNetcode sample for predictive spawning here:
    https://github.com/Unity-Technologi...redictedSpawning/ProcessFireCommandsSystem.cs
    It still use a unique ID for spawning, but it is handled automatically via InputEvent and you just then need to match the predicted entity using that id via a custom classification (you can see that in the sample).

    That being said, it is hard to provide something completely generic that fit all. This is why we preferred to let the user decided how to implement their predictive spawning logic.
    But I do agree that is not straightforward and very common.

    Even thought the process it itself is not complex:
    - Assign an id to the entity (always increasing counter is fine) to some component
    - Match the spawned entity with a classification system (the default one can't do that).
    It is still quite a bit of code to write.

    We can indeed provide a default logic that does that, along with components, so you don't need to re-invent the wheel for common case scenario like that. I will take a note and see what we can do!
     
    optimise likes this.
  11. Occuros

    Occuros

    Joined:
    Sep 4, 2018
    Posts:
    300
    That would be ideal if that use-case could be made simpler.

    But the linked example also fails when the grenade launcher is switched from an only fire on mouse click, to continue fire on mouseclick.


    I simply added:


    Code (CSharp):
    1.   public struct CharacterControllerPlayerInput : IInputComponentData
    2.     {
    3.          ...
    4.         [GhostField] public bool IsFiring;
    5.         ...
    6.     }
    7.  
    To the input system:
    Code (CSharp):
    1.  
    2. input.ValueRW.IsFiring = Input.GetKey(KeyCode.Mouse0);
    3.  
    Code (CSharp):
    1.     public struct Character : IComponentData
    2.     {
    3.          ...
    4.         [GhostField]
    5.         public float weaponCooldown;
    6.     }
    Then inside the `ProcessFireCommandsSystem`:


    Code (CSharp):
    1.             foreach (var (character, inputBuffer, anchorPoint) in SystemAPI.Query<CharacterAspect, DynamicBuffer<HelloNetcodeSamples.Generated.CharacterControllerPlayerInputInputBufferData>, RefRO<AnchorPoint>>().WithAll<Simulate>())
    2.             {
    3.                 character.Character.weaponCooldown = math.max( character.Character.weaponCooldown - deltaTime, 0);
    4.                 if (character.Input.SecondaryFire.IsSet || (character.Input.IsFiring && character.Character.weaponCooldown <= 0))
    5.                 {
    6.                     character.Character.weaponCooldown = 0.3f;
    When this is done, the grenades collide with each other and explode.

    What would be the easiest approach to handle continuous predictive spawning when a trigger of a gun is held down?
     

    Attached Files:

  12. bustedbunny2

    bustedbunny2

    Joined:
    Oct 27, 2021
    Posts:
    25
    So I have alternative solution: syncing via NetworkTick deterministically.

    Basically in ApplyInputSystem (predicted loop) write current NetworkTick (should be ghost field) when shooting starts.
    And then calculate ticks since shooting started in shooting loop and based on cooldown value (how many ticks it takes) figure which modulo to use to determine ticks for shot.

    This works really well even on very high ping.

    https://github.com/bustedbunny/unity_netcode_predictive_spawning/tree/tick_prediction
     
    NikiWalker and Occuros like this.
  13. optimise

    optimise

    Joined:
    Jan 22, 2014
    Posts:
    2,128
    Does spawn predicted ghost working by default feature will ship very soon at 1.1 exp release? I tried to implement ClassificationSystem and found that it's not possible to implement it for my use case. I have a lot of skill entities and each skill entity attached ghost prefab entity which make it not possible to implement without having major rewrite to make it work. I hope official can prioritize this feature and ship it asap.
     
  14. bustedbunny2

    bustedbunny2

    Joined:
    Oct 27, 2021
    Posts:
    25
    It works just fine by default. There could be glitches, like classification system destroying what shouldn't be destroyed from time to time, but in general this is just fine.
     
  15. optimise

    optimise

    Joined:
    Jan 22, 2014
    Posts:
    2,128
    Currently it's not working without creating custom classification system. When predictive spawn a ghost, it will just spawn 2 exact same ghost entity and 1 of it will quickly destroy itself which is not the expected behavior
     
  16. CMarastoni

    CMarastoni

    Unity Technologies

    Joined:
    Mar 18, 2020
    Posts:
    894
    In 1.1 we don't provide a classification system that work in all cases. It is up to you to provide one that work for you specific case scenario.
    For spawning multiple entities in the same frame, assigning an unique id to each ghost based on some replicated field (i.e an always increasing counter or something like that) would provide a decent starting point.