# Question
Title: Collision2d Unity To Change Another Scripts Int Value
I am looking to decrease the value stored in my script "progress" which takes 1 away from a value curHealth, when the Player sprite to which this script "collision", is attacked/ touching the Enemy 2d box collider. The decreasing of the value doesn't happen when the two objects touch. Both the Player and the Enemy have 2dbox colliders and other shape 2d colliders.

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

public class collision : MonoBehaviour {

    public progress Progress = GameObject.FindGameObjectWithTag("HealthBar").GetComponent<progress>();

    void OnCollisionStay2d(Collision2D coll){
        if (coll.gameObject.name == "Enemy") {

            Progress.curHealth -= 1;

            }
        }

}

```

# Answer
> 1 votes
Your `OnCollisionStay2D` function has a typo. Capitalize the letter "d" at the end, then it will work if there is not another problem. And also another tip, please do capitalize the first letter of **Classes**, **not the objects**.

---
Tags: unity, 2d
---


title: Start Broadcast Unity Network Discovery

text:
# Question
Title: Start Broadcast Unity Network Discovery
I am using the unity `NetworkDiscovery` component, and I am wondering how I can auto-start broadcasting when the server starts, instead of the client having to click on the gui: `Initialize Broadcast` =\> `Start Broadcasting`. I would like to be able to put some `C#` in my start host function so that the user does not have to do anything.

# Answer
> 0 votes
Couple of ideas, if possible subscribe to a "Start server event", if thats not available, you could try a Timer , onElapsedTime event and try connectiong every few seconds, until it works, and when it does turn the timer off.

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


# Question
Title: How to balance experience gain with player collaboration?
I'm developing an online game with friends, and we're currently blocked by a overall game design issue: how do you reward players with experience points and loot/gold yet still encourage them to play together, especially with players who are not necessarily in their skill range?

**Technical details of our game:**

* Grid-based, top-down overworld map layout (think *Legend of Zelda*)
* Randomly generated, turn-based dungeons (think *Pokemon Mystery Dungeon*)
* Experience curves, non-combat skills, trading, social interaction (think *Runescape*)

The plan is for players to socialize, do parts of quests, and skill in the overworld, then enter dungeons with groups of ~4 friends into order to skill combat and get loot. Ideally, more skilled players can enter harder dungeons and do harder tasks, yet still be able to join newer players in easier dungeons without it being mundane and without forcing one player to take up most of the combat.

**Possible fixes:**

* Remove all sorts of experience curves and rewards, and have everything be balanced (downside: no reason to grind)
* Restrict "leveling" to gaining more money and better weapons (downside: having more loot virtually becomes being a higher level)
* Raise low-leveled players to the level of the highest-leveled team member when in dungeons (downside: may be a loophole to allow players to skill quickly)
* Add an extra component of the game that requires user skill, so players won't rely solely on levels to be good at the game (e.g. quick time events) (downside: hard to implement in a turn-based game, ambiguous)

These are just some ideas, and I have been pondering this issue for a little while now. What are some thoughts on this issue and what mechanic may be introduced to reconcile this?

# Answer
> 4 votes
While completely removing your leveling curve might go against the typical genre convention of MMORPG games, you can at least try to keep it relatively flat (which means just a small gain of raw nummerical power per levelup). That way you increase the level ranges where cooperation still makes sense for players. You should also allow and encourage players to have more than one character. When players have multiple characters in different level ranges, their pool of potential playmates increases. The best way to do that is by offering a wide range of possible character options with different playstyles.

If you decide to go the level adjustment route to allow characters of different levels to interact better, I would rather recommend you to scale the high-level players down than the low-level players up. The reason is that upscaling will give the lowbies access to abilities and other content they haven't been introduced to yet. But make sure to design your loot and exp distribution systems to always reward cooperation, especially (but not only) for the stronger players. When a highbie gets scaled down in order to help lowbies to clear a dungeon which would usually be too easy for the highbie, make sure the highbie still gets rewards as if they were in a level-appropriate dungeon.

# Answer
> 4 votes
1. **Reward coordination** \- make it so that party members have to coordinate movement and tasks like activating game elements and fighting enemies in different locations of a dungeon in order to progress faster and / or get better loot (think Space Alert board game). This way you ensure that playing as a group is more efficient.
2. **"Mentor-Apprentice"** type dungeons can be created where different tasks require different character level to complete but the ultimate success in form of loot for the entire party is tied to everyone completing their individual objectives. "Mentor"-level rewards should be greater in order for high level players to go to this type of dungeons and train rookies (as opposed to playing regular high level content).

# Answer
> 2 votes
You could reward players for playing well with others. An example of this mechanic would be to divide experience between players, depending on the level. This would provide incentive for players to work with each other. This could be made more enjoyable, and less grindy, by beefing up the lower level monsters. These monsters would typically target the higher levelled players; making it harder for the high levelled player to progress. They would than need the lower level players to beat on the monster, to keep themselves from dying.

# Answer
> 1 votes
Don't share the experience in an equal way.

I mean if there are 2 players grinding together, don't share the experience in a 50% for each. Boost up it, make that each one get 60% of the experience. And yes that means that the monster doesn't give the usual 100% of the experience, if not a 120%. If there are 3 players the monster could give 150% shared between them.. u get it, no?

# Answer
> 1 votes
I think this problem is more two sided and should be viewed from the low level perspective aswell: why would a low level character want a high level player to join? Except for faster questing and transcendent

1. **Grinding craftable stuff**: maybe you get better weapons by crafting instead of only questing. So you need low level stuff instead and that's from low level dungeons. By joining a group you drastically increase drop chance and if it only drops if you have some in the party with a certain level. Lowbe's can pick it up and sell it for an immediate effect. Still, low and high level won't enjoy the dungeon.
2. **Level up equipment**: There might be high level equips that give heavy penalties, so you become as weak as a lower level char. But by leveling this, it may get stronger than comparable items that level. The high level player can enjoy some challenges and low level players the low level are equally strong but get more experience.
3. **Leveling a pet/companion**: Instead of his high level char, someone can send a pet to play in the dungeon. He has new skills, more support effects and couldn't beat a dungeon on its own, so you have a low level party with this support pet. You loose some damage but gain it's benefits. When a pet is leveled, it gives Boni to the high level Char, so the high level gets gameplay variety and by that better 'equipment'.

Balancing experience in this context seams hard, that's why I wouldn't touch that in any way.

---
Tags: game-design, multiplayer, game-mechanics, mmo
---


# Question
Title: How to solve conflicting OnValidate() functions
I have two `OnValidate()` functions in two scripts, one attached to the `Enemy` (EnemyScript) game object and the other to the `Enemies`(EnemiesScript) game object.

In `OnValidate()` in `EnemyScript` I have the following:

```
    void PrepareEnemyType(EnemyType enType) {

    // by default hasHibernated = false
    if (!hasHibernated) {
        if (enType == EnemyType.Green) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/greenEnemy");

        }
        else if (enType == EnemyType.Red) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/redEnemy");

        }
    }

    else if (hasHibernated) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/greyEnemy");

    }
}

```

In `OnValidate()` in `EnemiesScript` I have the following:

```
for (int i = 0; i < enemies.Length; i++) {
        if (!enemies [i]. hasHibernated) {
            enemies[i]. hasHibernated = true;

        }
    }

```

based on the above all the enemies should change sprite to `greyEnemy` sprite, but that doesn't happen. Before I run the application all of them change to `greyEnemy` sprite initially, then after I run the application some of them change back to their original sprites, and when I stop running the application they sprites remain the same as when the application was running (different sprites). At this point, the only time that they all become grey again is when I make some other edit to either one of the scripts and save it. Then the above transition repeats. I suspect there could be some conflict with the two `OnValidate()` functions, not certain though. How can I resolve this?

# Answer
> 1 votes
From documentation:

> This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).

`OnValidate` doesn't get called unless you *manually* set values in the inspector.

---
Tags: unity
---


# Question
Title: Detecting when a car is out of the track
I am completely new to Unity 3D, just started to follow some tutorials y'day. I am trying to build a 2D car racing game as a part of my learning (time beating, no opponents). I have a racing track as texture (repeating). My problem is knowing when the car is outside/inside the track (I wouldn't prefer to limit it to the track boundaries).

What I have tried after searching around : I read somewhere about Mesh Colliders so:

* I added a mesh collider to the track (with 'Convex' and 'Is Trigger' checked , to be honest I don't know what Convex is, but I couldn't check 'Is Trigger' w/out checking 'Convex').
* Added OnTriggerExit and OnTriggerEnter methods to the Track script (the script that scrolls the track) hoping the two would be called each timer the car goes out of the track or gets back in.

Apparently the two methods aren't called at all, Would someone please help. Thanks.

# Answer
I can think of 3 solutions of the top of my head i'll list them by simplicity (in my opinion):

1. You can check what texture is currently under the car, and test it against textures that are considered "track" textures, if not then its out otherwise its in.
2. You can use Triggers along the track and check if the car is in at least 1 trigger, being in one or more triggers means its inside the track, otherwise its outside of it, for this you will have to get the triggers info from a script bound to each of the empty objects with triggers attached to a final bigger script (one way for example).
3. Writing a code that can run through the terrain data, and check everywhere that is track (probably using textures again), pre process that data and just check the car position relative to your pre processed data.
> 2 votes

# Answer
Maybe it's a typo, watch out for Capital letters. Did you assign any name to the Trigger collided with?

If you just write `OnTriggerEnter(){...}` Or `OnTriggerExit(){...}` it won't work. You need a name for the Collider that triggered it. so for example `OnTriggerEnter(Collider2D Player){...}` Or `OnTriggerExit(Collider2D Player){...}`.

If you did that, it should at least be called.
> 0 votes

---
Tags: unity, meshcollider
---


title: Saving score in Unity

text:
# Question
Title: Saving score in Unity
I have the following script which I use for calculating the score

```
public class Score : MonoBehaviour {

    Score sc;

    void Start()
    {
        GameObject obj = GameObject.Find("ScoreSystem");
        sc = obj.GetComponent<Score>();

    }

    void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.tag == "Ball")
        {
            sc.score++;
        }
    }
}

```

and this is the class where I increase the value

```
public class Score : MonoBehaviour {

    public int score;

    void Start()
    {
        score = 0;
    }

}

```

But the problem I have is that the value always stays 0 when I switch to a different scene. I even used this code to store the value and display in the next scene but it didn't work

```
void Update()
{
    PlayerPrefs.SetInt("score", score);
    PlayerPrefs.Save();
}

```

and this code for taking the value

```
score = PlayerPrefs.GetInt("score");

```

How can I store the latest value inside an Int and display it in the next scene and when I leave that scene it reverts back to 0?

# Answer
> 0 votes
**Save to Disk**: Use a serialisation library like the built in BinaryFormatter class or a 3rd party library like Newtonsoft's JSON.Net which you can get via NuGet in most IDEs. This will allow you to save the score to disk which you can load in the start method of your "Score" class if the save file exists.

