# Question
Title: error CS1069: The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression'
When I build my project, which references the `System.IO.Compression` namespace, the build succeeds without issue inside Visual Studio.

However, inside the Unity editor, I see the following error:

```
error CS1069: The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression'. This type has been forwarded to assembly 'System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly.

```

I added a `csc.rsp` file inside my Assets folder, with the following line:

```
-r:System.IO.Compression.FileSystem.dll

```

Unfortunately, that did not resolve the issue.

Here are the properties of the `System.IO.Compression` DLL that I reference inside Visual Studio:

How can I fix this error?

# Answer
I had the same problem.

Try to replace the

```
-r:System.IO.Compression.FileSystem.dll

```

with

```
-r:System.IO.Compression.dll

```

in the `crc.rsp` file.

P.S.

You can also try to add

```
-r:System.IO.Compression.FileSystem.dll

```

to that file too.
> 3 votes

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


# Question
Title: User-friendly scripting when using an ECS?
I am currently creating a small hobby project to get back into game development, and I have decided to structure my entities using an ECS (Entity Component System). This implementation of an ECS is structured like so:

* **Entity**: In my case it's a unique `int` identifier that is used as a key to a list of components.
* **Component**: Holds *only* data, e.g. the `Position` component holds an `x` and `y` coordinate, and the `Movement` component holds a `speed` and `direction` variable.
* **System**: Handles components, e.g. it takes the `Position` and `Movement` components and adds the `speed` and `direction` to the position's `x` and `y` coordinates.

This works fine, but now I wish to implement scripting into my games, in the form of a scripting language. In previous projects I've used an OOP implementation of game objects, which meant that scripting was pretty straight forwards. For example, a simple script could look something like this:

```
function start()
    local future = entity:moveTo(pos1)
    wait(future)

    local response = entity:showDialog(dialog1)
    if wait(response) == 1 then
        local itemStack = entity:getInventory():removeItemByName("apple", 1)
        world:getPlayer():getInventory():addItemStack(itemStack)
    else
        entity:setBehavior(world:getPlayer(), BEHAVIOR_HOSTILE)
    end
end

```

However, when using an ECS, the entity itself does not have any functions like `moveTo` or `getInventory`, instead the above script written in ECS style would look something like this:

```
 function start()
    local movement = world:getComponent(MOVEMENT, entity)
    movement:moveTo(pos1)

    local position = world:getComponent(POSITION, entity)
    local future = Future:untilEquals(position.pos, pos1)
    wait(future)

    local dialogComp = world:getComponent(DIALOG, entity)
    local response = dialogComp:showDialog(dialog1)

    if wait(response) == 1 then
        local entityInventory = world:getComponent(INVENTORY, entity)
        local playerInventory = world:getComponent(INVENTORY, world:getPlayer())
        local itemStack = entityInventory:removeItemByName("apple", 1)
        playerInventory:addItemStack(itemStack)
    else
        local entityBehavior = world:getComponent(BEHAVIOR, entity)
        local playerBehavior = world:getComponent(BEHAVIOR, world:getPlayer())
        entityBehavior:set(playerBehavior, BEHAVIOR_HOSTILE)
    end
end

```

This is *a lot* more verbose compared to the OOP version, which is not desirable when the scripting is aimed towards mostly non-programmers (players of the game).

One solution would be to have some sort of wrapper object that encapsulates an `Entity` and supplies functions such as `moveTo` directly, and handles the rest internally, although such a solution seems sub-optimal since it takes a lot of work to cover all the components, and every time a new component is added you would need to change the wrapper object with new functions.

