title: Pixel Perfect 2D tiles

text:
# Question
Title: Pixel Perfect 2D tiles
I'm trying to make an 64x64 tilemap using Super Tilemap Editor & Unity but my tiles looks terrible. I did my research about pixel perfect 2D and all of the solutions were for pixel art, they didn't work for me.

I have the following tileset I made in Adobe Illustrator as an example

Tiles looks like this when placed in game (1x zoom)

I'm pretty sure they're not 64x64 in game, they also look pixelated probably because they're smaller than they actually are on camera.

So my question is, how can I calculate the correct camera size for 64x64 tiles and do I have to make any changes in order to make sprites look pixel perfect? I'm currently using 1080/64/2=8.4375 (vertical resolution / PPU / 2) as camera size.

# Answer
Even if your game uses a 2d art style which is not traditional pixel art, it can benefit from pixel-perfect rendering.

There used to be some convoluted tricks you had to employ to achieve pixel-perfect drawing of 2d sprites. But most of those are now obsolete, because since a couple versions Unity has a pixel-perfect camera.

Download the 2D Pixel Perfect package through the package manager. It comes with an alternative camera component, the "Pixel Perfect Camera" which solves a lot of common issues with tilemap rendering. As per the guide above, you also need to make sure that all your 2d image assets have the following import settings:

* Pixels Per Unit: Must be the same value for all sprites. I recommend to use your tile size, so one tile is one unit wide.
* Filter Mode: Point (no filter)
* Compression: None
> 1 votes

# Answer
Your game won't be very accessible if you're trying to set the camera size. If what you want is the pixel like look then when importing your sprites you'll want to change your pixels per unit to have them scale differently within the unity engine. You have them set to 64, but you can make it any size you want. Just figure out what looks good on your camera. Modern pixel art games rarely tie the camera to your pixel size. You'll also want to set your filter mode to "point". This will stop unity from smoothing when scaling your texture. If all your assets in your game are like this consider looking up AssetImporter. Unity gives you tools to automatically set these settings when importing assets.

EDIT: Misunderstood the part about changing the size of the camera. Disregard that. I think you're just missing the "point" filtering
> 0 votes

---
Tags: unity, 2d, camera, resolution
---


# Question
Title: Behavioural Items with ScriptableObjects
My game has an item system that is relatively small compared to most of the RPGs, but it is pretty similar to the games like Half-Life and Counter-Strike where you have an inventory consists of several menus (categories) and a few slots in them. Whenever the player picks up or receives the weapon, from then on they can select it using their inventory which is quite simplistic, in my opinion, and I like it.

First of all, I want to indicate that I am willing to separate logic and data. For data, I am using ScriptableObjects and the basic concept behind is basically referencing ScriptableObjects to MonoBehaviours and handle the tasks in there according to the data. This can be of course made with Prefabs but the thing is, you would de unconsciously duplicating common components that an item would use and only change some of the fields in one of your MonoBehaviours that is related to items. So my approach to that is, keep the data with ScriptableObjects, create only single Prefab, then tie the related components to it and the logic MonoBehaviour which will reference the certain data.

To begin with, I want to talk about how I designed my ScriptableObjects (in other words, data structures). There is the base (abstract) class called `ItemData` which contains common stuff like every item will have, for example, HUD icon. Then, there are two more abstract classes which are called `PassiveItemData` & `ActiveItemData` and derived from `ItemData`.

```
public enum ActiveItemType {
    Active,
    Firearm,
    Melee
}

public abstract class ActiveItemData : ItemData {
    public Sprite wieldingSprite;

    public ActiveItemType type;
    public int menuPosition;

    public SupplyData resourceType;
}

public abstract class PassiveItemData : ItemData {

}

```

`PassiveItemData` does not have any fields at the moment, but might do in the future. For now, the only class that derives from it is this:

```
public class SupplyData : PassiveItemData {
    [Tooltip("The maximum amount that the player can carry this type of resource at once.")]
    public int max;
}

```

`SupplyData` is the data of consumable items (e.g. ammo) which have no use on their own but can be consumed by other "active" items. Active items are the items that have actual functionalities (e.g. firearm, melee weapon) and can be directly used by the players and switched to via inventory. And a typical active item would also consume a supply. In games like Half-Life, there is no such thing called "active items", whatever that is can be switched to and directly used, they are called weapons in there. The reason that I named mine version as active items is that because, in my game, there won't be only weapons that can be directly used but also items like Medical Syringe (which consumes syringes) for healing purposes. My problem is I don't know where should I put the methods that perform the tasks like fire, use, swing, etc... Because they are not very generic and may belong to the only specific type of items, which is kinda tricky to implement.

My point was to put them inside a MonoBehaviour that will be tied to the Prefab. However, it is not possible to implement it with a single MonoBehaviour since the data would reference either a firearm or melee weapon data. Say, it is a melee weapon, it'd be non-sense to keep a field like `ammoInMagazine` that is related to only firearms within the script. But you can never know for sure if the reference data will be firearm or melee weapon. So you have to keep it in there whatsoever. Yet, I don't want this to happen. So I used several more classes that are going to keep the data and perform the tasks accordingly that derives from MonoBehaviour. And the issue has now come to how am I going to use these MonoBehaviours? Create prefabs for each MonoBehaviour? Like `Firearm.cs` MonoBehaviour to Firearm Prefab and `MeleeWeapon.cs` MonoBehaviour to Melee Weapon Prefab? Oh, my God. Does this mean I'd have to deal with this each time I implement a new item type? No way I do that. Or maybe I do, but not sure if this is the right approach.

I also thought of doing all these without creating MonoBehaviours and Prefabs that they are going to be tied. But in this case, there are going to be other situations where you might not be able to configure the "fire point", for example.

So, people, this might be a little longer than you expected but I still don't even think I included all the details. Nevertheless, I believe you have the big picture and can suggest a thing or two. Thanks in advance.

# Answer
> 0 votes
It sounds to me like your items have enough individual variation that trying to support them off a single prefab and a rigid inheritance hierarchy of ScriptableObject types is likely to be a headache.

For cases like this, where you have many item varieties that have their own particular needs, I think prefabs are actually a great way to go. While you say:

> This can be of course made with Prefabs but the thing is, you would de unconsciously duplicating common components that an item would use and only change some of the fields in one of your MonoBehaviours that is related to items

This data duplication is actually very cheap. Even over hundreds of items you're probably looking at only a matter of KiB. I'd argue that's a reasonable price to pay for the flexibility we gain.

Using a prefab for each item lets us use composition over inheritance. Special behaviours like ammunition get offloaded to a component that an item can "*have*" rather than getting baked into what type of item it "*is*", and that lets use mix and match them and create interesting variants of items just by combining components, without re-coding our inheritance hierarchy every time we want to add a new combination of behaviours.

For instance, you might make a core `Item` component that all your inventory interaction and item use gameplay scripts interact with. It does very little on its own - it just has slots to call into other components to customize its action:

```
public class Item : MonoBehaviour {

    public class TargetedEvent : UnityEvent<GameObject> {}

    [SerializeField]
    ItemSlot _slot;
    public ItemSlot slot { get { return _slot;} }

    [SerializeField]
    UnityEvent _onUse;

    [SerializeField]
    TargetedEvent _onUseOnTarget;

    [SerializeField]
    IUseRestriction[] _restrictions;

    public bool CanUse() {
        if(_onUse == null) return false;

        foreach(var restriction in _restrictions)
            if(restriction.CanUse() == false) return false;

        return true;
    }

    public bool CanUseOn(GameObject target) {
        if(_onUseOnTarget == null) return false;

        foreach(var restriction in _restrictions)
            if(restriction.CanUseOn(target) == false) return false;

        return true;
    }

    public bool TryUse() {
        if(CanUse() == false)
            return false;

        _onUse.Invoke();

        foreach(var restriction in _restrictions) {
            restriction.OnUse();
        }
        return true;
    }

    public bool TryUseOn(GameObject target) {
        if(CanUseOn(target) == false)
            return false;

        _onUseOnTarget.Invoke(target);

        foreach(var restriction in _restrictions) {
            restriction.OnUse();
        }
        return true;
    }
}

```

Using a UnityEvent means you can wire up any function you want as the action to perform when an item is used, so you can run wild with different item effects without modifying the core access point for interacting with items.

We've also abstracted any rule that might affect when we're allowed to use this item, making them just one or more components that we can attach to the item as needed, or even stack up in different combinations:

```
public interface IUseRestriction {
    bool CanUse();
    bool CanUseOn(GameObject target);

    void OnUse();
}

```

Your ammunition is then just one kind of `IUseRestriction` component that might be attached to an object.

```
public class Ammunition : MonoBehaviour, IUseRestriction {

    [SerializeField]
    int _currentAmmo;

    [SerializeField]
    int _maxAmmo;

    public bool CanUse() { return _currentAmmo > 0; }
    public bool CanUseOn(GameObject target) { return CanUse(); }

    public void OnUse() { _currentAmmo--; }

    public int Reload(int availableAmmo) {
        int amountLoaded = _maxAmmo - _currentAmmo;
        amountLoaded = Mathf.Max(amountLoaded, availableAmmo);

        _currentAmmo += amountLoaded;
        return amountLoaded;
    }
}

```

(If you have a centralized ammo inventory on your character rather than in the item itself, you can modify this to query the character's ammo inventory instead)

Other restrictions might include `Cooldown` or `SuperMeter` or `EffectiveRange` tests, friendly/enemy `UsableOnFaction` masks, even a `Consumable` restriction that self-destructs the item after use. ;)

Similarly, your concept of an "Active" item can be just another component:

```
public class Equipable : MonoBehaviour {
    public EquipmentSlot slot;
    public Sprite equippedSprite;
}

```

Now your code can test if something is equipable just by checking:

```
var equipable = item.GetComponent<Equipable>();
if(equipable != null) {
    // Offer/execute option to equip this item,
    // using the data in the equipable instance.
}

```

You can do similarly for `Sellable` items that need a price/value, `Throwable` items that need to draw a range-finder when used, etc.

This lets you mix and match different item effects, restrictions, etc. in any way you want, just by combining different components on the prefab, without a care for rigid inheritance hierarchies.

Maybe most of your potions are pure inventory items that can't be equipped except to a quick-use slot. But you have an acid potion that's allowed to be equipped as a weapon. No problem! You just add the `Equipable` component to that single prefab, and you don't have to create a whole new branch of the potion inheritance hierarchy that duplicates the equipable behaviour from the `ActiveItemData` type, or a branch of the `ActiveItemData` type that duplicates the stacking behaviour of the `PassiveItemData` type. New original gameplay combinations with zero code changes.