This would allow you to keep the score without having to change much code and any possible references that you have set up in the editor but would mean that you have to manage the file between games as by default a new game would have the score of the last (easy to solve by deleting the file when starting a new game).

**Keep the score object between scenes**: In unity it is possible to call "DontDestroyOnLoad" which will preserve your "Score" Object when you go to the next scene. If you have another "Score" object in the other scene there will be two (one from the last scene and a new one from the new scene) so you might have to manage which one is used.

If you only want one "Score" you might want to look at implementing the Singleton pattern Unity have a video on it and there is also a good example here that you can use. The Singleton ensures that there is only one instance of an object and (usually) provides easy access to the current instance. You would have to change the `GameObject.Find("ScoreSystem");` to something along the lines of `Score.Instance` which is more efficient when you have lots of objects.

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


# Question
Title: What are the legal implications of creators streaming their development?
Is there any question of losing ownership of their work if people stream themselves coding? I can understand that streaming modeling, animations, and game design would be fine because even if you see someone do it it will take time to do, but what about code?

Are there worries about other people recording their streams and using their code? Is there some special case for these games like being open source or non proprietary?

# Answer
Vlambeer had a GDC talk about streaming development of their game Nuclear Throne that you can watch on youtube. They streamed some parts of the game that an audience would find interesting. Give it a watch it answers a lot of your questions.

As far an I know they have not had any issues with people stealing their game. They still have the IP of their game and don't have issues.

If someone "stole their code" they would only have small fragments which they could use but what are they really going to do with one class without all the other classes that are needed to make that class work? Without a large chunk of the code or the code for a module you couldn't really make a direct copy it.

As for open source games like Simutrans and OpenTTD they have an open licence so you can use it for whatever you like. The catch is that they still have the Trademark of the game so you can copy and paste the code and change a line of code and sell it but that most likely won't hold up in court under copyright law.

Hope this helps

\*I'm not a lawyer.
> 2 votes

---
Tags: legal, intellectual-property
---


# Question
Title: Rotate LWJGL 2 Vector4f by an angle around an axis
There is a method in `LWJGL 2` to get the rotation Matrix around an axis with a certain angle- `Matrix4f.rotate(angle, axis, dest, src)`. Is there a similar way to rotate a `Vector4f` around a `Vector3f` or `Vector4f`? What can I do to rotate around 2 axes? I am implementing an FPS Camera

# Answer
What you will need to do is use LWJGL's `Matrix4f.transform()` method to transform your Vector4f by using a matrix with rotation information. This method takes in a Matrix4f and a vector. The vector can be whatever you want, but the matrix is what you really care about. You'll have to use LWJGL's rotate methods to rotate the matrix along whatever axis you want. On a side note, you can also do translations and scaling and other stuff as well. Once the matrix is done, you can transform your Vector4f using the matrix. Here's a quick demo

```
Vector4f toTransform = new Vector4f(0, 1, 0, 1);
Matrix4f matrix = new Matrix4f;
float rx = 90; //x axis rot in degrees
float ry = 0; //y axis rot
float rz = 0; //z axis rot
matrix.setIndentity();
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1, 0, 0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0, 1, 0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0, 0, 1), matrix, matrix);
Vector4f rotated = matrix.transform(matrix, toTransform, toTransform);
Vector3f vec3 = new Vector3f(rotated.x, rotated.y, rotated.z);
etc..

System.out.println(rotated);

```

Outputs Vector4f\[0, 0 (very small number), 1, 1\], which is correct.
> 1 votes

---
Tags: lwjgl
---


title: SharpDX instancing with D3D11

text:
# Question
Title: SharpDX instancing with D3D11
Could anybody provide working code using SharpDX with D3D11, which does instancing and uses SharpDX's content pipeline?

I have several problems there. I came to understand that one should use a `SharpDX.Direct3D11.InputLayout` to describe the vertex shader's input. There I already have a problem. I use SharpDX's content pipeline, so the shaders are compiled in compile time and not in runtime. Where do I get the shader's byte code then? It shouldn't be that hard, but it seems it's inaccessable from the effect object.

My other question is how can I set the created `SharpDX.Direct3D11.InputLayout` before the current `DrawIndexedInstanced` call?

# Answer
> 1 votes
the input layout is attached after compile, so you have defined the layout within the compiled shader code, you now need to attach the input layout. Remember, all your compile has done is create a binary file output, so you need to firstly load it (wherever it is) into a ShaderBytecode object then create in Sharpdx the relevant Shader from that bytecode.

For example:

```
D3D11.VertexShader m_vsShader = new SharpDX.Direct3D11.VertexShader(GlobalStatics.Device, m_vsShaderByteCode);
```

You then need to create your input layout (and as its instanced),

```
    m_bufferLayoutInstanced = new D3D11.InputLayout(GlobalStatics.Device, m_vsShaderByteCode.GetPart(SharpDX.D3DCompiler.ShaderBytecodePart.InputSignatureBlob), new[] {
             new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0, 0, D3D11.InputClassification.PerVertexData, 0),
                        new D3D11.InputElement("NORMAL",   0, DXGI.Format.R32G32B32A32_Float, 16, 0, D3D11.InputClassification.PerVertexData, 0),
                        new D3D11.InputElement("TEXCOORD", 0, DXGI.Format.R32G32B32A32_Float, 32, 0, D3D11.InputClassification.PerVertexData, 0),
                        new D3D11.InputElement("TEXCOORD", 1, DXGI.Format.R32G32B32A32_Float, 48, 0, D3D11.InputClassification.PerVertexData, 0),

                        new D3D11.InputElement("INSTANCE_TRANSFORM", 0, DXGI.Format.R32G32B32A32_Float, 0, 1, D3D11.InputClassification.PerInstanceData, 1),
                        new D3D11.InputElement("INSTANCE_TRANSFORM", 1, DXGI.Format.R32G32B32A32_Float, 16, 1, D3D11.InputClassification.PerInstanceData, 1),
                        new D3D11.InputElement("INSTANCE_TRANSFORM", 2, DXGI.Format.R32G32B32A32_Float, 32, 1, D3D11.InputClassification.PerInstanceData, 1),
                        new D3D11.InputElement("INSTANCE_TRANSFORM", 3, DXGI.Format.R32G32B32A32_Float, 48, 1 ,D3D11.InputClassification.PerInstanceData, 1),
                        new D3D11.InputElement("INSTANCE_FLOAT", 4, DXGI.Format.R32G32B32A32_Float, 64, 1 ,D3D11.InputClassification.PerInstanceData, 1)
                    });
```

# Answer
> -2 votes
Already solved, there are some nice pitfalls, one should avoid:

* For getting the shader's byte code, one must recompile the shader.
* To set the input layout, one should cast the device to a SharpDX.Direct3D11.Device and use it's immediate context. Note that existing vertex buffer layout can be used to create the begining of the input layout.
* One must also call the DrawIndexedInstanced method on the immediate context itself. Calling this method on a SharpDX.Toolkit.Graphics.GraphicsDevice will result in an incorrect parameter exception.

---
Tags: sharpdx, instancing
---


# Question
Title: What is the simplest way to calculate energy earned based on time?
A player has 0 energy, and gains 5 every 15 minutes, but has a maximum of 100 energy.

How would I be able to both store this in a database, and then recall the data later, to figure out how much energy the player now has?

The only way that I can think of is to save both the last updated time as well as the energy level at the last update, but that feels like it is not the best way.

Are there alternatives to this that are more efficient or 'better' and feel less kludge-y?

# Answer
I mean, you *could* store only a single variable for this, if you wanted to. Rather than a stored charge level and a stored time, you store the time you would have had to start charging from zero to reach where you are now. You can then compare against that fictional zero moment to get your current energy at any later time;

```
chargePerSecond = 5/(15 * 60)

SetEnergy(currentEnergy) {
   pseudoChargeStart = now
     - currentEnergy/chargePerSecond
}

GetEnergy() {
   return
      min(100,
         ( now - pseudoChargeStart )
         * chargePerSecond )
}

```

(Above assuming you're varying energy continuously for simplicity. Similar formulas can do this in a stepped fashion if needed)

I don't recommend this though. It's less obvious what this code does, and that clarity makes it easier for mistakes and bugs to creep in. Compare to the direct/basic method, which we can verify for correctness at a glance:

```
SetEnergy(currentEnergy) {
    lastSetEnergy = currentEnergy
    lastSetTime = now
}

GetEnergy() {
   return
      min(100, lastSetEnergy
         + ( now - lastSetTime )
         *  chargePerSecond )
}

```

The other point to consider is how easy it is to maintain as your game changes. If the designers suddenly decide they don't want a linear charge rate anymore, but some kind of custom non-linear curve, then the one-field method gets much more complicated to work out.

And really, all it saves you is a matter of bytes per player. A typical game almost certainly has bigger fish to fry. ;)
> 1 votes

---
Tags: algorithm
---


title: How do open-world game saves work?

text:
# Question
Title: How do open-world game saves work?
(Sorry if this shouldn't be asked here, I'm unsure if it's appropriate based on what's allowed here.)

I'm not developing a game, but I'm very curious about this. I've played some large open-world games recently (Dishonored, for example), and it boggles my mind how much information must be stored for save files. If I pick up a bottle from where it spawned and throw it, then save while it's in mid-air, the save file needs to contain a) what type of bottle it is, b) where it is right now, c) what orientation it's currently in, and d) what its current trajectory is. This is the case for every non-fixed asset in the current level. Pathing NPCs have to have their current state tracked as well.

So, in general, how do games accomplish this? I'm sure the implementation varies, I'm not asking for any specific game, but the overall concept must be similar across games. Even more impressive to me is that quick saves often seem to be instant, with no delay whatsoever after pressing the key.

# Answer
> 6 votes
Your hunch is pretty much spot on. Games like skyrim will save the orientation, speed, and all other physics for each object. Some games will speed this process up by skipping over distant object and simply replacing them to their starting position.

Games appear to be quick about it because they use multi-threading. This means the game can be running while performing another task in the background. Most games are multi-threaded without you realizing it: the physics engine, the audio engine, the rendering engine, the input, finally the game logic itself. So when the player presses save, the game creates a task to run independently from the game logic to log all the game data. This is called an *asynchronous behavior*.

Games can get crafty with the storage of the data. For example again, Skyrim saves little details of all the objects far away. But notice that the game takes time to place those objects back and it might not be perfect every time. This is because the game needs to save space so all that data is *compressed*. You can think of compression as just an algorithm to remove duplicate lines of bits while keeping note where the duplicates are. When they are uncompressed (or inflated/extracted) the duplicates go right back where they belong. So games like Skyrim may compress the save data and extract the data while you are playing the game.

---
Tags: savegame
---