To all game developers that has implemented scripting in an ECS before - how did you do it? The main focus here is usability for the end user, with as little "maintenance" cost as possible (preferably you don't need to change it every time you add a component).

# Answer
> 3 votes
ECS has its pros and cons. User-friendly scripting is not one of its pros.

The problem ECS solves is the ability to have a large number of similar things in your game at the same time while retaining performance. But this solution comes at a cost - the cost of an easy to use architecture. It is not the best architecture for every game.

For example, ECS would have been a fine choice for Space Invaders, but not so much for PacMan.

So not exactly the answer you were looking for, but its possible that ECS is just not the right tool for your job.

If you add a wrapper, watch the overhead cost. If you end up removing the performance boost of ECS in your wrapper, then you have the worst of both worlds.

---

But to directly answer your question - "To all game developers that has implemented scripting in an ECS before - how did you do it?"

Pretty much exactly as you are doing it, without a wrapper. Entities have nothing but an identifier. Components have nothing but data. Systems have nothing but logic. Systems that accept entities with the required components run through. Add systems, entities, and components freely.

I once used a framework with a fourth aspect, called a blackboard. It was basically a way for systems to communicate with eachother. It created more problems than it solved.

---

Related: Should I implement Entity Component System in all my projects?

# Answer
> 3 votes
You could create a system ScriptExecutionSystem which operates on all entities with a Script component. It obtains all components of the entity which could be useful to expose to the scripting system and passes those to the scripted function.

Another approach would be to get your users to also embrace ECS and allow them to define their own components and implement their own systems using the scripting language.

---
Tags: entity-system, scripting
---


# Question
Title: Image-Space coherence of the z-buffer algorithm
I'm reading *Hierarchical z-Buffer Visibility* by *Ned Greene et al.* and they state that

> *traditional Z buffering makes reasonably good use of image-space coherence in the course of scan conversion.*

I don't see *how* the z-buffer algorithm that I know makes use of image-space coherence at all. In the paper, they state that

> *implementations usually do a set-up computation for each polygon and then an incremental update for each pixel in the polygon.*

How *exactly* is this "set-up computation" and "incremental update" defined?

# Answer
> 1 votes
The Z-Buffer algorithm itself does not use image-space coherence concept, it works exactly as we know. But the result of this algorith **is** quite coherent, which means that for any given pixel there's a big chance that neighboring pixels have similar value.

This property (image-space coherence) of Z-Buffer data makes it possible to use i.e. Quad-Tree to make some tests faster. (If you had noise in ZBuffer then there's no point in using QuadTree over such data).

So in short: The coherence of data coming from traditional Z-Buffer makes it reasonable to use Hierarchical Visibility tests.

I hope this answers your first question. For the second let's say you're writing your own ZBuffer and you want to add a feature of Hierarchical Visibility tests. You have a grid of Z values already and you add a QuadTree, which contains `min/max` values for each node. At start you initialize those structures as needed.

Then you render a pixel, you compute its Z and test it with latest Z value of this pixel. If it's visible you store the new Z value but you also need to update the Quad-Tree and this is the 'incremental update' part.

# Answer
> 1 votes
There are two possibilities that occurred to me: 1) Triangles meshes are typically supplied in one of strip, fan, or indexed triangle lists. Since the first two automatically imply adjacency of (at least some) triangles and the last is typically optimised to maximise vertex cache reuse, these will also result in considerable spatial coherence. This, in turn, allows Greene's hierarchical Z-buffer to be effective.

2) If we can take it as read that the polygon (read triangle) vertices have been projected into screen coordinates, then setup in this case is any of the processing that takes the 3 triangle vertices, \\$V\_1, V\_2, V\_3\\$ (where each \\$V\\$ has components, \\$(X^{screen}, Y^{screen}, Z^{screen}, \\$ \+ inverse W,texture coordinates, RGB values etc\\$)\\$ and maps them to a per-pixel evaluation cooefficients.

In older systems that usually meant DDA values for walking along edges and then interpolating along the scan lines, but this gradually changed over to using 'half-plane' evaluation schemes which make parallel evaluation on multiple pixels feasible.

Assuming it is the latter, then for edge equations this can be achieved by computing the inverse/adjoint of a 3x3 matrix comprising a row of the 3 X values, a row of the Ys and a row of 1s. $$ \begin{vmatrix} V\_1^{xscreen}&V\_2^{xscreen}&V\_3^{xscreen}\\ V\_1^{yscreen}&V\_2^{yscreen}&V\_3^{yscreen}\\ 1&1&1 \end{vmatrix} $$

Each row of the adjoint of the above give the coefficients of a 'edge equation' of the form \\$d\_{edge}=a.X + b.Y + c\\$, which can be used for 'inside' tests.
*(FWIW this would be a good question for https://computergraphics.stackexchange.com/ )*

# Answer
> 0 votes
It seems to me that the setup refers to calculating the the Z values (as these can be determined a polygon at a time, once per frame) & the update is comparing a pair of Z values to update the pixel color as needed.

In terms of implementation, I've always seen it presented in an interleaved fashion (much like your definition link), but conceptually, you can think of them as separate steps.

# Answer
> 0 votes
I would say the traditional Z-buffer algorithm is *temporally* coherent in image-space. That is to say that, frame by frame, given fine adjustments of camera position and orientation, you are likely to see a lot of similarities between temporally-adjacent frames (frame `N` and `N+1`, for example).

I remember reading about the concept some years ago, for accelerating global illumination and/or raytracing(?). Here is a source that discusses this as an optimisational approach.

---
Tags: algorithm, rendering, depth-buffer, computational-geometry, occlusion
---


# Question
Title: Ensuring dash toward mouse position is always a consistent distance
I'm making a 2D game where the player character should dash toward the mouse position when the player clicks, but the dash is currently not a consistent distance each time.

Let's say you put the cursor far-right like x = 20, so the character moves 20 units. But if you put it closer, like at x = 5, the character dashes only 5 units.

How can I limit the position input to just a direction, so the player character would travel the same distance, no matter where the mouse is positioned?

```
void FixedUpdate() {
    //...
    float xor = Input.GetAxis("Horizontal"), yor = Input.GetAxis("Vertical");

    if ((xor != 0 || yor != 0) && !dash)
    {
        rg2d.velocity = new Vector2(xor * speed, yor * speed);
        anim.SetFloat("speed", Mathf.Abs(xor + yor));
    }
    if(Input.GetKeyDown(KeyCode.Mouse0) && !fire)
    {
        //PUNCH
        dash = true;
        fire = true;
        StartCoroutine(Stop_Fire(0.5f));
        anim.SetTrigger("attack");
        fist.GetComponent<Collider2D>().enabled = true;

        Vector2 pos = (transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition)).normalized;

        rg2d.AddForce(-pos * punch_force, ForceMode2D.Impulse);
    }
}

// I call this function at the end of the attack animation, in the Animation window
public void Stop_Dash()
{
    dash = false;
    fire = false;
    fist.GetComponent<Collider2D>().enabled = false;
    rg2d.velocity = Vector2.zero;
}

```

# Answer
said in the comment section:

> You're taking a 3D vector with a potentially-large z component, normalizing it, then discarding the z to make it a 2D vector. This will result in a vector that can be quite a bit smaller than unit length. Does converting to 2D before normalizing make any difference for your case?

```
        Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 moveDirection = (transform.position - mousepos);
        moveDirection.z = 0;
        moveDirection.Normalize();

        rg2d.AddForce(-moveDirection * punch_force, ForceMode2D.Impulse);

```
> 0 votes

# Answer
Seems like you are already doing the correct thing (getting `.normalized` which in any way will give you a vector of magnitude of 1) and your problem isn't related to how you get the direction. I guess that `Input.GetAxis("Fire1")` is a continuous event and this code is being executed multiple times per SECOND during multiple FRAMES. Thus you are getting a different distance each time, depending on how long you hold the `Fire1` event.

To fix this you can have some kind of a cooldown, or a bool that would restrict firing an event again until it was released.

**Edit 1**

The z position of Camera.ScreenToWorldPoint \- "position for depth (for example, a camera clipping plane)."

From official example `point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));`. Which would indicate that `cam.ScreenToWorldPoint(new Vector3(Input.mousePosition));` should disregard z as it's a `0`. Which in turn would give us `new Vector3(x, y, 0f)`, so normalizing it after conversion to `Vector2` shouldn't give a different result. But I may be wrong, indeed this is something I need to research.

**Edit 2**

Seems like `transform.position` is the culprit. `Vector2 pos = (transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition)).normalized;` If this Component's `transform.position` was changed on `z` axis from `0` to any other value, this would create a different `Vector3` each time a position of this `transform` was changed.
> 0 votes

---
Tags: unity, c#, physics, rigidbody
---


title: How can I make my tiles fall smoothly?

text:
# Question
Title: How can I make my tiles fall smoothly?
I'm working on a Tile-Based game and I can't figure out how to make my tiles fall down smoothly like in candy crush. All column tiles fall-down at the same time. And spawn new like how many tile place if null.

What I want:

# Update \[25.12.2015\]

But the my code works like this:

# Update \[26.12.2015\]

Hello Again,

World Scale (x,y) World Scale OLD: (10,10) World Scale NEW: (10,11)

Y=11 Tiles type = Empty

Now, when i click the random place like (5,7),above all blocks down to : block.transform.pozition += new Vector3(0,-1,0); It's working. But again, when i click same place (5,7) not working...

I changed Y scale 10 to 11. Because, when i clicked tile, the tile will return to Y=11 position and fall down, how many tile place null.

When Tiles state "fallling down", the space between two blocks distance not more "0.01".

I do not know how to do. But I approached. I need to more improve this.

Thanks...

Pseudo-code:

```
When I click the (4,7) coord, the tiles,
tile(4,8) is smooth down the coord(4,7)
tile(4,9) is smooth down the coord(4,8)
tile(4,9) is generate new tile.

```

What I have (Code not working properly :( ):

```
World.Height = 10
World.Widht = 10
Tile X and Y {get, protected set}

public void ColumnDown(int x , int yStart)
{
    if (IsColumnFull(x)) return;

    for (int y = yStart; y < World.Height; y++)
    {
        //Yeni tile spawnla
        if (y + 1 >= World.Height) continue;

        Tile tile = World.GetTileAt(x, y);
        Tile tile2 = World.GetTileAt(x, y + 1);

        GameObject go_Tile = GameObject.Find("Tile-(" + x + "," + y + ")");
        GameObject go_Tile2 = GameObject.Find("Tile-(" + x + "," + (y + 1) + ")");

        if (tile != null)
        {
            if (go_Tile == null && go_Tile2 == null)
            {
                Debug.Log("go_Tile NULL");
                continue;
            }

            tile2 = tile;
            go_Tile2.transform.position += new Vector3(0, -1, 0);
            go_Tile.name = "Tile-(" + x + "," + (y + 1) + ")";
            go_Tile2.name = "Tile-(" + x + "," + (y) + ")";
        }
    }
}

```

# Answer
Instead of treating the entire column as one entity, have each candy check if it can fall down.

Each candy checks if it collides with a candy below it (or the floor). If not the candy falls down -using gravity so they fall nice and realistic. Since the candy can only fall down per column, collisions are easy to check. Do a count for each vertical and have a new candy spawn on top if the number of candy is lower than the total candy a column can contain.

Keep track if any candy has fallen during the update loop. If no candy has fallen the board is 'locked' and a grid is created from the current candy to do your 'match 3' logic.

The beauty of each candy being a separate entity is that you can do collision detection that is beyond the grid. If you ever played the Disney Frozen match-3 game, you'll notice that a horizontal beam can also hit objects that are falling. So you only need to perform the match-3 logic when the board is in a 'locked' state.

Advanced logic can be created to have certain parts of the board to be locked so gameplay can be more fluid (the player can swap tiles while other area's of the board are still falling).
> 3 votes

# Answer
The solution is simple: just use the built-in Physic Engine.

Here's how:

* Instead of using "Box Collider 2D", use "Circle Collider 2D", this will solve the block-stuck problem.
* You just need the fall physic, so lock X and Z in RigidBody2D's Constraints. Don't worry, you can still control X via your script.
> -1 votes

---
Tags: unity, c#, 2d
---


# Question
Title: Unity editor, horizontal line in inspector
How to draw a horizontal line in the inspector like on the reference image? Kind of separation line.

# Answer
```
public static class EditorGUILayoutUtility
{
    public static readonly Color DEFAULT_COLOR = new Color(0f, 0f, 0f, 0.3f);
    public static readonly Vector2 DEFAULT_LINE_MARGIN = new Vector2(2f, 2f);

    public const float DEFAULT_LINE_HEIGHT = 1f;

    public static void HorizontalLine(Color color, float height, Vector2 margin)
    {
        GUILayout.Space(margin.x);

        EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, height), color);

        GUILayout.Space(margin.y);
    }
    public static void HorizontalLine(Color color, float height) => EditorGUILayoutUtility.HorizontalLine(color, height, DEFAULT_LINE_MARGIN);
    public static void HorizontalLine(Color color, Vector2 margin) => EditorGUILayoutUtility.HorizontalLine(color, DEFAULT_LINE_HEIGHT, margin);
    public static void HorizontalLine(float height, Vector2 margin) => EditorGUILayoutUtility.HorizontalLine(DEFAULT_COLOR, height, margin);

    public static void HorizontalLine(Color color) => EditorGUILayoutUtility.HorizontalLine(color, DEFAULT_LINE_HEIGHT, DEFAULT_LINE_MARGIN);
    public static void HorizontalLine(float height) => EditorGUILayoutUtility.HorizontalLine(DEFAULT_COLOR, height, DEFAULT_LINE_MARGIN);
    public static void HorizontalLine(Vector2 margin) => EditorGUILayoutUtility.HorizontalLine(DEFAULT_COLOR, DEFAULT_LINE_HEIGHT, margin);

    public static void HorizontalLine() => EditorGUILayoutUtility.HorizontalLine(DEFAULT_COLOR, DEFAULT_LINE_HEIGHT, DEFAULT_LINE_MARGIN);

#if UNITY_EDITOR
#endif
}

```

Call:

```
public override void OnInspectorGUI()
{
    base.OnInspectorGUI();

    EditorGUILayout.BeginVertical();

    EditorGUILayoutUtility.HorizontalLine(new Vector2(20f, 20f));

    EditorGUILayout.EndVertical();
}

```

Will yield this result.
> 2 votes

# Answer
Another option is to use a slider like this (Source):

`EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);`
> 0 votes

---
Tags: unity
---


title: Change scale values by Lerp?

text:
# Question
Title: Change scale values by Lerp?
How to change the scale values of object by using Lerp. from 0 to 0.01722f and reveals later ?

```
public Vector3 vp1;
public bool checkers;

void Start()
{
    checkers = false;
    vp1 = gameObject.transform.localScale; // (0.01722F,0.01722F,0.01722F)
}

void Update()
{

    if (checkers == true)
    {
            vp1 = Vector3.Lerp(new Vector3(0, 0, 0), vp1, 0.2f);
    }
     else
    {
            vp1 = Vector3.Lerp(vp1, new Vector3(0, 0, 0), 0.2f);
    }

}

```

# Answer
> 0 votes
Anyway. Here how to solve the scale lerp.

```
public Vector3 vp1,vp2,vp3;
public bool checkers;

void Start()
{
  checkers = false;
  vp2 = new Vector3(0.0f, 0.0f, 0.0f);
  vp3 = new Vector3(0.001722403f, 0.001722403f, 0.001722403f);
}

void Update()
{

    gameObject.transform.localScale = vp1;

  if (checkers == true)
  {
      vp1 = Vector3.Lerp(vp1, vp3, Time.deltaTime * 8f);
  }
   else
  {
      vp1 = Vector3.Lerp(vp1, vp2, Time.deltaTime * 20f);
  }

}

```

---
Tags: unity, scale, lerp
---


# Question
Title: Unity's Android Notification system works on my Xiaomi, but on a Huawei every notification has an "Unknown" status?
When my app starts I check whether there is a notification or not

* if there isn't I create one via `SendNotification(...)`
* if there is, I check their **status**:

+ `var status = CheckScheduledNotificationStatus(notificationId);`
    + On my **Xiaomi** their status is **Scheduled**, so I update them:

    - `SendNotificationWithExplicitID(...)`
    + But on a **Huwaei** it's always **Unknown**, in that case I create a new:

    - `SendNotification(...)`
        - And replace the old ID in the PlayerPrefs.
        - **But on the next startup it's unknown again.**

Maybe I should use `SendNotificationWithExplicitID(...)` as well when the status is **Unknown** so I can keep the **ID**?

Here is the code:

```
var notification = CreateNotification(jsonWrapper.Name, fireTime, title, text);
if (PlayerPrefs.HasKey(jsonWrapper.Name))
{
    var notificationId = PlayerPrefs.GetInt(jsonWrapper.Name);
    var status = AndroidNotificationCenter.CheckScheduledNotificationStatus(notificationId);
    if (status == NotificationStatus.Scheduled)
    {
        AndroidNotificationCenter.SendNotificationWithExplicitID(notification, "default", notificationId);
        Logger.Log($"Updated a notification: {jsonWrapper.Name} at {fireTime}.");
    }
    else if (status == NotificationStatus.Unknown)
    {
        var id = AndroidNotificationCenter.SendNotification(notification, "default");
        PlayerPrefs.SetInt(jsonWrapper.Name, id);
        PlayerPrefs.Save();
        Logger.Log($"UnknownStatus | Registered a new notification: {jsonWrapper.Name} at {fireTime}.");
    }
}
else
{
    var id = AndroidNotificationCenter.SendNotification(notification, "default");
    PlayerPrefs.SetInt(jsonWrapper.Name, id);
    PlayerPrefs.Save();
    Logger.Log($"Registered a new notification: {jsonWrapper.Name} at {fireTime}.");
}

```

# Answer
> -1 votes
I had to go into the Settings, and enable more permissions. (Don't know which one sadly)

---
Tags: unity, android, mobile
---


# Question
Title: Does P2P Matchmaking can make an online game without any cost?
I’m planning on making an online game. I’ve used Unity (with Photon’s PUN2), but after some research, I had the idea of instead of using a server, with ccu limit and charge fees, i could make a P2P multiplayer game, so that way, the server would be one of the two players, without having any cost on me. I don’t know If this is possible, and indeed, a good idea. I did a research on this but I couldn’t find a clear explanation or tutorial. PS: It’s not a big game (2d game) think of it as the size of an online version of PONG, where two players fight until one wins, it could have or not a time limit.

# Answer
Many multiplayer games allow hosting a server on player machine. **That's actually a feature people like to have.**

But matchmaking requires a server on your side(or hosted by community, actually anything as long as it can be discovered easily in game).

You can avoid costs by allowing players to join only via IP, but that's going to limit your player base to those who can handle router and firewall configuration(if they even care enough).

So, you have few options here:

1. Host your own "Master" Server, that keeps track of player hosted servers.
2. Use online subsystem like Steam
3. Ignore it, and leave players to handle connectivity issuses

**What you really should do now is implement a P2P server, that's the thing you will need anyway, everything else is "just a feature".**
> 1 votes

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


# Question
Title: Unity: Accessing method from (script_2) without hardcoding it in (script_1)
I have some custom script for enemy's AI. Let's call it: "firstEnemyAI.cs"

And I have "master" script called "Enemy.cs" attached to the GameObject.

Is there any way to attach "firstEnemyAI.cs" script to the "Enemy.cs" script for calling some "firstEnemyAI.cs" methods, without need to hardcoded class name of "firstEnemyAI.cs" script?

If I access it in "Enemy.cs" via

```
GetComponent<FirstEnemyAI>();

```

I will need to edit my "Enemy.cs" script every time, I want to try another AI pattern :(

# Answer
## The most convenient way: ScriptableObjects.

ScriptableObjects are Unity scripts, but unlike MonoBehaviours, they do not exist in the scene, they exist as .asset file and can be referenced from anywhere.

First, you should create AI template class. It's abstract, so it cannot be instantiated itself, only its inheritors. And it inherits from SO for extended functionality:

```
public abstract class AiTemplate : ScriptableObject
{
    // Method you want to call. Inheritors will implement different versions of it.
    public abstract void AiMethod(GameObject enemy);
}

```

Then you should create children of your template:

```
[CreateAssetMenu(menuName = "AI/First")]
public class FirstEnemyAI : AiTemplate
{
    public override void AiMethod(GameObject enemy)
    {
        // Do something with enemy.
    }
}

[CreateAssetMenu(menuName = "AI/Second")]
public class SecondEnemyAI : AiTemplate
{
    public override void AiMethod(GameObject enemy)
    {
        // Do something else with enemy.
    }
}

```

`CreateAssetMenu` attribute allows you to create your SO inside the editor (Toolbar/Create/AI/...).

After that you should modify your Enemy script:

```
class Enemy
{
    // Creating AI template variable which you can assign via inspector.
    [SerializeField] AiTemplate template;

    // ...
        // Calling method from current AI template.
        template.AiMethod(this.gameobject);
    // ...
}

```

Now you can write as many AiTemplates as you like and assign any of them to your enemy via inspector without modifying Enemy script ever again!

**Important notice**! ScriptableObjects used this way are **managers**, not **data holders**. They should not contain any enemy-related data! Simple example: first enemy calls your script and saves its HP inside it. After that second enemy calls the same manager and overwrites stored HP. When first enemy calls manager again, it receives HP of second enemy, which leads to incorrect behaviour.

Your managers should always get values, modify them and return back, so multiple enemies could work with the same manager independently.
> 2 votes

# Answer
According to the Unity Documentation (Add Component) you can add components to any gameobject at runtime.

You can do something like this:

```
FirstEnemyAI FEScript = this.gameObject.AddComponent<FirstEnemyAI>();
FEScript.YourCallFunction();

```

The variable will hold the attached script so you can reference it anywhere in that session.

This Forum link will provide you a heads up!
> 0 votes

---
Tags: unity
---


# Question
Title: LibGDX “EXCEPTION_ACCESS_VIOLATION” error when recreating previously disposed Box2DLights light
I just installed the Box2DLights dependency for LibGDX and I added a cave with 2 ConeLights inside. The first time I render the cave, everything works as expected. Then when I exit the cave, I make sure to `dispose()` all the lights. Then if I enter the cave again and try to create the same 2 ConeLights, it gives me this exception with a big error log (PasteBin added at the bottom of this post). If I don't `dispose()` the lights when exiting the cave, it won't crash the second time, but it will keep adding lights and it will get brighter and brighter and it's bad for performance. It doesn't matter if I use a PointLight or a ConeLight, the same exception will occur.

Everytime a map change occurs, `destroyLighting()` and then `loadLighting()` for the new map is called. The error happens when a ConeLight is created, the second time when you enter the cave (4th line in the loadLighting() method)

loadLighting():

```
for(MapObject o : lightingObjects) {
      EllipseMapObject circleMapObject = (EllipseMapObject) o;
      Ellipse ellipse = circleMapObject.getEllipse();
      Light light = new ConeLight(rayHandler, 60, new Color(255,225,166,1), 100, ellipse.x, ellipse.y, 90, 90);
      light.setSoftnessLength(0);
      lights.add(light);
}

```

destroyLighting():

```
for(Light light : lights) light.dispose();
lights.clear();

```

The error log: https://pastebin.com/1v36aNPg

# Answer
> 0 votes
Not really sure what causes the problem, but I think you should be disposing and recreating your `RayHandler` each time which internally takes care of disposing all the lights.

Have a look at the wiki.

---
Tags: libgdx, box2d, exceptions
---


title: Adding a map without recompiling

text:
# Question
Title: Adding a map without recompiling
I am creating a maze game in c++. I have a class that is used to create the walls with positioning and collision. I want the user to have the capability to include the header files needed for making the walls into a separate map file, and then be able to upload that file to the game without having to recompile the game itself. Should these map files be separate .exe or some other compiled file? could they be regular .cpp files that the game just reads? A friend suggested dynamic libraries, but that doesn't seem quite right.

# Answer
Most games put their map data into separate files. The game executable reads and parses these files at runtime. Read up on how to do file input in C++. You can then invent your own file format.

If you are looking for a solution which allows easy editing with the minimum amount of programming necessary, then you could use a text-based format where every map tile is one character. That makes it possible to create and edit maps with a text editor.

If you want to make map editing even easier or if you can't cover the whole feature set of your game with one character per tile, then you could program your own map editor, either as a separate feature of your game or as a stand-alone application. Or you could use an existing map editor like Tiled. You can load the Tiled map format (.tmx) in a C++ game with the library libtiled.
> 0 votes

# Answer
Looks like you are hardcoding the map of your game within your exe.

Don't do that.

Put the map data in text files, which will be read by your game at level start up.

There are no standard for this so you'll have the freedom to customize your map file format to your needs.
> 2 votes

---
Tags: c++, architecture, maps
---


# Question
Title: How do i pass variable dice FROM diceNumber(),DiceScript TO diceno IN Box_Collider Script
Want to pass dice variable to 10 same script(Box\_Collider). If i generate random no in Box\_collider then ten random numbers are generated.

# Answer
If you have only one instance of `DiceScript` in your scene, then you can declare the variable `dice` as static. (`public static int dice;`). This does two things. First, all instances of DiceScript share the value of that variable. But if you have only one instance then that makes no difference. Second, you can refer to that variable in any other script as `DiceScript.dice` without requiring a reference to an object of type DiceScript.

Like this:

```
if (value == DiceScript.dice) {
    // do something
}

```

But this solution won't work if you ever want to have more than one instance of DiceScript in your scene. In that case you would make the variable non-static and give the Box\_Collider a `public DiceScript controllingDiceScript` variable. You would then use the inspector to assign objects with DiceScript to the objects with Box\_Collider which are supposed to be controlled by it. You can then use `if (value == controllingDiceScript.dice)` to check the value of the specific DiceScript you assigned to this specific Box\_Collider.
> 0 votes

---
Tags: unity
---


# Question
Title: How to get `Label::createWithTTF` to support RTL languages such as Arabic
Firstly, I'm using `Cocos2d-x v3.6`, `Visual Studio 2013` uses(UTF-8 without signature option) and `C++`.

When using `Label::createWithTTF` method to write Arabic text, It appear like the following.

The previous arabic text has not been written correctly, It was supposed to look like this `السلام عليكم`, and it also supposed the Arabic language belong to Unicode encoding.

My code:

```
auto label = Label::createWithTTF("السلام عليكم", "fonts/arial.ttf", 34);

```

**Is there any way to solve that problem ?**

---

**Edit:**

I have applied what in this link \[ Right-to-left mark \] and the result was disappearance the Arabic text as in the following picture.

**The code:**

```
auto label = Label::createWithTTF("\u200fالسلام عليكم", "fonts/arial.ttf", 34);
label->setAlignment(TextHAlignment::RIGHT);

```

The problem still exists.

# Answer
*Cocos2d* seems missing Unicode *BiDi* and *Shaping*. Please, Submit a bug report to its development team. Or make it yourself.

High Level: *Pango* is a multi-platfom open source text layout library.

If you want more control on text processing, see:

Low Level: *HarfBuzz* is a multi-platfom open source text shaping library. Low Level: There are multiple BiDi libraries. example: *Fribidi*.

There are more options out there including the native Unicode shaping engines of (Windows, MacOS).
> 1 votes

# Answer
You can reverse UTF8 characters in cocos2d like this, but still, Persian and Arabic words won't connect. I am actually working on localization for both Arabic and Persian texts. But for quick fix use createWithSystemFont instead. I will send a complete fix for .ttf fonts in Github soon.

Edit : Hi, this is my Persian and Arabic support for cocos2d: It works 100% fine for Persian but it may have an issue for Arabic cause I don't know Arabic well.

https://github.com/MohammadFakhreddin/cocos2dx-persian-arabic-support

<pre><code>#include <cocos2d.h>
#include <string>
using namespace cocos2d::StringUtils;

std::string PersianLanguageSupport::reverseWord(const std::string& rawWord) {
    assert(rawWord.length() > 0);
    StringUTF8 utf8RawWord = StringUTF8(rawWord);
    std::string reversedWord = "";
    for (int i = utf8RawWord.getString().size() - 1; i >= 0; i--) {
        reversedWord += utf8RawWord.getString().at(i)._char;
    }
    StringUTF8 utf8ReversedWord = StringUTF8(reversedWord);
    return utf8ReversedWord.getAsCharSequence();
}
```
</code></pre>
> 0 votes

# Answer
Rotate vice-versa input arabic text.

```
#define COCOS2D_DEBUG 1 // At the beginning of file

CCFileUtils *fileUtils = CCFileUtils::sharedFileUtils();
std::string text = fileUtils->getStringFromFile("data.txt");
std::string label_text = "";
char *c;
c = (char *)&(*text.end());
c--;c--;
while (c > (char *)&(*text.begin())){
    while (*c == '\x20'){
       label_text+='\x20';
       c--;
    }
label_text+=(char)*(c-1);
    CCLOG("%d",*(c-1));
    label_text+=(char)*c;
    CCLOG("%d",*(c));
    c--;c--;
}
label_text+='\x0a';
label_text+='\0';
auto label = Label::createWithTTF(label_text, "fonts/arial.ttf", 34);

```
> -1 votes

---
Tags: c++, cocos2d-x
---


# Question
Title: Problem with rendering a quad from four lines
I am having a problem with rendering a quad in opengl via 4 lines (5 vertices via GL\_LINE\_STRIP). The rendering is generally working fine in terms of connecting the lines into a quad. The problem is, that the lines in the bottom left corner are not connected. Following screenshot shows what I am talking about. Left is a screenshot from the entire scene, right a close up zoom in where one can see that the lines do not connect correctly.

The coordinates for the corner vertices in NDC are (x,y)

```
top left     -0.5,  0.5
bottom left  -0.5, -0.5
bottom right  0.5, -0.5
top right     0.5, 0.5

```

I really tried to wrap my head around where this is coming from but I couldn't figure it out and I also didn't find any helpful information on the internet. It seems to me, that the line from top left to bottom left is just one pixel short and does not connect to the bottom line.

I included a working minimal example in c++. Maybe someone can help me find out where this is coming from. I am using Visual Studio 2017, OpenGL 460 core, glfw3 and glad 0.1.29.

Main program:

```
//cpp
#include <iostream>
#include <vector>
#include <cstdio>

//opengl, etc.
#include <glad/glad.h>
#include <glfw/glfw3.h>

//own
#include <shader.h>

//forward declarations
GLFWwindow* initOpenGL(const int pScreenWidth, const int pScreenHeight);
void framebufferSizeCallback(GLFWwindow *window, int width, int height);

int main(int argc, char *args[])
{
  const int SCREEN_WIDTH = 800;
  const int SCREEN_HEIGHT = 800;

  GLFWwindow *window = initOpenGL(SCREEN_WIDTH, SCREEN_HEIGHT);
  Shader shader("shader_code/vertex_shader_quad.glsl", "shader_code/fragment_shader_quad.glsl");
  shader.use();
  glfwSwapInterval(1);

  std::vector<float> quadVertices;
  quadVertices.push_back(-0.5f);
  quadVertices.push_back(0.5f);

  quadVertices.push_back(-0.5f);
  quadVertices.push_back(-0.5f);

  quadVertices.push_back(0.5f);
  quadVertices.push_back(-0.5f);

  quadVertices.push_back(0.5f);
  quadVertices.push_back(0.5f);

  quadVertices.push_back(-0.5f);
  quadVertices.push_back(0.5f);

  glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT);

  unsigned int vbo, vao;

  glGenVertexArrays(1, &vao);
  glGenBuffers(1, &vbo);
  glBindVertexArray(vao);

  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, quadVertices.size() * sizeof(float), &quadVertices.front(), GL_STATIC_DRAW);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
  glEnableVertexAttribArray(0);

  glDrawArrays(GL_LINE_STRIP, 0, (quadVertices.size() / 2));

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);

  glfwSwapBuffers(window);
  glfwPollEvents();

  //let program run until button is pressed
  std::getchar();
}

GLFWwindow* initOpenGL(const int pScreenWidth, const int pScreenHeight)
{
  glfwInit();
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  GLFWwindow *window = glfwCreateWindow(pScreenWidth, pScreenHeight, "OpenGLRenderer", NULL, NULL);
  if (window == NULL)
  {
    std::cout << "Failed to create glfw window" << std::endl;
    glfwTerminate();
    return NULL;
  }
  glfwMakeContextCurrent(window);
  glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);

  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
  {
    std::cout << "Failed to initialize GLAD" << std::endl;
    return NULL;
  }

  return window;
}

void framebufferSizeCallback(GLFWwindow *window, int width, int height)
{
  glViewport(0, 0, width, height);
}

```

Shaders:

vertex shader:

```
#version 460 core

layout (location=0) in vec2 inPos;
out vec3 vertexColor;

void main()
{
  gl_Position = vec4(inPos, 0.0f, 1.0f);
  vertexColor = vec3(0.91f, 0.84f, 0.42f);
}

```

fragment shader

```
#version 460 core
in vec3 vertexColor;
out vec4 color;
void main()
{
  color = vec4(vertexColor, 1.0f);
}

```

Custom Shader Class:

```
#include <shader.h>

Shader::Shader(const char *pVertexPath, const char *pFragmentPath)
{
  std::string vertexCodeInput, fragmentCodeInput;
  std::ifstream vertexFile, fragmentFile;
  vertexFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  fragmentFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  try
  {
    vertexFile.open(pVertexPath);
    fragmentFile.open(pFragmentPath);
    std::stringstream vertexFileStream, fragmentFileStream;
    vertexFileStream << vertexFile.rdbuf();
    fragmentFileStream << fragmentFile.rdbuf();
    vertexFile.close();
    fragmentFile.close();

    vertexCodeInput = vertexFileStream.str();
    fragmentCodeInput = fragmentFileStream.str();
  }
  catch(std::fstream::failure eX)
  {
    std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
  }

  const char* vShaderSource = vertexCodeInput.c_str();
  const char* fShaderSource = fragmentCodeInput.c_str();

  unsigned int vertexShader, fragmentShader;

  vertexShader = glCreateShader(GL_VERTEX_SHADER);
  glShaderSource(vertexShader, 1, &vShaderSource, NULL);
  glCompileShader(vertexShader);

  //check compilation result
  int success;
  glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

  if (!success)
  {
    char vShaderInfoLog[1024];
    glGetShaderInfoLog(vertexShader, 1024, NULL, vShaderInfoLog);
    std::cout << "Error::SHADER::VERTEX::COMPILATION_FAILED" << std::endl << vShaderInfoLog << std::endl;
  }
  success = 0;

  //FRAGMENT SHADER
  //create shader, load shader code, compile shader
  fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
  glShaderSource(fragmentShader, 1, &fShaderSource, NULL);
  glCompileShader(fragmentShader);

  glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
  if (!success)
  {
    char fShaderInfoLog[1024];
    glGetShaderInfoLog(fragmentShader, 1024, NULL, fShaderInfoLog);
    std::cout << "Error::SHADER::FRAGMENT::COMPILATION_FAILED" << std::endl << fShaderInfoLog << std::endl;
  }
  success = 0;

  //create shader program, attach shaders
  id = glCreateProgram();
  glAttachShader(id, vertexShader);
  glAttachShader(id, fragmentShader);
  glLinkProgram(id);

  glGetProgramiv(id, GL_LINK_STATUS, &success);
  if (!success)
  {
    char shaderProgramInfoLog[1024];
    glGetProgramInfoLog(id, 1024, NULL, shaderProgramInfoLog);
    std::cout << "Error::SHADER::PROGRAM::COMPILATION_FAILED" << std::endl << shaderProgramInfoLog << std::endl;
  }
  success = 0;

  //already linked shaders can be deleted
  glDeleteShader(vertexShader);
  glDeleteShader(fragmentShader);
}

void Shader::use()
{
  glUseProgram(id);
}

void Shader::setBoolUniform(const std::string pUniformName, const bool pValue) const
{
  glUniform1i(glGetUniformLocation(id, pUniformName.c_str()), (int)pValue);
}

void Shader::setFloatUniform(const std::string pUniformName, const float pValue) const
{
  glUniform1f(glGetUniformLocation(id, pUniformName.c_str()), pValue);
}

void Shader::setIntUniform(const std::string pUniformName, const unsigned int pValue) const
{
  unsigned int uniformLocation = glGetUniformLocation(id, pUniformName.c_str());
  glUniform1i(glGetUniformLocation(id, pUniformName.c_str()), pValue);
}

```

Thanks in advance!

# Answer
> 1 votes
You're out of luck. There is nothing wrong in your code, and there's nothing you can do in your code to guarantee any set of arbitrary lines will *always* meet perfectly by using the technique you are using.

For line rasterization, OpenGL uses the diamond exit line rasterization rule (there is a primer of rasterization rules on the Direct3D documentation), but it allows some deviation to be performed by the specific OpenGL driver you are using.

Per the OpenGL FAQ chapter 14 on rasterization:

> **14.090 How do I obtain exact pixelization of lines?**
>
> The OpenGL specification allows for a wide range of line rendering hardware, so exact pixelization may not be possible at all.
>
> \[...\]
>
> **14.100 How do I turn on wide-line endpoint capping or mitering?**
>
> \[...\]
>
> OpenGL doesn't provide a mechanism to cleanly join lines that share common vertices nor to cleanly cap the endpoints.
>
> \[...\]
>
> **14.120 If I draw a quad in fill mode and again in line mode, why don't the lines hit the same pixels as the filled quad?**
>
> Filled primitives and line primitives follow different rules for rasterization.
>
> \[...\]
>
> (The OpenGL specification allows for some deviation from the diamond exit line rasterization rule, but it makes no difference in this scenario.)

I don't know about your specific use case, but the general idea is that this shouldn't matter. You should ask yourself if having pixel perfect joins between the lines is necessary for your application, and if it is, I suggest you write your own rasterizer that you can completely control.

# Answer
> 1 votes
If you only need to render closed loops of lines, consider using GL\_LINE\_LOOP instead of Gl\_LINE\_STRIP. It should link all the vertices properly.

For example, `glDrawArrays(GL_LINE_STRIP, 0, (quadVertices.size() / 2));` Becomes `glDrawArrays(GL_LINE_LOOP, 0, (quadVertices.size() / 2));`

You also will need to remove the last vertex from quadVertives, as it's redundant.

---
Tags: opengl, c++, rendering
---


# Question
Title: In a team of 2 people (one front end, one scripting), is there any way I could write scripts without the use of Unity all together?
So, I'm curious whether or not it would be possible to write scripts for a Unity game without using Unity itself, but using a third-party IDE, such as Visual Studio. My reason for this would be the following: I have a very low-end laptop, so I can not run Unity in any usable fashion. So I'm wondering if I could do the programming only part for the game without using Unity? By this, I mean writing the actual code and sending it over some online platform to be integrated with the Unity environment. And I know, this would not be productive at all.

# Answer
So if I got your question correct, you don't want to open Unity but write the scripts that would work on it?

You **CAN** but you might not be sure about what you've written since it can not be tested without opening Unity. You might even solve syntax errors using intellisense (Visual Studio have intellisense for these) but if there's any logical error, calculation mistakes that you might've made, you will have to open up Unity to debug.

Since scripts are simple text files, you can write it on any IDE you want to, but testing will definitely require opening Unity.
> 1 votes

# Answer
You may write those scripts but you'll be unable to test and debug them without opening unity.
> 0 votes

---
Tags: unity, teamwork, workflow
---


# Question
Title: How can I make a collision detection on marching objects?
In a Raymarching project I need to have a collision detection for my Signed Distance Field shapes.

I find a project that Implemented simple collision detection.but I need a more stable Physic when walking on a complex shape (e.g Fractal).

I have an Idea to create collider for my complex shape by voxelizing It.this Is mean I want to Instancing cubes that have box collider , but I don't know how can I do It.

Suppose that we have SDF voxel tours.how can I do collision detection?

```
Shader "Voxel torus"
{
    Subshader
    {
        Tags {"Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent"}
        ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off
        Pass
        {
            CGPROGRAM
            #pragma vertex vertex_shader
            #pragma fragment pixel_shader
            #pragma target 3.0

            struct custom_type
            {
                float4 screen_vertex : SV_POSITION;
                float3 world_vertex : TEXCOORD1;
            };

            static const float voxel_size = 0.1;

            float torus (float3 p, float2 t) //torus signed distance field function
            {
                float2 q = float2(length(p.xz)-t.x,p.y);
                return length(q)-t.y;
            }

            float map (float3 p) //scene geometry
            {
                return torus(p-float3(4,4,4),float2(2.0,0.6));
            }

            float4 lighting (float3 p, float3 normal) //surface color
            {
                float3 voxel = fmod(p, voxel_size) / voxel_size;
                float3 a = max(abs(normal), smoothstep(0.0, 0.1, voxel));
                float3 b = max(abs(normal), smoothstep(0.0, 0.1, 1.0 - voxel));
                float Line = a.x * a.y * a.z *b.x * b.y * b.z;
                float4 AmbientLight = float4 (0.2,0.2,0.2,1.0);
                float3 LightDirection = normalize(float3(1,1,-20));
                float3 NormalDirection = normal;
                float4 LightColor = float4(0.7,0.7,0.7,1.0) ;
                float4 Lambert =  max(dot(LightDirection,NormalDirection),0.0)*LightColor+AmbientLight;
                return lerp(float4(0,0,1,1.0), Lambert, Line);
            }

            float4 raymarch (float3 ro, float3 rd) //renderer
            {
                float3 voxel = floor(ro / voxel_size);
                float3 next = ((voxel + max(sign(rd), 0.0)) * voxel_size - ro) / rd;
                float3 step = sign(rd);
                float3 delta = voxel_size / abs(rd);
                float3 normal;
                float t = 0.0;
                for(int i = 0; i < 256; i++)
                {
                    float d = map(voxel * voxel_size);
                    if (d < 0.0001)
                    {
                        ro += rd*t*(1.0-abs(normal));
                        return lighting(ro,normal);
                    }
                    if(next.x < next.y && next.x < next.z)
                    {
                        voxel.x += step.x;
                        t = next.x;
                        next.x += delta.x;
                        normal = float3(-step.x, 0.0, 0.0);
                    }
                    else if(next.y < next.x && next.y < next.z)
                    {
                        voxel.y += step.y;
                        t = next.y;
                        next.y += delta.y;
                        normal = float3(0.0, -step.y, 0.0);
                    }
                    else if(next.z < next.x && next.z < next.y)
                    {
                        voxel.z += step.z;
                        t = next.z;
                        next.z += delta.z;
                        normal = float3(0.0, 0.0, -step.z);
                    }
                }
                return float4(0,0,0,0);
            }

            custom_type vertex_shader (float4 vertex:POSITION) //vertex shader
            {
                custom_type vs;
                vs.screen_vertex = UnityObjectToClipPos (vertex);
                vs.world_vertex = mul(unity_ObjectToWorld,vertex);
                return vs;
            }

            float4 pixel_shader (custom_type ps ):SV_TARGET //fragment shader
            {
                float3 worldPosition = ps.world_vertex;
                float3 viewDirection = normalize(ps.world_vertex-_WorldSpaceCameraPos.xyz);
                return raymarch(worldPosition,viewDirection);
            }

            ENDCG

        }
    }
}

```

# Answer
> 1 votes
Ray marching is nothing more than a collision detection algorithm. It just tends to be used for finding ray collisions, partly because it's in the name and partly because engineers tend to think through visualization.

So I can think of a way, but I'm just thinking... You are probably familiar with how intersections are rendered. It's taking the max of two SDFs. In this case you could "render" intersections by taking the max of two physical bounds. This way you know when you intersect and by how much along any possible direction (it's more than you need). You also know the vectors along which objects travel. From this and what your buffer or "render" tells you you should be able to deduce how to react to a collision. Conveniently I'll stop here.

I can't emphesise this enough that this is just a thought. I don't really know much about ray marching or rendering in general. So it could be that it's wrong reasoning or missing something.

The reason I found this post was because I plan to prototype a game using ray marching for some systems in the future using sparse voxels. So I may come back to this with a more detailled and helpful answer, but right now I'm not even supposed to be on stackexchange.

This is another way, but exclusive to something that has a root object (a.k.a. a fractal). from CodeParade on Marble Marcher

---
Tags: unity, collision-detection, shaders, raymarching
---


title: How do Mobile Idle-Games work

text:
# Question
Title: How do Mobile Idle-Games work
I wonder how idle games, games where players only make a few clicks to get a game progress, work. These games appear to be running in the background, even when the app is closed. Therefore these games may be implemented on the server side and run on it accordingly. I'm interested in the kind of implementation.

* Is there a program running on the server that creates a separate instance for each player and performs the actions accordingly?
* Or is this realised via a database?

Furthermore I ask myself where the data is stored, on the client (susceptible to manipulation) or on the server (high memory requirements).

Maybe one of you has experience in this area and can give me more information, insights or explain how it works. I am also happy about further reading or links.

# Answer
> 3 votes
You don't necessarily need to run such games server-sided. When the user exits the app, you save the game-state with the current time and date. When the player restarts the app, you reload the savegame, check the time and date of the device to see how much real-world time expired and simulate that time.

You could also do this server-sided if you want to. For example, because you have some multiplayer features in the game or you want to sell microtransactions and want to make sure the player doesn't cheat. In that case you would do the same thing: When a player connects to the server, you check how much time elapsed since the last session and advance the state of the game accordingly by simulating that time.

---
Tags: game-design, client-server, server, mobile, databases
---


# Question
Title: Can I apply to a large game studio if I know Unity?
I'm a Unity Developer (intermediate)

I want to know, can I apply to a company like EA or Ubisoft if I know Unity, and don't switch from Unity to Unreal or any other game engine?

# Answer
> 3 votes
Most of these large game companies have multiple development teams all around the world who work with all kinds of different technology stacks.

Ubisoft, for example, currently has a couple job openings for Unity developers. EA itself is mostly a publisher who does little game development themselves. But the studios owned by EA have job openings for developers. I haven't checked them all, but it wouldn't surprise me if some of them use Unity.

However, many of the AAA flagship titles are developed using inhouse engines you won't be able to teach yourself. But nobody else who applies to these companies is able to do this either, so they won't expect you to know their inhouse engine. So what they are looking for are people who are able to teach themselves new technologies quickly. If your career goal is to work in AAA game development, you should aim to become a holistic programmer who dives into all kinds of tech stacks, not an expert for one specific engine.

---
Tags: unity, hiring
---


title: VR Camera and Hands height

text:
# Question
Title: VR Camera and Hands height
Using the Oculus Rift S, I just added OVRCameraRig and LocalAvatar or OVRPlayerController and when I press play I feel like I'm not as high as I want in my vision and hands, I change the position of Y of objets to make it more higher, but it affects to everything, my guardian setup floor goes more high too and it does not match with my floor. What can I do to solve this? What should I change or modify?

# Answer
I solved my problem by scaling the game objects that affects to my player, as if it were real life.
> 1 votes

---
Tags: camera, virtual-reality, oculus
---


# Question
Title: Coverting byte[] from stereo to mono produces crackling in OpenAL
I'm trying to convert a Stereo byte\[\] to mono byte\[\]

Here is my code :

```
    private byte[] ToMono(byte[] data)
    {
        byte[] newData = new byte[data.Length / 2];

        for(int i = 0; i < data.Length / 4; ++i)
        {
            int HI = 1; int LO = 0;
            int left = (data[i * 4 + HI] << 8) | (data[i * 4 + LO] & 0xff);
            int right = (data[i * 4 + 2 + HI] << 8) | (data[i * 4 + 2 + LO] & 0xff);
            int avg = ((right + left) / 2);

            newData[i * 2 + HI] = (byte)((avg >> 8) & 0xff);
            newData[i * 2 + LO] = (byte)((avg & 0xff));
        }
        return newData;
    }

```

It converts to mono alright, but It produces crackling in OpenAL.

It seems that if I compile with "int avg = left;" The crackling stops. But I wanted to mix down both channels.

What is wrong with my code? How can take out the crackling?

# Answer
so for anybody struggling with stereo to mono conversion (16 bit pcm stereo) Here go's a solution:

```
    private byte[] ToMono(byte[] data)
    {
        byte[] newData = new byte[data.Length / 2];

        for(int i = 0; i < data.Length / 4; ++i)
        {
            int HI = 1; int LO = 0;
            short left = (short)((data[i * 4 + HI] << 8) | (data[i * 4 + LO] & 0xff));
            short right = (short)((data[i * 4 + 2 + HI] << 8) | (data[i * 4 + 2 + LO] & 0xff));
            int avg = (left + right) / 2;

            newData[i * 2 + HI] = (byte)((avg >> 8) & 0xff);
            newData[i * 2 + LO] = (byte)((avg & 0xff));
        }

        return newData;
    }

```
> 1 votes

---
Tags: c#, .net, openal
---


title: Unable to create OpenGL window in SDL2

text:
# Question
Title: Unable to create OpenGL window in SDL2
I am currently working on a C++ + SDL2 game engine and I am stuck on a problem. The problem is that whenever I pass `SDL_WINDOW_OPENGL` to `SDL_CreateWindow()`, it return null and so my program stops. But it works fine if I pass any other flag while not passing `SDL_WINDOW_OPENGL`. This is the function I am calling `SDL_CreateWindow()`:

```
Game::Game(const char* title, int w, int h, int x, int y, int glmajversion, int glminversion, Uint32 flags){
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
        std::cout<<"[Error]: Unable to initialize SDL2."<<std::endl;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, glminversion);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, glmajversion);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32);
    window = SDL_CreateWindow(title, x, y, w, h, flags);
    if (!window){
        std::cout<<"[Error]: Unable to create SDL2 window."<<std::endl;
        exit(-1);
    }
    context = SDL_GL_CreateContext(window);
    SDL_GL_MakeCurrent(window, context);
}

