コード例 #1
0
    private void DestroyTiles(fix2 position, fix radius)
    {
        TileWorld         tileWorld = CommonReads.GetTileWorld(Accessor);
        NativeList <int2> tiles     = new NativeList <int2>(Allocator.Temp);

        var transformTileRequests = GetSingletonBuffer <SystemRequestTransformTile>();

        Job.WithCode(() =>
        {
            TilePhysics.GetAllTilesWithin(position, radius, tiles);

            for (int i = 0; i < tiles.Length; i++)
            {
                Entity tileEntity           = tileWorld.GetEntity(tiles[i]);
                TileFlagComponent tileFlags = tileWorld.GetFlags(tileEntity);

                if (!tileFlags.IsOutOfGrid && tileFlags.IsDestructible)
                {
                    // remove ladder and terrain flags
                    tileFlags.Value &= ~(TileFlags.Ladder | TileFlags.Terrain);
                    transformTileRequests.Add(new SystemRequestTransformTile()
                    {
                        Tile         = tiles[i],
                        NewTileFlags = tileFlags
                    });
                }
            }
        }).Run();
    }
コード例 #2
0
    protected override void OnGamePresentationUpdate()
    {
        if (TryGetComponent(out BindedSimEntityManaged bindedSimEntity))
        {
            Entity pawnController = CommonReads.TryGetPawnController(SimWorld, bindedSimEntity.SimEntity);
            if (SimWorld.TryGetComponent(pawnController, out Team pawnTeam))
            {
                Color spriteColor = new Color();
                switch ((DesignerFriendlyTeam)pawnTeam.Value)
                {
                case DesignerFriendlyTeam.Player:
                    spriteColor = Color.white;
                    break;

                case DesignerFriendlyTeam.Baddies:
                    if (IsElite)
                    {
                        spriteColor = Color.magenta;
                    }
                    else
                    {
                        spriteColor = Color.red;
                    }
                    break;
                }

                SpriteRenderer.color = spriteColor;
                return;
            }
        }
    }
コード例 #3
0
    private void UpdateTrajectoryVisuals()
    {
        Vector2 trajectoryVector = _shootAimingState == ShootAimingState.SelectingDirection ? _shootingVector : ViewToSimVector((_line.position - transform.position) * 2);

        // trajectory
        if (_shootAimingState != ShootAimingState.Shoot)
        {
            Vector2 startOffset = Vector2.zero;
            // custom entity origin (not the item)
            if (_vectorDesc.UsePreviousParameterOriginLocation)
            {
                _trajectoryDisplay.Radius = (float)CommonReads.GetActorRadius(Cache.SimWorld, _originEntity);
            }
            else
            {
                // throwing from the item
                if (PresentationHelpers.Surveys.GetItemTrajectorySettings(Cache, CurrentContext.UseContext, trajectoryVector.normalized, out Vector2 offset, out float radius))
                {
                    startOffset = offset;
                    _trajectoryDisplay.Radius = radius;
                }
            }

            _trajectoryDisplay.GravityScale = PresentationHelpers.Surveys.GetProjectileGravityScale(Cache, CurrentContext.UseContext);
            _trajectoryDisplay.Length       = _trajectoryLength;
            _trajectoryDisplay.StartPoint   = (Vector2)transform.position + startOffset;
            _trajectoryDisplay.Velocity     = trajectoryVector;
        }
    }
コード例 #4
0
    public static bool RequestUseItem(ISimGameWorldReadWriteAccessor accessor, Entity actor, Entity item, GameAction.UseParameters parameters = null)
    {
        if (!CommonReads.CanUseItem(accessor, actor, item, out ItemUnavailablityReason unavailabilityReason))
        {
            Log.Warning($"Instigator {accessor.GetNameSafe(actor)} cannot use item {accessor.GetNameSafe(item)} because of {unavailabilityReason}");
            return(false);
        }

        accessor.TryGetComponent(item, out ItemAction itemAction);

        CommonWrites.RequestExecuteGameAction(accessor, item, itemAction, parameters);

        // reduce consumable amount
        if (accessor.GetComponent <StackableFlag>(item))
        {
            CommonWrites.DecrementItem(accessor, item, actor);
        }

        // reduce instigator AP
        if (accessor.TryGetComponent(item, out ItemSettingAPCost itemActionPointCost) && itemActionPointCost.Value != 0)
        {
            CommonWrites.ModifyStatFix <ActionPoints>(accessor, actor, -itemActionPointCost.Value);
        }

        // Cooldown
        if (accessor.TryGetComponent(item, out ItemTimeCooldownData itemTimeCooldownData))
        {
            accessor.SetOrAddComponent(item, new ItemCooldownTimeCounter()
            {
                Value = itemTimeCooldownData.Value
            });
        }

        return(true);
    }