# Question
Title: How do I change from positive degrees to negative degrees?
Recently, in Unity, I tried to move a sphere along a figure-eight path. It first moves in a circle, and after completing the circle, it starts the second circle in reverse, using negative rotation. However, my plan did not work as I expected. The reason is that Unity changes negative degrees into positive degrees, so -15 degrees becomes 345 degree. Therefore, the direction of the circular movement won't change, when you flip from a positive degree to a negative degree. In other words, if the first path is clock-wise the second path (after changing the sign of the degree) will be clock-wise, too.

Is there any practical way to overcome this problem, and change the direction of rotation by changing from positive degrees to negative degrees?

Here is one of the scripts I have tried:

```
public class PlayerMover : MonoBehaviour
{
    float x;
    public float speed=100.1f;
    private Transform playerTransform = null;

    void Start ()
    {
        playerTransform = GetComponent<Transform>();
    }

    void Update ()
    {
        x=speed*Time.deltaTime;
        playerTransform.Rotate(0, 5 *funct(x) * x, 0);
        playerTransform.position += playerTransform.forward ;
    }

    public float funct(float u)
    {
        u=Mathf.Sin(u);
        return u;
    }
}

```

As you can see. even the function I use to flip from positive degrees to negative degrees is a smooth and continuous function, mathematically speaking.

# Answer
Your diagnosis of the problem is incorrect. Unity handles negative angles just fine, as you can see here:

The problem is how you're calculating your rotation increment. As described above, `Time.deltaTime` is the time in seconds that have elapsed since the last frame (typically 1/60 - 1/30). As long as your framerate holds steady, this value is nearly constant. It's good for *scaling* change over time to keep a consistent *rate*, but it doesn't itself progress over time.

If you want something to change over time, then you'll want to either:

Here's the code used above. You can see just like yours it rotates each frame by an increment that's scaled by a sine function. In this one though, the sine varies over `Time.time`, so the phase progresses from frame to frame

```
public class Figure8 : MonoBehaviour {

    public float secondsPerLoop = 3f;
    public float forwardSpeed = 1f;

    void Update () {
        // Sharp direction change.
        // float direction = Mathf.Sign(
        //  (Time.time / secondsPerLoop) % 1.0f - 0.5f);
        // float rotationDoubling = 2f;

        // Smooth direction change.
        float direction = Mathf.Sin(
            Time.time * 2f * Mathf.PI / secondsPerLoop);
        float rotationDoubling = 2.43f; // Eyeballed, not precise.

        float rotationIncrement =
            rotationDoubling * Time.deltaTime * 360f / secondsPerLoop;

        transform.Rotate(0f, direction * rotationIncrement, 0f);
        transform.Translate(0f, 0f, forwardSpeed * Time.deltaTime);
    }
}

```
> 0 votes

# Answer
Have you tried animations instead? Not saying it should be done with animations, just an alternative. He is one way to get the figure 8 done with code:

```
float x;
public float speed = 100.1f;
public int otherWay = 1;
public int count = 0;
public Vector3 startingPostion;

private Transform playerTransform = null;

void Start()
{
    playerTransform = GetComponent<Transform>();
    startingPostion = playerTransform.position;
}

void Update()
{
    x = speed * Time.deltaTime;
    playerTransform.Rotate(new Vector3(0, otherWay * 5 * funct(x) * x, 0));
    playerTransform.position += playerTransform.forward;

    if (count == 43)
    {
        otherWay = otherWay * -1;
        count = 0;
        playerTransform.transform.position = startingPostion;
    }
    count++;

}

public float funct(float u)
{
    u = Mathf.Sin(u);
    return u;
}

```
> 0 votes

---
Tags: unity, rotation
---


# Question
Title: C++ - Assimp - OpenGL vertex data feed problem
I'm getting a very weird problem where OpenGL doesn't use the hardware to render anything, so I get just a cleared blank screen.

Here's some code:

```
//Mesh.hpp
template <typename T>
struct Vertex
{
    glm::tvec3<T> Coordinate;
    glm::tvec3<T> Normal;
    glm::tvec2<T> TextureCoordinates;
};

using FVertex = Vertex<float>;
using DVertex = Vertex<double>;

class Mesh
{
public:
    explicit Mesh(aiMesh*, const aiScene*);
    explicit Mesh(const Mesh&);
    explicit Mesh(Mesh&&);
    virtual ~Mesh();

    Mesh& operator=(const Mesh&) = delete;
    Mesh& operator=(Mesh&&) = delete;

public:

public:
    virtual void Render(const uint32_t&);
    virtual void SetupMesh();

private:

private:

protected:
    std::vector<FVertex> VertexBuffer;
    std::vector<uint32_t> IndexBuffer;
    std::vector<Texture> Textures;

    gl::GLuint VAO;
    gl::GLuint VBO;
    gl::GLuint EBO;

protected:

};

//Mesh.cpp

//This is how I feed the buffers. I've double checked, and the
//data imported from a Wavefront file is inside the VertexBuffer and IndexBuffer,
//and it is correctly loaded.
void Mesh::SetupMesh()
{
    gl::glBindVertexArray(VAO);
    gl::glBindBuffer(gl::GL_ARRAY_BUFFER, VBO);
    gl::glBindBuffer(gl::GL_ELEMENT_ARRAY_BUFFER, EBO);

    gl::glBufferData(gl::GL_ARRAY_BUFFER, VertexBuffer.size() * sizeof(Realms::FVertex), &(VertexBuffer.at(0)), gl::GL_STATIC_DRAW);
    gl::glBufferData(gl::GL_ELEMENT_ARRAY_BUFFER, IndexBuffer.size() * sizeof(uint32_t), &(IndexBuffer.at(0)), gl::GL_STATIC_DRAW);

    using Realms::FVertex;

    gl::glVertexAttribPointer(0, 3, gl::GL_FLOAT, gl::GL_FALSE, sizeof(FVertex), (void*)(offsetof(FVertex, Coordinate)));
    gl::glVertexAttribPointer(1, 3, gl::GL_FLOAT, gl::GL_FALSE, sizeof(FVertex), (void*)(offsetof(FVertex, Normal)));
    gl::glVertexAttribPointer(2, 2, gl::GL_FLOAT, gl::GL_FALSE, sizeof(FVertex), (void*)(offsetof(FVertex, TextureCoordinates)));
    gl::glEnableVertexAttribArray(0);
    gl::glEnableVertexAttribArray(1);
    gl::glEnableVertexAttribArray(2);
 }

void Mesh::Render(const uint32_t& glProgram)
{
    gl::glBindVertexArray(VAO);
    gl::glDrawElements(gl::GL_TRIANGLES, IndexBuffer.size(), gl::GL_UNSIGNED_INT, &(IndexBuffer.at(0)));
}

```

I've used a debugger to make sure the data inside the buffers is correct and accurate, that the vertex array object, buffer object and element object are all correctly generated and bound. Since my engine concept always chunks it down to drawing Meshes, nothing is being rendered. Here are the vertex and fragment shaders using GLSL:

```
 //VERT
 #version 330 core

layout (location = 0) in vec3 triangle;
layout (location = 1) in vec3 normals;
layout (location = 2) in vec2 TextCoords;

uniform mat4 ProjectionMatrix;
uniform mat4 LookAtMatrix;
uniform mat4 ModelMatrix;

void main()
{
    gl_Position = ProjectionMatrix * LookAtMatrix * ModelMatrix * vec4(triangle, 1.0);
}

 //FRAG
#version 330 core

out vec4 FragColor;

void main()
{
    FragColor = vec4(0.6, 0.3, 1.0, 1.0);
}

```

I've made sure the ProjectionMatrix, LookAtMatrix, and ModelMatrix are all correctly sent to the vertex shader.

# Answer
Solved. Although the OpenGL specification documentation clearly states :

```
void glDrawElements(GLenum mode,
                    GLsizei count,
                    GLenum type,
                    const GLvoid * indices);

```

/

```
*indices*
Specifies a pointer to the location where the indices are stored.

```

, calling glDrawElements with indices = (void\*)(0) worked for me.
> 1 votes

---
Tags: opengl, c++, glsl, assimp
---


# Question
Title: Label does not maintain correct position within a Table
I'm hoping the fix is quite simple, but this has become increasingly frustrating. I've built a minimally reproducable example. This is how the table is rendered:

And this is the corresponding code:

```
    private Table testTable() {
        Table table = new Table();
        Skin skin = new Skin(Gdx.files.internal("skin/uiskin.json"));
        Label label1 = new Label("String", skin);
        Label label2 = new Label("Hello", skin);
        Label label3 = new Label("World", skin);

        table.add(label1);

        table.row();

        table.add(label2).width(100).height(100);
        table.add(label3).width(200).height(200);

        table.setFillParent(true);
        table.debugAll();

        return table;
    }

```

As you can see, the "Hello" and "World" labels are not centered within their logical tables. Further, even if I try `.width(100).height(100).center()`, or even `.bottom().right()`, for example, the two labels' positions are always fixed to the left, center of their logical table.

The only way I could 'fix' the problem is by excluding the `.width().height()`, but I need them for my UI.

Any thoughts?

# Answer
To understand why `left()` `right()` `center()` etc. doesn't work try doing `label1.left()` or `label2.top()`. See how they move to be top / left aligned? Well why is this?

This is because those methods align the `Actor` inside of the `Cell`, **not the content** inside of the `Actor`. To understand take a look at my (super professional) drawing:

See how `label1` and `label2` does not occupy the entire `cell`, but `label3` does? This is why we can change the alignment of `label1` and `label2` but not `label3`. From this picture we can also see that if we align `label1.top()` or `label2.left()` this wouldn't have any effect since they cannot be moved in that direction.

## Solution

If you want to align the text inside of a `Label` use `Label#setAlignment()` with one or more constants from the `Align` class (docs). In your case you need `setAlignment(Align.center)` to center the text inside of the label.

Code:

```
private Table testTable() {
    Table table = new Table();
    Skin skin = new Skin(Gdx.files.internal("skin/uiskin.json"));
    Label label1 = new Label("String", skin);
    Label label2 = new Label("Hello", skin);
    label2.setAlignment(Align.center); // Align
    Label label3 = new Label("World", skin);
    label3.setAlignment(Align.center); // Align

    table.add(label1);

    table.row();

    table.add(label2).width(100).height(100);
    table.add(label3).width(200).height(200);

    table.setFillParent(true);
    table.debugAll();

    return table;
}

```

This will produce this result:
> 2 votes

# Answer
In your current code you are expanding the actors (in this case labels) themselves by setting `.width(xxx)` and `.height(xxx)`. You can see this by the green rectangles which indicate your actor. Since the labels are by default aligned to the left your text will show aligned to the left. If you do `.right()` there will be no change since it's already on the right since it's stretches the whole cell.

One easy fix would be to set the alignment of your labels.

```
label2.setAlignment(Align.center);
label3.setAlignment(Align.center);

```

You can add additional alignments by using "|" like `label3.setAlignment(Align.center | Align.top);`.