```

If I call `SDL_GetError()` before exiting, it returns "Couldn't find matching GLX visual".

# Answer
> 1 votes
It was my mistake. I set the depth buffer to 32 bit which my computer doesn't have a visual for. Changing depth buffer to 24 bit fixed the error.

---
Tags: opengl, c++, sdl2
---


# Question
Title: Moving Windows Mixed Reality main camera in Unity3D programatically
I'm trying to programmatically move the main camera i.e. player's point of view/origin in a Windows Mixed Reality but for some reason it's not working for me (using newest latest stable Unity 2018 and HoloToolkit through which I've setup my WMR project)... I've done the following:

```
m_MainCamera = Camera.main;
m_MainCamera.transform.position.Set(100f, 100f, 100f);
UnityEngine.XR.InputTracking.Recenter();

```

if `(Input.GetKeyDown(KeyCode.A))` happens, but even though the code gets run, my VR view position remains unchanged, and I'm guessing at 0,0,0 (or whatever is set initially)...so how exactly do they do those movements in the WMR's UI cliff house when you use the motion controller to point to place you want to transport your view...do they actually move all of the objects showing instead?

Or am I missing something really trivial when I can't move except for by moving my own body inside of VR? Maybe HoloToolkit is disabling it somehow... But how do I reenable it then to move to a predetermined places within a large life sized 3D model objects please?

TIA

# Answer
> 1 votes
The camera’s local position and rotation are set by the VR input every frame. Not the world position, the local position. Just nest your camera in a parent GameObject and move that around instead.

Also, calling `Set` on the position won’t work the way you want it to. You need to assign a new value whenever you want to change it:

```
m_MainCamera = Camera.main;
//Move the camera’s parent to recenter the VR system (note: make sure the camera has a parent)
m_MainCamera.transform.parent.position = new Vector3(100f, 100f, 100f);

