Pedestrian

How To Create

Hybrid Legacy Skin

A Hybrid legacy skin is a hybrid entity that combines the default GameObject (with animator) and the DOTS entity.

Factory

  1. Open PedestrianSkinFactory in the scene.

    Hub/Pools/Npc/Pedestrian/PedestrianSkinFactory

    _images/PedestrianSkinFactory.png
  2. Enable the Show Add New Prefab Settings.

  3. Drag & drop source prefabs into the New Prefabs field.

  4. Customize the prefab names.

  5. Click the Try To Add Prefabs.

  6. If necessary, configure Ragdoll and assign to the Pedestrian Skin Factory Data (make sure Ragdoll is enabled).

Note

Each Hybrid legacy pedestrian prefab should have PedestrianReferences component.

Animations

By default, each pedestrian has a PedestrianBaseController animator.

Animation List:

Animation name

Parameters

Value

When it starts

Walking

  • yInput

  • SideMovement

  • 0.3

  • 0

By default

Running

  • yInput

  • SideMovement

  • 1

  • 0

By default

Idle

  • yInput

  • SideMovement

  • 0

  • 0

By default

Stand To Sit

  • IsSitting

  • true

By default

Sitting Idle

Starts when

Stand To Sit is completed

Sit To Stand

  • IsSitting

  • false

Starts after

Sitting Idle

Talking 1, 2, 3

  • Talking

  • 0,1,2

By default

How To Use

Code example:
Entities
.WithoutBurst()
.ForEach((
        Entity entity,
        Animator animator) =>
{
        animator.SetFloat("yInput", 1f);
}).Run();
Used in systems:
  • LegacyAnimatorSystem

  • LegacyAnimatorCustomStateSystem

  • LegacyTalkingAnimatorSystem

Pure GPU Skin

Pure GPU skin is a pure entity that combines the GPU texture animations and the DOTS entity.

How To Create

  1. Create textures and animation sheets.

  2. Create Animation Collection from the project context .

    Spirit604/Animation Baker/Animation Collection

    _images/AnimationCollectionExample.png
  3. Add and customize desired animations data.

  4. Open in the scene PedestrianCrowdSkinFactory.

    Hub/Pools/Npc/Pedestrian/PedestrianCrowdSkinFactory

  5. Assign Animation Collection to PedestrianCrowdSkinFactory.

    _images/AddNewEntryPanelExample.png
  6. Click + to show New Entry panel.

    _images/NewEntry.png
  7. Select created Baked Animation Sheet Data.

    _images/PedestrianAnimationSheetDataExample.png
  8. Open factory settings.

  9. Select Entry Key Source Type to Selected Mesh Name (or select Custom if you want to enter the name manually).

    _images/SettingsExample1.png
  10. Assign Default Atlas Texture (if selected pedestrians have the same texture material). [optional step]

    _images/SettingsExample3.png
  11. One by one click Select and Add entry button. Or click the Add all entries button to add all entries in the container.

    _images/NewEntry2.png
  12. Turn on the Find Related Animations button.

    _images/PedestrianAnimationSheetDataExample2.png
  13. Generate Animation Material.
    1. Assign main texture of selected model [if missing].

    2. Press the Generate button.

      _images/GenerateMaterialExample.png
  14. Select entry & assign animations:

    1. Animation baker binding:
      1. Bind the animation on the baking texture step.

    2. Manual way:
      1. In the inspector, select the animation that you want to assign to the selected character.

        _images/PedestrianAnimationsAssignExample.png
      2. Press the Assign button according to the selected animation in Animation Texture Data.

    3. Automated way:
      1. Automatic assignment works if the animation in the list matches (or partially matches) the animation name in the selected container.

      2. Press the Auto Bind Animations button.

      3. Make sure, that all animations are assigned.

        _images/PedestrianAnimationsAssignExample2.png
  15. Assign animations to each entry in the same way.

  16. Add custom optional animations for the desired pedestrians [optional step].
    1. In the Animation Collection add new Optional animations.

    2. Tick on Show optional animation popup in Pedestrian crowd skin factory settings.

    3. Add desired optional animations in the character list of the factory.

    4. Bind added animations.

  17. Assign Ragdolls. [optional step].

    _images/PedestrianGPURagdolleExample.png

