# Question
Title: How can I keep track of which "rooms" characters and NPCs are in?
I have a Unity 2D project which has a player character and numerous NPCs all potentially moving (top-down) at the same time during play. The number of NPCs is not to exceed 100 (and will be, probably, more like 40-50) but I'd still like to be performant.

The "rooms" are really just rectangles that correspond to sections of my tilemap. All the "rooms" are contiguous, and hence all characters will always be in exactly 1 "room". Like if you picture the floorplan of a house, you're in the "Hallway" or the "Living Room" or the "Front Porch" or the "Driveway", and so on.

My tilemap is not complete, so it would be nice to be able to easily move the rooms around in the Scene editor as I refine it.

I was thinking I could...

1. Create `Rect` objects (or maybe an AABE, although I just read very briefly about what this even is) for each room inside a "RoomsController" `GameObject`, and then on each `Update()` iterate through each and see who is within the bounds of each room. But that seems majorly wasteful, and pretty brute-force even if done every few frames.
2. Create a `GameObject` for each room with an appropriately-sized `BoxCollider 2D`, and look for collisions with NPCs, and have a script that handles changing the active room on the NPC when he "collides" with a new room. But this requires a `RigidBody 2D` for each room, and it feels like overkill.

Is there an existing "right way" to solve this problem?

# Answer
> 1 votes
I would define a class for each type of room shape. For rooms that are quadrilaterals or circles, it is easy to define those shapes and test if a given point is within them. If the shapes of your rooms are anything else, it may be easier to create a Polygon Collider and test `Collider2D.OverlapPoint` using that collider and the position of the unit:

```
public class Room
{
    public virtual bool IsInRoom(Vector2 point)
    {
        return false;
    }

    public class Quad : Room
    {
        public Vector2 min {get; private set;}
        public Vector2 max {get; private set;}
        public Quad(Vector2 min, Vector2 max)
        {
            this.min = min;
            this.max = max;
        }

        public override bool IsInRoom(Vector2 point)
        {
            if (point.x > min.x && point.x < max.x)
                if (point.y > min.y && point.y < max.y)
                    return true;
            return false;
        }
    }

    public class Circle : Room
    {
        public Vector3 center {get; private set;}
        public float radius {get; private set;}
        public Circle(Vector3 center, float radius)
        {
            this.center = center;
            this.radius = radius;
        }

        public override bool IsInRoom(Vector2 point)
        {
            if (Vector2.Distance(point, center) > radius)
                return true;
            else
                return false;
        }
    }

    public class Polygon : Room
    {
        public Collider2D collider {get; private set;}
        public Polygon(Collider2D collider)
        {
            this.collider = collider;
        }

        public override bool IsInRoom(Vector2 point)
        {
            return collider.OverlapPoint(point);
        }
    }
}

```

You could make use of the `[System.Serializable]` tag and `OnDrawGizmos` in order to edit these rooms from within the inspector.

After populating the list of rooms, a `foreach` loop could iterate through the rooms and units, testing each one:

```
foreach (Unit unit in units)
    foreach (Room room in rooms)
    {
        if(room.IsInRoom(unit.position))
        {
            unit.currentRoom = room;
            break;
        }
    }

```

I didn't test this code, so you may need to make minor changes to it for syntax/optimization. Good luck!

---

EDIT: I would like to answer some questions left in the comments to this question.

> Should the `Room` actually inherit from `MonoBehaviour`, and be a script attached to a set of `GameObject` that I position, or is it expected that these would be initialized by another script somewhere?

What I like to do in my games is have an object in my scene with some manager scripts attached to it. For example, I have an `AudioSource` and a script called `SFXManager` attached to it, and `SFXManager` holds a list with all the different sound effects in the game that are assigned in the inspector, then at runtime those clips are put into a static `Dictionary<string, AudioClip>` that I can reference publicly.

The manager I would create in your scenario would store a list of all the different `Rooms` in your game, but since these different types of rooms all inherit from the base class `Room`, I'm unsure of how exactly you would go about editing the room values in the inspector since the inspector won't know which type of room a given item in a `List<Room>` is. So, to backtrack a bit, I would separate the different room types into their own scripts:

```
public class Room : MonoBehaviour
{
    public string name;
    private void Awake()
    {
        MapManager.rooms.Add(this);
    }
    public virtual bool IsInRoom(Vector2 point)
    {
        return false;
    }
}

public class Quad : Room
{
    public Vector2 min;
    public Vector2 max;

    public override bool IsInRoom(Vector2 point)
    {
        if (point.x > min.x && point.x < max.x)
            if (point.y > min.y && point.y < max.y)
                return true;
        return false;
    }

    void OnDrawGizmos()
    {
         // draw the room
    }
}

public class Circle : Room
{
    public Vector3 center;
    public float radius;

    public override bool IsInRoom(Vector2 point)
    {
        if (Vector2.Distance(point, center) > radius)
            return true;
        else
            return false;
    }

    void OnDrawGizmos()
    {
         // draw the room
    }
}

public class Polygon : Room
{
    public Collider2D collider;

    public override bool IsInRoom(Vector2 point)
    {
        return collider.OverlapPoint(point);
    }

    void OnDrawGizmos()
    {
         // draw the room
    }
}

```

Here, I've maintained the inheritance, and had the base `Room` class inherit from `MonoBehaviour` since C# doesn't allow multiple inheritance. I've also changed the variables from properties to fields to allow inspector editing. These scripts would simply be attached to objects in your scene, allowing their `Awake()` function to be called which adds them to the static `List<Room>` we will store in our manager. `Units` will need to follow the same idea:

```
public class Unit : MonoBehaviour
{
    private void Awake()
    {
        MapManager.units.Add(this);
    }
}

```

Now, we can create our `MapManager`:

```
public class MapManager : MonoBehaviour
{
    public static MapManager ins {get; private set;}
    public static List<Room> rooms {get; private set;}
    public static List<Unit> units {get; private set;}

    private void Awake()
    {
        if (ins != null) Destroy(ins);
        ins = this;
        rooms = new List<Room>();
        units = new List<Unit>();
    }

    public Room GetRoomOfUnit(Unit unit)
    {
        foreach (Room room in rooms)
            if (room.IsInRoom(unit.transform.position))
                return true;

        return null;
    }

    public Unit[] GetUnitsInRoom(Room room)
    {
        List<Unit> units = new List<Unit>();
        foreach (Unit unit in this.units)
            if (room.IsInRoom(unit.transform.position))
                units.Add(unit);

        return units.ToArray();
    }
}

```

It's important to note that script execution order needs to be changed so that `MapManager` executes before both `Room` and `Unit`. Otherwise, `MapManager.rooms` and `MapManager.units` will both be null when the `Room.Awake()` and `Unit.Awake()` functions are called, resulting in a `NullReferenceException`.

---

> It seems like it would be easier to do maybe a Physics2D.OverlapBoxAll() somehow for the room, and check for colliders within my quad. But I'm not clear if (a) this -- or your Polygon implementation -- necessitates having RigidBodys for everything, and (b) what is more performant, academically, versus looping through each room for each character until it's found?

None of the `Physics.Overlap____` methods require `Rigidbody` components to be attached to the objects with the colliders. The `Rigidbody` component is for handling physics - which we aren't really doing here. We're simply using the colliders as a means to bypass the math involved in determining the intersections of 3D shapes. Since i assume there are more units than rooms, and the only complicated maths would come from irregularly shaped rooms, it makes more sense to only have colliders attached to irregularly shaped rooms, and to simply test the world position of each unit against the bounds of each room.

As to the second part of your question, you can have multiple methods of searching. For example, if you want to know which room a given unit is in, you only need to loop through the list of rooms, testing the given unit against each of them. If you want to know all of the units inside a given room, it is going to be a bit more expensive, but depending on how many units you have at a given moment, it's probably going to be cheaper to just call `Room.IsInRoom()` hundreds of times than having to redesign the system to work where every frame each unit checks for collisions with colliders you would then need to attach to each room.

---
Tags: unity, 2d, collision-detection, performance, npc
---


# Question
Title: Blend different biomes using linear interpolation
I've been scouring the internet for hours looking for a solution to blending biomes that have different amplitudes and frequencies together to create a seamless world. A recurring theme I'm seeing is that they have solved it by using linear or bilinear interpolation. I'm having trouble finding an implementation that would work for me.

Currently each biome is the same noise function but with adjusted frequencies and amplitudes to create variation. The problem is that it would result in "seams" between biomes, for example the plains and a mountains biome.

I think I understand how linear interpolation works. I have functions for it as well, but I'm confused as how to implement it. The game is essentially a 2D Minecraft type game. Would I have to determine the neighboring biomes by doing additional calculations across the x axis for every single block? I'm worried about performance if I somehow do this method.

I'm not sure if this would help but biomes are just determined using three instances of 1D noise, depth, temperature and rainfall. Depth is really just for oceans, but rainfall and temperature determine the biome. I have this basic setup (probably not the best code)

```
if(biome === 'desert') {
    frequency = 0.09;
    amplitude = 8;
    elevation = 65;
  } else if(biome === 'mountain') {
    frequency = 0.1;
    amplitude = 20;
    elevation = 65;
  } else if(biome === 'tundra') {
    frequency = 0.08;
    amplitude = 7;
    elevation = 65;
  } else if(biome === 'spruce') {
    frequency = 0.01;
    amplitude = 4;
    elevation = 65;
  } else if(biome === 'plains') {
    frequency = 0.08;
    amplitude = 8;
    elevation = 65;
  } else if(biome === 'forest') {
    frequency = 0.008;
    amplitude = 7;
    elevation = 65;
  } else if(biome === 'ocean') {
    frequency = 0.2;
    amplitude = 9;
    elevation = 30;
  } else if(biome === 'icy ocean') {
    frequency = 0.2;
    amplitude = 9;
    elevation = 30;
  }

  var height =
  (this.biome.noise.terrain.value(xt * frequency) * amplitude) + elevation;

```

# Answer
**Globally uniform chunk boundaries**

Resolving those chunk edge discrepancies can be done without interpolation. I would suggest using a global function (e.g. 2D Perlin) to define chunk edge heights, so that all chunk edges (at least) align. This is basically like having a series of empty buckets with each neighbour pair of bucket sides having matching heights:

```
|
|        ||
|   ||   ||        |
|___||___||___||___| etc.

```

Then you can generate each chunk's internals (`___`) using a different function per biome, if you wish, just as long as the boundary heights are respected (so that they link up seamlessly). Or you can use the same function e.g. Perlin for all internals, but adjust them through scaling or clipping.

**Generating along a smooth slope**

However, you still have the problem of finding a function that agrees with those preset edges. Here's one solution.

Let say you start with a straight slope (grey) between two edges (red). You can perturb these surface cells (grey to black).