```

---
Tags: unity
---


# Question
Title: Why is the IntelliSense not working when I open a new script in Visual Studio?
The strange thing is that opened scripts or newly opened ones are working fine. It's the new created C# scripts that are not working.

With not working, I mean the MonoBehaviour is not in light blue color it's in black color. In this screenshot I took, I marked it with a red circle.

What have I tried so far? I have closed Visual Studio and started over again. Since it didn't solve it, I closed the unity editor and started it over again, to no avail.

I pressed 'clean solution', I pressed 'rebuild solution', I pressed 'build solution'.

What else can I do ? And why are the other scripts working fine? If I type gameo...it will auto complete it to GameObject but in this specific script it's just not working.

This is a screenshot of the editor. I have in the Hierarchy a Ladder object. In the Assets I created a folder name Ladder and a script name Ladder. But this Ladder script is not working.

This is the Ladder script and this script was working before but once I created another script inside the ladder folder name Raise empty script the Raise script didn't work and now the Ladder is not working either. But other scripts are working fine.

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

public class Ladder : MonoBehaviour
{
    public Transform charcontroller;

    private bool inside = false;
    private float heightFactor = 3.2f;

    private void OnTriggerEnter(Collider other)
    {
            inside = true;
    }

    private void OnTriggerExit(Collider other)
    {
            inside = false;
    }

    private void Update()
    {
        if (inside == true && Input.GetKey("w"))
            charcontroller.transform.position += Vector3.up / heightFactor;
    }
}

```