How To Use

Code example:
    private NativeHashMap<SkinAnimationHash, HashToIndexData> hashToLocalDataLocalRef;

    void ISystemStartStop.OnStartRunning(ref SystemState state)
    {
            hashToLocalDataLocalRef = CrowdSkinProviderSystem.HashToLocalDataStaticRef;
    }

    [BurstCompile]
    void ISystem.OnUpdate(ref SystemState state)
    {
            var switchAnimJob = new SwitchAnimJob()
            {
                    HashToLocalData = hashToLocalDataLocalRef,
            };

            switchAnimJob.Schedule();
    }

[BurstCompile]
public partial struct SwitchAnimJob : IJobEntity
{
            [ReadOnly]
            public NativeHashMap<SkinAnimationHash, HashToIndexData> HashToLocalData;

            void Execute(
            Entity entity,
            ref SkinUpdateComponent skinUpdateComponent,
            EnabledRefRW<UpdateSkinTag> updateSkinTagRW)
            {
                    // Some animation hash calculated from animation name & AnimUtils.StringToHash method
                    var animHash = 54335363;
                    AnimEntitiesUtils.UpdateAnimation(ref skinUpdateComponent, ref updateSkinTagRW, animHash);
            }
            }
}
Used in systems:
  • GPUAnimatorSystem

  • GPUAnimatorCustomStateSystem

  • GPUTalkAnimatorSystem

Animation Texture Data

Data about baked animations in texture (How to create).

_images/PedestrianAnimationSheetDataExample3.png

Crowd GPU Custom Animator

The Crowd GPU Custom animator is used for transitions between baked animations (implemented by CrowdAnimatorTransitionSystem system).

How To Create Transition:
  1. Open in the scene CrowdGPUAnimatorAuthoring.

    Hub/Configs/BakerRefs/Settings/CrowdGPUAnimatorAuthoring

    _images/CrowdGPUAnimatorAuthoring.png
  2. Create an Animator Data Container from the project context and assign it to the animator (if required).

  3. Assign Animation Collection the same as in the PedestrianCrowdSkinFactory.

  4. Press the Open Animator button.

  5. Create a new transition layer (if needed).

  6. Enter the name of the trigger in the StartNode.

  7. Create and connect AnimationNode and TransitionNodes.

    _images/StartSitTransitionExample.png

    Start sit transition example.

    _images/SitoutTransitionExample.png

    Sitout transition example.

  8. Copy & paste the generated hash from the AnimatorContainer into the code (usage example).

    _images/AnimatorContainerExample.png

How To Use

Simple switch animation code example:

Entities
.WithoutBurst()
.WithNone<UpdateSkinTag>()
.WithAll<HasSkinTag, GPUSkinTag>()
.ForEach((
        Entity entity,
        ref GPUSkinUpdateComponent gpuSkinUpdateComponent) =>
{
        gpuSkinUpdateComponent.NewAnimationHash = PedestrianGPUAnimationsConstans.SittingIdle_Anim_Hash; //int animation hash
        commandBuffer.SetComponentEnabled<UpdateSkinTag>(entity, true);
}).Schedule();

Complex animation transition code example:

public partial class PedestrianSittingGPUAnimatorExampleSystem : SystemBase
{
        private const int StartSitAnimHash = -1880722739; //StartSit hash trigger

        private BeginPresentationEntityCommandBufferSystem entityCommandBufferSystem;
        private CrowdTransitionProviderSystem crowdTransitionProviderSystem;

        protected override void OnCreate()
        {
                base.OnCreate();
                entityCommandBufferSystem = World.GetOrCreateSystemManaged<BeginPresentationEntityCommandBufferSystem>();
                crowdTransitionProviderSystem = World.DefaultGameObjectInjectionWorld.GetOrCreateSystemManaged<CrowdTransitionProviderSystem>();
        }