I guess you want to be the world as large as possible and the main table to fill the whole screen. This can be done with the `expand()` and `fill()` method. This will adjust the size to fill the whole table, you already told the table to fit the stage by setting it to fill it's parent.

```
private Table testTable() {
    Table table = new Table();

    Label label1 = new Label("String", skin);
    Label label2 = new Label("Hello", skin);
    Label label3 = new Label("World", skin);

    table.columnDefaults(1).width(300);

    table.add(label1).row();

    table.add(label2);
    table.add(label3).expand().fillX(); //<-- only change

    table.setFillParent(true);
    table.debugAll();

    return table;
}

```

Since by default widgets/actors are aligned to center within the table cell both `label1` and `label2` will be centered. If you want to have some extra room in your left column you can also use padding and leave the alignment of text with

```
table.add(label1).pad(20).row();

```
> 1 votes

---
Tags: libgdx
---


# Question
Title: How to handle collision detection & response in voxel engine with slopes?
* Voxels are fairly small
* An object can span an area of 8x8x8 or more
* Vertices of `Voxel Type` are always *snapped to the grid*:

* Voxel types are *convex* (except the second type - which can be thought of as an OR between two rotated voxels of third type)
* Including all the configurations of the above, there are 77 distinct voxel types.

Seems like there could be a *fairly simple* algorithm for doing collision detection and response between `AABB` / `Bounding-Box` / `sphere` and a single `Voxel` \- considering the simple and rigid geometry restrictions in place, but I can't come up with one at the moment.

# Answer
> 3 votes
There is a fairly simple way to do collision detection between a single "voxel shape" and an AABB.

It relies on the SAT (separating axis theorem) - finding a plane which separates both objects. As soon as we find one we know there's no collision.

First off checking all planes of AABB of the voxel and then again against all sloped planes of the voxel.

4th voxel type also has 3 potential sloped edges to check against.

Now this only handles the collision detection part. In order to resolve the collision after we find that objects intersect, we have to enumerate all the potential separating planes to see which one has the least amount of overlap - and then move the object away along the plane normal using the penetration depth.

The real tricky part is figuring out how to resolve collision vs multiple sloped voxels at the same time - there are multiple penetration vectors and distances.

---
Tags: collision-detection, collision-resolution, voxels
---


# Question
Title: Unity Transport Layer API - How to manage client-server connections
I am currently working on a "Master server" system for our Unity Game using Unity's Low Level "Transport layer API" for networking.

My problem is that I would like to prevent clients from connecting to eachother. I have tried not giving them a port on the Addhost() call, but it doesn't seem to change anything. They also do not seem to detect the connections, so basically I find myself with NetworkTransport.Connect(..) calls that work (the error byte is 0, meaning no error) but no actual connections. I don't understand what's going on.

I can't really show my code because it's quite long, but here's how it works, in summary :

The Clients objects initialise a Socket as normal with only one Reliable channel, no port, and one connection allowed by default. Then they have the ability to connect to another socket, as you'd expect. My problem COULD be coming from there : for testing purposes the IP I use for testing is 127.0.0.1. What I do not understand is, how can it "find itself" when it is not bound to any port ? And more importantly how can it NOT find the Master Server object whose socket IS bound to a port ?

Speaking about Master Server, it's an object that also initialises its socket, but with a port and many allowed connections.

When a client connects and the connection did not yield any errors, it considers the connection to the Master server to be successful and proceeds sending a message containing some information for the server about this client : the username chosen by the player for example.

When the master server receives a connection event, it registers the received ConnectionID and waits for more information from that same connection, for example the aforementioned username.

Both the client and the server handle receiving messages with the NetworkListener class (Static). On each frame it executes the Listen() method which executes a "normal" NetworkTransport.Receive() body. I can give you that part of the code as it is fairly common in design :

```
public static void Listen()
{
    int recHostID;
    int recConnectionID;
    int recChannelID;
    byte[] buffer = new byte[1024];
    int recDataSize;
    byte error;
    NetworkEventType e = NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, 1024, out recDataSize, out error);
    Debug.Log("Listening");
    switch(e)
    {
        case (NetworkEventType.Nothing):
            break;
        case (NetworkEventType.ConnectEvent):
            Debug.Log("Connection established. ConnectionID = " + recConnectionID);
            if (OnConnectionReceived != null)
            OnConnectionReceived(recHostID, recConnectionID, recChannelID);
            break;
        case (NetworkEventType.DataEvent):
            Debug.Log("Received data !");
            BinaryFormatter f = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(buffer);
            Message = f.Deserialize(stream) as NetworkMessage;
            break;
        case (NetworkEventType.DisconnectEvent):
            Debug.Log("Connection terminated. ConnectionID = " + recConnectionID);
            break;
    }
}

```

Network message is a simple data structure which contains a ConnectionID (the one it's from), a message title and content. The title is used to determine the general purpose of the message. The content is the rest of the information.

What happens in my current build of the client :

The user is prompted to enter a username, then he clicks "Search for match". The search for match button is supposed to trigger the connection to the Master Server. The logs say that the connection was successful (as no errors are detected) but no Connection event is received on either side. This of course prevents everything else from working.

If you need further description of the problem just ask and I'll answer ASAP.

Thanks a lot in advance !

# Answer
> -2 votes
Your `Listen` method needs to be called in the `Update` "loop", like such:

```
void Update()
{
   Listen();
}

```

Edit: If the connection establishment works, you should check your if statement. Thanks for the downvote..

You could also use the debugger to check your source code or simply use google :)

---
Tags: unity, networking
---


# Question
Title: How can I create a "wireframe" texture for a sphere in SceneKit?
I've been struggling to figure this out. I would like to have a sphere in SceneKit that looks like this:

I think the easiest way would be to create a mostly transparent texture with the wireframe lines. I need some help figuring out how to create this texture.

I've been doing some trial and error with colored lines to try to figure this out, but it's a mess and I don't seem to be getting anywhere.

Eventually I want to procedurally generate the wireframe texture in a `CALayer`, but first I need to figure out where to draw the lines.

# Answer
> 2 votes
Quick solution didn't turn out quite as well as I'd like, but I'll post it up regardless as it may help someone out. To get something that better matches your figure I believe you'll need to build your own `SCNGeometry` with probably a box for each line. This can be done, and there's several examples on building your own geometry around, but it is a fair bit of code.

Anyway, I was hoping a quick shader modifier would get what you were after.

```
    let sm =
    "float u = _surface.diffuseTexcoord.x; \n" +
    "float v = _surface.diffuseTexcoord.y; \n" +
    "int u100 = int(u * 100.0); \n" +
    "int v100 = int(v * 100.0); \n" +
    "if (u100 % 10 == 1 || v100 % 10 == 1) { \n" +
    "    // do nothing \n" +
    "} else { \n" +
    "    discard_fragment(); \n" +
    "} \n"

    let sphere = SCNSphere(radius: 1)
    sphere.firstMaterial?.shaderModifiers = [SCNShaderModifierEntryPointSurface:sm]
    sphere.firstMaterial?.doubleSided = true

```

It uses the texture coordinates to calculate which fragments should be drawn, and which should be discarded.

# Answer
> 3 votes
Try setting the material `fillMode` to `.lines`:

```
sphereNode.geometry?.firstMaterial?.fillMode = .lines

```

---
Tags: ios, sphere, swift, scenekit
---


title: OpenGL specification error?

text:
# Question
Title: OpenGL specification error?
Follow up for my previous question, whose answer lead to another question:

As the OpenGL specification documentation states, in `glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)`, ***indices*** *"Specifies a pointer to the location where the indices are stored."*

So why does calling `gl::glDrawElements(gl::GL_TRIANGLES, IndexBuffer.size(), gl::GL_UNSIGNED_INT, (void*)(0));` work, but calling `gl::glDrawElements(gl::GL_TRIANGLES, IndexBuffer.size(), gl::GL_UNSIGNED_INT, &(IndexBuffer.at(0)));` doesn't ?

# Answer
> 1 votes
As stated in the comment:

Looking at the spec this actually is not stated there.. for whatever reason.

In the case that no buffer object is currently bound to `GL_ELEMENT_ARRAY_BUFFER` the statement in the spec is true.

But when there is an active buffer object, directly bound as `GL_ELEMENT_ARRAY_BUFFER` or via a VAO, the last parameter acts as an offset into the bound buffers data, starting at 0.

The spec really could be more specific here..

I can't clearly say it for all functions, but usually when the last parameter of an OpenGL function is of void\* type it acts like this. Sadly it seems like that it's not always stated which buffer object target applies to this for which function. In case of the `glTexImage*()` functions it does, for example.

# Answer
> 1 votes
**This is an artefact of the history of OpenGL**.

For OpenGL versions 1.1 to 1.4, providing a pointer to actual system memory data was the only way to use glDrawElements; the last parameter was interpreted as a pointer to data rather than an offset into a buffer, and the second code sample you give (`gl::glDrawElements(gl::GL_TRIANGLES, IndexBuffer.size(), gl::GL_UNSIGNED_INT, &(IndexBuffer.at(0)));`) actually did work.

With OpenGL 1.5 or the GL\_ARB\_vertex\_buffer\_object extension this behaviour changed. Now if a non-zero buffer object is bound to GL\_ELEMENT\_ARRAY\_BUFFER the pointer is re-interpreted as an offset into the buffer. I recommend reading the "Issues" section of the extension specification as it often gives insight into the reasons why certain decisions which may seem odd today actually made some degree of sense at the time they were originally made. For now it will suffice to quote:

> The standard GL pointer APIs have been overloaded to be able to refer to offsets within these buffers, rather than adding new entry points ..... It is easily and cleanly added with just the addition of a binding point for the index buffer object. Since our approach of overloading pointers works for any pointer in GL, no additional APIs need be defined...

In modern OpenGL this behaviour changed again. Because it was no longer legal to source vertex or index data from system memory pointers, the *only* variant that may be used is the overloaded variant, where the parameter is still a pointer but is reinterpreted as an offset.

So hopefully you'll see that what looks like a very odd API today was actually originally designed as something quite different but because of the way the API evolved it too evolved into what it is today.

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


# Question
Title: Why is my texture not applied correctly in OpenGL 2.0 with GLSL?
First off, this is a Uni assignment, but the lecturer is stumped too.

With the shader active, I get nothing, just black. With the shader disabled (fixed function pipeline) I get a rainbow pattern which is not the texture. Uncommenting the code block labeled with the comment `//this does the texturing correctly but can't be used by the shader` does as the comment states. My friends and I believe that I'm not loading the texture into OpenGL correctly, what am I doing wrong?

Here is the fragment shader:

```
const float     lightWeighting = 0.75;
const float     textureWeighting = 0.25;

const float     PI = 3.14;
const float     lightIntensity = 1.0;
const float     constFudge = 0.025;
const float     linearFudge = 0.025;
const float     quadraticFudge = 0.05;

float rend  = 250.0;
float rstart = 50.0;

uniform float       Intensity;
uniform sampler2D   grabTexture;
//varying   sampler2D   HeatValues

varying vec3        Normal;
varying vec3        Vertex;
varying vec2        texCoord;

void main(void)
{
  vec3 pigPos = Vertex;
  vec3 normPigPos = normalize(pigPos);

  vec3 lightPos = vec3(gl_LightSource[0].position.xyz);

  vec3 normLightPos = normalize(lightPos);

  float effectiveIntesity;

  vec3 normNormal = normalize(vec3(Normal.xyz));

  vec3 t = vec3(pigPos - lightPos);

  float distToLight = length(t);

  float d = dot(normNormal.xyz, normLightPos.xyz);
  if(d > 0.0)//facing the light
  {
    float falloff;

    if( distToLight < rstart )
      falloff = 1.0;
    else
    if( distToLight > rend )
      falloff = 0.0;
      else
      {
      falloff = rend-distToLight / rend-rstart;
      }

    effectiveIntesity = d*lightIntensity * falloff;

    effectiveIntesity = d*lightIntensity * (1.0/(constFudge + (linearFudge*distToLight) +(quadraticFudge*distToLight*distToLight)));

  }
  else
  {
    effectiveIntesity = 0.0;
  }

  //TODO: change the colour of the pixel
  vec4 lightingColour = vec4(vec4( 1.0 ) * effectiveIntesity); //TODO: improve

  //gl_FragColor = lightingColour;

  //texturing stuff
  //http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
  vec4 textureColour = vec4(texture2D(grabTexture, texCoord.xy)); // TODO: why is this blank?

  vec4 col = vec4(textureColour.rgb, 1.0);
  col.r *= 1.0;
  col.g *= 1.0;

  gl_FragColor = (col);

  //gl_FragColor = (lightingColour * lightWeighting) + (textureColour.rgb * textureWeighting);

  //simple check to make sure that shader compiles
  vec3 lP = vec3(abs(gl_LightSource[0].position.x/100), abs(gl_LightSource[0].position.y/100), abs(gl_LightSource[0].position.z/100));
  vec4 r = vec4( lP.x, lP.y, lP.z, 1.0 );
  gl_FragColor = r;

  gl_FragColor = (lightingColour * lightWeighting) + (r * textureWeighting);
}

```

Here is what I do to load textures:

```
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, rawLoadedTexture);
glBindTexture(GL_TEXTURE_2D, tex);

```

Using the texture:

```
glEnable(GL_TEXTURE_2D);

//this does the texturing correctly but can't be used by the shader
/*glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, rawLoadedTexture);*/

glActiveTexture(pigObj.id_texture); //the shader can use this texture
glBindTexture(GL_TEXTURE_2D, pigObj.id_texture);

cShader *pList = graphics.ShaderInfo.getList();
glUseProgram( pList[1].program()); //shader on: no pig // fixed, was vertex shader being empty, replaced it with intensity.vert
                  //shader off: ambient light only (tiny amount of diffuse or an illusion?)
extern NA_MathsLib na_maths;
float intensity = (float) na_maths.dice(100);

glUniform1i(pList[1].get_grabLoc(), pigObj.id_texture);
glUniform1f(pList[1].intensity(), intensity);
//glUniform1f(pList[1].get_heatValues(), heatValuesPsudoTexture);

//glutSolidSphere(2, 15, 2);
pigObj.render();

glDisable(GL_TEXTURE_2D);
glUseProgram(0); //disable pig heatlamp shader

```

# Answer
Your problem is here:

```
glActiveTexture(pigObj.id_texture); //the shader can use this texture

```

`glActiveTexture()` takes a value of `GL_TEXTURE*`, not the ID of your texture. It's the texture unit in which your texture is going to be bound (or is already bound). So for texture unit 0, you'd do:

```
glActiveTexture(GL_TEXTURE0);

```

You then need to also pass the texture unit index as the uniform for the sampler, rather than your texture ID.

This is by far one of the most confusing aspects of texturing in OpenGL! And because all OpenGL constants are `#define`s instead of proper named types, it's really hard to have the compiler catch this type of error. See the docs for `glActiveTexture()` for more info.
> 1 votes

---
Tags: opengl, c++, textures, glsl
---


# Question
Title: Will Unity automatically scale everything?
I don't have a GUI or anything. Just a bunch of game objects with pictures on them.

I want everything to scale with the size of the screen. So if it's a small screen, the character will take up less of the screen, instead of the screen just cutting off at the edges. If the screen is larger, everything is larger.

Is this something I should do? Will Unity automatically do this?

I've been told that the project should have the following specifications:

"The app should be appropriately scaled to fit the device screen to avoid letterboxing"

Use bg.png as the background of the app. Ideally, the background should be centered to the app such that the left and right edges go off the screen if the device aspect ratio is less than 16:9.

Is what I'm describing fitting the specifications here? What will Unity do for me? I don't have a phone to actually test this on so I don't know what the app will end up looking like.

# Answer
> 1 votes
Unity will *try* to scale things up/down to fit the current screen. So yes, your object will take less space in a smaller screen. However, the scaling will not always be perfect.