You can do repeated random perturbations like this, then apply something the algorithm here to ultimately get a smoothly undulating surface between points.
> 1 votes

---
Tags: 2d, javascript, procedural-generation
---


# Question
Title: Lighting large scene with dynamic lights - Unity3D
I am working on a game project where most of the action takes place in a large scene that is built to look like a space station. Because it is all technological and enclosed, I can't use a directional light to light the whole scene, and I need to be able to change the color of the lights for an alarm system. I can't bake the lights, because then I can't change their color, and I can't leave them all as dynamic lights, because I have about fifty spot-lights, and they take up a huge amount of memory, so much so that the lights can't even render on mobile devices.

Is there any way to do this without baking?

I am getting about 3000 batches in the Unity Editor Stats on average, in some places it is higher. Even viewing the game in full screen in the editor makes the game run super slow because of the amount of rendering it has to do, and I have a pretty new computer.

Here's a picture of my scene (As you can see, it is fairly large as you are able to see the UI box clearly from the scene editor):

And here's the Stats box:

Here is an example of my scene in play mode:

**UPDATE:** I removed the shadow casting, which isn't necessary for my project, and it improved the framerate slightly, and the batches number is smaller, averaging out at about 1500 now, but the performance still is not optimal.

# Answer
I ended up using occlusion culling like a few people suggested in the comments. It worked wonders for my situation.

Setting it up is very simple as well.

First, you have to mark everything you want to occlude other objects as occluder static, and everything that can be occluded as occludee static:

In my situation, my whole station doesn't move, so everything but the lights was marked as static already.

Second, you open the Occlusion Culling window (**Window-\>Occlusion Culling**)

If needed, you can alter the values, but the default values worked perfectly for me, then click bake!

Wait a few seconds, and that's it. You're done! You can view the occlusion culling real-time from the visualization tab while you play the game, and it's as simple as that. (Though there are options to occlude moving objects if that is necessary. You'll have to look at the full manual for that though. I didn't need to do any of that.)

Performance is great now. I have reduced it in most areas from 3000 batches to anywhere from 5 to 500, based on where you are facing in the game. Thanks for the helpful comments!
> 4 votes

# Answer
I know you don't want to use baked light, but you may be interested in LightProbes technique from unity. Here you can find more information about it https://docs.unity3d.com/ScriptReference/LightProbes.html

Here more examples of lights in unity http://www.edy.es/dev/docs/unity-5-lighting-cookbook/

I think you can achieve nice looking effect with combination of different types of light.
> 0 votes

# Answer
Not sure what's available with unity, but I think you could achieve the same effect with an emission map (think a texture that supplies additional values used to decide the rgb for the texture -\> and then in your shader you parameterize and intensity variable and you can get it to go on/off on parts of the object).

From there, if you have some bloom effect (which I guess would be global to the scene), I think it'd probably be decent looking. Maybe put a dynamic light behind some important lights if you need it
> 0 votes

---
Tags: unity, lighting
---


# Question
Title: Why do asymmetric specular highlights appear in a scene with only ambient lighting in Unity?
I have a scene in Unity (2019.3.0f3 Personal) using the High-Definition Render Pipeline. There are no lights in the scene, and Baked Global Illumination is disabled. The skybox is a `GradientSky`. By all means, the lighting in the scene should be absolutely uniform, but instead there is a gradient from one side to the other.

This is what the scene looks like:

Though the effect is faint, you can see that the right side of the plane is slightly lighter than the left. The ground shader is `HDRP/TesselationLit`, and by bringing the `Smoothness Remapping` to max I can exaggerate this effect, as shown below. This is why I am under the impression the effect is specular in nature.

Interestingly, if I switch the camera to the Isometric mode, the effect disappears:

Finally, the effect appears to occur in world rather than camera space, as shown by the changes in lighting when I rotate my camera in increments of 90 degrees:

What is causing this effect, and how can I disable it?

# Answer
I ended up solving the problem on my own. The texture type of normal map for the material assigned to the ground was set to `Default`, and setting it to `Normal map` resolved the problem. Duh...
> 1 votes

---
Tags: unity, graphics, lighting
---


title: How to create a refill system over time

text:
# Question
Title: How to create a refill system over time
I am making an energy beam firing system from a drone. In my code, I have setup a system in which the player presses and holds onto the firing button, then a countdown bar begins to countdown, and when it is empty(down to 0), the energy beam stops firing, then the button waits for sometime before it can be pressed again. All of these works fine but, my problem is: Assuming the countdown bar is not yet empty(maybe half way through), it gradually refills itself to maximum. I've tried to work on it, but I keep getting glitches on the countdown bar. How do I go about this?

EDIT: While the player presses and holds the fire button, the countdown bar begins to count down, then when the player let's go of the button about halfway through the countdown, the countdown bar gradually fills up as expected, now before the countdown bar is filled, if the player presses the fire button again, the countdown bar quickly increases(\*here is the glitch) then resumes countdown again.

Here is my code:

```
[SerializeField] private float EnergyBeamPowerOffTime = 14; //Get this value from the hanger
[SerializeField] private float TimeToRefillEnergy = 10f;
[SerializeField] private GameObject EnergyBeamCountdown;
private Slider EnergyBeamCountdownBar;
[SerializeField] private Image EnergyBeamButtonImage;

public float EnergyBeamFillRate; //This value should be handled when the player upgrades their ships

private float EnergyBeamActiveTime;
private float EnergyRefillRate;

private bool EnergyCoroutinePaused;
private bool FiringEnergyBeam;
private bool CoolEnergyBeamDown;
private bool CoolEnergyBeamButtonDown;
private bool RefillEnergy;

private void Update()
{
    EnergyBeamSetting();
}

public void OnDownShootEnergyBeam()     //Let's the user click and hold on this button
{
    //PlaceHolders.energyBeamFiringSFX.Play();      //Play the sound effects
    droneBrain.OnDownShootEnergyBeam();     //Fire beams towards a target returned by a raycstHit(Irrelevant to this code logic)
    FiringEnergyBeam = true;        //Lets the countdown bar know that we started firing energy beams
    StartCoroutine(EnergyBeamRoutine());        //Begins the energybar coroutine
}

public void OnUpShootEnergyBeam()       //Called when the user lets go off the button
{
    droneBrain.OnUpShootEnergyBeam();   //Stops firing energy beams(Irrelevant to this code logic)
    FiringEnergyBeam = false;       //Lets the countdown bar know that we started firing energy beams
    if (EnergyBeamActiveTime > 0f)
    {
        EnergyBeamButtonImage.raycastTarget = true;     //Allow this button to be pressed again
        EnergyCoroutinePaused = true;       //Pause coroutine execution
    } else
        EnergyCoroutinePaused = false;      //Resume coroutine execution
    ObjectivesChecker.NumberOfTimesEnergyBeamWasFired++;    //Increase the number of times the energybeam was fired(Irrelevant to this code logic)
}

public void OnUpShootEnergybeam()       //Called when the user lets go off the button
{
    RefillEnergy = true;        //Begin to refill energy bar
}

private void RefillEnergySettings()
{
    if (RefillEnergy && !FiringEnergyBeam)
    {
        EnergyRefillRate = 0f;      //Resets the rate of energy beam's refill
        EnergyRefillRate += Time.deltaTime;
        float Percent = EnergyRefillRate / TimeToRefillEnergy;
        EnergyBeamCountdownBar.value = Mathf.Lerp(EnergyBeamCountdownBar.value, 1, Percent);
        //EnergyBeamActiveTime = Mathf.Clamp(EnergyBeamActiveTime, EnergyBeamCountdownBar.value, 0);
        EnergyBeamActiveTime = Mathf.Lerp(EnergyBeamCountdownBar.value, 0, Percent);
        if (EnergyBeamCountdownBar.value >= 1)
            RefillEnergy = false;
    }
}

private IEnumerator EnergyBeamRoutine()
{
    CoolEnergyBeamDown = true;      //Lets the countdown(Energy remaining in the energy beam) begin countdown
    EnergyBeamButtonImage.raycastTarget = false;    //Won't allow Energybeam button to be pressed
    if(EnergyBeamActiveTime > EnergyBeamPowerOffTime && !EnergyCoroutinePaused)
    {
        EnergyBeamActiveTime = 0f;
    }
    EnergyBeamCountdown.gameObject.SetActive(true);     //Makes the countdown visible
    yield return new WaitWhile(() => CoolEnergyBeamDown);   //Waits untill CoolEnergyBeamDown is false
    //Here, the beam has finished firing, we deactivate it then load the button
    EnergyBeamCountdown.gameObject.SetActive(false);    //Makes the countdown invisible
    droneBrain.OnUpShootEnergyBeam();   //stops firing energy beam
    //Now we load the button
    EnergyBeamButtonImage.fillAmount = 0f;  //resets the energybeam button's inactivity timer
    CoolEnergyBeamButtonDown = true;    //begins to prepare the energybeam button to fire again
}

private void EnergyBeamSetting()
{
    if (CoolEnergyBeamDown && FiringEnergyBeam)     //Conditions for the countdown bar
    {
        //Countdown(Energy beam's energy)
        EnergyBeamActiveTime += Time.deltaTime;
        float Percent = EnergyBeamActiveTime / EnergyBeamPowerOffTime;
        EnergyBeamCountdownBar.value = Mathf.Lerp(1, 0, Percent);
        if (EnergyBeamCountdownBar.value <= 0)
            CoolEnergyBeamDown = false;
    }

    if (CoolEnergyBeamButtonDown)       //Wait time conditions before the button can be used again
    {
        //Countdown for the energybeam button to prepare next fire
        EnergyBeamButtonImage.fillAmount += 1f / DroneBrain.EnergyWaitTime * Time.deltaTime;
        if (EnergyBeamButtonImage.fillAmount >= 1f)
        {
            EnergyBeamButtonImage.fillAmount = 1f;
            CoolEnergyBeamButtonDown = false;
            EnergyBeamButtonImage.raycastTarget = true;
            EnergyBeamActiveTime = 0f;
        }
        else
            EnergyBeamButtonImage.raycastTarget = false;
    }

    RefillEnergySettings();
}

```

# Answer
I'm sorry, but the script in the question tries to do so many things at once in such a convoluted way that I gave up trying to understand how it works. So I decided to just rewrite it from scratch.

This script simply manages the value `Charge` between 0.0f and 1.0f. When the player presses space, the charge gets depleted and the property `IsFiring` is true, otherwise `IsFiring` is false and the charge recovers. When the charge ever reaches zero, then the script enters an `IsOverheating` state where firing isn't possible. These three variables `Charge`, `IsFiring` and `IsOverheating` are exposed as public properties, so they can be used by other scripts.