        protected override void OnUpdate()
        {
                var transitions = crowdTransitionProviderSystem.Transitions;

                if (!transitions.IsCreated)
                {
                        return;
                }

                var commandBuffer = entityCommandBufferSystem.CreateCommandBuffer();

                Entities
                .WithoutBurst()
                .WithReadOnly(transitions)
                .WithAll<HasSkinTag, GPUSkinTag>()
                .ForEach((
                        Entity entity,
                        ref AnimationTransitionData animationTransitionData) =>
                {
                        Entity animStateEntity = Entity.Null;

                        transitions.TryGetValue(StartSitAnimHash, out animStateEntity);

                        if (animStateEntity != Entity.Null)
                        {
                                animationTransitionData.CurrentAnimationState = animStateEntity;
                                commandBuffer.SetComponentEnabled<HasAnimTransitionTag>(entity, true);
                        }
                }).Schedule();

                entityCommandBufferSystem.AddJobHandleForProducer(Dependency);
        }
}
Used in systems:
  • LoadGPUSkinSystem

  • CrowdAnimatorTransitionSystem

  • GPUSittingAnimatorSystem

Ragdoll

Ragdoll is created at the scene of the pedestrian’s death. Make sure ragdoll is enabled.

How To Create

  1. Add all the colliders and rigidbodies to character according to the RagdollWizard tutorial.

    _images/RagdollAssignExample.png

    RagdollWizard example.

  2. Add the PedestrianRagdoll component.

    _images/RagdollComponent.png
  3. For the remaining characters, open the RagdollCloner tool.

    _images/RagdollClonerPath.png _images/RagdollCloner1.png
  4. Assign the source character created first and the target remaining characters.

    _images/RagdollCloner2.png
  5. Click the Create button.

  6. Assign the result to PedestrianHybridLegacyFactory or PedestrianCrowdSkinFactory depending on the type of rig you have chosen.

    Note

Common Info

Collision

In some cases pedestrians can get stuck in obstacles (vehicles), to solve this problem, adjust the Antistuck config.

Authoring Components

Authoring components that make up the pedestrian entity.

PedestrianAuthoring

Contains the main components of pedestrian entity [required].

PlayerTargetAuthoring

Component for player targeting systems [optional].

Physics

PhysicsBody and PhysicsShape components for physics related systems [optional].

States

Common Logic

  1. Custom system set the next Action state in the NextStateComponent by utils method.

    • bool NextStateComponent.TryToSetNextState(ActionState.WaitForGreenLight, ref destinationComponent)

      Example method, if state can’t be set, then target swap back.

    • bool NextStateComponent.TryToSetNextState(ActionState.WaitForGreenLight)

      Example method without retargeting.

  2. PedestrianStateSystem is checking NextStateComponent for non-default next Action state and checks if the list of available states contains that state.

    Available state list for the current state can be defined here.

  3. If state is available, set StateComponent to the new state and set Movement state according to Movement binding data.

  4. After the Movement state is set to a new state, the MovementStateChangedEventTag tag is enabled & new animation movement animation is running in the appropriate animation system.
  5. If you want to set the Custom animation for pedestrian read this.

How To Change

    // Switch state example

[WithDisabled(typeof(WaitForGreenLightTag))]
[BurstCompile]
public partial struct CheckTrafficLightJob : IJobEntity
{

void Execute(
    ref DestinationComponent destinationComponent,
    ref NextStateComponent nextStateComponent,
    EnabledRefRW<WaitForGreenLightTag> waitForGreenLightTagRW,
    EnabledRefRW<CheckTrafficLightStateTag> checkTrafficLightStateTagRW)
    {
            // Tag is triggering system
            checkTrafficLightStateTagRW.ValueRW = false;

            //Example red traffic light flag logic
            bool redLight = true;

            if (redLight)
            {
                    // If the next state is available, start waiting for a green light.

                    if (nextStateComponent.TryToSetNextState(ActionState.WaitForGreenLight, ref destinationComponent))
                    {
                            // Some logic

                            waitForGreenLightTagRW.ValueRW = true;

                            // If the entity has a custom animation for this state, use the 'AnimatorStateExtension.AddCustomAnimatorState' method
                    }
                    else
                    {
                            // Otherwise return to previous destination, for example
                    }
            }
            else
            {
                    // Not red traffic light then set cross the road state
                    nextStateComponent.TryToSetNextState(ActionState.CrossingTheRoad);
            }
    }
    }