# Answer
> 5 votes
The Solution shows that script under "Miscellaneous Files" This suggests that it hasn't been added to the project. Try manually adding it via the Project menu or dragging it into the appropriate area in your Project Explorer pane.

# Answer
> 4 votes
All you have to do is click on the assets folder in your solution explorer and click on the refresh button.

# Answer
> 2 votes
I get this all the time. Right-clicking on the project in solution explorer and selecting Unload project and then Reload project works for me

# Answer
> 2 votes
This is currently a general bug on pending release. Please have look at this : https://developercommunity.visualstudio.com/content/problem/130597/unity-intellisense-not-working-after-creating-new-1.html

For some poeple unloading and loading project is not working. For me, currently I'm creating my scripts inside Visual Studio via Unity Project Explorer window( View - Unity Project Explorer) which sees the script as a part of the solution.

# Answer
> 2 votes
When you modify a project with an external tool (explorer or unity or whatever) vs needs to reload the project. Sometimes unity doesn't trigger the automatic reload process and you either have to restart vs and unity or reload the project in vs manually.

# Answer
> 1 votes
I solved it with this steps: Go to the file inside Solution Explorer. Right-Click file and select Exclude from project. Right-Click your project/folder where the file was and click add Existing Item, and add the file you just removed back into your project.