コード例 #5
0
 protected override void OnUpdate()
 {
     foreach (var input in World.TickInputs)
     {
         if (input is SimPlayerInput playerInput)
         {
             Entity playerEntity = CommonReads.FindPlayerEntity(Accessor, playerInput.SimPlayerId);
             ExecutePlayerInput(playerInput, playerEntity);
         }
     }
 }
コード例 #6
0
    private void UpdateVisuals()
    {
        // drag target
        if (_dragState == DragState.Idle)
        {
            _dragTarget.position = _center.position;
        }
        else if (_dragState == DragState.Dragging)
        {
            _dragTarget.position = (Vector2)_center.position - SimToViewVector(_releaseVector);
        }
        else
        {
            _dragTarget.position = Vector3.MoveTowards(_dragTarget.position, _center.position, _releaseSpeed * Time.deltaTime);
        }

        // drag line
        Vector2 dragVector = _center.position - _dragTarget.position;

        _line.position   = (_center.position + _dragTarget.position) / 2;
        _line.localScale = new Vector3(dragVector.magnitude, 1, 1);
        _line.rotation   = Quaternion.Euler(0, 0, math.degrees(mathX.angle2d(dragVector)));

        // trajectory
        _trajectoryDisplay.Displayed = _dragState == DragState.Dragging || _dragState == DragState.Releasing;
        if (_trajectoryDisplay.Displayed)
        {
            Vector2 startOffset = Vector2.zero;
            // custom entity origin (not the item)
            if (_vectorDesc.UsePreviousParameterOriginLocation)
            {
                _trajectoryDisplay.Radius = (float)CommonReads.GetActorRadius(Cache.SimWorld, _originEntity);
            }
            else
            {
                // throwing from the item
                if (PresentationHelpers.Surveys.GetItemTrajectorySettings(Cache, CurrentContext.UseContext, _releaseVector.normalized, out Vector2 offset, out float radius))
                {
                    startOffset = offset;
                    _trajectoryDisplay.Radius = radius;
                }
            }

            _trajectoryDisplay.GravityScale = PresentationHelpers.Surveys.GetProjectileGravityScale(Cache, CurrentContext.UseContext);
            _trajectoryDisplay.Length       = _trajectoryLength;
            _trajectoryDisplay.StartPoint   = (Vector2)_center.position + startOffset;
            _trajectoryDisplay.Velocity     = _releaseVector;
        }
    }