Custom State System

    // Custom state system example

[BurstCompile]
public partial struct CustomStateJob : IJobEntity
{

    void Execute(
    ref StateComponent stateComponent,
    ref NextStateComponent nextStateComponent,
    EnabledRefRW<WaitForGreenLightTag> waitForGreenLightTagRW)
    {
            // Some logic for waiting traffic light
            bool greenLight = true;

            if (!greenLight)
            {
                    // Some logic while waiting for the green light
            }

            // If the traffic light is green or another system has changed state, leave current system
            var leaveState = greenLight || !stateComponent.HasActionState(in nextStateComponent, ActionState.WaitForGreenLight);

            if (leaveState)
            {
                    waitForGreenLightTagRW.ValueRW = false;

                    if (greenLight)
                    {
                            nextStateComponent.TryToSetNextState(ActionState.CrossingTheRoad);
                    }
                    else
                    {
                            // Otherwise logic if the state is interrupted with another system
                    }
            }
    }
    }

Custom Animator State

If you want to override the default motion animation, use these methods:

Method #1

  1. Add the custom anitator state by using the utils method:

    • AnimatorStateExtension.AddCustomAnimatorState(ref EntityCommandBuffer commandBuffer, Entity entity, CustomAnimatorState customAnimationState)

    • And add hash of your animation in the following systems.

    • For Legacy skin.
      • LegacyAnimatorCustomStateSystem

    • For GPU skin.
      • GPUAnimatorCustomStateSystem

  2. If the pedestrian already in the custom animator state use the method:

    • AnimatorStateExtension.ChangeAnimatorState(ref EntityCommandBuffer commandBuffer, Entity entity, CustomAnimatorState customAnimationState, bool immediateUpdate = true)

  3. After all the custom animation is complete, use the method to return the default animation system:

    • AnimatorStateExtension.RemoveCustomAnimator(ref EntityCommandBuffer commandBuffer, Entity entity)

    Note

    For an example of a system, please read the script below:
    • BenchStateSystem.cs.

Method #2

  • If the entity has the Idle Movement state, you can change the animation directly by using the following methods:

    Note

    For an example of a system, please read the script below:
    • SwitchTalkingKeySystem.cs.

Movement State

  • Default

  • Idle

  • Walking

  • Running

Action State

  • Default : no state.

  • Idle : when a pedestrian is waiting.

  • MovingToNextTargetPoint : when going from PedestrianNode to PedestrianNode (excluding crosswalk).

  • WaitForGreenLight : when a pedestrian is waiting for a green traffic light.

  • CrossingTheRoad : when a pedestrian goes crossing a crosswalk.

  • ScaryRunning : activated when a pedestrian runs away in a panic (for example, the sound of a gunshot or the death of a pedestrian nearby).

  • Sitting : when a pedestrian is sitting.

  • Talking : when a pedestrian is talking.

    Note

    You can edit state logic here.

Configs

Pedestrian Spawner Config

_images/PedestrianSpawnerConfig.png
Min pedestrian count : number of pedestrians in the city.
Pool size : pool size of HybridLegacy skins.
Ragdoll pool size : pedestrian ragdoll pool size.
Min/Max spawn delay : minimum and maximum delay between spawn iterations.

Pedestrian Settings Config

_images/PedestrianSettingsConfig.png

Skin Type

  • Rig show only in view : rig skin will be loaded in the camera’s view area.

  • Rig and dummy : rig will be in the camera’s view, and the dummy skin will be out of the camera’s view.

  • Dummy show only in view : dummy skin will be loaded in the camera’s view area.

  • Rig show always : rig skin will be loaded when the entity is created and will exist until it is destroyed.

  • Dummy show always : dummy skin will be loaded when the entity is created and will exist until it is destroyed..

  • No skin : entities without a skin will be created.