# Answer
> 0 votes
None of the above worked for me. What did work for me was to Add a new dummy class to the folder (example: "DeleteMe"). Then try to reference that new dummy class somewhere.

When I did this, Intellisense actually saw this dummy class (when it wasn't seeing any of my existing classes). After this, I was able to access the original class I was trying to reference. Just make sure you delete the dummy class you created.

# Answer
> 0 votes
What fixed it for me was looking in the Unity Package Manager, where I saw that my VS version wasn't up to date. When I updated, the problem went away.

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


# Question
Title: Unity prefab script "GameObjects" can't be ones on the scene?
Currently, I have an object on the scene, and one in prefab. I want the prefab's script to reference to the object on the scene through the

```
public GameObject obj;

```

code. However, when I tried to add the object in the editor, I cant seem to be able to select any objects from the scene, only ones in prefabs.

I am quite new at unity, so am I missing something really basic here?

Thanks for any help!

# Answer
> 3 votes
If you have the gameobject with the code attached selected, you can drag the gameobject in the scene using the hierarchy to the inspector.

Confusing I know, here is a picture:

EDIT: Strike that, this is more accurate:

With unity, you can not reference things in the hierarchy from a prefab. You need to somehow add it at runtime. A cheap way to do this is to store 'the gameobject in the scene' in a static variable. For instance something like:

```
public static GameObject thingonstage;
void Start(){
    thingonstage = this.gameobject;
}

```

Then later, you reference the static global variable to get at it.

# Answer
> 1 votes
Prefabs are supposed to be reusable between different scenes. They can not reference a game object in the scene hierarchy, because that object would be unavailable if the prefab is used in a different scene. That's why prefabs can only reference assets, other prefabs or parts of themselves (like their children).

What you can do instead:

* Have your Start method find the object to interact with in the scene. There are several ways you can do that. You can use GameObject.Find to find it by name (can be slow if you have a lot of objects in the scene), you can assign an unique tag to the object and then use GameObject.FindWithTag or you can use the singleton pattern in a script on the referenced object.
* Assign the object to interact with when you instantiate the prefab. If you spawn the prefab from a script, then that script will need to have a reference to the object. If you create a prefab instance in the Unity editor, you will have to assign that reference manually.

# Answer
> -1 votes
Drag & drop the appropriate gameobject from your scene hierarchy to the property you want to set.

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


title: Score does not increment by 1 in Unity

text:
# Question
Title: Score does not increment by 1 in Unity
I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why.

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

public class Game : MonoBehaviour
{
    public int Score = 0;

    void Start()
    {

    }

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

    }

    private void OnTriggerEnter2D(Collider2D other)
    {

        AddScore();
    }

    void AddScore()
    {

        Score++;

    }
}

```

# Answer
> 1 votes
We cannot be sure of the exact issue without seeing how the scene is set up and what the player object consists of. However, the problem seems to be that somehow when your player enters the collider it is triggering the event multiple times.

Some possible issues:

* The player is made up of 8 colliders
* Other objects are entering the trigger and interfering

---
Tags: unity
---


# Question
Title: How do I render a word in the middle of the screen using FreeType and OpenGL?
I'm following this tutorial series on making a simple 2D clone of the classic Breakout game, but its author doesn't mention how to render **a whole word** or sentence in the middle of the screen. He simply uses hard-coded X and Y coordinates that obviously work for his screen, but not for mine (hence why the mere suggestion of using hard-coded values for something like this makes my skin crawl).

For more details on how he accomplishes the task, see this page of the aforementioned tutorial.

My version of his game has two major differences:

1. I am rendering the GLFW window in fullscreen mode instead of a 800x600 window.
2. I suspect that even if I were to use a 800x600 window, things still wouldn't look consistent across every device. As such I have made many changes to hard-coded values across the entire code base.

I'm a perfectionist so even though no-one else will probably ever run my game, I'm trying to eliminate the possibility of different results on different resolutions. But to do that has turned out to be a massive undertaking!

Here is the code that I'm having particular trouble with:

```
void TextRenderer::RenderText(string text, GLfloat x, GLfloat y, GLfloat scale, vec3 color) {
    // Activate corresponding render state
    shader.Use();
    shader.SetVector3f("textColor", color);

    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(vao);

    // Iterate through all characters
    for (auto c = text.begin(); c != text.end(); c++) {
        auto ch = characters[*c];

        auto xPos = x + ch.bearing.x * scale;
        auto yPos = y + (characters['H'].bearing.
            y - ch.bearing.y) * scale;
        auto w = ch.size.x * scale;
        auto h = ch.size.y * scale;

        // Update VBO for each character
        GLfloat vertices[6][4] = {
            { xPos,     yPos + h, 0.0, 1.0 },
            { xPos + w, yPos,     1.0, 0.0 },
            { xPos,     yPos,     0.0, 0.0 },

            { xPos,     yPos + h, 0.0, 1.0 },
            { xPos + w, yPos + h, 1.0, 1.0 },
            { xPos + w, yPos,     1.0, 0.0 }
        };

        // Render glyph texture over quad
        glBindTexture(GL_TEXTURE_2D, ch.textureID);

        // Update content of VBO memory
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferSubData(GL_ARRAY_BUFFER, 0,
            sizeof(vertices), vertices);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        // Render quad and advance cursors for next glyph
        glDrawArrays(GL_TRIANGLES, 0, 6);
        // Bitshift by 6 to get value in pixels (1/64th times 2^6 = 64)
        x += (ch.advance >> 6) * scale;
    }

    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}

```

I have tried adding a `bool centreX` and `bool centreY` param to the function, as well as another `for` loop before the main one like this:

```
if (centreX || centreY) {
    auto textWidth = 0.0f;
    auto textHeight = 0.0f;

    for (auto c = text.begin(); c != text.end(); c++) {
        auto ch = characters[*c];

        if (centreX) {
            textWidth += (ch.bearing.x * scale) + (ch.size.
                x * scale) + ((ch.advance >> 6) * scale);
        }

        if (centreY) {
            textHeight += (y + (characters['H'].bearing.y -
                ch.bearing.y) * scale) + (ch.size.y * scale);
        }
    }

    if (centreX) {
        auto lastCh = text.end() - 1;
        textWidth -= (characters[*lastCh].advance >> 6) * scale;
    }
}

```

But for the sentence, font and font size used I'm getting a `textWidth` value of 1952 while a screenshot of the rendered text is 1143 px wide :S

Where has my math or understanding of the original code gone wrong? My display is a high DPI one and I have my Windows scaling settings at 200%; could either of those things be the culprit?

MTIA!

# Answer
The picture below (from the website you linked) is quite good to understand what is going on. `Advance` is the distance from one character's origin to the next. To get the width of the whole text you should add the `advances` together. Right now you are adding the bearing, the width and the advance.

Once you have the size of your text and the size of your window you can add an offset to each character that is `(window_width - text_width)/2`.
> 2 votes

---
Tags: opengl, c++, text
---


title: How do I generate a torus mesh?

text:
# Question
Title: How do I generate a torus mesh?
I'm trying to programmatically generate vertices and indices for a torus. I found this piece of code somewhere, and it looks like it works, but I'm not certain it is correct.

With my little knowledge of trigonometry, I figured out how the vertex generation part works, but I'm stuck at the index buffer part (though I know what the modulus operator is used for).

Does the code work correctly? Can anyone explain what it does to generate the correct indices?

I tried to output the index buffer and noticed there's a triangle with indices `(10,10,10)`, which is weird and makes me think this may be wrong. Plus the UVs look weird for the last 'slice' of the torus, as in this pic.

```
int sides = 10, cs_sides = 40;
float radius = 3.5 * 10.0;
float cs_radius = 0.75 * 10.0;