コード例 #7
0
    protected override void OnUpdate()
    {
        var       transformTileRequests = GetSingletonBuffer <SystemRequestTransformTile>();
        TileWorld tileWorld             = CommonReads.GetTileWorld(Accessor);

        Entities.ForEach((Entity entity, in DestroyTileOnOverlapTag destroyOnOverlapWithTile, in FixTranslation position) =>
        {
            int2 tile = Helpers.GetTile(position);
            TileFlagComponent tileFlags = tileWorld.GetFlags(tile);

            if (tileFlags.IsDestructible && !tileFlags.IsEmpty)
            {
                transformTileRequests.Add(new SystemRequestTransformTile()
                {
                    NewTileFlags = TileFlagComponent.Empty,
                    Tile         = tile
                });
            }
        }).Run();
コード例 #8
0
    protected override void OnUpdate()
    {
        Entities
        .WithoutBurst()
        .WithStructuralChanges()
        .ForEach((Entity entity, ref ReboundOnOverlapWithTileState reboundOnOverlapWithTileState, ref PhysicsVelocity physicsVelocity, in ReboundOnOverlapWithTileSetting reboundOnOverlapWithTileSetting, in FixTranslation fixTranslation) =>
        {
            fix2 PossibleNewPosition = fixTranslation.Value;

            Entity tileEntity = CommonReads.GetTileEntity(Accessor, Helpers.GetTile(PossibleNewPosition));
            if (tileEntity != Entity.Null)
            {
                fix2 tilePos = Helpers.GetTileCenter(EntityManager.GetComponentData <TileId>(tileEntity));
                if (tilePos != reboundOnOverlapWithTileState.PreviousTile || ((GetElapsedTime(TimeValue.ValueType.Seconds).Value - reboundOnOverlapWithTileState.LastCollisionTime.Value) >= fix.Half))
                {
                    if (EntityManager.TryGetComponentData(tileEntity, out TileFlagComponent tileFlagComponent))
                    {
                        if (!tileFlagComponent.IsEmpty && !tileFlagComponent.IsLadder)
                        {
                            if (reboundOnOverlapWithTileState.ReboundCount < reboundOnOverlapWithTileSetting.ReboundMax)
                            {
                                reboundOnOverlapWithTileState.PreviousTile      = tilePos;
                                reboundOnOverlapWithTileState.LastCollisionTime = GetElapsedTime(TimeValue.ValueType.Seconds);
                                reboundOnOverlapWithTileState.ReboundCount++;

                                fix2 normal        = FindNormalFromOverlap(tilePos, PossibleNewPosition);
                                fix2 reboundVector = physicsVelocity.Linear - (2 * fixMath.dot(physicsVelocity.Linear, normal) * normal);

                                physicsVelocity.Linear = reboundVector;
                            }
                            else
                            {
                                _toDestroy.Add(entity);
                            }
                        }
                    }
                }
            }
        }).Run();
コード例 #9
0
    public override void OnEnter()
    {
        _surveyStateMachine.Blackboard = _surveySMBlackboard;
        _surveySMBlackboard.Cache      = Cache;
        _surveySMBlackboard.ResultParameters.Clear();
        _surveySMBlackboard.IsDebug = false;

        CursorOverlayService.Instance.ResetCursorToDefault();

        if (InputParameter != null && InputParameter.ActionInstigator != Entity.Null && InputParameter.ActionPrefab != Entity.Null)
        {
            if (SimWorld.TryGetComponent(InputParameter.ActionPrefab, out SimAssetId objectSimAssetID))
            {
                _surveySMBlackboard.ActionAuth = PresentationHelpers.FindActionAuth(objectSimAssetID);
            }

            if (_surveySMBlackboard.ActionAuth == null)
            {
                StateMachine.TransitionTo(UIStateType.Gameplay);
                return;
            }

            // Init process of parameter selection
            GameActionId actionId         = SimWorld.GetComponent <GameActionId>(InputParameter.ActionPrefab);
            GameAction   objectGameAction = GameActionBank.GetAction(actionId);

            _surveySMBlackboard.UseContext             = CommonReads.GetActionContext(SimWorld, InputParameter.ActionInstigator, InputParameter.ActionPrefab);
            _surveySMBlackboard.ParametersDescriptions = objectGameAction.GetExecutionContract(SimWorld, InputParameter.ActionPrefab).ParameterTypes;
        }
        else
        {
            _surveySMBlackboard.IsDebug = true;
        }

        _surveyStateMachine.TransitionTo(new SurveyState());
    }
コード例 #10
0
    protected override void OnUpdate()
    {
        ////////////////////////////////////////////////////////////////////////////////////////
        //      Camera
        ////////////////////////////////////////////////////////////////////////////////////////
        if (CameraController.Instance != null)
        {
            Cache.CameraPosition = CameraController.Instance.CamPosition;
            Cache.CameraSize     = CameraController.Instance.CamSize;
        }

        ////////////////////////////////////////////////////////////////////////////////////////
        //      Player & Pawn
        ////////////////////////////////////////////////////////////////////////////////////////
        Cache.LocalPawn = PlayerHelpers.GetLocalSimPawnEntity(Cache.SimWorld);

        if (Cache.LocalPawn != Entity.Null)
        {
            Cache.LocalController        = CommonReads.TryGetPawnController(Cache.SimWorld, Cache.LocalPawn);
            Cache.LocalPawnPosition      = Cache.SimWorld.GetComponent <FixTranslation>(Cache.LocalPawn).Value;
            Cache.LocalPawnPositionFloat = Cache.LocalPawnPosition.ToUnityVec();

            Cache.PlayerAP    = Cache.SimWorld.GetComponent <ActionPoints>(Cache.LocalPawn).Value;
            Cache.PlayerMaxAP = Cache.SimWorld.GetComponent <MaximumFix <ActionPoints> >(Cache.LocalPawn).Value;
        }
        else
        {
            Cache.LocalController = Entity.Null;
        }

        ////////////////////////////////////////////////////////////////////////////////////////
        //      Player Group
        ////////////////////////////////////////////////////////////////////////////////////////
        if (Cache.SimWorld.HasSingleton <PlayerGroupDataTag>())
        {
            Cache.PlayerGroupEntity = Cache.SimWorld.GetSingletonEntity <PlayerGroupDataTag>();
            Cache.GroupLifePoints   = Cache.SimWorld.GetComponent <LifePoints>(Cache.PlayerGroupEntity);
            Cache.GroupHealth       = Cache.SimWorld.GetComponent <Health>(Cache.PlayerGroupEntity);
            Cache.GroupMaxHealth    = Cache.SimWorld.GetComponent <MaximumFix <Health> >(Cache.PlayerGroupEntity).Value;
            Cache.GroupShield       = Cache.SimWorld.GetComponent <Shield>(Cache.PlayerGroupEntity);
            Cache.GroupMaxShield    = Cache.SimWorld.GetComponent <MaximumFix <Shield> >(Cache.PlayerGroupEntity).Value;
            Cache.GroupPosition     = Cache.SimWorld.GetComponent <FixTranslation>(Cache.PlayerGroupEntity).Value;
        }


        ////////////////////////////////////////////////////////////////////////////////////////
        //      Pointer
        ////////////////////////////////////////////////////////////////////////////////////////
        {
            Cache.PointerWorldPosition = CameraService.Instance.ActiveCamera.ScreenToWorldPoint(Input.mousePosition);
            if (WorldUIEventSystem.Instance != null)
            {
                Cache.PointerInWorld = WorldUIEventSystem.Instance.MouseInWorld;
            }
            Cache.PointedTile = Helpers.GetTile(Cache.PointerWorldPosition);


            int hitCount = Physics2D.OverlapPointNonAlloc(Cache.PointerWorldPosition, _overlapResults, layerMask: ~0);

            Cache.PointedViewEntities.Clear();
            Cache.PointedColliders.Clear();
            Cache.PointedGameObjects.Clear();
            for (int i = 0; i < hitCount; i++)
            {
                Cache.PointedColliders.Add(_overlapResults[i]);
                Cache.PointedGameObjects.AddUnique(_overlapResults[i].gameObject);

                if (_overlapResults[i].gameObject.TryGetComponent(out BindedSimEntityManaged bindedSimEntity))
                {
                    Cache.PointedViewEntities.Add(bindedSimEntity);
                }
            }


            Cache.PointedBodies.Clear();
            var physicsWorldSys = Cache.SimWorld.GetExistingSystem <PhysicsWorldSystem>();
            if (physicsWorldSys.PhysicsWorldFullyUpdated)
            {
                NativeList <OverlapPointHit> hits  = new NativeList <OverlapPointHit>(Allocator.Temp);
                OverlapPointInput            input = OverlapPointInput.Default;
                input.Position = Cache.PointerWorldPosition;
                physicsWorldSys.PhysicsWorld.OverlapPoint(input, ref hits);
                foreach (var hit in hits)
                {
                    Cache.PointedBodies.Add(hit.Entity);
                }
            }
        }
    }
コード例 #11
0
    protected override void OnUpdate()
    {
        foreach (var input in World.TickInputs)
        {
            if (input is SimInputPlayerCreate createPlayerInput)
            {
                var newPlayerEntity = EntityManager.CreateEntity(
                    typeof(PlayerTag),
                    typeof(PersistentId),
                    typeof(Name),
                    typeof(ControlledEntity),
                    typeof(Team),
                    typeof(ReadyToPlay),
                    typeof(Active));

                // set persistent id
                SetComponent(newPlayerEntity, this.MakeUniquePersistentId());

                // cap player name at 30 characters
                string playerName = createPlayerInput.PlayerName;
                if (playerName.Length > 30)
                {
                    playerName = playerName.Substring(0, 30);
                }

                // set name
                SetComponent(newPlayerEntity, new Name()
                {
                    Value = playerName
                });

                // assign controllable entity if possible
                Entity uncontrolledEntity = FindUncontrolledPawn();

                if (uncontrolledEntity == Entity.Null) // if no pawn found, try spawing one
                {
                    uncontrolledEntity = SpawnUncontrolledPawn();
                }

                if (uncontrolledEntity != Entity.Null)
                {
                    SetComponent(newPlayerEntity, new ControlledEntity()
                    {
                        Value = uncontrolledEntity
                    });
                    SetComponent(uncontrolledEntity, new Controllable()
                    {
                        CurrentController = newPlayerEntity
                    });
                }

                // set team
                SetComponent(newPlayerEntity, new Team()
                {
                    Value = 0
                });

                // set 'not ready for next turn'
                SetComponent(newPlayerEntity, new ReadyToPlay()
                {
                    Value = false
                });

                // set new player controller as currently active
                SetComponent(newPlayerEntity, new Active()
                {
                    Value = true
                });

                // FOR DEBUGGING ONLY
#if UNITY_EDITOR
                EntityManager.SetName(newPlayerEntity, $"Player({playerName})");
#endif
            }

            if (input is SimInputSetPlayerActive setPlayerActiveInput)
            {
                Entity playerEntity = CommonReads.FindPlayerEntity(Accessor, setPlayerActiveInput.PlayerID);

                if (playerEntity != Entity.Null)
                {
                    SetComponent(playerEntity, new Active()
                    {
                        Value = setPlayerActiveInput.IsActive
                    });
                }
            }
        }
    }
コード例 #12
0
    // Add new cheat classes here!

    public void HandleCheat(SimCheatInput cheat)
    {
        switch (cheat)
        {
        case SimInputCheatToggleInvincible toggleInvicible:
        {
            Entity groupHeader = GetSingletonEntity <PlayerGroupDataTag>();

            if (EntityManager.Exists(groupHeader))
            {
                const int DISTANT_FUTURE = 9999999;
                if (TryGetComponent(groupHeader, out InvincibleUntilTime invincibleUntilTime))
                {
                    EntityManager.AddComponentData(groupHeader, new InvincibleUntilTime()
                        {
                            Time = invincibleUntilTime.Time == DISTANT_FUTURE ? 0 : DISTANT_FUTURE
                        });
                }
                else
                {
                    EntityManager.AddComponentData(groupHeader, new InvincibleUntilTime()
                        {
                            Time = DISTANT_FUTURE
                        });
                }
            }
            break;
        }

        case SimInputCheatDamageSelf damagePlayer:
        {
            Entity player = CommonReads.FindPlayerEntity(Accessor, damagePlayer.PlayerId);

            if (EntityManager.Exists(player) &&
                EntityManager.TryGetComponentData(player, out ControlledEntity pawn))
            {
                if (damagePlayer.Damage > 0)
                {
                    CommonWrites.RequestDamage(Accessor, pawn, damagePlayer.Damage);
                }
                else
                {
                    CommonWrites.RequestHeal(Accessor, pawn, -damagePlayer.Damage);
                }
            }
            break;
        }

        case SimInputCheatAddAllItems addAllItems:
        {
            Entity player = CommonReads.FindPlayerEntity(Accessor, addAllItems.PlayerId);

            if (EntityManager.Exists(player) &&
                EntityManager.TryGetComponentData(player, out ControlledEntity pawn))
            {
                if (HasComponent <InventoryCapacity>(pawn))
                {
                    SetComponent <InventoryCapacity>(pawn, 999);
                }

                var itemBankSystem = Accessor.GetExistingSystem <GlobalItemBankSystem>();
                var allItems       = itemBankSystem.GetAllItemPrefabs();

                NativeArray <(Entity item, int stack)> itemTransfers = new NativeArray <(Entity item, int stack)>(allItems.Length, Allocator.Temp);

                for (int i = 0; i < allItems.Length; i++)
                {
                    itemTransfers[i] = (allItems[i], 99);
                }

                ItemTransationBatch itemTransationBatch = new ItemTransationBatch()
                {
                    Source         = null,
                    Destination    = pawn,
                    ItemsAndStacks = itemTransfers,
                    OutResults     = default
                };

                CommonWrites.ExecuteItemTransaction(Accessor, itemTransationBatch);
            }
            break;
        }

        case SimInputCheatTeleport teleport:
        {
            Entity player = CommonReads.FindPlayerEntity(Accessor, teleport.PlayerId);

            if (EntityManager.Exists(player) &&
                EntityManager.TryGetComponentData(player, out ControlledEntity pawn))
            {
                CommonWrites.RequestTeleport(Accessor, pawn, teleport.Destination);
            }
            break;
        }

        case SimInputCheatRemoveAllCooldowns _:
        {
            if (HasSingleton <NoCooldownTag>())
            {
                EntityManager.DestroyEntity(GetSingletonEntity <NoCooldownTag>());
            }
            else
            {
                Entity entity = EntityManager.CreateEntity();
                EntityManager.AddComponentData(entity, new NoCooldownTag());
            }

            break;
        }

        case SimInputCheatImpulseSelf impulseSelf:
        {
            Entity player = CommonReads.FindPlayerEntity(Accessor, impulseSelf.PlayerId);

            if (EntityManager.Exists(player) &&
                EntityManager.TryGetComponentData(player, out ControlledEntity pawn))
            {
                PhysicsVelocity vel = EntityManager.GetComponentData <PhysicsVelocity>(pawn);
                vel.Linear += impulseSelf.ImpulseValue;
                SetComponent <PhysicsVelocity>(pawn, vel);
            }
            break;
        }

        case SimInputCheatSoloPlay soloPlay:
        {
            Entity player = CommonReads.FindPlayerEntity(Accessor, soloPlay.PlayerId);

            if (!HasComponent <ControlledEntity>(player))
            {
                return;
            }

            // _________________________________________ Find Pawns _________________________________________ //
            Entity currentPawn  = Entity.Null;
            Entity newPawn      = Entity.Null;
            int    newPawnIndex = soloPlay.PawnIndex;

            if (EntityManager.TryGetComponentData(player, out ControlledEntity pawn))
            {
                currentPawn = pawn;
            }

            Entities.ForEach((Entity entity, in PlayerGroupMemberIndex memberIndex) =>
                {
                    if (memberIndex == newPawnIndex)
                    {
                        newPawn = entity;
                    }
                }).Run();


            // _________________________________________ Update Possession _________________________________________ //
            if (currentPawn != Entity.Null)
            {
                SetComponent <Controllable>(currentPawn, default);
            }

            if (newPawn != Entity.Null)
            {
                SetComponent <Controllable>(newPawn, player);
            }

            SetComponent <ControlledEntity>(player, newPawn);

            // _________________________________________ Disable Auto Attack on Others _________________________________________ //
            Entities.WithAll <PlayerGroupMemberIndex>()
            .ForEach((Entity entity, DynamicBuffer <InventoryItemReference> inventory) =>
                {
                    // implementation note: Keep 'EntityManager.HasComponent', otherwise it will cause an "invalidated by a structural change" exception
                    var items = inventory.ToNativeArray(Allocator.Temp);
                    if (entity != newPawn)
                    {
                        foreach (var item in items)
                        {
                            if (EntityManager.HasComponent <AutoAttackProgress>(item.ItemEntity))
                            {
                                EntityManager.RemoveComponent <AutoAttackProgress>(item.ItemEntity);
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in items)
                        {
                            if (!EntityManager.HasComponent <AutoAttackProgress>(item.ItemEntity) && EntityManager.HasComponent <ShouldAutoAttack>(item.ItemEntity))
                            {
                                EntityManager.AddComponent <AutoAttackProgress>(item.ItemEntity);
                            }
                        }
                    }
                }).WithoutBurst()
            .WithStructuralChanges()
            .Run();

            break;
        }
        }
    }
コード例 #13
0
    private bool ExecuteGameAction(Entity actionInstigator, Entity actionEntity, NativeArray<Entity> targets, GameAction.UseParameters parameters = null)
    {
        if (!TryGetComponent(actionEntity, out GameActionId actionId) || !actionId.IsValid)
        {
            Log.Error($"Could not find valid game action id on action {EntityManager.GetNameSafe(actionEntity)}. Action instigator: {EntityManager.GetNameSafe(actionInstigator)}");
            return false;
        }

        GameAction gameAction = GameActionBank.GetAction(actionId);

        if (gameAction == null)
            return false; // error is already logged in 'GetAction' method

        GameAction.ExecInputs input = new GameAction.ExecInputs(Accessor, CommonReads.GetActionContext(Accessor, actionInstigator, actionEntity, targets), parameters);
        GameAction.ExecOutput output = new GameAction.ExecOutput()
        {
            ResultData = new List<GameAction.ResultDataElement>()
        };

        if (!gameAction.Execute(in input, ref output))
        {
            Log.Info($"Couldn't use {gameAction}.");
            return false;
        }

        // Feedbacks
        GameAction.ResultData resultData = new GameAction.ResultData() { Count = output.ResultData.Count };

        for (int i = 0; i < output.ResultData.Count; i++)
        {
            switch (i)
            {
                case 0:
                    resultData.DataElement_0 = output.ResultData[0];
                    break;
                case 1:
                    resultData.DataElement_1 = output.ResultData[1];
                    break;
                case 2:
                    resultData.DataElement_2 = output.ResultData[2];
                    break;
                case 3:
                    resultData.DataElement_3 = output.ResultData[3];
                    break;
                default:
                    break;
            }
        }


        // copy native array to make sure its persisten
        var persistentContext = input.Context;

        if (input.Context.Targets.IsCreated)
        {
            persistentContext.Targets = new NativeArray<Entity>(input.Context.Targets.Length, Allocator.Persistent);
            input.Context.Targets.CopyTo(persistentContext.Targets);
        }

        PresentationEvents.GameActionEvents.Push(new GameActionUsedEventData()
        {
            GameActionContext = persistentContext,
            GameActionResult = resultData
        });

        return true;
    }
コード例 #14
0
    private void UpdateInventorySlots()
    {
        if (SimWorld.TryGetBufferReadOnly(Cache.LocalPawn, out DynamicBuffer <InventoryItemReference> inventory))
        {
            List <DisplayedItemData> displayedInventory = ListPool <DisplayedItemData> .Take();

            // gather all items to display
            for (int i = 0; i < inventory.Length; i++)
            {
                Entity item = inventory[i].ItemEntity;

                if (SimWorld.TryGetComponent(item, out SimAssetId itemAssetId))
                {
                    ItemAuth itemGameActionAuth = PresentationHelpers.FindItemAuth(itemAssetId);
                    if (itemGameActionAuth != null && !itemGameActionAuth.HideInInventory)
                    {
                        displayedInventory.Add(new DisplayedItemData()
                        {
                            ItemAuth = itemGameActionAuth,
                            ItemRef  = inventory[i],
                            Index    = i
                        });
                    }
                }
            }

            // Ajust Slot amount accordiwdng to inventory max size
            InventoryCapacity inventoryCapacity = SimWorld.GetComponent <InventoryCapacity>(Cache.LocalPawn);

            _gridLayoutGroup.constraintCount = min(_maxCollumns, inventoryCapacity);

            PresentationHelpers.ResizeGameObjectList(_slotVisuals, max(min(_maxCollumns, inventoryCapacity), displayedInventory.Count), _inventorySlotPrefab, _slotsContainer);

            for (int i = 0; i < _slotVisuals.Count; i++)
            {
                if (i < displayedInventory.Count)
                {
                    Entity item   = displayedInventory[i].ItemRef.ItemEntity;
                    int    stacks = displayedInventory[i].ItemRef.Stacks;

                    if (stacks == 1 && !SimWorld.GetComponent <StackableFlag>(item))
                    {
                        stacks = -1; // used in display to hide stacks
                    }
                    _slotVisuals[i].UpdateCurrentInventorySlot(displayedInventory[i].ItemAuth,
                                                               displayedInventory[i].Index,
                                                               GetSlotShotcut(i),
                                                               OnIntentionToUsePrimaryActionOnItem,
                                                               OnIntentionToUseSecondaryActionOnItem,
                                                               stacks);

                    if (!CommonReads.CanUseItem(SimWorld, Cache.LocalPawn, item))
                    {
                        _slotVisuals[i].UpdateDisplayAsUnavailable(item);
                    }
                }
                else
                {
                    _slotVisuals[i].UpdateCurrentInventorySlot(null, i, GetSlotShotcut(i), null, null);
                }
            }

            ListPool <DisplayedItemData> .Release(displayedInventory);
        }
    }
コード例 #15
0
    protected override void OnUpdate()
    {
        TileWorld    tileWorld    = CommonReads.GetTileWorld(Accessor);
        PhysicsWorld physicsWorld = _physicsWorldSystem.PhysicsWorld;

        Entities
        .WithReadOnly(tileWorld)
        .WithReadOnly(physicsWorld)
        .ForEach((Entity entity, ref NavAgentFootingState footing, in FixTranslation fixTranslation, in PhysicsColliderBlob colliderRef, in PhysicsVelocity velocity) =>
        {
            if (!colliderRef.Collider.IsCreated)
            {
                return;
            }

            ref Collider collider = ref colliderRef.Collider.Value;
            fix pawnRadius        = (fix)collider.Radius;
            fix pawnFeetXOffset   = pawnRadius * (fix)0.8f;
            fix2 belowLeftFoot    = new fix2(fixTranslation.Value.x - pawnFeetXOffset, fixTranslation.Value.y - pawnRadius - (fix)0.05);
            fix2 belowRightFoot   = new fix2(fixTranslation.Value.x + pawnFeetXOffset, fixTranslation.Value.y - pawnRadius - (fix)0.05);
            fix2 belowLongDick    = new fix2(fixTranslation.Value.x, fixTranslation.Value.y - pawnRadius - (fix)0.05);


            // GOTO Ladder IF on ladder && (already has footing on ladder || already has footing on ground)
            if (tileWorld.GetFlags(Helpers.GetTile(fixTranslation)).IsLadder &&
                (footing.Value == NavAgentFooting.Ladder || footing.Value == NavAgentFooting.Ground))
            {
                footing.Value = NavAgentFooting.Ladder;
            }
            else
            {
                OverlapPointInput detectTerrain = new OverlapPointInput()
                {
                    Filter = SimulationGameConstants.Physics.CharacterFilter.Data,
                };

                OverlapPointInput detectTerrainLeftFoot  = detectTerrain;
                detectTerrainLeftFoot.Position           = (float2)belowLeftFoot;
                OverlapPointInput detectTerrainLongDick  = detectTerrain;
                detectTerrainLongDick.Position           = (float2)belowLongDick;
                OverlapPointInput detectTerrainRightFoot = detectTerrain;
                detectTerrainRightFoot.Position          = (float2)belowRightFoot;

                // GOTO Ground IF above terrain && (previously grounded || previously ladder || previously airControl and not jumping || velocity is low)
                if ((physicsWorld.OverlapPoint(detectTerrainLeftFoot) || physicsWorld.OverlapPoint(detectTerrainLongDick) || physicsWorld.OverlapPoint(detectTerrainRightFoot)) &&
                    (footing.Value == NavAgentFooting.Ground ||
                     footing.Value == NavAgentFooting.Ladder ||
                     (footing.Value == NavAgentFooting.AirControl && velocity.Linear.y <= (fix)0.5) ||
                     velocity.Linear.lengthSquared < 4))
                {
                    footing.Value = NavAgentFooting.Ground;
                }
                else
                {
                    // GOTO air control IF in mid-air && was not in None
                    if (footing.Value != NavAgentFooting.None)
                    {
                        footing.Value = NavAgentFooting.AirControl;
                    }
                }
            }
        }).Run();
コード例 #16
0
    private void HandleTransformRequests()
    {
        var requests = GetSingletonBuffer <SystemRequestTransformTile>();

        if (requests.Length <= 0)
        {
            return;
        }

        var tiles     = new NativeArray <Entity>(requests.Length, Allocator.TempJob);
        var tileWorld = CommonReads.GetTileWorld(Accessor);
        DefaultTilesInfo defaultTileInfos = GetSingleton <DefaultTilesInfo>();

        var tileFlags   = GetComponentDataFromEntity <TileFlagComponent>();
        var simAssetIds = GetComponentDataFromEntity <SimAssetId>();

        Job.WithCode(() =>
        {
            for (int i = 0; i < requests.Length; i++)
            {
                tiles[i] = tileWorld.GetEntity(requests[i].Tile);
            }

            for (int i = 0; i < requests.Length; i++)
            {
                var tile = tiles[i];

                if (!tileFlags.HasComponent(tile))
                {
                    continue;
                }

                var request      = requests[i];
                var oldTileFlags = tileFlags[tile];

                // if flag is the same, skip
                if (oldTileFlags == request.NewTileFlags)
                {
                    continue;
                }

                // set new asset id, if needed
                if (request.ForcedNewSimAssetId.HasValue)
                {
                    if (simAssetIds[tile] != request.ForcedNewSimAssetId.Value)
                    {
                        simAssetIds[tile] = request.ForcedNewSimAssetId.Value;
                    }
                }
                else if (request.NewTileFlags.IsLadder)
                {
                    if (!oldTileFlags.IsLadder)
                    {
                        simAssetIds[tile] = defaultTileInfos.DefaultLadderTile;
                    }
                }
                else if (request.NewTileFlags.IsTerrain)
                {
                    if (!oldTileFlags.IsTerrain)
                    {
                        simAssetIds[tile] = defaultTileInfos.DefaultTerrainTile;
                    }
                }
                else if (request.NewTileFlags.IsEmpty)
                {
                    if (!oldTileFlags.IsEmpty)
                    {
                        simAssetIds[tile] = SimAssetId.Invalid;
                    }
                }

                tileFlags[tile] = request.NewTileFlags;
            }

            requests.Clear();
        }).Run();

        tiles.Dispose();
    }