For instance, the iPhone 5, 6 and 6 Plus all have the same ratio. So if you develop for any of them, the game will seamlessly scale and fit perfectly the screens. However, the iPad Mini devices for example do not have the same ratios as the iPhones. In fact, you will notice that the sides (if you're working on landscape) will be **cut** a bit.

So really the first thing you should consider is what devices will you support, and then find out their resolution ratios. Then design your background/interface stuff with that in mind.

# Answer
> 1 votes
im quite new to using unity too. But i see in the 'Game' preview window, you can select the exact screen size. I'm not sure if this sets a Fixed Viewport or not once it is finally built for iPhone etc but it does seem to give you the fixed viewport in the preview so i assume that it would also one the build for each device type

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


# Question
Title: How to interrupt an animation and transition to another?
I am trying to make a 2D platform game which is Megaman-style. I have some problems when I make shooting animation. In Megaman game, the animation can interrupt by press keys. Just like this:

For instance, when move button was pressed, the animation frame will loop in D0~D9, if fire button was pressed, it interrupts the current animation and transition to shooting animation(A,B,C). If stop shooting, it goes back to move(D).

I have no idea how to design "interrupt/transition animation system" in my game. Here is my pseudo code(JavaScript):

```
animation.play('move',[0,1,2,3,4,5,6,7,8,9],loop);

if(isMoving && key['fire']) {
    //I don't know how to make this work
    animation.play('fire',[A1,A2,B3,B4,B5,C6,D7]);
}

```

and each frame has a metaData like this:

```
{x:37,y:0,w:36,h:41,offsetX:0,offsetY:0,duration:100,collisionBox:[0.4,0,0.84,1.875],
    interrupt:{
        nextMotion:'A',
        nextFrame:7
    }
}

```

What is common solution in this scene? Please, Any help would be appreciated.

# Answer
A very simple solution would be to use a queue. Like this:

```
queue.push(function() {
    animation.play('fire',[A1,A2,B3,B4,B5,C6,D7]);
    queue.pop()
});
if(isMoving && key['fire']) {
    queue.push(function() {
        animation.play('fire',[A1,A2,B3,B4,B5,C6,D7]);
        queue.pop()
    });
}

```
> 0 votes

---
Tags: javascript, animation, platformer
---


# Question
Title: Swept aabb 3d incorrect collision resolution along negative normals
I have followed this tutorial and ported it to 3d with glm. Everything works fine when the collision normal is reported as positive ((1,0,0),(0,1,0),(0,0,1)) but when it is negative the player aabb gets "stuck: on the wall demonstrated here.

Here is the code used to detect collisions:

```
  Hit AABB::intersectSegment(glm::vec3 pos,glm::vec3 delta,glm::vec3 padding)
  {
    glm::vec3 scale = glm::vec3(1.0)/delta;
    glm::vec3 sign = glm::vec3(glm::sign(scale.x),glm::sign(scale.y),glm::sign(scale.z));
    glm::vec3 nearTime = (position - sign * (hwidth + padding) - pos) * scale;
    glm::vec3 farTime = (position + sign * (hwidth + padding) - pos) * scale;
    if ((nearTime.x > farTime.y) || (nearTime.x > farTime.z) || (nearTime.y > farTime.x) || (nearTime.y > farTime.z) || (nearTime.z > farTime.x) || (nearTime.z > farTime.y))
      return Hit(false);

    float near = glm::max(glm::max(nearTime.x,nearTime.y),nearTime.z);
    float far = glm::min(glm::min(farTime.x,farTime.y),farTime.z);

    if ((near >= 1) || (far <= 0))
      return Hit(false);

    Hit hit;
    hit.time = near;//glm::clamp(near , 0.f, 1.f);
    if ((nearTime.x > nearTime.y) && (nearTime.x > nearTime.z))
    {
      hit.normal = glm::vec3(-sign.x,0,0);
    }
    else if ((nearTime.y > nearTime.x) && (nearTime.y > nearTime.z))
    {
      hit.normal = glm::vec3(0,-sign.y,0);
    }
    else if ((nearTime.z > nearTime.y) && (nearTime.z > nearTime.x))
    {
      hit.normal = glm::vec3(0,0,-sign.z);
    }

    hit.delta = hit.time * delta;

    hit.pos = pos + hit.delta;
    hit.timeVect = nearTime;

    return hit;

  }
Sweep AABB::sweepAABB(AABB box,glm::vec3 delta)
  {
    if (delta == glm::vec3(0,0,0))
    {
      Sweep s;
      s.hit.colided = false;
      s.time = 1;
      return s;
    }
    Sweep sweep;
    sweep.hit = intersectSegment(box.position, delta, box.hwidth);

     if (sweep.hit.colided)
     {
       sweep.time = glm::clamp(sweep.hit.time - EPSILON,0.f,1.f);
       sweep.pos = box.position + (delta * sweep.time);

       glm::vec3 direction = glm::normalize(delta);

       sweep.hit.pos += direction * box.hwidth;
       sweep.item = box.getSimple();
       sweep.other = getSimple();

     }
     else
     {
       sweep.pos = box.position + delta;

       sweep.time = 1;
     }

   return sweep;
  }

```

Here is my recursive method for resolving the collisions:

```
glm::vec3 project(glm::vec3 a,glm::vec3 b)
{
  return (glm::dot(a,b)/glm::dot(b,b))*b;
}
void Player::resolveColision(math_custom::Sweep& least,math_custom::CollisionMode mode,float remTime)
{
  if (mode == math_custom::SLIDE)
  {
   velocity = velocity - project(velocity,glm::abs(least.hit.normal));
  }
  if (mode == math_custom::BOUNCE)
  {
    float dot = velocity.x * least.hit.normal.x + velocity.y * least.hit.normal.y + velocity.z * least.hit.normal.z ;
    glm::vec3 u = least.hit.normal * dot;
    glm::vec3 w = velocity - u;
    velocity = w - u;

  }
  if (mode == math_custom::TOUCH)
  {
    velocity = glm::vec3(0,0,0);
  }

  if(least.hit.normal == glm::vec3(0,-1,0))
    grounded = true;

    colided = true;
    colidedAabb = aabbs->at(least.id);

}
void Player::getCollisons(std::vector<math_custom::AABB*>* aabbs)
{
  sweeps.clear();
  for (int i =0;i < aabbs->size();i++)//for every aabb in the list
  {

    math_custom::AABB broadphase = math_custom::GetSweptBroadphaseBox(*aabb,velocity);

    if (broadphase.isColiding(*aabbs->at(i)))
    {
      math_custom::Sweep s = aabbs->at(i)->sweepAABB(*aabb,velocity);
      if (s.hit.colided)
      {
        s.id = i;
        sweeps.push_back(s);
      }

    }

  }
  std::sort(sweeps.begin(),sweeps.end(),math_custom::sortByTiAndDistance);
}

void Player::move(int iter)
{

  getCollisons(&tempaabbs);
  if ((sweeps.size() != 0))
  {

    aabb->translate(sweeps[0].pos-aabb->position);

    debug::print(sweeps[0].hit.normal);
    debug::print(velocity);
    resolveColision(sweeps[0],defaultMode,1.f);

    tempaabbs.erase(tempaabbs.begin()+(sweeps[0].id));
    move(iter + 1);
  }
  else
  {
    aabb->translate(velocity);
  }
}

```

# Answer
> 0 votes
If you used the one in the tutorial, the value you used for epsilon is too small. I modified the JavaScript from the tutorial, and realized you problem happens there, too. Just lower the value of epsilon to about `0.000001f`, and you should be fine.

---
Tags: c++, collision-detection, 3d, glm, aabb
---


title: How do I create a custom tool in Unity?

text:
# Question
Title: How do I create a custom tool in Unity?
Unity Editor has the usual bunch of standard tools: translate, rotate, and scale. I want add custom tools (to e.g. "paint" metadata onto the ground, or drag-and-drop stuff between gizmos). How?

# Answer
For posterity, this is what I ended up doing:

```
/// <summary>Derive from this to implement an editor capable of clicking and dragging
/// stuff in the scene view.</summary>
public class SceneViewEditor : Editor
{
    protected static Type currentEditor;
    private bool keepEditing;
    private int mouseDownButton;
    private static Tool previousTool;

    protected bool sceneEditingEnabled
    {
        get { return Tools.current == Tool.None && currentEditor == this.GetType(); }
        set
        {
            var editor = this.GetType();
            if (value ? currentEditor == editor : currentEditor != editor)
                return;
            if (currentEditor == null)
                previousTool = Tools.current;
            Tools.current = value ? Tool.None : previousTool;
            currentEditor = value ? editor : null;
        }
    }

    protected virtual void OnDestroy()
    {
        if (!keepEditing && currentEditor == this.GetType())
        {
            currentEditor = null;
            Tools.current = previousTool;
        }
    }

    // Override this to do your custom scene tool.
    protected virtual void OnSceneClick() { }

    protected virtual void OnSceneGUI()
    {
        // The alt check is there so we don't interfere with orbiting.
        if (!sceneEditingEnabled || Event.current.alt)
            return;
        // The standard hack to take control of all mouse events in the scene view.
        HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

        var e = Event.current;
        if (!e.isMouse)
            return;

        if (e.type == EventType.MouseUp && e.button == mouseDownButton)
            OnSceneClick();

        mouseDownButton = e.type == EventType.MouseDown ? e.button : -1;
    }

    protected void SetActiveObject(Object value)
    {
        if (value == target)
            return;
        Event.current.Use();
        // If the newly selected object is of the same type as the current, pass the
        // editing baton to the new editor that will be spawned for the newly selected
        // object.
        if (value.GetType() == target.GetType())
            keepEditing = true;
        Selection.activeObject = value;
    }
}

```

Usage example:

```
[CustomEditor(typeof(VisibilityArea))]
public sealed class VisibilityAreaEditor : SceneViewEditor
{
    public override void OnInspectorGUI()
    {
        // The usual Editor stuff.
    }

    [DrawGizmo(GizmoType.Active)]
    private static void OnDrawGizmos(VisibilityArea area, GizmoType gizmoType)
    {
        // Get Selection.activeObject, cast it to your type, and draw your custom shit.
        // I never got to implementing this method, so no sample code in here. :(
    }

    protected override void OnSceneClick()
    {
        if (Event.current.button != 0)
            return;
        var gameObject = HandleUtility.PickGameObject(Event.current.mousePosition, false);
        if (gameObject == null)
            return;
        var area = gameObject.GetComponentInParent<VisibilityArea>();
        if (area == null)
            return;
        SetActiveObject(area);
    }
}

```
> 2 votes

# Answer
you can extend the editor with your own custom inspectors and Editor Windows. like this:

check their official documentation: Extending the Editor
> 1 votes

---
Tags: unity
---


# Question
Title: making special blocks in a voxel game OpenGL
I'm making a voxel game and it looks quite good but then i thought of special blocks like minecrafts grass leaf blocks, and translucent water. I had the idea for the grass blocks to put them in a seperate VAO and render them after the blocks because they might look like an X from above.

How could you do water? I know you could enable blending in OpenGL and render from back to front and you could sort their distances each frame with a map.

My problem is how to render all of these waters, I could use instanced rendering but then i would have to update the buffers every time the player moved or i could draw them all individually but that would involve thousands of draw calls ex. 8000 draw calls for 20\*20\*20 blocks (each draw call sends a whole cube)

what would be a fast method of doing this?

# Answer
> 0 votes
A solution to rendering transparent objects without resorting by distance all of the time would be to use order independent transparency. Disable depth writing and change the blend mode to add the fragment colour to the current colour. glBlendFunc(GL\_ONE, GL\_ONE) also I would make sure that only the visible faces of the voxels are rendered so you don't see extra sides underwater. This is an easy method that makes pretty good transparent water without much complexity.

see more about order independent transparency

Order Independent Transparency - OpenGL SuperBible

---
Tags: opengl, voxels, water
---


# Question
Title: Only first vertex of data used in shader OpenGL
I'm making a voxel game like Minecraft which was working fine until I added water. Then I realized that whatever the texture was for the first visible block was applied to the rest of the blocks in the chunk. I am drawing a total of 36 vertices per cube and it seems that although the instanced array for the cube positions is working, only the first 36 texture coordinates are being used.

I raised all visible ocean. Locks in the second picture which is how I determined the actual coastline.

creating the buffers

glGenVertexArrays(1,&chunk-\>chunkVAO); //glGenBuffers(1,&chunk-\>chunkEBO); glGenBuffers(1,&chunk-\>cubeVBO); glGenBuffers(1,&chunk-\>posOffsetVBO); glGenBuffers(1,&chunk-\>texCoordVBO);

```
glBindVertexArray(chunk->chunkVAO);

glBindBuffer(GL_ARRAY_BUFFER,chunk->cubeVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(cubeVertices),cubeVertices,GL_STATIC_DRAW);

glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER,chunk->texCoordVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec2)*36*65536,NULL,GL_DYNAMIC_DRAW);

glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,2*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER,chunk->posOffsetVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec3)*65536,NULL,GL_DYNAMIC_DRAW);

glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,3*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(2);
glVertexAttribDivisor(2,1);

```

filling the texture and position VBO after occlusion culling

```
glBindBuffer(GL_ARRAY_BUFFER,chunk->texCoordVBO);

glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(texCoords),&texCoords[0]);

glBindBuffer(GL_ARRAY_BUFFER,chunk->posOffsetVBO);

glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(positions),&positions[0]);

glBindBuffer(GL_ARRAY_BUFFER,0);

```

rendering

```
glBindVertexArray(temp->chunkVAO);

glDrawArraysInstanced(GL_TRIANGLES,0,36,temp->visibleBlocks);

```

How come only one of the blocks worth of texture coordinates is being used?

# Answer
Here was the problem. I stored all of the textures on a texture atlas and referred to them by including an integer in the instance data. The problem was that I used `glVertexAttribPointer` with the parameter that says the data is normalized. When using integers as vertex attributes you use `glVerteAttribIPointer` (extra I). Then the coastline looked fine.
> 0 votes

---
Tags: voxels, vbo, perlin-noise, data, water
---


# Question
Title: Box2D - World step on Android game using LibGDX
I'm running a simple Libgdx game using Box2D physic and i get different speed on different Android devices.

I believe that this is because timestep.

If I use 1 and 2 example i get different speed on different devices and the 3 example it works nice but on old devices (on my old smartphone Galaxy Wonder) lose fps and is unplayable

1)

```
world.step(1f/60f, 6, 2);

```

2)

```
static final float STEP_TIME = 1f/60f;
float accumulator = 0;

private void stepWorld() {
    float delta = Gdx.graphics.getDeltaTime();

    accumulator += Math.min(delta, 0.25f);

    if (accumulator >= STEP_TIME) {
        accumulator -= STEP_TIME;

        world.step(STEP_TIME, 6, 2);
    }
}

```

3)

```
world.step(Gdx.graphics.getDeltaTime(), 6, 2);

```

There is an other way how to get the same speed?

# Answer
So let's take a look at what each of those code examples are doing:

```
world.step(1f/60f, 6, 2);

```

Example #1 tells the physics engine that 1/60th of a second has passed every time you call it. If your game loop is being called more than 60 times a second it will go fast; less than 60 times a second and it'll be slow. The number of times it gets called per second will depend on the speed of the underlying hardware, so this method will end up in different behavior on different devices.

```
static final float STEP_TIME = 1f/60f;
float accumulator = 0;

private void stepWorld() {
    float delta = Gdx.graphics.getDeltaTime();

    accumulator += Math.min(delta, 0.25f);

    if (accumulator >= STEP_TIME) {
        accumulator -= STEP_TIME;

        world.step(STEP_TIME, 6, 2);
    }
}

```

Example #2 uses a cooldown pattern- **this is the right way to do it.** Like @Charanor said, you'll want to use a while loop instead of an if statement (it'll be slightly more accurate), but otherwise it is correct. If it is too slow for your phone, you might consider changing the step from 1/60f to 1/45f.

```
world.step(Gdx.graphics.getDeltaTime(), 6, 2);

```

Example #3 has you calling the engine every frame, which means that your results will be very accurate, but it also means that you'll be calling the engine way more often than you need to (you don't need to update the position of your objects faster than you can display the changes).
> 0 votes

# Answer
According to the LibGDX Box2D Wiki it is recommended to use a **fixed time step** with a step time of `1/45` or `1/300`; i.e. your *Example #2* but with `STEP_TIME` as `1/45` or `1/300`.

You should also change your `if (accumulator >= STEP_TIME)` to `while (accumulator >= STEP_TIME)` so it can properly step multiple times per frame if needed.