numVertices = sides * cs_sides;
Vertices = malloc(sizeof(Vertex) * numVertices);

numIndices = (2 * ((sides+1) * cs_sides) + cs_sides);
Indices = malloc(sizeof(GLushort) * numIndices);

int angleincs = 360/sides;
int cs_angleincs = 360/cs_sides;
float currentradius, zval;

//calculating the vertex array
for (int j=0, m=0; j<360; j+=cs_angleincs, m++)
{
    currentradius = radius + (cs_radius * cosf(j * D_TO_R ));
    zval = cs_radius * sinf(j * D_TO_R );

    int index = (m*sides);
    for (int i=0, n=0; i<360; i+=angleincs, n++)
    {
        Vertices[index + n].Position[0] = currentradius * cosf(i * D_TO_R ); // x
        Vertices[index + n].Position[1] = currentradius * sinf(i * D_TO_R ); // y
        Vertices[index + n].Position[2] = zval;                              // z

        Vertices[index + n].Color[0] = 1.0;
        Vertices[index + n].Color[1] = 0.0;
        Vertices[index + n].Color[2] = 0.0;
        Vertices[index + n].Color[3] = 1.0;

        float u = (float)i/sides;
        float v = ((float)j + u)/cs_sides;

        Vertices[index + n].TexCoord[0] = u;
        Vertices[index + n].TexCoord[1] = v;
    }
}

// cs_sides = 40
// sides = 10

int i=0, n=0;
//calculating the index array
for (;i<cs_sides; i++) {
    for (int j=0; j<sides; j++) {
        Indices[n++] = i * sides + j;
        Indices[n++] = ((i+1) % cs_sides) * sides + j;
    }

    Indices[n++] = i * sides;
    Indices[n++] = ((i+1)%cs_sides) * sides;
    Indices[n++] = ((i+1)%cs_sides) * sides;
}

```

# Answer
In order to build a torus you'll need to understand some basic vector algebra:

1. vectors sums: **X**:=(x1,x2,x3), **Y**:=(y1,y2,y3); **X** \+ **Y**=(x1+y1, x2+y2, x3+y3)
2. scalar multiplication: **X**:=(x1,X2,x3); a·**X** = (a·x1, a·x2, a·x3)
3. norm: |**X**| = √(x1·x1 + x2·x2 + x3·x3)
4. *\[optional\]* scalar/dot product: **X·Y**= (x1·y1 + x2·y2 + x3·y3) so |**X**|² = **X·X**

Our Torus will be centered on C, its radius1 (*d*) will be parallel to the **XY** plane and the radius will be *d'*. We will use *u* to run on the first circle and *v* to run to the second circle around the ring. Both *u* and *v* will go from 0 to 2π in radians.

We use *u* to compute the point **P** on the circle centered on **C**. To construct the second circle, we similarly construct a second circle that is centered on **P** and parallel to the direction **C**-\>**P**. I hope this image explains what I mean:

The reddish circle is constructed same as the first, with a difference: the circle does not lies on a standard plane but on the plane parallel both to the **Z** axis and the **C**--\>**P** direction (the segment labeled *d*, the radius).

Lets go back to the first circle: when we say

we are saying that

where **X** = (1,0,0), **Y** = (0,1,0), **Z** = (0,0,1): the "component adding".

We can do the same for the second circle using **P** as center, discarding the third component (as it is zero), using the **Z** axis as for the *sin* component and the **W** axis for the *cos* component.

The *W* axis is simply an arbitrary axis that we construct so it is directed from **C** to **P** and has unitary length (as **X**, **Y** and **Z** were).

The *norm* of a vector is its length so we can define **W** as follows:

we take **W'** = **P** \- **C** because it the vector that "moves" **C** to **P** ( **C** \+ **W'** = **C** \+ **P** \- **C** = **P**); then we set **W** to have the direction of **W'** and the length of 1.

This is the result:

Now you have a way to compute the point **Q** in terms of *u* and *v*.

Noticing **W** is always *(cos(u),sin(u),0)*, we can put it all together and write the function **Q**(*u*, *v*):

You can now construct your quads by connecting: (*u*, *v*) -\> (*u*, *v*+1) -\> (*u*-1, *v*+1) -\> (*u*-1, *v*)

For triangles, only connect:

(*u*, *v*) -\> (*u*, *v*+1) -\> (*u*-1, *v*) and

(*u*-1, *v*) -\> (*u*, *v*+1) -\> (*u*-1, *v*+1)

*(P.S. Doesn't your framework have some sort of torus primitive?)*

1(the author messed up and called radius diameter originally, hence the *d*)
> 24 votes

# Answer
I have been looking for a small algorithm to generate a torus mesh along its UV texture coordinates (I simply use cross product for normals). To my surprise, the only useful result that came through different search engines were this answer (and other answers telling you to use a god damn API).

The thing is there is a few issues with this algorithm and to spare you the hassle of a few hours of debugging, here are my corrections:

First issue: the UV coordinates seems completely wrong :

```
float u = (float)i/sides;
float v = ((float)j + u)/cs_sides;

```

The values assigned to u and v should be between 0 and 1. Here the u coordinates contain the slice number. I don't know how the values are used on the opengl side, but I fail to see a practical use for these. Instead just use:

```
float u = i / 360.;
float v = 2. * j / 360 - 1;
if (v < 0) v = -v;

```

Here I mirror the texture, otherwise it is way too squished (or at least use a very wide texture). That way you can give those values directly to glTexCoord().

Next issue: although the indices generates a mesh of a torus, it will look weird if you try to texture it, even with the correction I gave for UV values:

Here I use a simple white and black checkboard texture. You can see that one section of the torus looks wrong. What happened here is that the last ring has its U coordinate very close to 1. The index array will then generate a mesh that link the last ring with the first ring (which has a U coordinate of 0) : that's why the last slice of the torus appears with almost an entire copy of the texture.

Easy fix: iterate both loops from 0 to 360 including (instead excluding).

Edit: added and tested normals with Gouraud shading (no texture, 20 sides):

Corrected version:

```
typedef struct Model_t *       Model;

struct Model_t
{
    int        vertex, index;
    float *    vertices;
    float *    tex;
    float *    normals;
    uint16_t * indices;
};
void vecNormalize(float A[3])
{
    float len = 1 / sqrt(A[0]*A[0] + A[1]*A[1] + A[2]*A[2]);
    A[0] *= len;
    A[1] *= len;
    A[2] *= len;
}
#define D_TO_R     (M_PI/180)
Model modelGenTorus(int sides, int cs_sides, float radius, float cs_radius)
{
    int numVertices = (sides+1) * (cs_sides+1);
    int numIndices = (2*sides+4) * cs_sides;

    Model torus = malloc(sizeof *torus + numVertices * 8 * sizeof (float) + numIndices * 2);
    float * Vertices;
    float * TexCoord;
    uint16_t * Indices;

    torus->vertices = Vertices = (float *) (torus + 1);
    torus->normals  = Normals  = Vertices + numVertices * 3;
    torus->tex      = TexCoord = Normals + numVertices * 3;
    torus->indices  = Indices  = (uint16_t *) (torus->tex + numVertices * 2);
    torus->index    = numIndices;
    torus->vertex   = numVertices;

    int angleincs = 360/sides;
    int cs_angleincs = 360/cs_sides;
    float currentradius, zval;
    int i, j, nextrow;

    /* iterate cs_sides: inner ring */
    for (j = 0; j <= 360; j += cs_angleincs)
    {
        currentradius = radius + (cs_radius * cosf(j * D_TO_R));
        zval = cs_radius * sinf(j * D_TO_R);

        /* iterate sides: outer ring */
        for (i = 0; i <= 360; i += angleincs, Vertices += 3, TexCoord += 2)
        {
            Vertices[0] = currentradius * cosf(i * D_TO_R);
            Vertices[1] = currentradius * sinf(i * D_TO_R);
            Vertices[2] = zval;

            float u = i / 360.;
            float v = 2. * j / 360 - 1;
            if (v < 0) v = -v;

            TexCoord[0] = u;
            TexCoord[1] = v;
        }
    }

    /* compute normals: loops are swapped */
    for (i = 0, nextrow = (sides+1) * 3, Vertices = torus->vertices; i <= 360; i += angleincs, Normals += 3, Vertices += 3)
    {
        float * vert;
        float * norm;
        float xc = radius * cos(i * D_TO_R);
        float yc = radius * sin(i * D_TO_R);
        for (j = 0, vert = Vertices, norm = Normals; j <= 360; j += cs_angleincs, norm += nextrow, vert += nextrow)
        {
            norm[0] = vert[0] - xc;
            norm[1] = vert[1] - yc;
            norm[2] = vert[2];
            vecNormalize(norm);
        }
    }

    /* indices grouped by GL_TRIANGLE_STRIP, face oriented clock-wise */

    /* inner ring */
    for (i = 0, nextrow = sides + 1; i < cs_sides; i ++)
    {
        /* outer ring */
        for (j = 0; j < sides; j ++)
        {
            *Indices++ = i * nextrow + j;
            *Indices++ = (i + 1) * nextrow + j;
        }

        /* generate dummy triangle to avoid messing next ring */
        Indices[0] = i * nextrow + j;
        Indices[1] = Indices[2] = Indices[3] = Indices[0] + nextrow;
        Indices += 4;
    }
    return torus;
}

```
> 4 votes

---
Tags: algorithm, content-generation
---


title: IL2CPP Vector.Dot inconsistency

text:
# Question
Title: IL2CPP Vector.Dot inconsistency
I get inconsistent results when I run this code as standalone Windows on Mono and IL2CPP backends.

```
var a = new Vector3(-1.26998901f, 0, -0.849998474f);
var b = new Vector3(20.0799999f, -1, 164.580002f);
var dot = Vector3.Dot(a, b);
var mydot = (float) ((double) a.x * (double) b.x + (double) a.y * (double) b.y + (double) a.z * (double) b.z);

```

```
+-------+----------------+-------------+
|       | Mono or Editor |   IL2CPP    |
+-------+----------------+-------------+
| dot   | -165.394135    | -165.394119 |
| mydot | -165.394135    | -165.394135 |
+-------+----------------+-------------+

```

Take a look at the `dot` result on IL2CPP backend in the table above.

My `mydot` implementation should be equivalent to `Vector3.Dot(Vector3, Vector3)` according to dotPeek in Rider.

Decompiled Vector3.Dot(Vector3, Vector3)

```
/// <summary>
///   <para>Dot Product of two vectors.</para>
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
public static float Dot(Vector3 lhs, Vector3 rhs)
{
  return (float) ((double) lhs.x * (double) rhs.x + (double) lhs.y * (double) rhs.y + (double) lhs.z * (double) rhs.z);
}