```
using UnityEngine;

public class Recharge : MonoBehaviour {
    // values to set up in inspector (with reasonable defaults)
    [SerializeField]
    private float dechargeRate = 0.6f; // decharge per second when the player presses space
    [SerializeField]
    private float rechargeRate = 0.4f; // recharge per second when the player releases space
    [SerializeField]
    private float recoveryTime = 1.0f; // time in seconds until firing is possible after the bar was completely depletedafter the bar was completely depleted
    // exposed properties to be used by other classes
    public float Charge { get; private set; }
    public bool IsFiring { get; private set; }
    public bool IsOverheating { get => recoveryTimeLeft > 0.0f; }
    // internal state
    private float recoveryTimeLeft = 0.0f;

    void Update() {
        // check if the conditions for firing are met
        if (Input.GetKey(KeyCode.Space) && recoveryTimeLeft <= 0.0f && Charge > 0.0f) {
            // if yes we are firing
            IsFiring = true;
            Charge -= dechargeRate * Time.deltaTime;
        } else {
            // if no we are recovering
            IsFiring = false;
            Charge += rechargeRate * Time.deltaTime;
            recoveryTimeLeft -= Time.deltaTime;
        }
        // check for over-depletion
        if (Charge < 0.0f) {
            recoveryTimeLeft = recoveryTime;
        }
        // do not allow charge or recovery time to get negative or larger than 1.0
        Charge = Mathf.Clamp01(Charge);
        recoveryTimeLeft = Mathf.Clamp(recoveryTimeLeft, 0.0f, recoveryTime);
    }
}

```

But now you might wonder "Where did the UI stuff go?".

I moved this to a separate script. It is always a good idea to decouple your game mechanics from your visualization. This keeps your code easier to read and makes it easier to change one without having to also change the other.

This script requires that you assign an `Image` to control and a `Recharge` component to obtain the current state from. It visualizes the current shooting state with the color. Green for ready to fire, Blue for firing and Red for overheat.

```
using UnityEngine;
using UnityEngine.UI;

public class RechargeUi : MonoBehaviour
{
    public Recharge recharge;
    public Image rechargeBar;

    void Update()
    {
        rechargeBar.fillAmount = recharge.Charge;

        if (recharge.IsFiring) {
            rechargeBar.color = Color.blue;
        } else if ( recharge.IsOverheating ) {
            rechargeBar.color = Color.red;
        } else {
            rechargeBar.color = Color.green;
        }
    }
}

```

If you have any other UI-related stuff which is supposed to depend on the current recharge state (the script in the question mentions a "EnergyBeamButtonImage", for example), this should likely also go here.

But if you have any game mechanics which depend on the recharge mechanics (like actually damage objects in the game) those should go into a separate script.
> 1 votes

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


title: Simulate wind in a powder game

text:
# Question
Title: Simulate wind in a powder game
I would like to create a game similar to powder game.

I've got a 2d array that stores different types of powder such as sand, water, gas, and fire. I've managed to get these to all move around successfully.

I would now like the powders to react to wind. For example if there is fire it should push air upwards. If the air is moving upwards it will move other bits of powder around.

The way I've been trying is to have two more 2d byte arrays. One for the wind `x` direction and another for the wind `y` direction. The fire will then add an amount to the cells and each update will add the wind x and y to the piece of powder that is on that cell. This almost works but pushes the powder much to fast.

The difficulty in doing this is that the powder is on a grid while the wind could be going a variety of directions.

What is the most efficient way of doing this?

# Answer
> 1 votes
I believe the problem you are experiencing is that while wind can blow in any direction from 0 to 360 degrees, your particles can only move aligned to the grid you've established. To remedy this, I would give each particle a real `position`, but snap each particle to your grid. That way, diagonal movements are still accounted for, but they don't cause particles to misalign with other particles.

For example, let's say a particle is resting at the bottom of your level. We'll say its `worldPosition` is (14, 0). We'll say that each particle is 3 pixels wide, and so the particles snap to the grid in increments of 3, putting our particle's `gridPosition` at (4, 0).

Then, a `force` acts on the particle, translating it by (2, 2). Our particle's new `worldPosition` is (16, 2), and its new `gridPosition` moves to (5, 0).

Over time, `gravity` would act and bring the particle back down to rest on the floor at `worldPosition` (16, 0). However, its `gridPosition` remains at (5 , 0).

Basically, you're storing and operating on all the relevant physics information within the `worldPosition`, then organizing and displaying it to the player at `gridPosition`. That way you can operate "between" cells without your game falling apart.

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


title: 'Destroyed Actors' and 'Save Games'

text:
# Question
Title: 'Destroyed Actors' and 'Save Games'
---

**Background**

Our team is creating an adventure platformer, and I have been tasked with creating a Save Game system.

Our game features the usual progression systems, and is relatively linear.

---

**Approach**

I have began my approach by using the *EMS Easy Multi-Save plugin* for *Unreal*.

---

**Problem**

We have a 'Switch' system:

* Player takes cube to switch.
* cube gets used by switch
* switch can now be activated.

In stage 2, where the cube is used by the switch - the actor for the cube is destroyed in Unreal, and the switch's model is changed to one with a switch.

The EMS plugin does not provide plug-and-play functionality for keeping track of destroyed actors, which means I must do this myself.

---

**Example problem scenario**

* Player approaches area with switch and cube.
* Player saves game (cube present and switch deactivated)
* Player picks up cube and takes to switch (cube destroyed and switch activated)
* Player loads prior save game
* Scene reloads with **switch** in the correct state, however the **cube** is no longer present (it has been destroyed by Unreal and is no longer tracked by EMS)

---

**Problem solving approach**

Reading around, I have been given the idea of creating my own class that keeps track of destroyed actors when they are destroyed.

This class can be saved by EMS, and then can reload these destroyed actors if needed when a game is loaded.

---

**Question**

There is a lack of real advice for the task at hand here, so I wanted to come here and ask for people's advice and opinions on the best approach to making Destroyed Actors within Unreal compatible with Save Games.

# Answer
> 1 votes
I'am the developer of EMS. There have been several different approaches in handling destroyed Actors with my plugin.

1. Fake destruction by turning the Actor off. Disable collision, tick and hide it. Just save a bool to check and turn it off again on the Actor Loaded event.
2. Maintain a list of Actors in your level blueprint(Or your own class) that is saved/loaded, a simple name array will do it. On destruction, the Actor is added to the list. On level start, you iterate through the list and destroy the Actors in it. If you have a huge amount of Actors, you might want to defer destruction using Lifespan.

I hope this helps.

---
Tags: c++, architecture, software-engineering, unreal-4
---


# Question
Title: Unity Script and game not syncing after player respawn
I have a health system for my player that looks like this:

```
public int fallBoundary = -10;
public int Health;
public int numOfHearts;

public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;

void Update() {
    if(Health > numOfHearts) //Health script works, why does heart display not?
    {
        Health = numOfHearts;
    }

    for (int i = 0; i < hearts.Length; i++) {
        if (i < Health) {
            hearts[i].sprite = fullHeart;
        } else {
            hearts[i].sprite = emptyHeart;
        }

        if (i < numOfHearts) {
            hearts[i].enabled = true;
        } else {
            hearts[i].enabled = false;
        }
    }
}

```

Unfortunately, after respawn, the hearts do not sync anymore. My debugging showed, that the elements of `hearts` still did their job, resetted and got replaced correctly. However, in my game, nothing changes after the respawn (should reset to full health and change if player gets damaged). For the respawn, I am loading my prefab, which I also checked (everything is there). To avoid confusion: my hearts never reset to 0, but stay at 1.

Player Prefab that loads during respawn

Hearts after respawn

# Answer
How I normally handle this type of thing is by having my player script store and operate on properties like `Health`, and then have a separate script attached to a Canvas object that simply reads those properties from the player script and displays them on the UI.

Normally, the player script would look something like this...

```
// Attach this script to the player object
public class Player : Monobehaviour
{
    public static Player ins {get; private set;} // keep a static reference to the current player instance - otherwise known as the Singleton pattern
    public float currentHealth {get; private set;}
    public float maxHealth {get; private set;}
    public float healthPct
    {
        get
        {
            if (maxHealth <= 0) return 0;
            return currentHealth / maxHealth;
        }
    }

    void Awake()
    {
        // if there is already a player object, destroy it
        if (ins != null)
        Destroy(ins.gameObject);

        // set the current player object to this one
        ins = this;
    }

    void Update()
    {
        // Here, we edit the values of the player's stats.
        // We do not display them, all of that is handled within the PlayerHUD script.

        if (currentHealth > maxHealth)
            currentHealth = maxHealth; // clamp health to maximum
        else if (currentHealth < 0)
            Destroy(gameObject); // player death
    }
}

```

...And the HUD script something like this...

```
// Attach this script to a game object nested within a canvas and attach the necessary components to it
public class PlayerHUD : Monobehaviour
{
    public Text healthText;
    public Image healthBar;
    public const float healthBarLength = 500;
    public const float healthBarHeight = 20;

    void Update()
    {
        // Here, we read the values of the player's stats and display them however we like.
        // We do not edit them in any way - all of that is handled within the player script.

        if (Player.ins != null) // check if there is a player object in the scene - important so that no errors are thrown between respawns
        {
            healthText.text = Player.ins.currentHealth.ToString("F0"); // display the numerical value of the player's current health
            healthBar.rectTransform.sizeDelta = new Vector2(Player.ins.pctHealth * healthBarLength, healthBarHeight); // adjust the size of the health bar
            healthBar.color = Color.HSVtoRGB(Player.ins.pcthealth * 0.5f, 1, 1); // adjust the color of the healthBar
        }
    }
}

```

This way, you know that any inconsistency with the stat values themselves is being caused by the player script, and any inconsistency with the way the stats are displayed is being caused by the HUD script. With it narrowed down, you can attach a debugger to Unity and step through the code line-by-line to figure out what the issue is.
> 1 votes

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


# Question
Title: Unexpected behavior of bodies affected by gravity in 2D
I have a simple code that calculates the acceleration of a body every update of my simulation using the Newton's law of universal gravitation and the second law of motion.

```
def move_bodies():
    def get_dist(b1, b2):
        return math.hypot(b2['x'] - b1['x'], b2['y'] - b1['y'])

    for body in bodies:
        acceleration = 0
        angle = 0

        for other_body in bodies:
            dist = get_dist(body, other_body)

            if body != other_body:
                angle = math.atan2(other_body['y'] - body['y'], other_body['x'] - body['x'])
                acceleration = (GRAVITY_CONSTANT * body['m'] * other_body['m'] / dist ** 2) / body['m']

            body['x'] += math.cos(angle) * body['vx']
            body['vx'] += acceleration

            body['y'] += math.sin(angle) * body['vy']
            body['vy'] += acceleration

```

when these bodies interact, something unexpected happens when their x/y values are approaching one another -- the bodies move at extremely high speeds and seemingly disappear off the screen.