If you find you have a lot of components that need to reference the same information, and the duplication bothers you, you can still parcel up just that information to a shared ScriptableObject that they all reference, without losing the flexibility of individual prefabs. Say for instance you have 20 different varieties of potion, where you're allowed to carry a stack of 20 of each, and 12 different varieties of food, where you're allowed to carry a stack of 50 of each, and 5 varieties of gemstone, where you're allowed to carry a stack of 99 of each. Each `Stackable` component on these prefabs can expose a `StackType` enum, from which you select `Potion`, `Food`, or `Gem`, and you can have a separate `InventoryCapacity` `ScriptableObject` that contains a map from `StackType` to the max item count.

---
Tags: unity, c#, architecture, data-structure
---


# Question
Title: How do mobile games implement time gates unhackably? Is it possible in offline games?
I'm thinking about porting my game to **Google Play**, and it would be free to play with **time gates** which are skippable if you **watch an ad**.

What are the ways of implementing an **unhackable time gating?**

* Is it possible **without internet connection**? If yes, how?
* If no, is there a way to implement it **without custom backend, using Google Play's services**?

Or should **I care about this at all?** Because...

* It **doesn't affect other players**...
* Most of the audience **couldn't do it** anyway, and if the game stays small, hacks couldn't really spread.
* Then maybe I should just let them hack those time gates, it's a **marginal revenue loss**.

What do you think?

# Answer
> 2 votes
We don’t worry about unhackability in our games. It’s not worth it. We just worry about making sure it works in the simpler, more frequent cases of the user changing their device clock, restarting their device, etc. As long as you don’t worry about people decompiling your code, it gets really simple.

You can put in checks to make sure your app isn’t a hacked version, and if it is, behave differently. We had experimented with that in the past, but ended up removing it since it didn’t really help or hurt much. Those checks only work if the hacker doesn’t find them as well, so they would need to be subtle if you want to avoid the hacker finding a workaround.

All that said, we have never seen hackers with a lot of intelligence hack our games. Generally it’s just people who don’t even play the game see that there is a new game that has virtual currency in it, swoop in and change the code to report an infinite balance, and release it with minimal/no testing. Half the time it doesn’t even work. Presumably we are not a big enough target. You probably won’t be either.

How to handle timing locally:

On launch, fetch and store (in a file) the current value of a non-modifiable clock (NMC), eg. CLOCK\_MONOTONIC in native C, or SystemClock.elapsedRealtime() in Java. You will also need to track a known elapsed time (KET), starting at zero. Or, if you happen to have a known accurate time (eg. from a server) then you can use that value.

At any point, you can be certain that the KET is no less than the stored KET plus the current value of the NMC minus the stored NMC (assuming the device itself is not running its clock quickly, which I have never seen).

The source for the NMC value is generally a time since the device booted, meaning that if the user resets their device, that value also resets. You can therefore not be certain at any point that you have the actual KET, unless you are also tracking the time from a server, but you can be sure it isn’t past that, which is sufficient for time-gating.

On app close, store the current value of the NMC and the current KET (equal to the KET on launch plus the current NMC minus the stored NMC). Then check on launch if the current NMC is less than the stored NMC. If it is, then you know the KET is at *least* the stored KET plus the current value of the NMC (the user loses the amount of time between last app close and device reboot). Otherwise (the current value of the NMC is greater than the last stored NMC), the only thing you know is that the KET is the current value of the NMC, minus the stored NMC, plus the stored KET. This is the normal case when the user does not reboot their device, and will guarantee an accurate elapsed time tracker.

Normally, the KET is only advanced by the difference in values of stored NMC and current NMC. If you bring a server into the mix, the KET can also be advanced by differences in server time so that the user can restart their device and have their KET stay up to date (not losing time between last app close and device reboot). To do this, you can store KETs based on the NMC and the server. On launch, if you don’t have server access, use the NMC-based KET. If you do have server access, use the server-based KET and update the NMC-based KET at the same time.

---
Tags: unity, android, hacks
---


title: Handling Unity Animations In C# Script

text:
# Question
Title: Handling Unity Animations In C# Script
So, I'm fairly new to coding with unity and c#, and I want to change my animations based on the player's mouse position. This is my script so far:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
    public float moveSpeed = 2f;
    private bool right = true;
    private bool left = false;
    private bool up = false;
    private bool down = true;
    public Animation rightUpAnim;
    public Animation leftUpAnim;
    public Animation rightDownAnim;
    public Animation leftDownAnim;
    public string horizontalAxis;
    public string verticalAxis;
    private Vector2 movement = Vector2.zero;
    private Rigidbody2D rb;
    public Transform tf;
    public Animator an;

    private void Start() {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update() {
        movement.x = Input.GetAxisRaw(horizontalAxis);
        movement.y = Input.GetAxisRaw(verticalAxis);
    }
    private void FixedUpdate() {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.deltaTime);
        var mousePos = Input.mousePosition;
        mousePos.x -= Screen.width / 2;
        mousePos.y -= Screen.height / 2;
        if (mousePos.y > tf.position.y) {
            up = true;
            down = false;
        }
        else if (mousePos.y < tf.position.y) {
            down = true;
            up = false;
        }

        if (mousePos.x > tf.position.x) {
            right = true;
            left = false;
        }
        else if (mousePos.x < tf.position.x) {
            left = true;
            right = false;
        }

        if (left && up) {
            an.controller = leftUpAnim;
        }
        else if (right && up) {
            an.controller = rightUpAnim;
        }
        else if (left && down) {
            an.controller = leftDownAnim;
        }
        else if (right && down) {
            an.controller = rightDownAnim;
        }
    }
}

```

However, I get an error saying that 'Animator' does not contain a definition for 'controller'. What is the correct way to do this?

# Answer
The error is saying, the Animator component has no .controller member, which is correct when you visit https://docs.unity3d.com/ScriptReference/Animator.html.

It looks to me as though you are trying to play some animations directly rather than through the **Animator** which is a state machine.

To play back clips that you have referenced in the script you would need to use the **Animation** (not Animator) component

Add a Animation component to the Gameobject on which your script is already attached.

A very stripped down example for playing an animation clip like you have currently.

```
public class AnimationClipExample : MonoBehaviour
{
    private Animation an;
    //be sure to assign your clip in the inspector
    public AnimationClip myAnimationClip;

    // Start is called before the first frame update
    void Start()
    {
        //You will either need to get a reference to this objects Animation Component via code or assigning it in the inspector, here I as you may guess I'm getting the reference through code.
        an = GetComponent<Animation>();
    }

    // Update is called once per frame
    void Update()
    {
        //if A is pressed down
        if (Input.GetKeyDown(KeyCode.A))
        {
            //set the animation clip
            an.clip = myAnimationClip;
            //play the clip
            an.Play();
        }
    }
}

```

I would hugely recommend looking over the Animator component and the Unity tutorials, as it allows you to free up the mess of If-else conditionals and being visual its much easier to understand whats going on.

https://www.youtube.com/watch?v=JeZkctmoBPw \- Unity Animator Controller tutorial.
> 1 votes

---
Tags: unity, c#, animation
---


title: State Machine implementation issues

text:
# Question
Title: State Machine implementation issues
I have been working on a project for a while now, and i'm reaching the point where my character controller is starting to do more than just move/jump/crouch so I split the interaction stuff off into its own State machine, there are only two states so far for the interaction FSM but I am having problems with input firing in both states.

For example:

Target Object \> Press E to fire Interaction \> Is Carryable Type \> Pick up \> Move Around \> Press E to fire release carry \> Item is dropped \> Frame Passes \> I shoot straight through the first default state (idle) back to Player\_Interaction\_Carry resulting in the object being picked back up before it can even hit the floor.

I understand what the issue is, as I am holding a Object, pressing E to release the object works, but then next frame I pass straight through Interaction\_idle (E is still down because its a fractions of a second) again to Interaction\_Carry.

**I thought a state machine would help me fix such problems in that the input would be 'per state'? have I implemented the states or state machine incorrectly? Perhaps I need an event input queue?**

Any help appreciated, I have included my statemachine component, and the two interaction states.

Apologies if there is a lot to read, I also couldnt manage to split the scripts into seperate code blocks for easier reading.

Thank you

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class EntityStateMachine_Comp : MonoBehaviour
{
    public BaseState currentState;
    private BaseState lastState;
    private PlayerController _playerController;

    private void Start()
    {
        _playerController = GetComponent<PlayerController>();
    }

    public void Update()
    {
        if (currentState != null)
        {
            currentState.OnUpdate();
        }

    }

    public void ChangeToState(BaseState nextState)
    {
        if (currentState != null)
        {
            currentState.OnExit();
        }

        Debug.Log("change to state called");
        Debug.Log(nextState.ToString());
        lastState = currentState;

        currentState = nextState;
        currentState.OnEnter();
    }

    public BaseState GetLastState()
    {
        if (lastState != null)
        {
            return lastState;
        }

        return null;
    }
}

public class Player_Interaction_Idle_State : BaseState
{

    public GameObject carryTarget;
    public IInteractable interactable;

    private PlayerInteractable_Raycaster_Comp _playerRaycaster;

    public Player_Interaction_Idle_State(PlayerController playerController, EntityStateMachine_Comp entityStateMachineComponent) : base(playerController, entityStateMachineComponent)
    {
    }

    public override void OnEnter()
    {
        _playerRaycaster = _playerController.interactableRaycast;
        _playerRaycaster.OnInteractable.AddListener(InteractWithWidget);
    }

    public override void OnExit()
    {

    }

    public void InteractWithWidget(IInteractable interactable)
    {
        InteractableType interactableType = interactable.InteractionType;

        if (Input.GetKeyDown(KeyCode.E))
        {
            switch (interactableType)
            {
                case InteractableType.USE:
                    interactable.OnInteract();
                    break;

                case InteractableType.CARRY:
                    _playerController.carryTarget = interactable.Transform.gameObject;
                    _playerController.isCarrying = true;
                    _stateMachineController.ChangeToState(new Player_Interaction_Carry_State(_playerController, _stateMachineController));
                    break;

                case InteractableType.LOOT:
                    _playerController.playerInventory.AddItem(interactable.Item, 1);

                    RemoveWidgetFromWorld(interactable);
                    break;
            }
        }
    }

    public void RemoveWidgetFromWorld(IInteractable interactable)
    {
        GameObject.Destroy(interactable.gameObject);
        //make sure to reset targets on raycaster
        _playerController.interactableRaycast.Reset();
    }

    public override void OnUpdate()
    {

    }

}

public class Player_Interaction_Carry_State : BaseState
{

    private AttachmentPoint attachTarget;

    private GameObject _carryTarget;
    private ICarryable _carryTargetCarryable;

    public Player_Interaction_Carry_State(PlayerController playerController, EntityStateMachine_Comp entityStateMachineComponent) : base(playerController, entityStateMachineComponent)
    {
    }

    public override void OnEnter()
    {
        _carryTarget = _playerController.carryTarget;
        _carryTargetCarryable = _carryTarget.GetComponent<ICarryable>();
        CanCarry(_carryTargetCarryable);
        Debug.Log("On enter interaction carry");
    }

    public override void OnExit()
    {

    }

    public void CanCarry(ICarryable carryable)
    {
        attachTarget = _playerController.attachComp.GetNextUnoccupiedHand(carryable.CarryType);

        if (attachTarget != null)
        {
            _playerController.isCarrying = true;
        }
    }

    public override void OnUpdate()
    {
        if (Input.GetKeyDown(KeyCode.E) && _playerController.isCarrying)
        {
            //release?
            Debug.Log("E Down Called, Player is carrying and currentinteractable target is same as carry target");
            _playerController.isCarrying = false;
            //interactable.Transform.parent = null;
            Debug.Log("Release object");
            _carryTargetCarryable.OnDropped();
            attachTarget.Detach(_carryTarget.transform);

            attachTarget = null;
            _playerController.carryTarget = null;

            _stateMachineController.ChangeToState(new Player_Interaction_Idle_State(_playerController, _stateMachineController));
        }
        else if (_playerController.isCarrying)
        {
            if (_playerController.carryTarget != null && attachTarget != null)
            {
                _carryTargetCarryable.OnCarried();
                attachTarget.Attach(_carryTarget.transform);
            }
        }
    }

}

```