If you find that you still have lag on slow devices you could try to play with the `0.25` value of this line: `accumulator += Math.min(delta, 0.25f)`. I found that a lower value generates better performance but sacrifices more accuracy in the simulation.
> 1 votes

---
Tags: java, libgdx, box2d, multiple-graphics-devices
---


title: IntersectMovingAABBAABB weird behavior

text:
# Question
Title: IntersectMovingAABBAABB weird behavior
I'm using the `IntersectMovingAABBAABB` implementation from the book `Realtime Collision Detection` and I'm having a little bit of an issue. When I have two AABBs next to each other (not touching), A being stationnary and B moving up or down, I'm getting a result saying there's a collision. Obviously this is wrong.

```
 _______     _______
|       |   |       |
|   A   |   |   B   |  B moving up/down
|_______|   |_______|

```

I've rechecked my code multiple times to make sure I had the same thing as in the book. Stepping through the code, I realized that the check for `v[i] < 0` and `v[i] > 0` will never be true for either X or Z axis when moving straight up or down. Therefor, no checks for intersections on these axis will be done. I find that quite weird, and I was wondering if I was missing something, or if this code is simply bad.

Here's my implementation for reference:

```
public static bool IntersectMovingAABBAABB(AABB a, AABB b, Vector3 va, Vector3 vb, out float first, out float last, out BlockFace face)
{
    face = BlockFace.None;
    if (TestAABB(a, b))
    {
        first = last = 0;
        return true;
    }

    Vector3 v = vb - va;
    float current;

    first = 0;
    last = 1;

    for (int i = 0; i < 3; i++)
    {
        if (v[i] < 0)
        {
            if (b.Max[i] < a.Min[i]) return false;
            if (a.Max[i] < b.Min[i]) if ((first = Math.Max(current= (a.Max[i] - b.Min[i]) / v[i], first)) == current) face = (BlockFace)(1 << (i));
            if (b.Max[i] > a.Min[i]) last = Math.Min((a.Min[i] - b.Max[i]) / v[i], last);
        }

        if (v[i] > 0)
        {
            if (a.Max[i] < b.Min[i]) return false;
            if (b.Max[i] < a.Min[i]) if ((first = Math.Max(current = (a.Min[i] - b.Max[i]) / v[i], first)) == current) face = (BlockFace)(1 << (i + 3));
            if (a.Max[i] > b.Min[i]) last = Math.Min((a.Max[i] - b.Min[i]) / v[i], last);
        }

        if (first > last) return false;
    }

    return true;
}

```

# Answer
Realtime collision detection is a great book, but that code is clearly wrong. If the relative velocity was zero, it would always return true, which is clearly incorrect. I believe the first test in each of the if (v\[i\] ...) blocks needs to be done if the velocity is \<= 0 and \>= 0 respectively. Note that you can't just change those tests though, because you could then end up dividing by zero. There may be a more elegant way, but I think this should work:

```
    if (v[i] < 0)
    {
        if (b.Max[i] < a.Min[i]) return false;
        if (a.Max[i] < b.Min[i]) if ((first = Math.Max(current= (a.Max[i] - b.Min[i]) / v[i], first)) == current) face = (BlockFace)(1 << (i));
        if (b.Max[i] > a.Min[i]) last = Math.Min((a.Min[i] - b.Max[i]) / v[i], last);
    }
    else if (v[i] > 0)
    {
        if (a.Max[i] < b.Min[i]) return false;
        if (b.Max[i] < a.Min[i]) if ((first = Math.Max(current = (a.Min[i] - b.Max[i]) / v[i], first)) == current) face = (BlockFace)(1 << (i + 3));
        if (a.Max[i] > b.Min[i]) last = Math.Min((a.Max[i] - b.Min[i]) / v[i], last);
    }
    else
    {
        if (b.Max[i] < a.Min[i] || a.Max[i] < b.Min[i]) return false;
    }

```
> 2 votes

---
Tags: collision-detection, physics, realtime
---


# Question
Title: How do you stack things in between a Table?
So I understand that a `Stack` is used to overlay things on top of each other, but is it possible to sandwich something in between a `Table`? For example, let's say I build my main menu using a `Table`, but after the UI is built, I want to place a full-screen overlay right underneath my play button. How can I achieve this? Here's a simple sketch of what I'm looking for:

The problem I'm facing is that, even if I use a `Stack`, the button that I want to place on top of the overlay has to be a separate entity apart from the `Table` I want it to be a participant of, so I can't place it within the underlying `Table`'s structure.

# Answer
> 2 votes
You should use the built-in z-index ordering of `Actors`. For z-ordering to work the `Actors` **have to have the same parent**. This can be kind of tricky to do without messing up the positioning and you have to do it in a kind of "hack-y" way by using an `Image` as your overlay like this:

```
// Add to table BEFORE changing z index!
table.add(button1);
table.add(button2);
table.add(button3);
table.addActor(overlay); // addActor not add!

overlay.setFillParent(true); // Fill entire table important!

button1.setZIndex(3); // On top of overlay
overlay.setZIndex(2); // Overlay
button2.setZIndex(1); // Below overlay
button3.setZIndex(0); // Below overlay

```
* **Why addActor?** The reason we use addActor instead of add is so we can add the overlay to the table without messing up the position of the other children.
* **Why add before zIndex?** zIndex works by re-ordering the children of the actor's parent. If there are no children it cannot be re-ordered.

---
Tags: libgdx
---


# Question
Title: Optimizing data structure for my text adventure?
In my text adventure I'm making, I store the story data in a hashtable (I'm using unity's javascript/unity script since I'm more comfortable with the syntax than C#).