For example, if we have a body at (200, 100) and another at (200, 300), they do not gravitate towards one another as they would do in a situation where they have unique (x, y) values such as (200, 100) and (300, 400).

Looking at the code, as the y-values of `body` and `other_body` approach one another, values get exceedingly large(?)

I can't quite pin down the issue as I'm a beginner. Any suggestions/criticism?

# Answer
I'm on my phone and can't provide a super detailed answer, but here goes.

This answer will not cover the physics calculation that you use, only the logic.

It looks like there is trash data in your loop.

When evaluating a body with itself, you do not update the angle and the acceleration, it remeains to what was used with a previous body. Whatever is in there is still used with the body influencing itself.

I would expect that bodies don't influence themselves in that loop, so perhaps it should look a bit more like this:

```
def move_bodies():
    def get_dist(b1, b2):
        return math.hypot(b2['x'] - b1['x'], b2['y'] - b1['y'])

    for body in bodies:
        for other_body in bodies:
            if body == other_body:
                continue

            dist = get_dist(body, other_body)
            angle = math.atan2(other_body['y'] - body['y'], other_body['x'] - body['x'])
            acceleration = (GRAVITY_CONSTANT * body['m'] * other_body['m'] / dist ** 2) / body['m']

            body['x'] += math.cos(angle) * body['vx']
            body['vx'] += acceleration

            body['y'] += math.sin(angle) * body['vy']
            body['vy'] += acceleration

```

As a final note: this will most likely give inacurate results. As you update the x and the y values of bodies during the loop, you change how the next bodies are influenced by it.

A more accurate approach would be to use the "current position" to do the calculations, and to store it somewhere else for further processing:

```
def move_bodies():
    def get_dist(b1, b2):
        return math.hypot(b2['x'] - b1['x'], b2['y'] - b1['y'])

    for body in bodies:
        for other_body in bodies:
            if body == other_body:
                continue

            dist = get_dist(body, other_body)
            angle = math.atan2(other_body['y'] - body['y'], other_body['x'] - body['x'])
            acceleration = (GRAVITY_CONSTANT * body['m'] * other_body['m'] / dist ** 2) / body['m']

            body['x_sum'] += math.cos(angle) * body['vx']
            body['vx_sum'] += acceleration

            body['y_sum'] += math.sin(angle) * body['vy']
            body['vy_sum'] += acceleration

    for body in bodies:
        body['x'] = body['x_sum'] / (len(bodies) - 1)
        body['vx'] = body['vx_sum'] / (len(bodies) - 1)

        body['y'] = body['y_sum'] / (len(bodies) - 1)
        body['vy'] = body['vy_sum'] / (len(bodies) - 1)

        body['x_sum'] = 0
        body['vx_sum'] = 0

        body['y_sum'] = 0
        body['vy_sum'] = 0

```
> 1 votes

---
Tags: 2d, physics, python
---


title: Game states and events

text:
# Question
Title: Game states and events
I'm writting a game in C++ and I'm struggling with getting events and game states work together.

By game states I mean something like this

```
class GameState
{
public:
    virtual void onPause();
    virtual void draw();
    virtual void update();
};

class PauseScreen : public GameState
{
     //stuff
};

class Game : public GameState
{
     //stuff
};

```

And I've created dope event observer based system where I have simple EventObserver class which has register function to what Event I want to subscribe and EventManager where I have map of vectors of all possible EventObservers (everything made with templates) and callback functions. No pointers, no inheritance - everything works like charm.

So there is my problem - how to connect these? In my main loop I'm getting current active game state - and then updating and drawing it. But for example when state is not active its still receiving event. This is pretty bad beacuse if I have MainMenu gamestate and for example if escape key is pressed it would just exit the game even if I'm currently in Game.

I could only came with some bool checking - if current state is not more active it would disable all EventListeners but I would need to manually call EventListener::disable in all game states for every EventListeners I have in onPause() methods and I don't like this solution (and since it's my hobby project I would like things that I like). I could store EventListeners in vector in GameState interface class so I wouldn't need to disable it manually and just iterate thought it and disable it 'automatically' but I would have to deal with A LOT of templates and naaah I don't wanna do it (just keep it simple).