Player Interactable RayCaster

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

[System.Serializable]
public class PlayerInteractable_Raycaster_Comp : PlayerComponent
{
    [Range(0, 100f)]
    public float raycastRange = 100f;

    private PlayerController _controller;
    private PlayerCamera _playerCamera;

    public IInteractable interactableCurrentTarget;
    public IInteractable CurrentInteractable => interactableCurrentTarget;

    public IInteractable lastInteractableTarget;
    public IInteractable LastInteractable => lastInteractableTarget;

    public InteractableEvent OnInteractable;

    // Start is called before the first frame update
    public override void Start()
    {

        _controller = transform.GetComponent<PlayerController>();
        base.Start();
    }

    // Update is called once per frame
    void Update()
    {
        CheckForInteractables();
    }

    public void Reset()
    {
        interactableCurrentTarget = null;
        lastInteractableTarget = null;
    }

    void CheckForInteractables()
    {
        //Create a ray in the world using the middle of the viewport as the start point
        Vector3 rayOrigin = _controller.PlayerCamera.cameraComp.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));

        int allLayersButPlayer = ~LayerMask.GetMask("Player");

        if (Physics.Raycast(rayOrigin, _controller.PlayerCamera.cameraComp.transform.forward, out RaycastHit hitInfo, raycastRange, allLayersButPlayer))
        {
            interactableCurrentTarget = hitInfo.collider.gameObject.GetComponent<IInteractable>();
            float distanceFromInteractable = Vector3.Distance(transform.position, hitInfo.collider.transform.position);

            //Check the hitwidget interface exists
            if (interactableCurrentTarget != null)
            {
                interactableCurrentTarget.OnTargetted();
                //if the last interactable is not equal to the current one, that means this is a new one
                if (interactableCurrentTarget != lastInteractableTarget)
                {
                    if (lastInteractableTarget != null && lastInteractableTarget.Transform.gameObject != null)
                    {
                        lastInteractableTarget.OnTargetDropped();
                    }
                    //set this new widget as the last used
                    lastInteractableTarget = interactableCurrentTarget;
                }
                //else if it is the same widget as last time
                else if (interactableCurrentTarget == lastInteractableTarget)
                {
                    //do nothing for now
                }

                //If the distance between the player and interactable is less than the widgets interaction distance
                if (distanceFromInteractable < interactableCurrentTarget.InteractionDistance)
                {
                      OnInteractable.Invoke(interactableCurrentTarget);
                }

            }
            //Else If ray hits nothing
            else
            {
                ////Check the last interactable isnt null
                if (lastInteractableTarget != null)
                {
                    if (lastInteractableTarget.gameObject != null)
                    {

                        //if it isnt call on target dropped
                        lastInteractableTarget.OnTargetDropped();
                        lastInteractableTarget = null;
                    }
                }
            }

        }

    }
}

```

# Answer
Here's a theory on what's happening, all in a single frame:

* The player presses "E" - `Input.GetKeyDown(KeyCode.E)` will return true for this frame.
* Your state machine update runs, and calls `Player_Interaction_Carry_State.OnUpdate()`
* The carry state checks to see if E was pressed this frame. It was, so it drops the item and triggers the change to the idle state.
* The state machine calls `Player_Interaction_Idle_State.OnEnter()`, which subscribes itself to the raycaster's `OnInteractable` event.
* The state machine update finishes, and passes control to the next script that needs updating.
* The raycaster's update runs, and detects there's an interactable object in front of the player, so it invokes the `OnInteractable` event. This calls `Player_Interaction_Idle_State.InteractWithWidget()`
* `Player_Interaction_Idle_State.InteractWithWidget()` checks whether E was pressed this frame - and it was, *because it's still the same frame!* So it picks up the item, triggering the state change back.

Because you check for button presses in two different places that can be called at different times, you have created an opportunity to double-handle input in a single frame.

It looks like you'll want to centralize the way you provide inputs to your states.

One possibility would be to do all your input checking in the state machine update - then you can standardize how input is checked for all states, and guarantee it's handled only once, because you have a single flow of input into the state.

An example might look like this:

```
public struct StateMachineInput {
    public bool interactButtonDown;
    public IInteractable interactionTarget;
    public bool interactionTargetChanged;
    //... etc.
}

StateMachineInput inputState;

// State Machine Update:
public void Update()
{

    var currentTarget = raycaster.CheckForInteractable();

    inputState.interactButtonDown = Input.GetKeyDown(KeyCode.E);
    inputState.interactionTargetChanged = currentTarget != inputState.interactionTarget;
    inputState.interactionTarget = currentTarget;

    if (currentState != null)
    {
        currentState.OnUpdate(inputState);
    }
}

```

We forbid any state from getting input each frame from any means other than the `inputState` struct provided to it in `OnUpdate` by the state machine. If the state does any work at all on the frames while it's active, it's in `OnUpdate`

Since we call `OnUpdate()` on exactly one state per frame, we're guaranteed that we don't double-handle a single frame's input in two different states.
> 1 votes

---
Tags: unity, fsm, character-controller
---


# Question
Title: Unity & inheritance. Different results DebugMode/Build
Here are my 2 Classes

```
public class Item : MonoBehaviour
{
    [SerializeField] protected TextMeshProUGUI txt_itemNom;
    [SerializeField] protected string itemNom;

 //No Start
 //No Update
}

public class Article : Item
{
    public int articleLevel = 1;

    public void Start()
    {
        txt_itemNom.SetText(itemNom);
    }

//Called by a button OnClick
    public void OpenBuyWindow()
    {
            PlayerRessources.instance.OpenBuyWindow(base.txt_itemNom.text + " Lvl " + articleLevel);
    }
}

```

It is very simple. When I start the game, the GameObject with the Article script set the correct item name in the TextMeshProUGUI object named txt\_itemNom. The player can click a button to buy this item, it will displays a confirmation window. And it works perfectly! Or at least, it works when I press Play in the editor but weirldy it behaves differently in the build version.

In the build version, the value of `base.txt_itemNom.text` in

```
PlayerRessources.instance.OpenBuyWindow(base.txt_itemNom.text + " Lvl " + articleLevel);

```

is the original value of `base.txt_itemNom.text`. (which is "Item name" or something). So I don't get it because `base.txt_itemNom.text` is correctly setted in the `Start` because it's displayed in the UI.

It looks like the Article loses its parent class (Item) reference when the player click to OpenBuyWindow(). But only for the TextMeshProUGUI contained in the Item class.

Additionnal info:

* The `Article` script is attached to a prefab.
* The prefab is not instantiated by a script. I just added it in the Hierarchy
* If I use the string variable `itemNom` instead of `base.txt_itemNom.text`, then it will work.

# Answer
It doesn't look like this has anything to do with inheritance.

Rather, it seems to be a quirk with the `TextMeshProUGUI` component.

Its `text` getter doesn't seem to be updated in builds - so it keeps a cache of whatever default value it had populated in the inspector at edit time. (This might be a bug to report to Unity - even if this is by design for runtime efficiency, it should at least issue a warning so the behaviour doesn't catch developers by surprise!)

You can work around this by asking for `txt_itemNom.GetParsedText()`, which works correctly in build.

Just note that if you've recently set the text (ie. in the same frame, that hasn't had a chance to finish rendering yet), you'll need to call `txt_itemNom.ForceMeshUpdate()` first, to make sure the text parsing has run on the latest value you set.

Or, since you still have the value you set locally, you cam just use your `itemNom` string variable directly, without trying to extract the text you set out of the text component itself.
> 0 votes

---
Tags: unity, inheritance
---


title: How to reset RectTransform's position?

text:
# Question
Title: How to reset RectTransform's position?
So, I am trying to make a simple GUI Instantiate system. The GUI is going to spawn successfully, but the position is wrong.

```
Position : (Left, Right: 249.8423 ; Top, Bottom : 400)
Anchors : (Min: X:0 Y:0 ; Max: X:1 Y:1)
Pivots : (X:0.5 Y:0.5)
Rotation : (X:0 Y:0 Z:0)
Scale : (X:1 Y:1 Z:1) always...

```

My Code :

```
    GUIPausePopup pause = UI.Create<GUIPausePopup>(GameObject.Find("Canvas"));
    //Spawn and set parent(Canvas)
    pause.GetComponent<Transform>().gameObject.SetActive(true);
    //Working without any issues.

    //Position system not work. I don't know why.
    pause.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(0f, 0f, 0f);
    pause.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, 0f);
    pause.GetComponent<RectTransform>().localPosition = new Vector3(0f, 0f, 0f);
    pause.GetComponent<RectTransform>().position = new Vector3(0f, 0f, 0f);
    pause.transform.position = new Vector3(0f, 0f, 0f);
    pause.transform.localPosition = new Vector3(0f, 0f, 0f);