The problem is, the way I structure the hashtable means that it gets incredibly bloated very quickly (I've used the same structure in all of my text adventures across multiple languages. It quickly grows to nearly 1k lines long) which makes it hard to edit in the future (especially if I need to go back to edit certain parts later on)

Here's the hashtable as it's currently structured:

```
public static var story = {
    "0":
    {
        "text":"",
        "choices":
        {
            "response1":
            {
                "text":"",
                "nextPart":"1"
            },
            "response2":
            {
                "text":"",
                "nextPart":"2"
            },
            "response3":
            {
                "text":"",
                "nextPart":"3"
            }

       }
    },
    "1":
    {
        "text":"",
        "lastPart":"0"
    },
    "2":
    {
        "text":"",
        "lastPart":"0"
    }
};

```

If anyone could help me optimize the structure of the hashtable that'll make it so it's more easier for me to edit it in the future, that would be great

Quick information for parts that may not be self-explanatory:

* "lastPart" indicates to the hashtable parser that the player has died and the number refers to the part where they chose the response/choice.
* "nextPart" refers to the part of the story the response leads to.

# Answer
I strongly recommend making your own file format that optimizes viewing and editing of the text parts.

Get rid of redundancy to reduce errors while editing.

You'll also want to get rid of numeric IDs and replace them with readable names.

And you'll want to allow splitting a single story into multiple files.

```
:Start: You're in a forest, bla bla...
>Start_Left: Move left.
>Start_Right: Move right.
>Tree: Hug a Tree.

:Start_Left: You fall into a spike trap and die
>Dead.

:Start_Right: You enter a clearing. What do you do?
>Victory: Take a nap.
>Tree: Hug a tree

:Tree: The tree is laced with poison. You die.
>Dead.

```

You then write a simple parser that populates your program data structure from the data in the file. The data structure in the program can thus be optimized for ease of use when accessing the structure.
> 2 votes

---
Tags: unity, javascript, unityscript
---


# Question
Title: Vertex attributes with strides between them vs blocks of data
Using opengl, does it make a difference if I upload plain vertex attribute structs, and then define the strides between them using `glVertexAttribPointer`, **or** if I do something like this

```
//we have position, texCoords, and normal vertex attributes
//allocate enough room for all attributes, set it to null for now
glBufferData(GL_ARRAY_BUFFER, positions.size() + normals.size() + textCoords.size(), NULL, BUFFER_USAGE);

//set positions data
glBufferSubData(GL_ARRAY_BUFFER, 0, positions.size(), positions.data());

//... call glBufferSubData for normals and texCoords as well

```

# Answer
> 1 votes
This "problem" (it's more of a choice than a problem) is something I've bashed against before, so I did some reading on it.

First of all, you still need to call glVertexAttribPointer(...) in both cases, because OpenGL has no other way of knowing how to interpret the data in the buffers.

Second, there is no significant difference(that is, the performance impact is insignificant to non-existent) between the two methods. If you can use both to reach a goal, use the one that you find easier to understand, debug, and extend.

Third, and last, there are some cases in which you can only use one method. For example, you can encode huge amounts of data into a texture using a framebuffer and send it to the GPU, where you just use the data, as it was already "decoded" by setting the right attribute pointers. This is a clear example of a case in which you'll want to use `glBufferData(...)` and `glBufferSubdata(...)` among other OpenGL calls.

There's still some more stuff about it, but you can refer to this great tutorial article to better understand the concepts (**note**: passing data around using textures is a technique out of the scope of this question or the following article): Tutorial

# Answer
> 1 votes
If you're using separate arrays for different attributes, you can just use a different buffer object for each. Just bind each one before setting the attrib pointer.

---
Tags: opengl
---


# Question
Title: Why doesn't games use CORDIC for sin and cos?
If the game devs add CORDIC sin cos calculation to their games, their games will have much better FPS. Why do they use normal sin cos function (e.g. Math.sin) instead of CORDIC?

# Answer
> 9 votes
Because on the **x87** (the x86's FPU) the fsin, fcos and fsincos instructions are much faster than software CORDIC.

On other architectures such as **PowerPC** and **ARM** you usually can rely on an optimized implementation within the standard c library, the performance cost in normal use cases is still so minimal to not be worth the time re-implementing.

fsin or fcos timing (latency cycles) on x86:

* Pentium (1st generation): 65 to 100 cycles typical, 16 minimum
* Pentium II and Pentium III: 17 to 97 cycles
* Pentium 4: approx 180 cycles
* Pentium M: 80 to 100 cycles
* Atom: around 260 cycles
* Nehalem: around 100 cycles
* Sandy Bridge: 20 to 100 cycles
* Ivy Bridge: 21 to 78 cycles
* Haswell: 71 to 100 cycles
* Broadwell: 70 to 100 cycles
* Skylake: 53 to 105 cycles
* Knights Landing (Xeon Phi): 40 to 250 cycles
* K7: 90 to 100 cycles
* Jaguar: 4 to 44 cycles
* Bobcat: 4 to 44 cycles
* Ryzen: 11 to 60 cycles

Timing source: http://www.agner.org/optimize/instruction\_tables.pdf

When calculating CORDIC extra delays are added due to FPU pipelining latency, counting the cycles of fadd and fcmp operations does not give a true picture of the time CORDIC takes on a modern CPU due to all the pipeline stalls involved in the CORDIC algorithm.

Even on x86 CPUs where fsin takes 260 cycles (worst case) it would still take much longer looping over the CORDIC algorithm for the same reasons: the FPU is slow.

If performance of sin/cos is critical, and in those case usually precision is not as important, a lookup table is much faster than even a single loop of CORDIC.

A small 16bit x 128 entries quarter-sine interpolated table gives more than enough precision for practical video game uses.

# Answer
> 3 votes
First of all, the FPS wouldn't be better. Most modern games are bottlenecked by the GPU mostly and are pretty OK with the CPU (often times only reaching a CPU usage of around 50% or less).

Second, CORDIC is designed to be precise and easily implementable in the hardware. The sinus method (cosinus is basically a sinus with an offset) in most languages use the sinus method from the x86 architecture or other similar alternatives. It cuts corners using smart bit trickery (similar to the inverse square root formula from Quake) instead of calculating the value in the normal way, thus loses precision in favor to speed.

Even if the hardware isn't strong enough to calculate the amount of trigonometric functions the program needs, it's easier and faster to use lookup tables than to implement a different algorithm.

---
Tags: mathematics, rendering, trigonometry
---


# Question
Title: Unity - blur on one camera effects the other as well
I'm trying to fake a DOF effect for *Sprites* by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like **Blur** and **Sharp** accordingly.

So I have these 2 cameras, and I use Unity's **Blur (optimized)** script to blur things, and I have this script on only **one** camera, the one that is responsible for the blurred render.

I have the cameras like:

**Cam 1:**

* Clear flags: Don't clear (this is the main, sharp cam)
* Culling mask: sharp layer
* has **no** blur effect (or any other post proc effect).

**Cam 2:**

* Clear flags: don't clear (this is the blur cam)
* culling mask: blur
* Has Blur (optimized).

Now, if this blur cam is on the back, meaning its **depth** is **LESS** than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground.

The issue starts when I set the **blur camera's** depth **higher** than the main cam's. In this case, **everything gets blurred, no matter that the main cam has no blur effect on it**.

Question is, how to set this up so only the desired layers get the blur?

# Answer
With the help of *DMGregory* there is some neat workaround to basically *fake depth of field for sprites*. The reason we can't just blur the foreground cam is that these post-processing effects take the final image and work the magic on them.

There are of course more than one ways to do so. One is to sort of pre-blur your sprites in an external 2D app (GIMP or PS for example) and export it to Unity, that way you have a "static" sprite that doesn't need much calculation other than a simple sprite as it is.

This however forbids you from a lot of options like animating the blur, making it more dynamic, reduce the blur if you are unsatisfied and so on.

The other is to use *RenderTextures*. To do so, you max want to create one in the inspector *Right click \> Create \> RenderTexture* and set it up so it suits your needs. I kept it low res as blurred images don't really need to be crisp.

Once you have it, create another camera and set up its layers so it renders **only** the foreground. In the meantime your main cam should exclude the foreground. Make this BlurCam a child of your MainCam so it follows it. Its depth shall be higher than your MainCam's.

Unity has some scripts, like *Blur (optimized)* to get you a nice result fast enough. Put that on your BlurCam. After that, assign your RenderTexture as *Target Texture* for the BlurCam. Set BlurCam's clear flags Solid Color and make its alpha 0.

Drop a mesh plane on the canvas and make it a child of the BlurCam (so it follows it).

Assign a transparent unlit shader (or whatever you wish, it worked nice with my sprites) to that plane and make texture your RenderTexture.

After that, if you placed the plane right, you basically see all your "Foreground" layer sprites blurred. You just have to toss around those sprites to the scene, the blur happens rendertime.

Bear in mind though, that this RenderTexture method, if abused, can propose a meaningful performance hit, especially for mobile as it is a weaker hardware. Always keep an eye on your profiler before setting up these.
> 2 votes

---
Tags: unity, camera, post-processing, image-effects, layers
---


# Question
Title: Designing an end-less running game with levels-using LibGdx JSON
I am working on an end-less running game where obstacles are placed along the way on moving background. I have a lot of levels in the game,and I am implementing it using JSON.

My JSON file for first level look like this:

```
 "obstacles": [
 {"name":"rock","position":"middle","distance":"1000","speed":"350"},
 {"name":"crow","position":"up","distance":"1600","speed":"350"},
 {"name":"gap","position":"down","distance":"1600","speed":"350"},
 {"name":"monkey","position":"middle","distance":"2200","speed":"350"},
 {"name":"fish2","position":"down","distance":"2400","speed":"350"},
 {"name":"crow","position":"up","distance":"2600","speed":"350"},
 {"name":"snake","position":"up","distance":"3400","speed":"350"},
 {"name":"fish","position":"down","distance":"3400","speed":"350"},
 {"name":"fish2","position":"down","distance":"4400","speed":"350"},
 {"name":"monkey","position":"middle","distance":"5500","speed":"350"},
 {"name":"rock","position":"middle","distance":"6500","speed":"350"},
 {"name":"fish","position":"down","distance":"6500","speed":"350"},
 {"name":"cloud","position":"up","distance":"7200","speed":"350"},
  {"name":"rock","position":"middle","distance":"8000","speed":"350"},
 {"name":"gap","position":"down","distance":"8000","speed":"350"},
 {"name":"snake","position":"up","distance":"8700","speed":"350"}
 ]

```

Here I am placing obstacles up to an x position of 8700 on a moving parallax back ground.

Level1 is working fine,but my issue is that how I should place the next level obstacles.I have only one way that some position after 8700 I have to choose for placing next level obstacles.

Here I want to clarify one thing.Will it become a problem when I use larger values like this?

There is more than 20 level planned in my project,and each level get loaded automatically when one is completed.

I expect suggestions from experienced persons ,for designing the levels with these aspects.

Thanks in advance.

# Answer
> 2 votes
I would place objects in a procedural way. Keep track of the distance while ingame and try to spawn obstacles in intervals. Check for the current distance travelled and spawn obstacles according to it. Maybe hold level-specific obstacles in a dictionary, where the key is the minimum distance to spawn the obstacle

# Answer
> 1 votes
If it is an endless running game there is no point of designing all the levels. Maybe design the first 1000 meters as a tutorial, and after it use some procedurally way of generating the next objects. As you go further the shorter are the intervals of obstacles, p.e.

Anyway if u want to go with json way you can try it:

```
"level1": [
 {"name":"rock","position":"middle","distance":"1000","speed":"350"},
 {"name":"crow","position":"up","distance":"1600","speed":"350"},
 {"name":"gap","position":"down","distance":"1600","speed":"350"}],
"level2":[
 {"name":"cat","position":"middle","distance":"500","speed":"350"},
 {"name":"gap","position":"up","distance":"1500","speed":"350"},
 {"name":"rock","position":"down","distance":"1700","speed":"350"}]

```

At the moment of spawning the obstacles, multiply the current level for the distance. It will make you json more readable.

---
Tags: libgdx
---


title: Implementing an online database

text:
# Question
Title: Implementing an online database
I'd like to get into online games programming. I thought that as a start i'd be a good idea to implement an online database that would store the progress and score for a game i have made, i'll probably want to implement an account system too.

My issue is, i can't see to be able to ask google the right question. I don't know where to start. I've touched some on SQL and PHP, HTML and XSL, but, to me they're just languages, i can't see the big picture, how do these things connect to form a working service? I'm not looking for a solution, i just don't know what should i learn.

I'm not looking for knowledge on sockets, i'm familiar with network programming, i just don't understand the "modern" process of handling databases. I'd be very happy if somebody could lay out the structure of a database, how you put it out on the web, how you access the information and change it (not in a direct solution, just "this is done by programming a filter in SQL"), what languages are used for it, etc.

# Answer
The database is the backend, your game is the client. Since you can't (well, technically you can but you really shouldn't) connect to the DB directly, you'll have to write some kind of middleware for that.

The middleware usually runs as a web-service or deamon on a server and exposes an interface for you to access/store game data. This stuff can be implemented in a lot of different languages.. basically any language that you can run on a server and access a database with.

For things like highscores, achievements etc. you can write a simple PHP (or Ruby, Java,..) script that you can access via HTTP. A common architecture for web APIs like this is REST. If you would implement a highscore system as RESTful service, you might have an URL like this:

```
http://my.server.com/highscores

```

Sending a `GET` request to that URL would fetch the scores from the DB and return them (you could send them as XML, JSON or similar).

To add a new score-entry, you maybe have an URL like:

```
http://my.server.com/highscores/add

```

And you would send a new Highscore to that address using a HTTP `POST` request. Then you read out the `POST` data and insert it into the database.

Of course you don't have to conform to any architecture (such as REST), but I'd say it's good practice.

Here are some things you should be aware of when you do something like this for the first time:

* Don't trust the client. If your game can send a highscore, anybody else can do so also... this question touches on that topic.
* Always validate and sanitize incoming data (remember, don't trust the client). Being sloppy with these things will make your service susceptible to SQL injection attacks.
> 5 votes

# Answer
I just want to complement the @bummzack \`s answer.

RESTful service is a good idea to implement the programming interface between the game clienet and server.If you plan to implement the communication way with this type of architecture.I recommend the existed website developing framwork such as Lumen, a light-weight framework.

Firstly, native language such as PHP is verbose and inconvenient to implement the RESTful API, but the route of framework can easily bind the controller and URL,and convenient to maintain.Besides, the database model of framework also is powerful to operate the data with OOP style.

Secondly, popular website framework such as Django and Laravel is built for developing the entire website with the MVC architecture, but their "view" part just for the HTML output.You know, the "view" of online game is the game client itself.So the heavy-weight framework maybe not suitable,because the bigger space taking and the runing efficiency(some view relative modules will be loaded in the entrance of framwork).

However,Lumen just is one of recommended frameworks,hope to it can help you:)
> 1 votes

---
Tags: networking, multiplayer, databases
---


# Question
Title: How can I implement path finding with obstacles between cells?
I'm trying to make a game at the moment and have some trouble with the A\* algorithm for path finding.

In the picture the orange and rainbow cells are walkable, but the orange cells have walls around them that should not be crossed. I don't know how to define these walls for my A\* algorithm.

So my player is going over the wall to get to the point (red path) but I want it to avoid the wall (green path).

I'm currently using this library: astar-javascript but I can't define "special" cells with it that could be crossed on one side only.

If anyone has an idea, thank you :)

# Answer
> 2 votes
Two cells are connected iff they are adjacent and there is no wall between them. After that, A\* works as normal.

If your path-finding library doesn't support defining adjacency like that *(which seems unlikely, they usually support generic graphs)*, you can use this trick to turn thin-walls into full cells.

# Answer
> 2 votes
This library appears to use an adjacency matrix, with a value of 0 denoting a wall. See this line in the library's readme:

> 1. A weight of 0 denotes a wall.

What you want then in order to denote a wall between cells 1 and 2 is a matrix where matrix\[1\]\[2\] and matrix\[2\]\[1\] are both 0. More documentation for the adjacency matrix model is easily accessible online, but I cannot easily link it as I am on mobile.

---
Tags: path-finding
---