Rig Type

Entity Type

  • No physics : pedestrian not contains PhysicsShape component.

  • Physics : pedestrian contains PhysicsShape component.

Common Settings

Pedestrian collider radius : pedestrian collider radius for No physics type.
Walking speed : walking speed.
Running speed : running speed.
Rotation speed : rotation speed.
Health : number of hit points for pedestrians.
Talking pedestrian spawn chance : chance of spawning talking pedestrians
Min/Max talk time : min/max talk time.

Obstacle Avoidance Type

Calc nav path : navigating based on NavMesh (config).
Local avoidance : simple obstacle avoidance navigation (config).

Pedestrian Navigation Type [ NavMesh navigation only]

  • Temp : navigation will be enabled if there is an obstacle in front of pedestrian.

  • Persist : navigation is always on.

  • Disabled

Collision type

Has ragdoll : on/off ragdoll for pedestrian.

Obstacle Local Avoidance Config

Config for Local Avoidance navigating.

_images/PedestrianObstacleLocalAvoidanceSettings.png
Obstacle avoidance method:
  • Simple : is able to avoid only 1 object.

  • Find neighbors : multiple objects close to each other are grouped as one (more costly in performance).

Max surface angle : maximum surface tilt angle at which the avoidance is calculated.
Target point offset : offset between an obstacle and avoidance waypoints.
Achieve distance : distance to achieve the avoidance waypoint.
Check target availability : check if destination can be reached, if not and can’t be found new, destination returns.

Antistuck Config

Anti-stuck config for pedestrians stucked in a collision.

_images/PedestrianAntistuckConfig.png
Antistuck enabled : on/off anti-stuck feature (if disabled previous target will be selected).
Target direction dot : direction between the pedestrian’s forward and the anti-stuck point.
Achieve distance : achieve distance to the antistuck target point.
Target point offset : distance between collision and anti-stuck point.

Trigger Config

_images/PedestrianTriggerConfig.png
Trigger HashMap capacity : initial hashmap capacity that contains data of triggers.
Trigger HashMap cell size : hashmap cell size.
Trigger data:
  • Fear Point Trigger :
    • Impact trigger duration : duration of the trigger on the pedestrian.

Scary Trigger Config

_images/PedestrianScaryTriggerConfig.png

Trigger settings

Death trigger squared distance : death trigger squared distance (squared distance == distance * distance).
Death trigger duration : death trigger duration.

Sound settings

Has scream sound : on/off scream sound.
Scream entity limit : maximum number of screaming pedestrians at the same time.
Chance to scream : chance of a pedestrian screaming.
Scream delay : delay between screams.
Scream sound data : scream sound data source.

Bench Config

_images/PedestrianBenchConfig.png
Min/Max idle time : min/max idle duration on the bench.
Custom achieve enter point distance : distance to achieve the entry point on the bench.
Idle after achieved exit duration : idle after achieved exit point duration.
Sitting movement speed : pedestrian movement speed when sitting on the bench.
Sitting rotation speed : pedestrian turn speed when sitting on the bench.
Custom achieve sit point distance : distance to achieve the sit point on the bench.

Common Sound Config

Common pedestrian sound settings

_images/PedestrianCommonSoundConfig.png
Sound death : sound when a pedestrian died.
Enter tram sound : sound when entering a tram.
Exit tram sound : sound when exiting a tram.

State Authoring

State Dictionary

_images/PedestrianStateAuthoring1.png
Next states : which states can override the current state.
State type:
  • Default : the state proccessed by PedestrianStateSystem system (code processing for state should be there PedestrianStateSystem.cs:144).

  • External system : the state proccessed by external system (code processing for state should be in the separate system).

  • Additive : additive state flag adds to the current state and is processed by the External system.

  • Additive any : additive state flag adds to the current state and is processed by the External system & ignores available next state flags.

Movement State Binding Dictionary

_images/PedestrianStateAuthoring2.png

Contains data - which Movement state is assigned after the Action state is assigned.

Note