```

Thanks for help...

# Answer
4 years later but I bring an answer that solved it for me.

This is using a World Space Canvas and I was trying to instantiate a prefab (menu)

```
menu.GetComponent<RectTransform>().anchoredPosition3D = this.GetComponent<RectTransform>().anchoredPosition3D;

```

"this" being the parent

I think what was messing it up for me was that since I'd been at this for a while I tried the same thing you did: after calling this I had other things trying to reset it's position and those were the ones causing issues! Just do anchoredPosition3D and nothing else and it should work - if your situation was like mine.

**EDIT**: As @DMGregory explains in the comments the correct way would be:

```
((RectTransform)(menu.transform))anchoredPosition3D
   = ((RectTransform)transform).anchoredPosition3D;

```

But one year ago the code that I included here worked for me.
> 1 votes

---
Tags: unity, gui
---


title: Having trouble defining a FindMyTag

text:
# Question
Title: Having trouble defining a FindMyTag
I'm not a coder, im an artist, so this stuff doesn't make a ton of sense to me. I know enough to know I don't know enough, and i'm old enough to know my brain doesn't 'get' code... that said for context of what level of help I need :) ...

I'm trying to get an AI path based on an object tag. When I instantiate the object this script is on, it should look for 'mytag' on another object in the scene, and set that as 'target'

```
    public class pickAItarget : VersionedMonoBehaviour
    {
        /// <summary>The object that the AI should move to</summary>
        private Transform target;
        public string mytag;
        IAstarAI ai;

        void Start()
        {
            Debug.Log(GameObject.FindWithTag("mytag"));
            GetComponent<pickAItarget>().target = GameObject.FindWithTag("mytag").transform;
        }

```

The script compiles fine and im able to put in the tag I want to find in the inspector but when the object instantiates I get

```
UnityEngine.GameObject.FindWithTag (System.String tag) (at C:/buildslave/unity/build/Runtime/Export/Scripting/GameObject.bindings.cs:195)
Pathfinding.pickAItarget.Start () (at Assets/Scripts/pickAItarget.cs:26)

```

I feel like I HAVE defined mytag, but obviously I don't understand something.

# Answer
> 1 votes
When you put some text in double quotation marks, like:

```
 "Application.Quit()"

```

What you're saying to the compiler is: "this is literally just text. Please just treat it as a string of characters, and don't try to parse it as code instructions or the name of a variable".

So instead of quitting the game, the example above just gives us a `string` containing literally those characters - what we call a string literal.

By that logic,

```
GameObject.FindWithTag("mytag")

```

This code says 'Find a game object with the tag "mytag" ' - not the contents of the variable *named* `mytag`, but look for a game object whose tag is literally m-y-t-a-g.

If you want to refer to the *variable named* `mytag`, which might contain some other text entirely, like "Player", then just delete the double quotation marks around it and leave it plain, like the other code instructions.

```
GameObject.FindWithTag(mytag)

```

This says "Find a game object whose tag matches *the text stored in the variable* `mytag`"

# Answer
> 0 votes
* You don't need to use `GetComponent<pickAItarget>()` from `pickAItarget`, as you don't need to refer yourself from yourself.
* If there are multiple tags with the same name in your hierarchy, then it will find the first object only. So if there are multiple objects with same tag then you should try `GameObject.FindGameObjectsWithTag(mytag)`, this will return array of all objects with same tag i.e.

```
public static GameObject[] FindGameObjectsWithTag(string tag);

```

If this answer is not what you are looking for, please tell us:

* Is this script is added on the gameobject that you are instantiating?
* Does the instantiated object contain the "mytag" tag?

---
Tags: unity, c#
---


title: Sensor quaternion to Unity conversion

text:
# Question
Title: Sensor quaternion to Unity conversion
I want to convert rotations given as quaternion from sensors to Unity. The sensors (documentation here) axis are the following ones:

Unity is the following one:

I don't know how to map axis other than Z is up for the axis. Note that I don't really mind if I have a global rotation offset. I just want the sensors (they are multiple ones) relative orientation to be the same in Unity that in real life

Given this other answer I think the following code should to the transformation:

```
Quaternion ConvertToUnity(Quaternion input) {
    return new Quaternion(
        -input.y,
        -input.z,
        -input.x,
        input.w
    );
}

```

Is that correct?

# Answer
Summarizing the diagram:

```
Attribute      Unity Coordinates     Sensor Coordinates
-------------------------------------------------------
Right                 +X                   -Y
Up                    +Y                   +Z
Forward               +Z                   +X
Handedness        Left Handed          Right Handed

```

So to convert to Unity...

* Unity's x axis should use the sensor's y axis, negated
* Unity's y axis should use the sensor's z axis
* Unity's z axis should use the sensor's x axis
* ...and since we're changing handedness, we need to negate the angle, which means negating all imaginary components of the quaternion and leaving the real part w unchanged.

So you were close, you just missed the double-flip of the sign on the first argument:

```
Quaternion ConvertToUnity(Quaternion sensorQuaternion) {
    return new Quaternion(
         sensorQuaternion.y, // -1 * (   Right = -Left    )
        -sensorQuaternion.z, // -1 * (      Up =  Up      )
        -sensorQuaternion.x, // -1 * ( Forward =  Forward )
         sensorQuaternion.w
    );
}

```
> 0 votes

---
Tags: unity, quaternion
---


# Question
Title: C# Divide points based on players damage
How can i divide points based on highest damage? For e.g i have monster which drop 50 experience points and 4 different players has dealt damage to this monster. But i will like to split the experience points based on the players damage.

So far i got this:

```
private Dictionary<Player, int> damageMap = new Dictionary<Player, int>();

public void TakeDamage(Player attacker, int damage)
{
    damageMap.Add(attacker, damage);
}

private void OnDeath()
{
    foreach (KeyValuePair<Player, int> entry in damageMap)
    {
        Player player = entry.Key;
        int damage = entry.Value;

        player.addExperience(50);
    }
}

```

# Answer
> 2 votes
If you have experience as a float

```
float totalExperience = 50.0f;
foreach (KeyValuePair<Player, int> entry in damageMap)
{
    Player player = entry.Key;
    int damage = entry.Value;

    float playerDamageFraction = (float)damage/(float)totalMonsterHealth;

    player.addExperience(totalExperience * playerDamageFraction);
}

```

Should work

If your experience is an int then do the same thing but round to an int at the last step

```
player.addExperience(Mathf.RoundToInt(totalExperience * playerDamageFraction));

```

---

This is beyond the scope of your question but I noticed that you may find you have a problem with your `TakeDamage()` function

```
public void TakeDamage(Player attacker, int damage)
{
    damageMap.Add(attacker, damage);
}

```

Probably needs to be

```
public void TakeDamage(Player attacker, int damage)
{
    if (dict.ContainsKey(player)){
        damageMap[player] += damage;
    } else{
        damageMap.Add(attacker, damage);
    }
}

```

To get the behavior you want

---
Tags: unity, c#
---


# Question
Title: How do I design my RPG-like class system in a more modular way?
I'm building a mod for Terraria that will add classes and their corresponding abilities to the game. You're a warrior? Push your ability key and you'll use your berserk ability.

I'm trying to make my player code as simple as possible. I'd like to set the player's in-game "class" by doing something like this at the top of the player class so the rest of the methods in it can access it later:

```
//Set class
WarriorClass playerClass == new WarriorClass(playerReference, level)

```

Herein lies the first issue. I get an error at playerReference that says:

```
Error   CS0236  A field initializer cannot reference the non-static field, method, or property 'ModPlayer.playerReference'  MyMod

```

Ok, so I looked that up and set the initialization in the WarriorClass instead:

```
public Player playerReference = new Player();

```

And I have this now in my player code:

```
//Set class
     WarriorClass playerClass = new WarriorClass(level);

```

Here's the beauty of it. In the gamepad input method within my player code all I ever have to do is:

```
    //On key presses
    public override void ProcessTriggers(TriggersSet triggersSet)
    {
        if (MyMod.ability1Key.JustPressed)
        {
             playerClass.UseAbility(MyMod.ability1Key);
        }

```

Now that the ability1 key was pressed, let the WarriorClass handle what to do:

```
    public void UseAbility(ModHotKey key)
    {
            //Ability 1
            if (key.JustPressed == MyMod.ability1Key)
            {
                //Start berserking
                if (player.HasBuff(ModContent.BuffType<BerserkBuff>()) == false )
                {
                    //Lose 10% of your life
                    lifeLost = player.statLifeMax2 / 10;
                    player.statLife = player.statLife - (int)lifeLost;

                    //Berserk and add damage over in the Buff code
                    player.AddBuff(ModContent.BuffType<BerserkBuff>(), 600, false);
                }

```

This is all great!!! I can add any amount of classes I want and this player code never changes. *Except If I want to add if/then logic to select a class in say, Update() then it breaks the following reference in my gamepad input code:*

```
playerClass.UseAbility(MyMod.ability1Key);

```

Of course it won't have a reference unless I hard code it at the top of the player file, *but I don't know what class a player will be until they pick one*.

Am I doing this fundamentally in a bad way or am I missing something else in terms of OO programming? I don't want to have to initialize every class for the character at the top of the file like this:

```
WarriorClass warriorClass = new WarriorClass(level);
ArcherClass archerClass = new ArcherClass(level);
...

```

... just to do this in the gamepad input method:

```
if (classChoice == "Warrior")
{
     warriorClass.UseAbility(MyMod.ability1Key);
}
else if (classChoice == "Archer")
{
     archerClass.UseAbility(MyMod.ability1Key);
}

```

# Answer
> 1 votes
What you want is baseclass inheritance or an interface.
If the UseAbility method is same or similar among "Classes", you probably want a baseclass otherwise an interface. Lets take the interface route for now.

The interface (lets call it `PlayerClass`) defines the `UseAbility` method.

```
interface PlayerClass {
    void UseAbility(yourKeyType key);
}

```

All your playerclasses (WarriorClass, ArcherClass) implement this interface.

```
class WarriorClass : PlayerClass {
    void UseAbility(yourKeyType key) {
        // implement ability usage
    }
}

```

Then in your code above you use `PlayerClass playerClass;` and assign it to whatever the player picks *at the time the player picks it* not when the player uses the ability: `playerClass = new WarriorClass(level);` after that, when the player uses the ability you can do

```
playerClass.UseAbility(MyMod.ability1Key);

```

and don't care about which exact class he picked in the beginning.

It works almost identical when using inheritance, you can move the UseAbility code in the baseclass to reduce duplication. This should be done if your player classes have common code.

# Answer
> 0 votes
Ok, this is how I solved this ultimately. I found three distinct things I wanted to define by classes:

1. The player (already done by default)
2. The player's class (warrior, rogue, etc)
3. The abilities used by classes (berserk, stealth, etc)

This is how I did it, starting with #1 The Player:

```
        PlayerClass playerClass;
        public static ModHotKey ability1 = new ModHotKey("F");
        ...

        Update()
        {
        ...
            else if (choice == "Warrior")
            {
                playerClass = new WarriorClass(player, 100);
            }
        ...
        }

        KeyTriggers(TriggersSet triggersSet)
        {
            if (ability1.JustPressed)
        {
            playerClass.UseAbility(ability1);
        }

    }

```

PlayerClass is a mostly empty class that guides what methods should be called when inherited. Example WarriorClass inheriting from PlayerClass:

```
public class WarriorClass : PlayerClass
{
    int level;
    Player player = new Player();
    //Ability placeholders
    public IAbility primaryAbility;
    public IPassive primaryPassive;

    //Constructor. Needs player reference and level to set skills and stats correctly (when progression is a thing)
    public WarriorClass(Player player,  int level)
    {
        this.player = player;
        this.level = level;
        //Set ability manually for now
        primaryAbility = new BerserkAbility();
        primaryPassive = new LifeRegenPassive();
    }

    public override void DoPassives()
    {
        primaryPassive.DoPassive(player);
    }

    public override void UseAbility(ModHotKey key)
    {
        if (key == MinionTest.ability1)
        {
            primaryAbility.UseAbility(player);
        }
    }
}

```

It doesn't seem like much now that I've finished the entire design, but it will hold WarriorSpecific things like its progression and possibly talent tree (or maybe those will be classes themselves!).

Next up, the abilities the classes use. Notice above that the warrior doesn't know what ability it is going to use in UseAbility() until the constructor is called. Here is some ability code:

```
    public class BerserkAbility : IAbility
{
    int lifeLost;

    public void UseAbility(Player player)
    {
        //If the buff is off completely... start the buff on stack one
        if (player.HasBuff(ModContent.BuffType<BerserkBuff1>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff2>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff3>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff4>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff5>()) == false)
        {
            //Lose 10% of your life
            lifeLost = player.statLifeMax2 / 10;
            player.statLife = player.statLife - (int)lifeLost;

            //Start first stack of berserk for 10 seconds
            player.AddBuff(ModContent.BuffType<BerserkBuff1>(), 600, false);
        }
        //If it's already at stack 1, start stack two...
        else if (player.HasBuff(ModContent.BuffType<BerserkBuff1>()))
        ...

```

Where UseAbility (maybe a poor choice due to not being unique project wide) is required due to the interface IAbility interface. If you are stuck on Buffs above, those are already a distinct object or class in the mod library. IAbility is just this:

```
namespace MinionTest.Abilities
{
    public interface IAbility
    {
        void UseAbility(Player player);
    }

    //Should add cooldown here later
}

```

Why did I user class inheritance for player classes and an interface for abilities? I'm not really sure and wanted to try both.

Essentially what I end up with is a player that hits a key and asks the warrior to do the correct ability, and the warrior asks the ability how to do it. This adds three main benefits I see right now:

1. Really nice, readable code and code architecture. You know exactly what file and class to edit to change a class or ability.
2. It allows for game design choices like choosing a new class on the fly in-game, and talent trees that may change up what abilities your class can use.
3. The possibility to be extended incredibly easily. People can work on an *ability* in and of itself. A person can work on a *class* in and of itself, and plug and play abilities to it.

---
Tags: c#, architecture, rpg
---


# Question
Title: How do I design my classes so that my Player.cs code can use class-specific abilities from another script?
Right now, I have a Player.cs class that handles button pushes, movement speed, damage, Update() etc. At the moment, all of the logic for button presses triggering an ability, and the logic surrounding that ability lives in my player.class. I'd like to take that logic and put it into an Abilities.cs class. All I want in my player at most would be:

```
public override void Update()
{
    if (button.pushed == "berserkKey")
    {
       ability.berserk();
    }
}

```

... where for example berserk is a stacking buff but none of that logic is in my player class anymore.

For additional context, I plan to implement a Classes.cs class which will hold the info on classes (warrior/archer/etc) which will know exactly what the class and therefor player can use. The code above will likely abstract out even more when that is the case.

The problem is that my Player class already inherits from another class. How do I go about designing my Classes and Abilities classes in a way that my player can use them in the example above?

I'm also open to a completely different way if my initial thought here isn't ideal.

# Answer
> 1 votes
I'd recommend you solve this with composition over inheritance.

Let's say we have an ability interface:

```
public interface IAbility {
    void UseAbility();
}

```

Now my berserk ability can be a MonoBehaviour component that implements this interface:

```
public class BerserkAbility : MonoBehaviour, IAbility {

    public float duration = 5f;
    public float damageModifier = 1.5f;
    public float defenseModifier = 2.0f;

    public void UseAbility() {
        // TODO: do some berserk stuff.
    }
}

```

Now your player control class can look something like this:

```
public class PlayerControl : MonoBehaviour {

    public IAbility primaryAbility;
    public IAbility secondaryAbility;

    void Update() {
        if (button.pushed == "primaryAbility" && primaryAbility != null) {
            primaryAbility.UseAbility();
        }

        if (button.pushed == "secondaryAbility" && secondaryAbility != null) {
            secondaryAbility.UseAbility();
        }
    }
}

```

...and it doesn't need to know just what those abilities are, just that it's allowed to use them.

Your class advancement script can then attach new ability components to your player and wire them up to the control script as your character gains new class abilities.

# Answer
> 0 votes
Ok, this is how I solved this ultimately. I found three distinct things I wanted to define by classes:

1. The player (already done by default)
2. The player's class (warrior, rogue, etc)
3. The abilities used by classes (berserk, stealth, etc)

This is how I did it, starting with #1 The Player:

```
        PlayerClass playerClass;
        public static ModHotKey ability1 = new ModHotKey("F");
        ...

        Update()
        {
        ...
            else if (choice == "Warrior")
            {
                playerClass = new WarriorClass(player, 100);
            }
        ...
        }

        KeyTriggers(TriggersSet triggersSet)
        {
            if (ability1.JustPressed)
        {
            playerClass.UseAbility(ability1);
        }

    }

```

PlayerClass is a mostly empty class that guides what methods should be called when inherited. Example WarriorClass inheriting from PlayerClass:

```
public class WarriorClass : PlayerClass
{
    int level;
    Player player = new Player();
    //Ability placeholders
    public IAbility primaryAbility;
    public IPassive primaryPassive;

    //Constructor. Needs player reference and level to set skills and stats correctly (when progression is a thing)
    public WarriorClass(Player player,  int level)
    {
        this.player = player;
        this.level = level;
        //Set ability manually for now
        primaryAbility = new BerserkAbility();
        primaryPassive = new LifeRegenPassive();
    }

    public override void DoPassives()
    {
        primaryPassive.DoPassive(player);
    }

    public override void UseAbility(ModHotKey key)
    {
        if (key == MinionTest.ability1)
        {
            primaryAbility.UseAbility(player);
        }
    }
}

```

It doesn't seem like much now that I've finished the entire design, but it will hold WarriorSpecific things like its progression and possibly talent tree (or maybe those will be classes themselves!).

Next up, the abilities the classes use. Notice above that the warrior doesn't know what ability it is going to use in UseAbility() until the constructor is called. Here is some ability code:

```
    public class BerserkAbility : IAbility
{
    int lifeLost;

    public void UseAbility(Player player)
    {
        //If the buff is off completely... start the buff on stack one
        if (player.HasBuff(ModContent.BuffType<BerserkBuff1>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff2>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff3>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff4>()) == false && player.HasBuff(ModContent.BuffType<BerserkBuff5>()) == false)
        {
            //Lose 10% of your life
            lifeLost = player.statLifeMax2 / 10;
            player.statLife = player.statLife - (int)lifeLost;

            //Start first stack of berserk for 10 seconds
            player.AddBuff(ModContent.BuffType<BerserkBuff1>(), 600, false);
        }
        //If it's already at stack 1, start stack two...
        else if (player.HasBuff(ModContent.BuffType<BerserkBuff1>()))
        ...

```

Where UseAbility (maybe a poor choice due to not being unique project wide) is required due to the interface IAbility interface. If you are stuck on Buffs above, those are already a distinct object or class in the mod library. IAbility is just this:

```
namespace MinionTest.Abilities
{
    public interface IAbility
    {
        void UseAbility(Player player);
    }

    //Should add cooldown here later
}

```

Why did I user class inheritance for player classes and an interface for abilities? I'm not really sure and wanted to try both.

Essentially what I end up with is a player that hits a key and asks the warrior to do the correct ability, and the warrior asks the ability how to do it. This adds three main benefits I see right now:

1. Really nice, readable code and code architecture. You know exactly what file and class to edit to change a class or ability.
2. It allows for game design choices like choosing a new class on the fly in-game, and talent trees that may change up what abilities your class can use.
3. The possibility to be extended incredibly easily. People can work on an *ability* in and of itself. A person can work on a *class* in and of itself, and plug and play abilities to it.

---
Tags: c#, architecture, oop
---


# Question
Title: Can you use the RangeAttribute to limit the size of an array?
I recently found out about the `RangeAttribute` and how you could use it to limit the values of your parameter when entering them in in the inspector window. However, I needed to use an array for randomly selecting Prefabs so they can spawn randomly at any given time. The problem is Unity lets me have an array size of zero, but I also want to limit the number of possible prefabs. I was wondering if there is a way to use `RangedAttribute` to limit the size of an array, and if not is there a different way to achieve this? I have extensive experience in Java and C# but recently started in Unity, so I don't know if I'm asking the right questions, so any guidance right now would be greatly appreciated. Thanks.

P.S. I would be able to attach the script to give an example if needed.

# Answer
AFAIK `Range` attribute won't be usable on arrays. As you can see here this attribute is limited to `int` and `float` restrictions.

However you can totally limit an array max size in the Editor by creating a custom inspector view. Here you will be able to check the content of your array, and reject any addition above a certain amount.
> 1 votes

---
Tags: unity, c#
---


# Question
Title: What's the difference between rendering and shaders?
What is rendering? What are shaders like vertex ,tessellation shaders etc? I am confused what's the difference between rendering and shaders? and how rendering is performed using shaders? Can we perform rendering without shaders? are shaders used in both films(like toy story) and games?

# Answer
> 4 votes
Rendering is a very generic term which is basically can be defined as "creating an image", which can be, obviously, created in many ways. For example if you fill memory with color values (software rendering) it is also a "rendering".

Shaders are completely other thing. They are related to how modern GPUs work. Say you want to render a triangle. You supply triangle coordinates to GPU. You also load a shader to GPU. Then GPU is rendering data you supplied, it is executing your shader on every triangle vertex (vertex shader) and every triangle pixel (pixel shader). In shader you basically transform coordinates (vertex) and change color (pixel) of your final image. That's VERY basic on what shaders are. Shaders are very powerful and very fast, most effects in modern games are possible because of shaders.

As @tkausl correctly mentioned, modern GPU pipeline actually requres shaders do draw anything. They are often hidden behind frameworks like, for example, XNA. They can be called "Identity" shaders, which only transform your "screen coordinates" to OpenGL or DirectX coordinates and do not modify pixels, except for handling transparency.

So to answer your questions:

> I am confused what's the difference between rendering and shaders?

They are not comparable.

> and how rendering is performed using shaders?

I guess I answered that above.

> Can we perform rendering without shaders?

Absolutely we can.

> are shaders used in both films(like toy story) and games?

Yes. Though I would guess they differ significantly since Pixar is not using your typical OpenGL or DirectX API, but the concept of "shader" should be the same. Also Pixar is not rendering in real-time, so they could use much more complex algorithms.

# Answer
> 1 votes
Rendering is the whole process of drawing something on the screen.

And this process consists of multiple steps. In a modern GPU based renderer this means basically and simplified:

* Uploading vertices of triangle-meshes to the GPU (done by the program running on the CPU)
* Positioning these vertices in the view-frustum of the screen. Typically by applying a model-view-projection matrix. (done by a vertex-shader)
* Assemble 3 vertices to a triangle (done by the GPU)
* Clipping = Throw away triangles, that are outside of the screen (done by the GPU)
* Optional: tesselation: cutting these triangles into multiple smaller triangles (Done by a tesselation- shader, a fixed tesselator and a geometry-shader)
* Rasterizing the remaining triangles = calculating, which fragments are covered by these triangles. There can be multiple fragments per pixel. And fragments have a depth component (done by the GPU)
* Throw away fragments, that are not visible (outside of the screen, or covered by other fragments) (done by the GPU)
* Calculating the color of each fragment. For example a phong-shader. (this is done by fragment-shaders)
* Combining colors of the fragments of each pixel (for anti aliasing, or transparency effects) (done by the GPU)
* Showing the final image on the screen

Some of these steps are executed by the application on the CPU. Some of these steps are executed by fixed circuits on the GPU, and some of these steps are executed by shaders, that run on the GPU. These shaders are small programs, that are provided by the application (like a game). They are executed on the GPU. On older GPUs without shaders, these steps are also performed by a fixed circuit on the GPU. But then they are not called shaders (so: rendering also works without shaders).

See more: https://en.wikipedia.org/wiki/Graphics\_pipeline

# Answer
> 0 votes
Renderer executes the final image/as a whole, including its part, the shader. They are both mathematical in nature, coded into programs. This makes a shader a subset of a renderer.

A metaphor for this is, the 'shaders' are the visual effects people, in the scene in a movie but the director, the 'renderer', is responsible for the final look of a scene.

\[as bitmapped image/images formed by logical pixels (coz' there are many more physical pixels in a pixel nowadays, like in Retina displays, there are subpixels even more divided into subpixels for the individual red, green & blue colors), also called rasterized image, which are images generated line by line, thus the refresh rates\]

---
Tags: shaders, rendering
---


# Question
Title: How do I generalise Bresenham's line algorithm to floating-point endpoints?
I'm trying to combine two things. I'm writing a game and I need to determine the grid squares lying on a line with the floating-point endpoints.

Moreover I need it to include all the grid squares it touches (i.e. not just Bresenham's line but the blue one):

Can someone offer me any insight on how to do it? The obvious solution is to use naive line algorithm, but is there something more optimized (faster)?

# Answer
You are looking for a grid traversal algorithm. This paper gives a good implementation;

Here's the basic implementation in 2D found on the paper:

```
loop {
    if (tMaxX < tMaxY) {
        tMaxX = tMaxX + tDeltaX;
        X = X + stepX;
    } else {
        tMaxY = tMaxY + tDeltaY;
        Y = Y + stepY;
    }
    NextVoxel(X, Y);
}

```

There's also a 3D ray-casting version on the paper.

In case the link rots, you can find many mirrors with its name: *A faster voxel traversal algorithm for raytracing*.

---

Relevant bits from the paper:

> ...it is a variant of the DDA line algorithm. However, instead of basing it on the simple DDA..., in which an unconditional step along one axis is required, ours has no preferred axis. This considerably simplifies the inner loop and allows for easy testing of an intersection point to see if it is in the current voxel.
>
> ...
>
> The new traversal algorithm breaks down the ray into intervals of t, each of which spans one voxel. We start at the ray origin and visit each of these voxels in interval order. The traversal algorithm consists of two phases: initialization and incremental traversal.
>
> ...
>
> The integer variables X and Y are initialized to the starting voxel coordinates. In addition, the variables stepX and stepY are initialized to either 1 or -1 indicating whether X and Y are incremented or decremented as the ray crosses voxel boundaries (this is determined by the sign of the x and y components...)
>
> ...
>
> Next, we determine the value of t at which the ray crosses the first vertical voxel boundary and store it in variable tMaxX. We perform a similar computation in y and store the result in tMaxY. The minimum of these two values will indicate how much we can travel along the ray and still remain in the current voxel.
>
> Finally, we compute tDeltaX and tDeltaY. tDeltaX indicates how far along the ray we must move (in units of t) for the horizontal component of such a movement to equal the width of a voxel. Similarly, we store in tDeltaY the amount of movement along the ray which has a vertical component equal to the height of a voxel.
> 11 votes

# Answer
Blue's idea is good, but the implementation is a bit clumsy. In fact, you can easily do it without sqrt. Let's assume for the moment that you exclude degenerate cases (`BeginX==EndX || BeginY==EndY`) and focus only on line directions in the first quadrant, so `BeginX < EndX && BeginY < EndY`. You'll have to implement a version for at least one other quadrant too, but that's very similar to the version for the first quadrant - you only check other edges. In C'ish pseudo code:

```
int cx = floor(BeginX); // Begin/current cell coords
int cy = floor(BeginY);
int ex = floor(EndX); // End cell coords
int ey = floor(EndY);

// Delta or direction
double dx = EndX-BeginX;
double dy = EndY-BeginY;

while (cx < ex && cy < ey)
{
  // find intersection "time" in x dir
  float t0 = (ceil(BeginX)-BeginX)/dx;
  float t1 = (ceil(BeginY)-BeginY)/dy;

  visit_cell(cx, cy);

  if (t0 < t1) // cross x boundary first=?
  {
    ++cx;
    BeginX += t0*dx;
    BeginY += t0*dy;
  }
  else
  {
    ++cy;
    BeginX += t1*dx;
    BeginY += t1*dy;
  }
}

```

Now for other quadrants, you just change the `++cx` or `++cy` and the loop condition. If you use this for collision, you probably have to implement all 4 versions, otherwise you can get away with two by appropriately swapping begin and end points.
> 5 votes

# Answer
```
float difX = end.x - start.x;
float difY = end.y - start.y;
float dist = abs(difX) + abs(difY);

float dx = difX / dist;
float dy = difY / dist;

for (int i = 0, int x, int y; i <= ceil(dist); i++) {
    x = floor(start.x + dx * i);
    y = floor(start.y + dy * i);
    draw(x,y);
}
return true;

```

**JS Demo :**

```
//C# stackoverflow

function verifyLoS(start, end) {
    var difX = end.x - start.x;
    var difY = end.y - start.y;
 var dist = Math.abs(difX) + Math.abs(difY);

    var dx = difX / dist;
    var dy = difY / dist;

    for (var i = 0, x, y; i <= Math.ceil(dist); i++) {
        x = Math.floor(start.x + dx * i);
        y = Math.floor(start.y + dy * i);
        draw(x,y);
    }
    return true;
}

var HEIGHT = 14,
    WIDTH = 14,
    PX = 32;

var canvas, ctx;

function main () {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");

  canvas.height = HEIGHT * PX;
  canvas.width = WIDTH * PX;

  loop();
}

function loop() {
  for (var x=0;x<HEIGHT; x++) {
    for (var y=0; y<WIDTH; y++) {
      ctx.fillStyle = ((x+y)%2===0)?"#AFA":"#AEA";
      ctx.fillRect(x*PX,y*PX,PX,PX);
    }
  }
  var a = {x:1.5, y:9.5},
      b = {x:12.5, y:1.5};
  verifyLoS(a, b);
  ctx.beginPath();
  ctx.moveTo(a.x*PX,a.y*PX);
  ctx.lineTo(b.x*PX,b.y*PX);
  ctx.stroke();
  //window.requestAnimationFrame(loop);
}

function draw(x, y) {
    ctx.fillStyle = "rgba(255,0,0,0.2)";
    ctx.fillRect(x*PX,y*PX,PX,PX);
}

main();
```

```
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>
```
> 4 votes

# Answer
Your assumption isn't necessarily to find the cells but the lines it cross on this grid.

For example taking your image we can highlight not the cells, but lines of the grid it crosses:

This then shows that if it crosses a grid line that the cells either side of this line are those that are filled.

You can use an intersection algorithm to find if your floating point line will cross these by scaling your points to pixels. If you have a 1.0:1 ratio of floating coordinates:pixels then you're sorted and you can just translate it directly. Using the Line segment intersection algorithm you can check if your lower left line (1,7)(2,7) intersects with your line (1.3,6.2)(6.51,2.9). http://alienryderflex.com/intersect/

Some translation from c to C# will be needed but you can get the idea from that paper. I'll put the code below in-case the link breaks.

```
//  public domain function by Darel Rex Finley, 2006

//  Determines the intersection point of the line defined by points A and B with the
//  line defined by points C and D.
//
//  Returns YES if the intersection point was found, and stores that point in X,Y.
//  Returns NO if there is no determinable intersection point, in which case X,Y will
//  be unmodified.

bool lineIntersection(
double Ax, double Ay,
double Bx, double By,
double Cx, double Cy,
double Dx, double Dy,
double *X, double *Y) {

  double  distAB, theCos, theSin, newX, ABpos ;

  //  Fail if either line is undefined.
  if (Ax==Bx && Ay==By || Cx==Dx && Cy==Dy) return NO;

  //  (1) Translate the system so that point A is on the origin.
  Bx-=Ax; By-=Ay;
  Cx-=Ax; Cy-=Ay;
  Dx-=Ax; Dy-=Ay;

  //  Discover the length of segment A-B.
  distAB=sqrt(Bx*Bx+By*By);

  //  (2) Rotate the system so that point B is on the positive X axis.
  theCos=Bx/distAB;
  theSin=By/distAB;
  newX=Cx*theCos+Cy*theSin;
  Cy  =Cy*theCos-Cx*theSin; Cx=newX;
  newX=Dx*theCos+Dy*theSin;
  Dy  =Dy*theCos-Dx*theSin; Dx=newX;

  //  Fail if the lines are parallel.
  if (Cy==Dy) return NO;

  //  (3) Discover the position of the intersection point along line A-B.
  ABpos=Dx+(Cx-Dx)*Dy/(Dy-Cy);

  //  (4) Apply the discovered position to line A-B in the original coordinate system.
  *X=Ax+ABpos*theCos;
  *Y=Ay+ABpos*theSin;

  //  Success.
  return YES; }

```

If you need to find out only when (and where) the line segments intersect, you can modify the function as follows:

```
//  public domain function by Darel Rex Finley, 2006

//  Determines the intersection point of the line segment defined by points A and B
//  with the line segment defined by points C and D.
//
//  Returns YES if the intersection point was found, and stores that point in X,Y.
//  Returns NO if there is no determinable intersection point, in which case X,Y will
//  be unmodified.

bool lineSegmentIntersection(
double Ax, double Ay,
double Bx, double By,
double Cx, double Cy,
double Dx, double Dy,
double *X, double *Y) {

  double  distAB, theCos, theSin, newX, ABpos ;

  //  Fail if either line segment is zero-length.
  if (Ax==Bx && Ay==By || Cx==Dx && Cy==Dy) return NO;

  //  Fail if the segments share an end-point.
  if (Ax==Cx && Ay==Cy || Bx==Cx && By==Cy
  ||  Ax==Dx && Ay==Dy || Bx==Dx && By==Dy) {
    return NO; }

  //  (1) Translate the system so that point A is on the origin.
  Bx-=Ax; By-=Ay;
  Cx-=Ax; Cy-=Ay;
  Dx-=Ax; Dy-=Ay;

  //  Discover the length of segment A-B.
  distAB=sqrt(Bx*Bx+By*By);

  //  (2) Rotate the system so that point B is on the positive X axis.
  theCos=Bx/distAB;
  theSin=By/distAB;
  newX=Cx*theCos+Cy*theSin;
  Cy  =Cy*theCos-Cx*theSin; Cx=newX;
  newX=Dx*theCos+Dy*theSin;
  Dy  =Dy*theCos-Dx*theSin; Dx=newX;

  //  Fail if segment C-D doesn't cross line A-B.
  if (Cy<0. && Dy<0. || Cy>=0. && Dy>=0.) return NO;

  //  (3) Discover the position of the intersection point along line A-B.
  ABpos=Dx+(Cx-Dx)*Dy/(Dy-Cy);

  //  Fail if segment C-D crosses line A-B outside of segment A-B.
  if (ABpos<0. || ABpos>distAB) return NO;

  //  (4) Apply the discovered position to line A-B in the original coordinate system.
  *X=Ax+ABpos*theCos;
  *Y=Ay+ABpos*theSin;

  //  Success.
  return YES; }

```
> 3 votes

# Answer
I ran into the same problem today and made a pretty big mountain of spaghetti out of a mole hill but ended up with something that works: https://github.com/SnpM/Pan-Line-Algorithm.

From the ReadMe:

> The core concept of this algorithm is similar to Bresenham's in that it increments by 1 unit on one axis and tests the increase on the other axis. Fractions make incrementing considerably more difficult, however, and a lot of pizzas had to be added in. For example, incrementing from X = .21 to X = 1.21 with a slope of 5 makes for a complex problem (coordinate patterns between those nasty numbers are hard to predict) but incrementing from 1 to 2 with a slope of 5 makes for an easy problem. Coordinate pattern between integers is very easy to solve (just a line perpendicular to the incrementing axis). To get the easy problem, the incrementing is offset to an integer number with all the calculations done seperately for the fractional piece. So instead of starting the incrementing on .21, the algorithm tries to start the incrementing on 1 and goes from there.

The ReadMe explains the solution much better than the code. I'm planning on revising it to be less headache-inducing.

I know I'm about a year late to this question but I hope this gets to others who are looking for a solution to this problem.
> 1 votes

# Answer
Got it working perfectly! I combined Gustavo Maciel's answer with A-312's (using algorithm from paper Gustavo cited). Thanks guys!

Solution (see `intersect()` function and comments): https://jsfiddle.net/6x7t4q1o/5

```
function intersect(start, end) {
  //Grid cells are 1.0 X 1.0.
  let x = Math.floor(start.x);
  let y = Math.floor(start.y);
  let diffX = end.x - start.x;
  let diffY = end.y - start.y;
  let stepX = Math.sign(diffX);
  let stepY = Math.sign(diffY);

  //Ray/Slope related maths.
  //Straight distance to the first vertical grid boundary.
  let xOffset = end.x > start.x ?
   (Math.ceil(start.x) - start.x) :
    (start.x - Math.floor(start.x));
  //Straight distance to the first horizontal grid boundary.
  let yOffset = end.y > start.y ?
   (Math.ceil(start.y) - start.y) :
    (start.y - Math.floor(start.y));
  //Angle of ray/slope.
  let angle = Math.atan2(-diffY, diffX);
  //NOTE: These can be divide by 0's, but JS just yields Infinity! :)
  //How far to move along the ray to cross the first vertical grid cell boundary.
  let tMaxX = xOffset / Math.cos(angle);
  //How far to move along the ray to cross the first horizontal grid cell boundary.
  let tMaxY = yOffset / Math.sin(angle);
  //How far to move along the ray to move horizontally 1 grid cell.
  let tDeltaX = 1.0 / Math.cos(angle);
  //How far to move along the ray to move vertically 1 grid cell.
  let tDeltaY = 1.0 / Math.sin(angle);

  //Travel one grid cell at a time.
  let manhattanDistance = Math.abs(Math.floor(end.x) - Math.floor(start.x)) +
   Math.abs(Math.floor(end.y) - Math.floor(start.y));
  for (let t = 0; t <= manhattanDistance; ++t) {
    drawSquare(x, y);
    //Only move in either X or Y coordinates, not both.
   if (Math.abs(tMaxX) < Math.abs(tMaxY)) {
     tMaxX += tDeltaX;
      x += stepX;
    } else {
     tMaxY += tDeltaY;
      y += stepY;
    }
  }

  infos.innerHTML = "";
  infos.innerHTML += "diffX:   " + diffX   + "<br/>diffY:   " + diffY + "<br/>";
  infos.innerHTML += "stepX:   " + stepX   + "<br/>stepY:   " + stepY + "<br/>";
  infos.innerHTML += "xOffset: " + xOffset + "<br/>yOffset: " + yOffset + "<br/>";
  infos.innerHTML += "tMaxX:   " + tMaxX   + "<br/>tMaxY:   " + tMaxY + "<br/>";
  infos.innerHTML += "tDeltaX: " + tDeltaX + "<br/>tDeltaY: " + tDeltaY + "<br/><br/>";
  infos.innerHTML += "angle: " + angle + "<br/>";
  infos.innerHTML += "manhattanDistance: " + manhattanDistance + "<br/>";
}

let WIDTH = 15,
    HEIGHT = 15,
    PX = 32;
let animationRate = 100;

let canvas, ctx;
let lastAnimationTime = -animationRate;
let animations = 0;

//Line coordinates.
let a = { x: WIDTH / 3,     y: HEIGHT * 2 / 3 };
let b = { x: WIDTH * 2 / 3, y: HEIGHT / 3 };
let resetA = { x: a.x, y: a.y };
let resetB = { x: b.x, y: b.y };

let infos;

function main () {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  canvas.height = HEIGHT * PX;
  canvas.width = WIDTH * PX;
  ctx.lineWidth = 1.5;

  infos = document.getElementById("infos");

  requestAnimationFrame(animate);
}

function animate(elapsedTime) {
 if (elapsedTime - lastAnimationTime > animationRate) {
   lastAnimationTime += animationRate;
    ++animations;
    loop(elapsedTime);
  }
  if (animations > 500) {
   a = { x: resetA.x, y: resetA. y };
    b = { x: resetB.x, y: resetB. y };
    animations = 0;
  }
 requestAnimationFrame(animate);
}

function loop(elapsedTime) {
  //Draw checkerboard.
  for (let x = 0; x < HEIGHT; x++) {
    for (let y = 0; y < WIDTH; y++) {
      ctx.fillStyle = ((x + y) % 2) ? "#90FF90": "#90F090";
      ctx.fillRect(x * PX, y * PX, PX, PX);
    }
  }

  let radius = Math.sin(elapsedTime * 0.0001) * 5.0;
  a.x = Math.cos(elapsedTime * 0.0002) * -radius + WIDTH * 0.5;
  a.y = Math.sin(elapsedTime * 0.0002) * radius + HEIGHT * 0.5;
  b.x = Math.cos(elapsedTime * 0.0002) * radius + WIDTH * 0.5;
  b.y = Math.sin(elapsedTime * 0.0002) * -radius + HEIGHT * 0.5;

  //Calculate and draw intersection squares.
  intersect(a, b);

  //Draw line.
  ctx.beginPath();
  ctx.moveTo(a.x * PX, a.y * PX);
  ctx.lineTo(b.x * PX, b.y * PX);
  ctx.stroke();

  //Draw S and E.
  ctx.fillStyle = "#00000050";
  ctx.fillText("S",
   a.x * PX + 50.0 * Math.sign(a.x - b.x),
   a.y * PX + 50.0 * Math.sign(a.y - b.y));
  ctx.fillText("E",
   b.x * PX + 50.0 * Math.sign(b.x - a.x),
   b.y * PX + 50.0 * Math.sign(b.y - a.y));
}

function drawSquare(x, y) {
  ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
  ctx.fillRect(x * PX, y * PX, PX, PX);
}

main();
```

```
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body style="background-color: white;">
  <canvas id="canvas"></canvas>
  <pre id="infos"></pre>
</body>
</html>
```
> 0 votes

---
Tags: c#, algorithm, grid, interpolation, floating-point
---


title: Increasing spawn difficulty

text:
# Question
Title: Increasing spawn difficulty
I'm trying to increase the difficulty of the game over time. I'm using InvokeRepeating to spawn enemies and in the update function I calculate the next spawn time using the following code:

```
public Vector2 secondsBetweenSpawnsMinMax;
float nextSpawnTime;

void Update()
 {
    if (Time.deltaTime >= nextSpawnTime)
    {
        float secondsBetweenSpawns = Mathf.Lerp(secondsBetweenSpawnsMinMax.y, secondsBetweenSpawnsMinMax.x, Mathf.Clamp01(Time.time / 60));
        nextSpawnTime = Time.deltaTime + secondsBetweenSpawns;
    }
 }

public void StartNewGame()
{
    InvokeRepeating("Spawn", 0.1f, nextSpawnTime);
}

public void Spawn()
 {
    Vector3 enemySpawnPos = spawnPoint.position;
    Instantiate(enemy, enemySpawnPos, Quaternion.identity);
 }

```

I'm fixing the secondsBetweenSpawnsMinMax.y to 3 and secondsBetweenSpawnsMinMax.x to 1. The issue I'm facing is that the nextSpawnTime doesn't change. It starts at 3 and stays at that value when it should go down to 1. I'm not sure what's wrong with the code here.

# Answer
The problem is that when you call `InvokeRepeating`, the current value of `nextSpawnTime` gets copied to the Unity coroutine system. When you change the value of that variable later, the coroutine system doesn't even notice it. Its copy of the value won't be affected. There is no way (I am aware of) to retroactively change the time interval of a repeating invoke. All you can do is deschedule it with `CancelInvoke` and reschedule it again with the new value.

However, I would not use InvokeRepeating at all in this case. I would instead replicate the functionality on my own in Update, just like you did it with the logic which decreases `nextSpawnTime` in regular intervals.

My solution for this would look something like this:

```
private float speedFactor = 1.0f; // start with regular speed
public float spawnInterval = 2.0f;  // default spawn rate = one every 2 seconds
private float spawnTimeLeft;

void Update()
{
    // spawning logic
    spawnTimeLeft -= Time.deltaTime * speedFactor; // higher speed factor = faster spawns;
    while (spawnTimeLeft < 0.0f) {
        spawnTimeLeft += spawnInterval;
        Spawn();
    }
}

```

Now you just need to add some logic which manipulates the variable `speedFactor` in order to control the spawning speed. For example, a value of `2.0` will cause `spawnTimeLeft` to decrease twice as fast from then on and thus cause Spawn() to get called twice as often.

By the way, you might wonder why I use `while (spawnTimeLeft < 0.0f)` instead of `if (spawnTimeLeft < 0.0f)`. The reason is that your game might get so fast that you occasionally need to spawn two or more enemies in a single update.

---

However, if you actually like the Unity coroutine system (I don't, but that's just my preference), then you could use a Coroutine instead of InvokeRepeating which uses `yield return new WaitForSeconds(nextSpawnTime)` to wait until it's time to spawn another enemy. This will use the current value of `nextSpawnTime` at that moment. But remember that it again uses a copy of the variable. If you change it while the coroutine is waiting, the wait time will not be affected.

```
public void StartNewGame()
{
    StartCoroutine(Spawn);
}

private IEnumerator Spawn() {
     while(true) {
         yield return new WaitForSeconds(nextSpawnTime);
         Vector3 enemySpawnPos = spawnPoint.position;
         Instantiate(enemy, enemySpawnPos, Quaternion.identity);
     }
}

```
> 1 votes

---
Tags: unity, spawning
---


title: Normals are flipped

text:
# Question
Title: Normals are flipped
I colored normals with negative `y` red and here's what I get:

Any idea why some normals are flipped?

Here's simplified version of my code that add vertices, triangles, normals, etc.

I'm playing around with Godot, so axes are are the following:

* Vertical is `y` axis, up is positive
* Horizontal is `x` axis, left is positive (left in image)
* Depth is `z` axis, forward is positive (up in image)

```
public static TerrainMesh GenerateMesh(float[,] heights, Color[,] colors) {
  int width = heights.GetLength(0);
  int height = heights.GetLength(1);
  float topLeftX = (width - 1) / 2f;
  float topLeftZ = (height - 1) / 2f;

  TerrainMesh mesh = new TerrainMesh(width, height);
  int vertexIndex = 0;

  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      mesh.Vertices[vertexIndex] = new Vector3(topLeftX - x, heights[x, y], topLeftZ - y);
      mesh.Uvs[vertexIndex] = new Vector2(x / (float)width, y / (float)height);

      // rudimentary normals
      if (x != 0) {
        // PS! if I swap Vector3's in Cross, upper half of the map has flipped normals
        Vector3 normal = mesh.Vertices[vertexIndex].Cross(mesh.Vertices[vertexIndex - 1]).Normalized();
        mesh.Normals[vertexIndex] = normal;
      } else if (x == 1) {
        Vector3 normal = mesh.Vertices[vertexIndex - 1].Cross(mesh.Vertices[vertexIndex]).Normalized();
        mesh.Normals[vertexIndex - 1] = normal;
      }

      if (x < width - 1 && y < height - 1) {
        mesh.AddTriangle(vertexIndex, vertexIndex + width + 1, vertexIndex + width);
        mesh.AddTriangle(vertexIndex + width + 1, vertexIndex, vertexIndex + 1);
      }

      vertexIndex += 1;
    }
  }

  return mesh;
}

```

# Answer
> 2 votes
The method of computing normals shown here is beyond "rudimentary" - it's just flat out wrong. What you're computing there in no way corresponds to a terrain normal.

It's taking two vectors from the origin to different vertices in your mesh - which don't always belong to the same mesh triangle, even - and computing a normal of the triangle they form with the origin. Naturally, when you cross the origin, this triangle - which has nothing to do with the triangles of the mesh you're drawing - flips over, resulting in the inverted normals you see for half your mesh.

Try something like this instead:

```
Vector3 GetNormal(int x, int y, float[,] heights, float stepSize = 1.0f) {
    float center = heights[x, y];

    float left  = x > 0                        ? heights[x-1, y], center;
    float right = x < heights.GetLength(0) - 1 ? heights[x+1, y], center;

    float bottom = y > 0                        ? heights[x, y-1], center;
    float top    = y < heights.GetLength(1) - 1 ? heights[x, y+1], center;

    return Vector3.Normalize(new Vector3(left - right, 2 * stepSize, bottom - top)
}

```

The `stepSize` variable corresponds to how great a distance there is between adjacent cells of your heightmap grid. Smaller values will exaggerate the normals, while larger values will tend to pull the normals closer to vertical.

---
Tags: c#, godot
---


title: How to scale smaller values more

text:
# Question
Title: How to scale smaller values more
Hello it seems like it should be easy and i am missing something but i really couldn't find a solution as i am fairly new to programming. So basically i want to rotate a object faster when its closer to another object. My code is below and i want the rotationSpeed to be a higher value when its closer.

```
rotationSpeed = Mathf.Sqrt(
        Mathf.Pow(sphere.center.X - playerSphere.center.X, 2)
        + Mathf.Pow(sphere.center.Y - playerSphere.center.Y, 2)
        + Mathf.Pow(sphere.center.Z - playerSphere.center.Z, 2));

```

eg: 10 * x = 50, 5 * x = 100

# Answer
> 0 votes
Here is the code:

```
rotationSpeed = aConstant / Vector3.Distance(sphere.position, playerSphere.position)

```

So basically the idea here is that you have a float constant and you're dividing it by distance. So when they're close to each other, the rotation speed will be higher. You can also limit it with an if statement or take the square root of the distance to make it smaller. Just make sure that the distance is never being 0, the division may throw an exception.

P.S. `Vector3.Distance(a,b)` is the same as `(a-b).magnitude`

---
Tags: unity, c#, mathematics, rotation, vector
---


# Question
Title: Finding the line segments where 2 polygons share an edge
I am working on code to place doors between rooms on my levels. Rooms are lists of points which make up a polygon. In order to find a place for a door between two rooms, I need to find what line segment(s) are along the edge of both polygons. Here are some examples, where I would need to identify the highlighted segment(s):

The code which generates the room polygons will always create polygons that don't overlap, but only touch. How would I go about finding a shared edge like this? I am using Godot with the built-in scripting language, but the language doesn't matter as much as the algorithm itself.

# Answer
I figured it out. The process goes like this (using python; `is_point_in_polygon` is a conceit, but could be replaced with something like `Polygon.contains` from Shapely):

1. Iterate over every point (in both polygons) and check to see if it is inside *both* polygons. Save these to a list

```
def find_shared_edges(poly_1, poly_2):
    shared_verts = []
    for vert in poly_1+poly_2:
        if is_point_in_polygon(vert, poly_1) and is_point_in_polygon(vert, poly_2):
            shared_verts.append(vert)

```
2. Compare each of these points to each other point. If the midpoint between two of them is also inside both polygons, then they are a shared edge.

```
    shared_edges = []
    for vert_a in shared_verts:
        for vert_b in shared_verts:
            midpoint = (vert_a + vert_b) / 2

            if is_point_in_polygon(midpoint, poly_1) and \
               is_point_in_polygon(midpoint, poly_2):
                shared_edges.append( (vert_a, vert_b) )

```
3. Eliminate duplicate entries which are the same line segments, just with their endpoints reversed. This shouldn't be a problem in python if you use `itertools.combinations` instead of the nested for-loops in the above step.

```
    return shared_edges

```
> 1 votes

# Answer
I warn you that you might find a problem with rounding. In particular in diagonals such as in your last example, the segments might not match, or at least appear to not match in a strict check due to the positions of the vertex being truncated to whatever resolution the number data type supports. Hopefully you have a minimum size (i.e. a pixel) such that anything closer than that is considered in the same place. Or at least we have some idea of how big the polygons are.

---

Warning aside, the way you are going to deal with this follows…

First you need candidate segment pairs. If you know what polygons are contiguous, you can consider all of their segments to be candidates for a match. If you do not know which polygons are contiguous, you want to have some idea of where they are, so you only consider those that are nearby.

Once you have a candidate segment pair, collide their bounding boxes (AABB). If no collision, they do not match.

If they collide, it means they are close, however they might still not match.

In this case project the vertex of one segment on the other (it does not matter which one). Compute the distance from the vertex to its projection. If the distance, for both vertex of a segment to their projection on the other segment, is zero (within rounding error), it means they are on top of each other. That is, they match.

Yo can use the collision bounding box will correspond to the part of the segment that is common to both polygons.

---

You say your code generate polygons with this property. Is there any chance you can modify the code to output how they are linked? Perhaps generate a supplementary structure where you can query how the polygons are related.
> 0 votes

---
Tags: geometry, godot
---