```

Unity version: `2018.4.12f1`

What causes `Vector3.Dot(Vector3, Vector3)` to give a different result on IL2CPP?

# Answer
> 0 votes
This is the IL2CPP output of the `Vector3.Dot` method:

```
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Vector3_Dot_m0C530E1C51278DE28B77906D56356506232272C1 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  ___lhs0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  ___rhs1, const RuntimeMethod* method)
{
    float V_0 = 0.0f;
    {
        float L_0 = (&___lhs0)->get_x_2();
        float L_1 = (&___rhs1)->get_x_2();
        float L_2 = (&___lhs0)->get_y_3();
        float L_3 = (&___rhs1)->get_y_3();
        float L_4 = (&___lhs0)->get_z_4();
        float L_5 = (&___rhs1)->get_z_4();
        V_0 = ((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_multiply((float)L_0, (float)L_1)), (float)((float)il2cpp_codegen_multiply((float)L_2, (float)L_3)))), (float)((float)il2cpp_codegen_multiply((float)L_4, (float)L_5))));
        goto IL_0036;
    }

IL_0036:
    {
        float L_6 = V_0;
        return L_6;
    }
}

```

Note that it does nothing related to casting to doubles. It is unclear why, but the IL2CPP version of `Vector3.Dot` does not match the Mono implementation in that respect. On the other hand, the mydot version compiles to this:

```
    // var mydot = (float)((double)a.x * (double)b.x + (double)a.y * (double)b.y + (double)a.z * (double)b.z);
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_12 = V_0;
    float L_13 = L_12.get_x_2();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_14 = V_1;
    float L_15 = L_14.get_x_2();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_16 = V_0;
    float L_17 = L_16.get_y_3();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_18 = V_1;
    float L_19 = L_18.get_y_3();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_20 = V_0;
    float L_21 = L_20.get_z_4();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_22 = V_1;
    float L_23 = L_22.get_z_4();
    V_3 = (((float)((float)(float)((double)il2cpp_codegen_add((double)((double)il2cpp_codegen_add((double)((double)il2cpp_codegen_multiply((double)(((double)((double)(double)L_13))), (double)(((double)((double)(double)L_15))))), (double)((double)il2cpp_codegen_multiply((double)(((double)((double)(double)L_17))), (double)(((double)((double)(double)L_19))))))), (double)((double)il2cpp_codegen_multiply((double)(((double)((double)(double)L_21))), (double)(((double)((double)(double)L_23))))))))));

```

That's a lot of casts, and definitely makes sure we are using doubles.

This is what it looks like when you remove the explicit double casting:

```
    // var mydot = a.x * b.x + a.y * b.y + a.z * b.z;
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_24 = V_0;
    float L_25 = L_24.get_x_2();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_26 = V_1;
    float L_27 = L_26.get_x_2();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_28 = V_0;
    float L_29 = L_28.get_y_3();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_30 = V_1;
    float L_31 = L_30.get_y_3();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_32 = V_0;
    float L_33 = L_32.get_z_4();
    Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720  L_34 = V_1;
    float L_35 = L_34.get_z_4();
    V_4 = ((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_multiply((float)L_25, (float)L_27)), (float)((float)il2cpp_codegen_multiply((float)L_29, (float)L_31)))), (float)((float)il2cpp_codegen_multiply((float)L_33, (float)L_35))));

```

I don't know *why* the `Vector3.Dot` implementation is different between IL2CPP and Mono (perhaps for performance?), but it is different, and there is the reason for your discrepancy anyway.

---
Tags: unity, il2cpp
---


# Question
Title: Why does my recursive coroutine freeze Unity?
I want the bounds (left wall and right wall) to follow the player's y position, a couple of times. However when I use this code, Unity freezez as soon as it runs, and I have to manually shut it down.

Any idea why?

```
public Transform bounds;

//in another function
StartCoroutine(Follow_Bounds(0));

IEnumerator Follow_Bounds(int a)
{
    yield return new WaitForSeconds(1f);
    while(a < 3)
    {
        StartCoroutine(Follow_Bounds(a + 1));
    }
   bounds.position = new Vector2(bounds.position.x, transform.position.y);
}

```

# Answer
> 1 votes
The loop:

```
while(a < 3)
{
    StartCoroutine(Follow_Bounds(a + 1));
}

```

Runs forever. `a + 1` doesn't change `a`'s value, it just passes a new value to the new coroutine instance.

You're likely crashing because each `StartCoroutine` call generates a helper object behind the scenes, since the loop runs forever, you'll run out of memory and crash.

# Answer
> 1 votes
You want to move the bounds (only y position) with player after a few seconds of delay?

I do have a workaround that might work, it doesn't use recursion. You can use `InvokeRepeating` in this.

```
void SomeOtherFunction()
{
   InvokeRepeating("MoveBounds", InitialDelay, RepeatDelay);
}

void MoveBounds()
{
   bounds.position = new Vector2(bounds.position.x, transform.position.y);
}

```

SomeOtherFunction can be a Start() function as well. It will automatically repeat the MoveBounds function for you with every RepeatDelay Seconds (in your case it can be 1 seconds)

If you want to stop this function you can simply use `CancelInvoke("MoveBounds");` and it will cancel the invoke function.

I hope it helps, here's the Documentation link for the function.

**NOTE:** It needs to be called only once, and it will repeat itself.

# Answer
> 0 votes
<sup>*I don't have much experience with Unity and its coroutines, so things might not be completely exact.*</sup>

You have something like infinite nested loops.

```
StartCoroutine(Follow_Bounds(0));

IEnumerator Follow_Bounds(int a)
{
    yield return new WaitForSeconds(1f);
    while(a < 3)
    {
        StartCoroutine(Follow_Bounds(a + 1));
    }
    bounds.position = new Vector2(bounds.position.x, transform.position.y);
}

```

Could conceptually be expanded to something like this:

```
StartCoroutine(Follow_Bounds(0));

IEnumerator Follow_Bounds(int a) // With a == 0
{
    yield return new WaitForSeconds(1f);
    while(0 < 3)
    {
        yield return new WaitForSeconds(1f);
        while(1 < 3)
        {
            yield return new WaitForSeconds(1f);
            while(2 < 3)
            {
                yield return new WaitForSeconds(1f);
                while(3 < 3)
                {
                    // This will not be called
                    // yield return new WaitForSeconds(1f);
                    // StartCoroutine(Follow_Bounds(a + 1));
                }
                bounds.position = new Vector2(bounds.position.x, transform.position.y);
            }
            bounds.position = new Vector2(bounds.position.x, transform.position.y);
        }
        bounds.position = new Vector2(bounds.position.x, transform.position.y);
    }
    bounds.position = new Vector2(bounds.position.x, transform.position.y);
}

```

In no situation here you make sure that the end condition is met. When your program freezes, or hangs, it's generally a symptom of an infinite loop.

If you want to use recursion, you could modify your code to something like:

```
StartCoroutine(Follow_Bounds(0));

IEnumerator Follow_Bounds(int a)
{
    if(a < 3)
    {
        StartCoroutine(Follow_Bounds(a + 1));
        yield return new WaitForSeconds(a + 1f);
        bounds.position = new Vector2(bounds.position.x, transform.position.y);
    }
}

```

Things to note here: we "loop" using the recursion, not a "code" loop; all your 'wait' are started upfront, with a different delay; we have a clear end condition.

However, this is overly complicated code. Recursive code should be avoided when possible, and should be explained and justified in the comments when unavoidable. If you can use an API or language construct instead, use that. (Another answer covers this.) If not, use a loop instead.

So the preferred algorithm to complete such a task is **API or language construct** \> **loop** \> **recursive code**.

---
Tags: unity, coroutines
---


# Question
Title: Unity Initializing class of a script not working
I have been trying to find a solution for the last couple of hours so please hear me out. At first I got a NullReferenceException, which I resolved(?) by initializing the class first (This is my problem! I can't seem to initialize my class sucessfully). However, here are my next errors. I tried using the `new` keyword, which resulted in `You are trying to create a MonoBehaviour using the 'new' keyword`. Next I tried `GetComponent<>()`, which resulted in a `CS0120`, that I didn't know how to fix. The `AddComponent<>()`, resulted in a `CS0103` `The name AddComponent does not exist in the current context`. What I tried next was `GameObject.AddComponent<>()`, which threw a `CS0120`, and `gameObject.Addcomponent<>()` which threw a `CS0236`.

Here is my code for the class I am trying to initialize if it should be needed:

```
public class Dialogue : MonoBehaviour {
public TextMeshProUGUI textDisplay;
public string[] sentences;
private int index;
public float typingSpeed;

public GameObject continueButton;

void Update() {
    if (textDisplay.text == sentences[index]) {
        continueButton.SetActive(true);
    }
}

public IEnumerator Type() {
    foreach (char letter in sentences[index].ToCharArray()) {
      textDisplay.text += letter;
      yield return new WaitForSeconds(0.01f);
    }
}

public void NextSentence() {
    continueButton.SetActive(false);

    if (index < sentences.Length - 1) {
        index++;
        textDisplay.text = "";
        StartCoroutine(Type());
    } else {
        textDisplay.text = "";
        continueButton.SetActive(false);
    }
  }
}

```

Here is from where I tried to initialize:

```
public class Mace : MonoBehaviour {
//Dialogue dialogue = gameObject.AddComponent<Dialogue>();

private void OnTriggerEnter2D(Collider2D otherCollider) {
    if (otherCollider.CompareTag("Player")) {
        StartCoroutine(dialogue.Type());
    }
}

```

}

# Answer
Your main problem here is that you're trying to put code into a field initializer that is not valid there. As your error messages are telling you, field initializers are not allowed to reference non-static members, because when they run, by definition, the instance they're running for hasn't finished initializing yet!

You have two main options (which are already explained thoroughly here — this is why it's important to read thoroughly when someone links you to an existing duplicate Q&A)

**1.** Make your reference `public` and populate it in the Unity Inspector interface before you run your game. Then the variable will be filled in by Unity's deserializer automatically when your object loads/spawns.

```
public class Mace : MonoBehaviour {

    // This adds a field you can set in the Inspector.
    public Dialogue dialogue;

    void Start() {
        if(dialogue == null)
            Debug.LogError("You forgot to populate the dialogue field before running!");
    }

    // ...the rest of your script goes here.

}

```

**2.** Fetch/add the component you need when this script "boots up," in Start or Awake:

```
public class Mace : MonoBehaviour {

    // We can leave this private if wiring it up ourselves.
    Dialogue _dialogue;

    void Awake() {
        // Create a new dialogue component attached
        // to the same object as this script,
        // and cache a reference to it.
        _dialogue = AddComponent<Dialogue>();
    }

    // ...the rest of your script goes here.

}

```

Myself, if the script only makes sense when there's a specific dependency present, I like to make that dependency visible to Unity so it can enforce it for me at edit time, then at runtime I can just pick up a reference to the component I know will be there waiting for me;

```
// This attribute tells Unity to add a Dialogue
// component anytime I add a Mace component.
[RequireComponent(typeof(Dialogue))]
public class Mace : MonoBehaviour {

    Dialogue _dialogue;

    void Awake() {
        // Since the editor enforces our dependency,
        // we can be confident it's there to "Get"
        _dialogue = GetComponent<Dialogue>();
    }

    // ...the rest of your script goes here.

}

```
> 0 votes

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