On the other hand I could add method to GameState handleEvent(Event\* event) (well since this is now dynamic memory I would probably prefer to use smart pointers so I don't need to worry when I have to delete event) but then I would have giant switch statement for every game state that I have and this also doesn't seems like good solution. Now I'm just binding one method per one event so everything is nice divided and simple.

So any tips how to design this? Can event observers (or subscribers) work with game states?

# Answer
> 1 votes
I don't have the luxury to write a full answer, unfortunately, but here it is, at a glance. Note that there seems to be some fundamental architecture differences between what we have and what you have, but here goes.

First, when we enter a game state, we register `this` as a listener to the events in which the game state is interested; we kind of have a mechanism to auto-de-listen using smart pointers, so when we exit the state (or it's paused), we de-register `this` for these events. ...and we register the new events for the new state, etc... This takes care of things that if you hit "escape", then only one state will be listening to it.

This is coupled to a special feature for our input manager. Some key events can have a special meaning depending on what's going on. For instance, if you hit "A" during the "normal gameplay", it will interact with the environment, but if there is a pop-up, we need "A" to do something else instead (like close the pop-up), even if we're in the same game state as before. To achieve this, the input manager has a concept of 'context'. At the beginning of the state, we supply the different contexts for that state, like "in game", "pop-up". Each context as a priority, and each context can be enabled or disabled, the "pop-up" one having a higher priority, but being disabled at the beginning of the state.

Once we show the pop-up, we enable the "pop-up" context in the input manager, thus when the user presses "A", it does something related to the pop-up only, because the event is steered there instead of going to the game state. Once we hide the pop-up, we disable the context.

I'm not sure this solves your issue, but I hope it will give you some ideas.

---
Tags: c++, architecture, events, game-state
---


title: Unity: Car Rollover Protection

text:
# Question
Title: Unity: Car Rollover Protection
I have a standart Unity car with Unity Car physics. What would be the best approach to protect my car from a rollover?

I dont want to mess up and try and error 10 different approaches, so maybe here is an expert who really knows how to do it right?

I couldnt find anything decent on the internet.

# Answer
Ideally use AddRelativeTorque. In its simplest form, flip the car on its Z axis when the car is upside down.

```
RigidBody RB = ...;
float flipStrength = 1f;

if (Mathf.Abs(transform.localRotation.eulerAngles.z) > 90f) {
    RB.AddRelativeTorque(0f, 0f, flipStrength, ForceMode.Acceleration);
}

```
> 1 votes

# Answer
Quick and dirty: Just lock the x and z axis of the rigidbody. Now the car will always stay horizontal. But it also will have difficulties with ramps.
> 0 votes

---
Tags: unity, car
---


# Question
Title: How to translate prefab made of hierarchy of 3d objects
I am trying to translate a prefab of a puzzle piece made of a hierarchy of cubes but it's not working.

I have tried translating the GameObject using its transform and the function Translate, it did not move. And I have tried translating each child of the GameObject's transform as well and it did not move either. Looking at the transform position's value in the debugger showed that it did change however. Also "activeinHierarchy" is set to false and I am wondering if it could be the problem.

Here is the code for the second method:

```
enum NanoPieceType
{
    IPIECE,
    TPIECE,
    LPIECE,
    OPIECE
}

public class GameController : MonoBehaviour
{
    public GameObject INanoPiece, TNanoPiece, LNanoPiece, ONanoPiece;
    private NanoPieceType currentPiece;
    private int speed;

    void Start()
    {
        currentPiece = (NanoPieceType)Random.Range(0, 3);
        speed = 1;
        CreateNanoPiece((NanoPieceType)currentPiece, new Vector3(0f, 10f, 0f),
   new Quaternion(0f, 0f, 0f, 0f));

   }

   // Update is called once per frame
   void Update()
   {

        switch (currentPiece)
        {
            case NanoPieceType.IPIECE:
                MovePieceDown(INanoPiece);
                break;
            case NanoPieceType.LPIECE:
                MovePieceDown(LNanoPiece);
                break;
            case NanoPieceType.OPIECE:
                MovePieceDown(ONanoPiece);
                break;
            case NanoPieceType.TPIECE:
                MovePieceDown(TNanoPiece);
                break;

            default:
                break;
        }

   }

   void MovePieceDown(GameObject obj)
   {
        GameObject child = obj;

        child.transform.Translate(0f, -1.0f*Time.deltaTime, 0f);

        for (int i = 0; i < child.transform.childCount;i++)
        {
            GameObject newObj = child.transform.GetChild(i).gameObject;
            newObj.transform.Translate(0f, -1.0f * Time.deltaTime, 0f);
        }

    }
}

void CreateNanoPiece(NanoPieceType type, Vector3 pos, Quaternion rot)
{
    switch (type)
    {
        case NanoPieceType.IPIECE:
            Instantiate(INanoPiece, pos, rot);
            break;
        case NanoPieceType.LPIECE:
            Instantiate(LNanoPiece, pos, rot);
            break;
        case NanoPieceType.OPIECE:
            Instantiate(ONanoPiece, pos, rot);
            break;
        case NanoPieceType.TPIECE:
            Instantiate(TNanoPiece, pos, rot);
            break;

        default:
            break;
        }
    }
}

```

# Answer
> 0 votes
I'm sorry I just found that I had to attach a movement/translation script to the prefab, and then instantiate it in another script. I did this and it works.

I come from an UE4 background so this philosophy is entirely new to me.

---
Tags: unity, prefabs
---


# Question
Title: How can I implement a side scrolling seamless fog shader?
I've run into a problem trying to code a 2d game. The way I've set up the game is that you run through underground dungeons and fight enemies, for ambiance I've added a smoke/fog shader to superimpose over the dungeon backdrop. However, the noise/fog isn't seamless. As in, the fog is always the same even when moving through the map, it doesn't move with the player/camera.

How do I make it so the fog is generated whenever the camera moves sideways/upwards while still being seamless, as in fitting in with the fog from before moving the camera?

For example, when I move right, the fog background should move left, instead of being the same backdrop anywhere I am on the map.

The shader I've set up is based on this one from Morgan McGuire/patriciogv:

```
// Author @patriciogv - 2015
// http://patriciogonzalezvivo.com

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

float random (in vec2 _st) {
    return fract(sin(dot(_st.xy,
                         vec2(12.9898,78.233)))*
        43758.5453123);
}

// Based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 _st) {
    vec2 i = floor(_st);
    vec2 f = fract(_st);

    // Four corners in 2D of a tile
    float a = random(i);
    float b = random(i + vec2(1.0, 0.0));
    float c = random(i + vec2(0.0, 1.0));
    float d = random(i + vec2(1.0, 1.0));

    vec2 u = f * f * (3.0 - 2.0 * f);

    return mix(a, b, u.x) +
            (c - a)* u.y * (1.0 - u.x) +
            (d - b) * u.x * u.y;
}

#define NUM_OCTAVES 5

float fbm ( in vec2 _st) {
    float v = 0.0;
    float a = 0.5;
    vec2 shift = vec2(100.0);
    // Rotate to reduce axial bias
    mat2 rot = mat2(cos(0.5), sin(0.5),
                    -sin(0.5), cos(0.50));
    for (int i = 0; i < NUM_OCTAVES; ++i) {
        v += a * noise(_st);
        _st = rot * _st * 2.0 + shift;
        a *= 0.5;
    }
    return v;
}

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution.xy*3.;
    // st += st * abs(sin(u_time*0.1)*3.0);
    vec3 color = vec3(0.0);

    vec2 q = vec2(0.);
    q.x = fbm( st + 0.00*u_time);
    q.y = fbm( st + vec2(1.0));

    vec2 r = vec2(0.);
    r.x = fbm( st + 1.0*q + vec2(1.7,9.2)+ 0.15*u_time );
    r.y = fbm( st + 1.0*q + vec2(8.3,2.8)+ 0.126*u_time);

    float f = fbm(st+r);

    color = mix(vec3(0.101961,0.619608,0.666667),
                vec3(0.666667,0.666667,0.498039),
                clamp((f*f)*4.0,0.0,1.0));

    color = mix(color,
                vec3(0,0,0.164706),
                clamp(length(q),0.0,1.0));

    color = mix(color,
                vec3(0.666667,1,1),
                clamp(length(r.x),0.0,1.0));

    gl_FragColor = vec4((f*f*f+.6*f*f+.5*f)*color,1.);
}

```

# Answer
I figured out a solution, now I keep track of the cameraoffset/delta (xy distance the camera moved from the initial position) as a uniform vec2 and then add it to gl\_FragCoord.xy in main() Line #1
> 0 votes

---
Tags: opengl, glsl
---


# Question
Title: Adding Grass to a Low-Poly Mesh in Unity
How would I go about adding grass to a *low-poly* mesh in Unity?

---

Here is what I have looked into:

1. **Object2Terrain**: I am not using Unity's built in terrain system because I am going for a low-poly art style. I tried converting my terrain mesh object to a terrain (using Object2Terrain) however this removes the sharp edges on the terrain, because Unity uses a height map for optimization.
2. **PolyMesh**: From the get-go I knew this approach wasn't going to work. I knew it would be incredibly inefficient to render that many meshes at once. I still tried it though, and to no surprise, it was very laggy.
3. **Particle System**: From what I've read, this should work fine for randomly scattering grass over your mesh, however I do want some control when placing grass. I followed this tutorial image as suggested by a comment in this question on Reddit, however, I was never able to achieve the desired result. Nevertheless, I do want control over placing the grass, and so I moved onto another approach.
4. **Shaders**: I'm not experienced at all when it comes to creating (or even using) shaders, and it's quite a daunting topic to me. I've read that this is the most efficient approach, however haven't been able to understand how this means I could draw grass onto a mesh? On the same Reddit post linked above, "UpstairsCurrency" was kind enough to link their source code (here), however I'd like to understand what is happening? I'm reluctant to say that I'm not even sure I understand how to implement it into my project in the first place. Would appreciate any sources for reading up to help understand what is going on!

Thanks!

# Answer
For those interested, I found an asset on the asset store called Polaris, which is a low poly terrain engine.
> 0 votes

# Answer
One option is to use the terrain system for rendering grass but still use your low poly mesh for the terrain itself. Backwards as it may seem, your can turn off rendering the terrain in the terrain inspector. In the settings tab, under Basic Terrain, uncheck “Draw”
> 1 votes

# Answer
If you've already got the mesh that represents your terrain and you simply want to make it grassy, you can look into this tutorial by Roystan on how to make a geometry shader that generates blades of grass on the surface of the object. If you like the look of it but can't be bothered to follow the tutorial (I tried it myself and encountered many errors), there is a github repository linked in the tutorial that contains the completed shader code, and the necessary files are in the starter project - also linked.
> 0 votes

---
Tags: unity, blender, mesh, low-poly
---


# Question
Title: How to make a 3D mesh invisible in Godot?
Just like the title says i'm trying to make the mesh disappear after a set value reaches zero. Current code is trying to simply turn the entity invisible so that later i can implement a resurrect function.

```
if Sname == get_node("Entity").get_name():
    print("punched number 1")
    selected.health = selected.health - 10
    if selected.health <= 0:
        selected.health = 0
        get_node("Control/Button").disabled = true
        $Entity.visable = false

```

Is it even possible to toggle that value or is there an easier way to do this? I dont want to use free\_queue() as that would interfere with other entitys.

Thanks for the help in advance, im new to Godot so sorry if this ends up being a no brainer.

# Answer
You should set `$Entity.visible`, not `$Entity.visable`.
> 1 votes

---
Tags: godot
---


# Question
Title: How to smooth terrain to lower polygon count?
I'm using Unity. I've created a simple Beach using Terrain editor. The problem is that Stats show me already a lot of Triangles only for Terrain renderer: 40K .

So my question is: how can I create a Unity Terrain suitable for Mobile game ? How can I smooth terrain edge ?

Thanks

# Answer
> 6 votes
If you select your terrain and go to the last tab which is settings you will see a slider called 'pixel error'. That determines the accuracy of the mapping between the terrain maps and generated terrain. The higher the value, the lower the accuracy and rendering. The default should be about 5 which is why your number of tris is so high.

Increasing this slider should lower the tris and the rendering.

There are also resolution values you can alter, but they may lower the quality without affecting the tris like you want.

# Answer
> 0 votes
You can change your terrain to a lower HeightMap Resolution like 33, 65, 129. The lower the heightMap resolution, there are less points to interpolate in the mesh.

You could change the Pixel Error as one of the answers states but increasing the Terrain Pixel Error can lead to other side effects since it affects LOD. For example, when increasing the Pixel Error too much, you will see your terrain reshape as your camera approaches it.

This explains more on the pixel error. https://forum.unity.com/threads/understanding-implementation-of-terrain-pixel-error-setting.424622/

In short, been able to get the best results for using a LOW pixel Error value and a low heightMap resolution for a low polyish look for terrains.

---
Tags: unity, terrain-rendering
---


# Question
Title: How to reach IK Pass and weight by script?
I need to reach IK Pass box, and control the weight by time from 1 to 0. I tried GetLayerIndex and did not give me any of those options.

# Answer
> 1 votes
I don't think you are able to set the flag during runtime. You should tick the box in editor if you plan to use IK features and then during runtime use the weight to adjust behaviour.

GetLayerIndex only returns the layer index for that layer as integer. After you know it, you can use Animator.SetLayerWeight to adjust the layer weight.

---
Tags: unity, inverse-kinematics, animator
---


title: Adding a profile to a dialogue box

text:
# Question
Title: Adding a profile to a dialogue box
I am trying to create dialogue boxes that contain the profile picture of the speaking character in them. As such, I want the profile pic to be attached to the object itself. If I understand this right, the following creates a variable space for profilePic that I then populate within the GUI.

```

using UnityEngine.UI;

public class NPC : Character {

[SerializeField] private Image profilePic;
}

```

Then over in my dialogue script I have the following:

```
using UnityEngine.UI;

//This currently only allows for one sided conversations
//this can be later modified to add profile picture as well as several iterated conversations

public class Dialogue : MonoBehaviour {

    [SerializeField]
    private UnityEngine.UI.Text dialogueText;

    [SerializeField]
    private GameObject dialoguePanel;

    [SerializeField]
    private UnityEngine.UI.Image profilePic;

    private string[] dialogue;
    private int dialogueIndex;

    public void StartDialogue(string[] dialogue)
    {

        dialogueIndex = 0;
        this.dialogue = dialogue;
        dialoguePanel.SetActive(true);
        //This is what actually affects the GUI
        dialogueText.text = dialogue[dialogueIndex];
        this.profilePic = profilePic;

    }

```

The dialogue functions work. It should be taking the contents of this.profilePic and putting them into the UI.image profilePic component, right? The text works. The panel pops up. Just no picture.

Anyone have any thoughts?

# Answer
The problem that you have is that you are referencing an `Image` component in your scripts. `Image` is a component of `UnityEngine.UI` which main purpose is to draw `Sprite` in `Canvas`. When you are doing `this.profilePic = profilePic` you are saying that your variable should reference an `Image` component that you have passed to a method. But still you have a logical issue in your code, you don't even reference the component of an NPC, but you are referencing the same component. In a nutshell - `this.image = this.image;`.

`Sprite.Create` \- is costly operation and in this instance you can avoid it by directly referencing `Sprite` object.

```
public class NPC : MonoBehaviour
{
  [SerializeField] private Sprite npcSprite;
  public Sprite NPCSprite => this.npcSprite;
}

public class Dialogue : MonoBehaviour
{
  [SerializeField] private Image profilePic;

  ...

  public void StartDialogue(..., Sprite profilePic)
  {
    ...

    this.profilePic.sprite = profilePic;
  }
}

// Somewhere in code:
dialogue.StartDialogue(..., npc.NPCSprite);

```
> 1 votes

# Answer
you can re-create the sprite and set the size of the texture 2d being assigned to the pic.

```
                                                             //assign size to match ui pic
this.profilePic.sprite = Sprite.Create(tex, new Rect(0, 0, 128, 128), new Vector2(0, 0));

```
> 0 votes

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


# Question
Title: How do I remove the objects when it is not seen on the camera?
I am a beginner C# Developer and I am creating my own version of the "No Internet Dinosaur Game." How do I remove the Object like (Platforms, Cactus, etc.) When it is not seen on the camera?

# Answer
There are plenty of tutorials about infinite procedural generation. Usually they all have the behaviour of cleaning up objects that are left behind the player, and creating objects in front of the player when required. It can be done in multiple ways.

If you just want to know if the object is off screen or not, this question may help: Identify whether object is off screen or not

Simply put, easiest way: you keep track of all generated objects, generate a certain quantiy of platforms right away, so that they cover visibility from both sides. Keep track of point where player has been last time something was generated, when player moves some distance away from this last point = generate a new platform and delete platform from behind, usually it will be at 0 index in the list of all generated objects.

Infinite Runner in Unity - PLATFORM GENERATOR

Actually there are too many approaches, so: Youtube Search
> 1 votes

# Answer
Just add this script on the object you want to get destroyed as soon as it leaves view:

```
using UnityEngine;

public class DestroyWhenInvisible: MonoBehaviour {
    void OnBecameInvisible() {
         Destroy(this.gameObject);
    }
}

```

However, in many cases this will go a bit too far. There might be situations where an object becomes invisible for another reason than leaving the play area, for example when you start to implement fancier camera controls. So it can be useful to solve this with a different approach.

A common approach is to create a kind of "cleanup zone". A collider with "Is Trigger" enabled which is just outside of the play area and destroys any object that enters it. Here is an example script:

```
using UnityEngine;

public class CleanupArea: MonoBehaviour {
    void OnTriggerEnter(Collider other) {
         Destroy(other.gameObject);
    }
}

```

When the cleanup area ends up not cleaning up things it should or cleans up things it shouldn't clean up, then there are various reasons why this could happen. Check the Unity manual article on colliders, on layer-based collision detection for more information on how to correctly use trigger areas.
> 0 votes

---
Tags: c#, camera, platformer, frustum-culling
---


title: Understanding Send Message

text:
# Question
Title: Understanding Send Message
I'm trying to understand the Send Message Function but I'm a bit confused. Currently I have a game object character and I want it to send a message to the main body if one of its children hits something.

On the Child object, I have:

```
void OnTriggerEnter2D(Collider2D col) {

    Destroy(col.gameObject);
    Debug.Log(this.name + " Hit!");
    gameObject.SendMessage("PlayerHitting", this.name);

```

On the Parent Object, I have

```
public void PlayerHitting(string Move) {
    Debug.Log("Player hits with " + Move);
}

```

The Destroy code and Debug.Log on the Child work, so it is colliding, but I keep getting an error that there is no reciever.

```
SendMessage PlayerHitting has no receiver!
UnityEngine.GameObject:SendMessage(String, Object, SendMessageOptions)

```

I don't quite understand how to use Send Message to send messages and notices between objects. Can someone explain?

# Answer
I'm unable to reproduce this problem in a new project. I've set up a hierarchy like this:

* Parent object, "Body"
`Rigidbody2D`
`TriggerListener` (implements the "PlayerHitting" method)

+ Child object, "Collision Rep"
    `BoxCollider2D`
    `TriggerReporter` (calls `SendMessageUpwards("PlayerHitting", name)` in `OnTriggerEnter2D`)

When I move this object over a trigger shape, the listener script on the parent correctly reports the message received from its child "Collision Rep" and I do not see any "no receiver" errors.

So I'm not sure why it's causing this error in your scene. It could be that my example differs from what you're doing in some way. Can you edit your question to include a minimal complete verifiable example, so users can reproduce the problem exactly as you're seeing it?

---

However, **I think the best fix here is to not use `SendMessage` at all**.

This is a legacy feature in Unity, and modern versions of the engine have much better tools for solving similar problems. Some of the issues with `SendMessage`:

* **It's slow**, because it requires searching and reflection. Each time the message fires, Unity has to walk through each component on the object, check if it has a method matching this string, then invoke the method through reflection if so. For the "Upwards" version, it has to repeat this for every object up the hierarchy.
* **It's error-prone**, because it makes your code "stringly typed": one typo in the name can make the message fail to find its recipient, in a way that's invisible to your compiler and refactoring tools. The message will just fail and you'll be scratching your head as to why (much as you are now), with no tool support to help you find the issue. If you later choose to rename the method, your IDE can automatically update all direct calls to it no problem, but will miss updating any SendMessage strings, breaking all your messaging.
* **It's difficult to debug**, due to a combination of the two points above. Your control flow is now at the whims of the search routine and string comparisons, which tends to leave you with a very confusing call stack when you're trying to diagnose why a particular method is being called and where it's being called from.

For a situation like this, where there's a fixed relationship between the message-sender (the child) and the receiver (its parent), **I'd recommend using Events**.

First, I'd make an `enum` for your different move types, so these moves are *strongly*-typed instead of *stringly*-typed. This ensures any typos get caught at compile time, and they're faster to compare, `switch` over, map to arrays of outcomes/resistances, etc.

```
public enum MoveType {
    Punch,
    Kick,
    Headbutt
}

```

Now your trigger scripts can expose a dropdown field to select their move type, and an event to fire when their collider hits something:

```
using UnityEngine.Events;

public class MoveTrigger : MonoBehaviour {
    // Define a type of event that has a MoveType argument.
    [System.Serializable]
    public class MoveEvent : UnityEvent<MoveType> {}

    // Expose a MoveType drop-down in the inspector.
    public MoveType myMove;
    // Expose an event to fire when the trigger hits.
    public MoveEvent onTriggered;

    // When our trigger is activated, destroy what activated us and report to whoever is listening.
    void OnTriggerEnter2D(Collider2D other) {
        Destroy(other.gameObject);

        if(onTriggered != null)
            onTriggered.Invoke(myMove);
    }
}

```

Now in the inspector, you can wire up your `MoveTrigger` instances to call the parent's `OnMoveTriggered` handler method:

Advantages of this approach:

* No runtime searching / reflection: you've told the engine exactly where to address the message, so it can send it there directly at very little cost.
* No string matching: the references are explicit and visible to the compiler and refactoring tools, so they can catch typos before you run, and enforce consistency in naming as your project evolves and multiple contributors make changes.
* Flexible: you don't need to re-write your scripts when you want to direct the trigger message to a different recipient, or select just one recipient out of several that happen to have a method of the same name. You can control this precisely through the list of addressees in the event, customized per-instance.
> 3 votes

---
Tags: unity
---


# Question
Title: Trying to rotate a point around another point and it's not working
I am trying to make a function to rotate a point around another point. My maths are very rusty but i did some research and i just dont understand why my function is not working.

```
public void rotatePoint(int pX,int pY,int angle) {
    int newX = 0, newY = 0;
    int centerX = 400, centerY = 300;

    angle *= Math.PI / 180; // convert angle from deg to rad

    double rotatedX = Math.cos(angle)*(pX-centerX)-Math.sin(angle)*(pY-centerY) + centerX;
    double rotatedY = Math.sin(angle) * (pX-centerX) + Math.cos(angle) * (pY-centerY) + centerY;

    newX = (int)Math.round(rotatedX);
    newY = (int)Math.round(rotatedY);
}

```

On the image i just provide my original point is in grey. After a rotation of 90 or 180deg i would expect the point to arrive where the green ones are. They arrive where the red points are.

# Answer
It looks like your red points are rotated something like 60 degrees from your starting point, rather than the full 90 you expected. Let's investigate why that could be...

```
angle *= Math.PI / 180;

```

As we substitute in an initial value of 90 for `angle`, this translates to...

```
angle = angle * 3.141592653589 / 180.0
angle = 90 * 0.01745329251
angle = 1.57079632679

```

But wait, our `angle` variable is an integer, so we have to truncate to convert this floating point intermediate to an integer value we can store in this variable:

```
angle = 1 radian

```

Or about 57 degrees, which matches up to what we're seeing in your graph.

So, use a float or double as your intermediate:

```
double radianAngle = angle * Math.PI / 180.0;

```

And compute your sine and cosine ratios off of this fractional intermediate instead.
> 0 votes

---
Tags: mathematics, rotation
---


# Question
Title: Heir Class Constructor Throws CS7036 "No Argument Given" Exception
I'm trying to create a class that holds the data for an an attack, called `Attack`. I also have special attacks that have more properties, and so I wanted to create a different class that inherits all of the properties of `Attack` while adding some more, so I created a class called `Special` that inherits `Attack`.

This is what my class structure looks like:

```
public class Attack
{
    public Attack()
    {

    }

    public class Special : Attack
    {
        public Special()
        {

        }
    }
}

```

My compiler is okay with this. However, as soon as I try adding arguments to the constructor of the `Attack` class, for example...

```
public class Attack
{
    public Attack(float damage, float staminaCost)
    {

    }

    public class Special : Attack
    {
        public Special()
        {

        }
    }
}

```

My compiler throws an error:

```
Line 13: There is no argument given that corresponds to the required formal parameter 'damage' of 'Attack.Attack(float, float)'

```

I don't understand why I'm getting this error. I'm not calling `Attack(float damage, float staminaCost)`, so why is it giving me grief over arguments? I tried un-nesting the classes but it doesn't make a difference. I need the constructor for `Attack.Special` to take in different arguments. Can someone help me achieve this?

# Answer
By default, when `new SpecialAttack()` is called, before the `SpecialAttack()` constructor is hit, parent constructors are hit.

The language lets you omit/ignore typing the explicit call to the constructor, but that's only for no-arg `()` constructors.

Behind the scenes, the structure in the first example looks more like

```
public class Attack
{
    public Attack()
    {

    }

    public class Special : Attack
    {
        public Special() : base()
        {

        }
    }
}

```

If the parent only has one constructor, and that constructor has arguments, you have to tell the compiler how to invoke the parent constructor. Thankfully it's pretty easy regardless.

```
public class Attack
{
    public Attack(float damage, float staminaCost)
    {

    }

    public class Special : Attack
    {
        public Special(): base(0, 0)
        {

        }
    }
}

```
> 1 votes

---
Tags: c#, inheritance, exceptions
---


# Question
Title: My vertex cache for reusing vertices in marching cubes algorithm in unity fails for one case, but I cant figure out what case
I implemented the marching cubes algorithm in unity and wanted to reuse vertices instead of creating new ones for every triangle. I am looping through a 3D array of points as I generate the mesh in the order x y z. To cache the points for reuse I save the relevant vertices for each yz layer of cubes to reference for the next cubes, then after the y loop exits, I save the currentLayer as behindLayer so I can get the last vertex, along edge 8 in my case, from cache.

I'm using the diagram on the first page of this paper as my reference to numbering edges and vertices as well as the edgeTable and triTable: http://paulbourke.net/geometry/polygonise/

In the 3rd dimension of the cache arrays (currentLayer and behindLayer): edge 0 is stored in 0; 1 in 1; 4 in 2; 5 in 3; 6 in 4; 7 in 5; 8 in 6; 9 in 7; 10 in 8.

The exact issue I'm having is that there are double vertices in some intersections. In this example there are double vertices in the center intersection and the middle left intersection. These correspond to edges 8, 9, 10, or 11 as defined in the paper linked above.

```
public class MeshGenerator : MonoBehaviour {

private Vector3[] vertices;
private Vector3[] normals;
private int[] triangles;

public Mesh GenerateMesh(float[,,] pointCloud, float surfaceLevel, int borderedSize, int height) {
    Polygonize(pointCloud, surfaceLevel, borderedSize, height);
    Mesh mesh = new Mesh();
    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.normals = normals;
    return mesh;
}

public void Polygonize(float[,,] pointCloud, float surfaceLevel, int borderedSize, int height) {
    List<Vector3> vertList = new List<Vector3>();
    List<int> triList = new List<int>();

    int[,,] behindCache = new int[height, borderedSize, 9];
    int[,,] currentCache;
    for (int x = 0; x < borderedSize - 1; x++) {
        currentCache = new int[height, borderedSize, 9];
        for (int y = 0; y < height - 1; y++) {
            for (int z = 0; z < borderedSize - 1; z++) {
                int cubeIndex = 0;
                //0
                if (pointCloud[x, y, z + 1] < surfaceLevel) cubeIndex |= 1;
                //1
                if (pointCloud[x + 1, y, z + 1] < surfaceLevel) cubeIndex |= 2;
                //2
                if (pointCloud[x + 1, y, z] < surfaceLevel) cubeIndex |= 4;
                //3
                if (pointCloud[x, y, z] < surfaceLevel) cubeIndex |= 8;
                //4
                if (pointCloud[x, y + 1, z + 1] < surfaceLevel) cubeIndex |= 16;
                //5
                if (pointCloud[x + 1, y + 1, z + 1] < surfaceLevel) cubeIndex |= 32;
                //6
                if (pointCloud[x + 1, y + 1, z] < surfaceLevel) cubeIndex |= 64;
                //7
                if (pointCloud[x, y + 1, z] < surfaceLevel) cubeIndex |= 128;

                if (edgeTable[cubeIndex] != 0) {
                    int[] vertIndices = new int[12];
                    if ((edgeTable[cubeIndex] & 1) == 1) {
                        //Vertex 0
                        if (y > 0 && currentCache[y - 1, z, 2] != 0) {
                            vertIndices[0] = currentCache[y - 1, z, 2];
                        } else {
                            vertIndices[0] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x, y, z + 1), pointCloud[x, y, z + 1], new Vector3(x + 1, y, z + 1), pointCloud[x + 1, y, z + 1], surfaceLevel));
                            currentCache[y, z, 0] = vertIndices[0];
                        }
                    }
                    if ((edgeTable[cubeIndex] & 2) == 2) {
                        //Vertex 1
                        if (y > 0 && currentCache[y - 1, z, 3] != 0) {
                            vertIndices[1] = currentCache[y - 1, z, 3];
                        } else {
                            vertIndices[1] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x + 1, y, z + 1), pointCloud[x + 1, y, z + 1], new Vector3(x + 1, y, z), pointCloud[x + 1, y, z], surfaceLevel));
                            currentCache[y, z, 1] = vertIndices[1];
                        }
                    }
                    if ((edgeTable[cubeIndex] & 4) == 4) {
                        //Vertex 2 - Dont Cache
                        if (y > 0 && currentCache[y - 1, z, 4] != 0) {
                            vertIndices[2] = currentCache[y - 1, z, 4];
                        } else {
                            vertIndices[2] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x + 1, y, z), pointCloud[x + 1, y, z], new Vector3(x, y, z), pointCloud[x, y, z], surfaceLevel));
                        }
                    }
                    if ((edgeTable[cubeIndex] & 8) == 8) {
                        //Vertex 3 - Dont Cache
                        if (y > 0 && currentCache[y - 1, z, 5] != 0) {
                            vertIndices[3] = currentCache[y - 1, z, 5];
                        } else {
                            vertIndices[3] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x, y, z), pointCloud[x, y, z], new Vector3(x, y, z + 1), pointCloud[x, y, z + 1], surfaceLevel));
                        }
                    }
                    if ((edgeTable[cubeIndex] & 16) == 16) {
                        //Vertex 4 - Leading Edge
                        vertIndices[4] = vertList.Count;
                        vertList.Add(LerpVert(new Vector3(x, y + 1, z + 1), pointCloud[x, y + 1, z + 1], new Vector3(x + 1, y + 1, z + 1), pointCloud[x + 1, y + 1, z + 1], surfaceLevel));
                        currentCache[y, z, 2] = vertIndices[4];
                    }
                    if ((edgeTable[cubeIndex] & 32) == 32) {
                        //Vertex 5 - Leading Edge
                        vertIndices[5] = vertList.Count;
                        vertList.Add(LerpVert(new Vector3(x + 1, y + 1, z + 1), pointCloud[x + 1, y + 1, z + 1], new Vector3(x + 1, y + 1, z), pointCloud[x + 1, y + 1, z], surfaceLevel));
                        currentCache[y, z, 3] = vertIndices[5];
                    }
                    if ((edgeTable[cubeIndex] & 64) == 64) {
                        //Vertex 6
                        if (z > 0 && currentCache[y, z - 1, 2] != 0) {
                            vertIndices[6] = currentCache[y, z - 1, 2];
                        } else {
                            vertIndices[6] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x + 1, y + 1, z), pointCloud[x + 1, y + 1, z], new Vector3(x, y + 1, z), pointCloud[x, y + 1, z], surfaceLevel));
                            currentCache[y, z, 4] = vertIndices[6];
                        }
                    }
                    if ((edgeTable[cubeIndex] & 128) == 128) {
                        //Vertex 7
                        if (x > 0 && behindCache[y, z, 3] != 0) {
                            vertIndices[7] = behindCache[y, z, 3];
                        } else {
                            vertIndices[7] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x, y + 1, z), pointCloud[x, y + 1, z], new Vector3(x, y + 1, z + 1), pointCloud[x, y + 1, z + 1], surfaceLevel));
                            currentCache[y, z, 5] = vertIndices[7];
                        }
                    }
                    if ((edgeTable[cubeIndex] & 256) == 256) {
                        //Vertex 8
                        if (x > 0 && behindCache[y, z, 7] != 0) {
                            vertIndices[8] = behindCache[y, z, 7];
                        } else {
                            vertIndices[8] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x, y, z + 1), pointCloud[x, y, z + 1], new Vector3(x, y + 1, z + 1), pointCloud[x, y + 1, z + 1], surfaceLevel));
                            currentCache[y, z, 6] = vertIndices[8];
                        }
                    }
                    if ((edgeTable[cubeIndex] & 512) == 512) {
                        //Vertex 9 - Leading Edge
                        vertIndices[9] = vertList.Count;
                        vertList.Add(LerpVert(new Vector3(x + 1, y, z + 1), pointCloud[x + 1, y, z + 1], new Vector3(x + 1, y + 1, z + 1), pointCloud[x + 1, y + 1, z + 1], surfaceLevel));
                        currentCache[y, z, 7] = vertIndices[9];
                    }
                    if ((edgeTable[cubeIndex] & 1024) == 1024) {
                        //Vertex 10
                        if (z > 0 && currentCache[y, z - 1, 7] != 0) {
                            vertIndices[10] = currentCache[y, z - 1, 7];
                        } else {
                            vertIndices[10] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x + 1, y, z), pointCloud[x + 1, y, z], new Vector3(x + 1, y + 1, z), pointCloud[x + 1, y + 1, z], surfaceLevel));
                            currentCache[y, z, 8] = vertIndices[10];
                        }
                    }
                    if ((edgeTable[cubeIndex] & 2048) == 2048) {
                        //Vertex 11 - Dont Cache
                        if (z > 0 && currentCache[y, z - 1, 6] != 0) {
                            vertIndices[11] = currentCache[y, z - 1, 6];
                        } else if (x > 0 && behindCache[y, z, 8] != 0) {
                            vertIndices[11] = behindCache[y, z, 8];
                        } else {
                            vertIndices[11] = vertList.Count;
                            vertList.Add(LerpVert(new Vector3(x, y, z), pointCloud[x, y, z], new Vector3(x, y + 1, z), pointCloud[x, y + 1, z], surfaceLevel));
                        }
                    }
                    for (int i = 0; triTable[cubeIndex, i] != -1; i += 3) {
                        triList.Add(vertIndices[triTable[cubeIndex, i]]);
                        triList.Add(vertIndices[triTable[cubeIndex, i + 1]]);
                        triList.Add(vertIndices[triTable[cubeIndex, i + 2]]);
                    }
                }
            }
        }
        behindCache = currentCache;
    }
    triangles = triList.ToArray();
    vertices = vertList.ToArray();
    normals = CalculateNormals(triangles, vertices);
}

Vector3 LerpVert(Vector3 p1, float v1, Vector3 p2, float v2, float surfaceLevel) {
    float percent = (surfaceLevel - v1) / (v2 - v1);
    return Vector3.Lerp(p1, p2, percent);
}

Vector3[] CalculateNormals(int[] tris, Vector3[] verts) {
    Vector3[] normals = new Vector3[verts.Length];
    for (int i = 0; i < tris.Length; i += 3) {
        Vector3 pointA = verts[tris[i]];
        Vector3 pointB = verts[tris[i + 1]];
        Vector3 pointC = verts[tris[i + 2]];

        Vector3 normal = Vector3.Cross(pointA - pointB, pointA - pointC);

        normals[tris[i]] += normal;
        normals[tris[i + 1]] += normal;
        normals[tris[i + 2]] += normal;
    }

    for (int i = 0; i < normals.Length; i++) {
        normals[i].Normalize();
    }
    return normals;
}

```

Any Help is greatly appreciated I have been staring at this for way too long now unable to figure out whats wrong.

# Answer
I figured it out! The problem was when there was a cache hit for vertex 8 in the behindLayer array, it didn't update currentLayer so then when vertex 11 checked if there was a cached index for vertex 8 in currentLayer, it didnt find out and created its own vertex.
> 1 votes

---
Tags: unity, c#, 3d-meshes, mesh, marching-cubes
---


# Question
Title: How to solve the Google Ads problem in iOS?
**Step 1**: I'm implementing a Google AdMob using this link.

**Step 2**: When I import this plugin in unity-\>build(ios)-\> and implement in xcode then give this error: `'GoogleMobileAds\GoogleMobileAds.h' file not found`

I'm tried this one for iOS but the error is still not solved.

Reference:

**GoogleMobileAds.h Not Found**

I'm surfacing this problem the last 3 days - what is the issue with the plugin?

# Answer
> 1 votes
I was having this same problem when making a build in windows for unity IOS and then porting over to my Mac to build with Xcode. Unity provides a Podfile in it's IOS build to get the Google Ad SDK.

Solution that worked for me:

Open terminal on your Mac In terminal: sudo gem install cococapods

After it finishes navagate, in terminal, to your project folder. e.g cd /local/Desktop/

type in: pod update

Wait 15-20 min for this to complete. There is no progress so just be patient.

It will create a Pod folder and download the SDK needed for your build.

Now use the .xcworkspace file it created to open your project from now on. DO NOT USE the old .xcodeproj file. If you don't see a Pods section in your hierarchy when you open Xcode then you selected the wrong file.

---
Tags: ios, xcode, advertisements, admob
---


# Question
Title: 2D Collision detection: rewinding to moment of first intersection
I am working on a collision system in a Platformer tile-based game. All tiles are AABB.

I am trying to implement *"Rewind to Moment of First Intersection"* mentioned in this post's second point.

The following case is to be considered:

Without vectors for clarity:

With vectors:

I am trying to find the vector \\$\vec{w}\\$, which is the vector \\$\color{red}{\vec{v}}\\$ multiplied by a factor \\$f \in (0, 1) \\$. All other vectors are known.

\\$\color{red}{\vec{v}}\\$ represents the reversed movement (or velocity) vector between current and previous frame, whereas \\$\vec{w}\\$ represents \\$\color{red}{\vec{v}}\\$ scaled in such a way, that translating the player object over \\$\vec w\\$ leaves the player in the moment of first intersection.

\\$\color{green}{\vec{a}, \vec{b}}, \color{blue}{\vec{c}, \vec{d}}\\$ represent the penetration depths of colliding objects on corresponding horizontal/vertical axises.

Tiles' width and height is also known.

Assuming that tiles are AABB, strictly-aligned, immovable and all share the same width/height - **how do I find the vector \\$\vec{w}\\$?**

Seeing pseudocode would be awesome.

I am also having surprisingly hard time finding any collision solving learning materials that would suit my needs; if anyone knows such materials, I would be thankful for sharing.

# Answer
I managed to solve collisions problem by splitting the collision handling into horizontal and vertical components, one at a time. The implemented idea is:

1. Move player on horizontal axis.
2. Check for collisions.
3. Solve collision on horizontal axis.
4. Move player on vertical axis.
5. Check for collisions.
6. Solve collisions on vertical axis.

This system does not support high-velocity movements, of course. Other than that I did not found any collision-related 'bugs' in my tile-based game. Not sure about the efficiency.

I am still, however, very interested on the question I asked.
> 1 votes

---
Tags: 2d, collision-detection, vector, collision-resolution, linear-algebra
---


title: Velocity Issue With MonoGame

text:
# Question
Title: Velocity Issue With MonoGame
I'm relatively new to programming velocity and such as I used to use Unity so it was already implemented. Right now, I'm using MonoGame and have an issue with my velocity code. Whenever I decelerate, my "velocity.X" never becomes 0 it just keeps going down to numbers like "-8.775121E-10". I tried to check if it's less than or equal to 0.05 but that just causes issues.

Movement Code:

```
currentState = Keyboard.GetState();

        deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

        bounds.X = (int)position.X;
        bounds.Y = (int)position.Y;

        position.X += velocity.X;
        position.Y += velocity.Y;

        if (velocity.X >= MAX_ACCELERATION)
            velocity.X = MAX_ACCELERATION;
        if (velocity.X <= -MAX_ACCELERATION)
            velocity.X = -MAX_ACCELERATION;

        if (currentState.IsKeyDown(Keys.A))
        {
            if (velocity.X > -MAX_ACCELERATION)
                velocity.X -= acceleration * deltaTime;
        }
        else if (currentState.IsKeyDown(Keys.D))
        {
            if (velocity.X < MAX_ACCELERATION)
                velocity.X += acceleration * deltaTime;
        }

        Console.WriteLine("Velocity: " + velocity);
        Console.WriteLine("Current KeyState: " + currentState.IsKeyUp(Keys.A));

        prevState = currentState;

        Console.WriteLine("Prev KeyState: " + prevState.IsKeyDown(Keys.A));

        SlowDown();

```

SlowDown Method:

```
            /*if (!prevState.IsKeyUp(Keys.A) && currentState.IsKeyUp(Keys.A))
        {
            if (velocity.X >= -0.5f)
                velocity.X = 0;
        }*/

        velocity.X *= FRICTION;

```

# Answer
> 0 votes
The math around drag usually slows things down as a function of how fast it is already going, hence your `velocity.X *= FRICTION;` which seems generally right. The problem is that with that math, mathematically, it will never come to a complete stop. Half of 1 is 1/2, half of that is 1/4, half of that is 1/8, ... 1/1024, 1/2048, 1/4096... Mathematically, you never hit 0. There's nothing strictly wrong with that, unless you do something to assume that something can only be done if you're completely stopped. (Since computers can't represent minuscule numbers, it will eventually become 0. It just might take a minute.)

What I typically do in these situations, if I want it to go to 0, is just move the value to 0 if it is already sufficiently small. Something like:

```
velocity.X *= FRICTION;
if(Math.Abs(velocity.X) < 0.001) // Pick your favorite small number here...
    velocity.X = 0;

```

This covers the situation regardless of if you're really small and positive, or really small and negative, which you might have been having some issues with originally. I believe this also makes it so you don't have to put the bit about `isRight` that you had in your own answer.

# Answer
> 0 votes
Fixed it. For anyone having the same issue, I just added a bool variable called "isRight" and made it true when I am pressing the right key and false when pressing the left key. Then I check the velocity to see if it is less than or greater than (depending on the bool) 0.5 in the SlowDown method and set it to 0.

Code:

```
velocity.X *= FRICTION;

        if (isRight && velocity.X <= 0.5f)
        {
            velocity.X = 0;
        }

        if (!isRight && velocity.X >= -0.5f)
        {
            velocity.X = 0;
        }

```

---
Tags: monogame
---


# Question
Title: Visual studio alternatives for unity as intellisense not working
I am new to unity and unity tools for game dev are unavailable in vs community,i also tried vs code.So what are some alternatives for vs for unity scripts for a beginner?

# Answer
> 3 votes
Are you sure that Unity Tools for Game Dev is unavailabe in VS Community? It should come with the Unity install file but can also be found from the Visual Studio Installer. Also it would help if you stated which version of Unity, Visual Studio and Visual Studio Code you are using.

Regardless this link shows the supported IDE's for Unity: https://docs.unity3d.com/Manual/ScriptingToolsIDEs.html According to the docs it should support Visual Studio, Visual Studio Code and Jetbrains Rider.

Though before switching your editor, are you sure that the Intellisense isn't working at all? Make sure the following are correct before proceeding:

1. Is your Visual Studio installation set as the external script editor in Unity? Check by navigating to: Edit/Preferences/External Tools/External Script Editor
2. Does your project contain a .csproj file? (You can check in the root folder of your project.)
3. Have you made your first script via the Unity Engine? I noticed when I made my first C# script outside of Unity the UnityC# project or csproj wasn't set correctly resulting in the Unity not being loaded in the project and intellisense not being available.

---
Tags: unity, c#, visual-studio, ide
---


# Question
Title: Poor performance in android when running APK, runs fine in browser
I have created a small game project in HTML5 using Phaser engine (tried both 1.1.5 and 1.1.6). Then to port it to mobile platform, used Phonegap/Cordova for Windows Phone 8, Android and iOS.

In my game, there are around 10 elements, which get animated (moving from point a to point b and some rotation at same time). On iOS and Windows Phone 8, I didn't face any issue.

But with Android, performance is unacceptable. On the other hand, if I run my game via device browser, it run smooth without any lag. But compiled APK runs very jerky and elements move very slow & in flickering manner.

I have checked android hardware acceleration flag is set to "true" in manifest file. Tried changing it false too, but that didn't reflected any change in performance.

I have checked same on Android 4.2 on Samsung S2 device and on that performance is better. But on Asus Nexus Tab 7 (running Android 4.4) its very jerky, while the OS and Device both are latest. Also checked on another device running Android 4.3 (Samsung Galaxy Grand Duos) and on that too performance is not good at all.

In my game tried both WebGL / Canvas rendering (Phaser engine uses Pixi.js, which fallback to 2d canvas if WebGL isn't supported), but no change. Similarly with easeljs.

If anyone else faced similar issue and can suggest any way to get native like performance. I checked cocoonjs examples and while they seems smooth and acceptable, I can't go for that route.

# Answer
> 2 votes
The Chromium-based WebView causing this issue was eventually updated in KitKat version 4.4.3/4.4.4 in mid 2014, but that is cold comfort considering some vendors have made some seemingly arbitrary decisions about which of their phones got the update and which did not. Samsung Galaxy S4, for instance, is still trapped at 4.4.2.

Follow the advice given by other answers: if you have a canvas-based game then avoid PhoneGap unless you can determine that being stuck with excluding phones that are running KitKat versions below 4.4.3 is acceptable.

# Answer
> 1 votes
Try to remake your game in libgdx. Libgdx is fast enough and doesnt have issues like that and it works on all platforms. Unfortunately this is only what I can think of right now and I dont like the idea of converting js to android java or whatever that coverter does. Although it will take some time, give LibGDX a test.

# Answer
> 1 votes
Seems like this is a issue with most game developers. Similar issue

"I'be often heard that phonegap wasn't the best choice when wanting to make canvas game. It's more adapted to web app to native."

It seems to be rendering issue capabilities for android phones. There are some engines that can not handle more sprites rendering. I know 10 objects are easy to render but it definitely looks problem with rendering capabilities.

My suggestion is that you go with **cocoonjs**.

# Answer
> 1 votes
I ran into the same issue with Phaser (with this simple game). Unfortunately, with HTML5 and web/canvas rendering, you're at the mercy of your phone -- there will be users with broken or poorly-performing browsers (like mine).

Like @captainbuzz123 suggested, the only real solution is to move to a non-HTML5 platform. My tool of choice for now is OpenFL.

While my (very simple) Phaser app runs at around 8-12FPS on my phone, with OpenFL (because it's transpiled to C++ and run through the Android NDK), I end up getting very smooth, fluid performance on my phone.

It's definitely worth a try.

# Answer
> 1 votes
An update for the first week of 2020's:

**Cocoonjs** was probably a solid solution for this issue in the past but they are shutting down.. a quote from their official web site that says it all

> It is with deep regret that we announce that we will stop providing our beloved service, Cocoon.
>
> We started Ludei/Cocoon because we believed the future of app and game development would be based in HTML5. Unfortunately, it didn’t happen and native development is stronger than ever.

This actually reflects HTML5 development for mobile in 2019.. not that its not possible, but its not effective as was expected...

Im switching to native development after some production games built with Phaser and Cordova for IOS and Android. Fed up with hitting performance ceiling on even the simplest mechanics on medium end devices

Just to share my next tech/stack solution options to pick from for anyone seeing this in the present or the near future:

* SpriteKit for IOS and LibGDX for Android: This will probably be the most performant solution although it will require developing for each platform separately.. but also will be most "low level"
* Cocos2D-X not really sure how well supported it is and is it still a valid choice but it should be very mature and performant + you can write in C++ and build for any platform there is
* Corona seems like an interesting (and free) cross platform and performant framework, using Lua will need to test it vs the other solutions mentioned here
* Use one of the modern engines like Unity or Godot. Not sure how this is comparing to the mentioned frameworks performance wise

Hope this helps anyone..

# Answer
> 0 votes
Saw this the other day, might well be worth a look to solve this problem. Sounds like a pretty nice idea to me: http://tmtg.net/glesjs/

The fact that it works fine when in browser, but not when on Phonegap/Cordova is very strange indeed. The whole canvas/webGL situation on Android (can't speak for iOS) has always seemed pretty dire to me. Definitely something GOogle needs to put more energy into, perhaps Lollipop will be an improvement!

---
Tags: android, javascript, html5, performance, html-canvas
---