# Question
Title: How to make a text box where text "types" smoothly
I want to create a textbox that behaves like most textboxes seen in other games where the text appears gradually. So far this has been my attempt at it but unfortunately, the text appears very unevenly and slow even when changing the letter pause to an insanely low amount.

```
public float letterPause = 0.1f;

IEnumerator TypeText()
{
    //number of char typed per loop
    int len = 3;
    for (int i = 0; i < text.Length; i += len)
    {

        if (i + len > text.Length)
        {
            ibubbletext.text += text.Substring(i, text.Length - i);
        }

        else
        {
            ibubbletext.text += text.Substring(i, len);
        }
        yield return new WaitForSeconds(letterPause);
    }
}

```

# Answer
**WaitForSeconds isn't accurate enough for this. Here's a better way:**

```
using UnityEngine;

public class TextTyper : MonoBehaviour {

    string textToType;
    float singleKeyDuration;
    string textDisplayed;
    float timeStarted;

    // Use this for initialization
    void Start () {
        TypeText("Hello, my name is Lilo Elia.\nYou ate my hamster.\nPrepare to cry!", 6);
    }

    public void TypeText(string text, float timeToType) {
    textToType = text;
    var numOfChars = textToType.Length;
    singleKeyDuration = timeToType / numOfChars;
    textDisplayed = "";
        timeStarted = Time.time;
    }

    void Update () {
        var numOfCharsSoFar = (Time.time - timeStarted) / singleKeyDuration;
        textDisplayed = textToType.Substring(0, (int)numOfCharsSoFar);
    }

    private void OnGUI() {
        var style = GUIStyle.none;
        style.padding = new RectOffset(10, 10, 10, 10);
        style.normal.textColor = Color.black;
        GUILayout.Label(textDisplayed,style);
    }
}

```

**And the result... :o)**
> 3 votes

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


title: How to structure a non rectangular maze

text:
# Question
Title: How to structure a non rectangular maze
I have built a few mazes and are familiar with maze algorithms however all examples I have learnt from are square or rectangular.

In these mazes the code structure usally has a 2d array of maze cells and it is easy to navigate or test to adjacent cells.

How do you structure the code for a say a Y or circular shaped maze to know what the avaliable joints between cells/nodes in the maze are?

# Answer
If your maze doesn't easily map to a 2d array, make it a graph.

Make each cell a structure which includes where that cell is, how it looks and most importantly an array of references to the the cells which are adjacent to it. Unless you plan to change the connections between cells at runtime, you might only want to keep those connections which are actually walkable.

This graph:

Might represent this dungeon:

```
        +-----+
        |     |
        |     |
+-------+     +--------+
|       |  3  |        |
|   2                  +----+
|       |     |          6  |
+- -+- -+-----+   4    |    |
|   |         |        +----+
| 1                    |
|   |         |        |
+---     5    +--------+
    |         |
    |         |
    +---------+

```

The JSON representation of node 1 would look something like this:

```
{
    // information about the node itself:
    x: 0,
    y: 7,
    width: 5,
    height; 5,
    // information about connections to other nodes:
    connections: [
        { x: 2, y: 0, destination: 2 },
        { x: 4, y: 2, destination: 5 }
    ]
}

```

The nice thing about representing your mazes with graphs is that they don't even need to have an euclidean geometry. That gives you a lot of interesting possibilities:

* You can connect two cells which are far away from each other. This might, for example, represent a teleporter. Or a maze which loops with itself.
* You can represent connections which only work in one direction (like pitfalls) by connecting cell A to B but not B to A.
* You can easily make the maze three-dimensional (or, heck, four-dimensional if you want to really screw with your player's minds).
* You can have a maze which isn't even spatially possible, like one where two rooms overlap each other. When you only show one room at a time, the player might not even notice.

Most route finding algorithms are designed to work on graphs anyway, so they will easily deal with such "weird" maze topographies.
> 3 votes

---
Tags: procedural-generation, data-structure, maze
---


title: Sprites With Vastly Disparate Scales

text:
# Question
Title: Sprites With Vastly Disparate Scales
So, I'm developing a 2D game where I'm dealing with sprites with vastly different scales. I'm attempting to represent the scales accurately, where I have a 10-m wingspan fighter and a 1400-m carrier that launches it. The trouble I'm running into, is if I draw the fighter out to be 100px wide, then the carrier needs to be 14,000 px. I believe the XNA game engine I'm running supports only up to 8096x8096 sizes, so I'm a little unsure what to do. Thank for your help, guys!

# Answer
Don't represent the carrier with a single sprite. Represent it with a tilemap.

So instead of having one 14000px wide sprite for the carrier flight deck, have a 32x32px sprite for runway without markings and one with lines on it. Then draw these two tiles as often as you need to.

This might sound slower than drawing just one sprite, but has the advantage that you only need to draw those tiles which are actually on the screen.
> 3 votes

---
Tags: xna, 2d, sprites, monogame
---


title: Pygame moving rectangle

text:
# Question
Title: Pygame moving rectangle
I am coding a snake game with pygame for Python 3.6 and wonder how I can make the snake move all the time, changing direction when buttons right, down, left and up pressed, like in the real snake game.

# Answer
> 1 votes
This is actually very simple. You don't want to zero out the velocity on frames but only change it.

```
speed = (0, 0)

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed = (-10, 0)
            if event.key == pygame.K_RIGHT:
                speed = (10, 0)
            if event.key == pygame.K_UP:
                speed = (0,-10)
            if event.key == pygame.K_DOWN:
                speed = (0, 10)

    snake.position.x += speed[0]
    snake.position.y += speed[1]

```

As you can see, the speed is changed when a button is pressed, and the speed stays constant until a new button is pressed. You can replace the `10`s with a speed variable.

---
Tags: python, pygame, snake
---


title: What is an offset?

text:
# Question
Title: What is an offset?
Pretty simple question and I didn't find any place that explains it in the context of game development, wiki explains offset in the context of geometry (parallel curves) and I am pretty sure its not the same offset in game development. I use Unity, and I encounter this term a lot.

Please explain it to me, thank you in advance.

# Answer
It is, in fact, basically the same concept. An offset is just a displacement, a difference between two things. Most of the time it's used by adding it to some original value to obtain a new value.

It's used in a lot of different *contexts* in game development, which is perhaps what may be confusing you. You could have a 2D vector that is an offset representing how far an object moves when struck with an attack. You could have a scalar value called an "offset" that represents how many degrees to sway the camera in a FPS while the player is experiencing a "drunken" effect. There are innumerable ways to use the concept, but it's basically the same thing.
> 5 votes

# Answer
Offset means difference from the base/begin/origin. For example if my origin is `Vector3(0,0,0)` and you offset something with `Vector3(1, 0, 0)` the resulting position will be the `origin + offset` meaning `Vector3 (1, 0, 0)`. Another example:

```
origin: Vector3 (15, 23, 19)
offset: Vector3 (8, 3, 1)
Resulting position: Vector3 (23, 26, 20)

```
> 3 votes

---
Tags: terminology
---


# Question
Title: Is it a good idea to use per pixel collision detection in an isometric game?
I've completed the per-pixel collision detection for a small side-scroller game, for learning purposes using a Lazyfoo.net tutorial, and I am wondering if it is a good method for detecting collision in an isometric game consisting of a pure 2D world.

**My plan is described in this picture:**

As you can see, I want to start with bounding boxes, and if I collide with it I start iterating through the tiles rectangles (19, in this case) for better precision. Is it a good way to handle collisions in this type of game? If not, what would be a suitable alternative?

# Answer
The problem with per-pixel collision detection is that 1. it can be very slow and 2. your graphic design can have a lot more impact on your game mechanics than you would like. It is usually better to try to approximate the collision zones of the objects in your game with simple geometrical shapes.

The last time I made a game with an isometric perspective, I found it very useful to calculate all the game mechanics in orthogonal perspective. So on the game logic layer, all tiles were still rectangular. The transformation of all the orthogonal logic coordinates into the isometric screen perspective didn't happen before the rendering loop. That made many things a lot easier.

But if you really want to handle everything in screen coordinates, then you don't have bounding boxes, you have bounding rhombuses. Fortunately, these are not much more difficult to check for collision with each other than boxes.

* The distance between two points in the upleft -\> downright diagonal is `abs((x1 + y1) - (x2 + y2))`.
* The distance between two points in the upright -\> downleft diagonal is `abs((y1 - x1) - (y2 - x2))`
* Note that if your tiles are not as wide as they are high, you need to multiply all the x-coordinates in the above two formulas with half your tile-width and all the y-coordinates with half your tile-height.
* You have a collision in the same situation where you have a collision between two boxes: If the absolute value of the difference on both diagonals is smaller than the sum of the distance between center and edge of both rhombuses on the respective axis. Or in code, if both distances are smaller than `sqrt(tilewidth * tilewidth + tileheight * tileheight)` (which is, as you might notice, a constant you can hardcode).
> 5 votes

---
Tags: 2d, collision-detection, isometric, sdl2
---


title: Terrain Destruction Accuracy

text:
# Question
Title: Terrain Destruction Accuracy
I am making a game in unity that allows you to destroy terrain, The problem I am having is that the farther away that I get from the origin (0,0), The more inaccurate the point where the destruction occurs is. Is there a way to make it more accurate?

```
// Use this for initialization
void Start ()
{
    //The width and height of the heightMap
    xRes = TerrainMain.terrainData.heightmapWidth;
    yRes = TerrainMain.terrainData.heightmapHeight;

    //Getting the heightMap points
    saved = TerrainMain.terrainData.GetHeights(0, 0, xRes, yRes);
    heights = TerrainMain.terrainData.GetHeights(0, 0, xRes, yRes);
}

void TerrainDestruction()
{

    Vector3 actualPosition;

    actualPosition.x = MyPosition.x;
    actualPosition.y = MyPosition.y;
    actualPosition.z = MyPosition.z;

    //Getting the x and y position of the player
    int xPosition = (int)(actualPosition.x);
    int zPosition = (int)(actualPosition.z);

    Debug.Log("x: " + xPosition);
    Debug.Log("z: " + zPosition);

    heights[zPosition, xPosition] -= 0.001f;

    TerrainMain.terrainData.SetHeights(0, 0, heights);

    TerrainMain.terrainData.SetHeights(0, 0, heights);

}

void OnApplicationQuit()
{
    TerrainMain.terrainData.SetHeights(0, 0, saved);
}

// Update is called once per frame
void Update ()
{
    //Getting the actual Position of the player with respect to the terrain
    MyPosition = MyMouse.mousePosition;

    if (Input.GetMouseButtonDown(0))
    {
        TerrainDestruction();
    }
}

```

# Answer
From what I understand of your vague question... Your player's position is a float. You're trying to keep pixel-level precision on texture/terrain edits.

So what happens is, the further you are from the texture/terrain's origin point, the more inaccuracy piles up?

If that's so: This is just how floats work. Floats jump in value by several units or something, and dynamically scale their decimal point.

Basically, if you're between coordinate 0f and 1f, you get like 0.00001f precision. But if you're between coordinate 0f and 10000000f, you get like 1.0f precision.

Floats are, like, 32bit, meaning your accuracy can just represent 2147483647 different coordinates. But float can be larger than that.

That, and floats have an annoying problem with being indecisive about their value. Hence why most software that uses floats keeps them between 0f and 1f for the high "approximate" decimal precision.

Basically floats are garbage for precision, get some 64 bit longs in there. In programming, you need to design TO the computer and language; not twist the language to your design. Think of your SMALLEST coordinate and LARGEST coordinate, then figure out which data types are suitable to that.

Sorry if my answer sounds like trash, I tried :(
> 1 votes

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


# Question
Title: Game Maker: How do I make a score display move with the view?
I have drawn everything needed to the screen including a HUD for the score, but I have my room set to follow my player: When the camera follows the player, the score HUD stays doesn't scroll with him!

How do I make the score display follow along with the player also?

# Answer
You'll have to set the score position relative to the view position every update event.

Some basic pseudo code from what I remember of GML.

```
    score.x = view[0].x + 15;
    score.y = view[0].y + 15;

```

You can do something similar with the drag and drop interface, but I haven't touched GameMaker for years so I can't help you with that.
> 4 votes

# Answer
I added this to event draw, of the object Score and it worked for me

```
x= view_xview[0] + 320;
y= view_yview[0];
draw_set_font(fnt_score);
draw_set_color(c_white);
draw_text(x, y, (score));

```
> 2 votes

# Answer
@Simon was pretty close.

If you are trying to draw relative to the View that is *Enabled* you can use `view_xview[view_current], view_yview[view_current]`.

For most situations you can get away with using `view_xview[0]` because most games do not utilize multiple views.
> 0 votes

# Answer
Have a look at the Draw GUI event for this particular problem.

I needed some left/right arrows on my screen to control player movement. I placed two buttons in the room, added a Draw event to each with nothing in it. I then added a Draw GUI event, with

```
draw_self();

```

as the only code in the event.

However, this only works for the full version.
> 0 votes

---
Tags: camera, game-maker, hud
---


title: Unity using "as" vs "GetComponent<>()"

text:
# Question
Title: Unity using "as" vs "GetComponent<>()"
Hello im new to unity and im learning raycast right now , after checking the documentation here https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html , i got something that's confusing me , what is the difference between :

```
 MeshCollider themeshhit = thehit.collider as MeshCollider;
 //
 if (themeshhit == null) {
 Debug.Log (" | themeshhit == null ! | ");
 }
 //

```

and :

```
 MeshCollider themeshhittwo =  thehit.collider.gameObject.GetComponent<MeshCollider> ();
 //
 if (themeshhittwo == null) {
 Debug.Log (" | themeshhittwo == null ! | ");
 }
 //

```

Both method is working correctly , but i want to know what is the difference between them , and i also want to know which one is better if comparing against speed , compatibility , and ability .

Edit : variable thehit is look similar to this

```
 RaycastHit thehit;

```

# Answer
The correct way to do what you want is the first one :

```
 MeshCollider theMeshHit = thehit.collider as MeshCollider;

```

In contrary to simple gameobjects `.collider` does not call `GetComponent` when using RaycastHit. The reference of the collider is stored in the object when the `Physics.Raycast` is called, and `.collider` is the getter to this collider.

The 2nd piece of code you tried calls a useless `.gameobject` make it slower.

TL; DR :

* `thehit.collider.gameObject.GetComponent<MeshCollider> ();` : 1 call to `GetComponent` \+ 1 call to `.gameobject`
* `thehit.collider as MeshCollider` : 1 cast used
> 4 votes

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


# Question
Title: Create a series of points round a globe (Polar to Cartesian) C++
I am trying to create a series of waypoints for my globe planet, in a little simulation I'm doing, and I'm trying to use polar to cartesian coordinates, I learnt this formula off its wikipedia page. Though I still don't quite understand it.

https://en.wikipedia.org/wiki/Spherical\_coordinate\_system
Attempt 1; This is the image of my first attempt, I do not want to cluster the points near the poles, the poles are also at the completely wrong point, I will supply my code later on. But also I do not want to put points too close to the poles, as they are not in use, and due to camera gimbal locking, there is no point me going too far close to the north or south pole in my program.

---

Attempt 2: Now I know how to create a single line, and the code I use for this is provided below. I sort of figured this out by just testing out different values and seeing how it came about.

##

---

Now what I want to do to this, I think as the way I wish to construct it, is to get the vector of each of those points, and rotate them round the centre of the planet which in this example is (0,0,0)  I want to create a single line of longitude per pas, so I can number the points 0-50 on each line, that will allow me to use it as a connected grid,lets say 0-50 going upwards, so that if i start at point 1 which would be the first point near the south pole, and I want to go to the next row I would add 50 to get to 51 (which would be the point right of it) or take 50 to get the point left of it), and so on and so forth, this will allow me to easily join waypoints for pathfinding setup.

I made another attempt in the link \[ABOVE\], where I try and make a nested for loop and change the latitude per step, but it does not get the desired result, I have even swapped the values of lat and longitude around in the code and the coordinates are the same.

Latitude = should be the angle from east to west. Longitude = should be the angle north to south.

To do this I think but I am not sure, I assume I will have to store a temporary value of each of those points, and then create a new vector from them, by rotating their vectors around the origin of the planet (0,0,0) and then creating a new set of these points at the temporary vectors.

Does anybody have an idea how to help me solve my problem, as Image 4 is the best explanation I can think of showing my problem to explain what I am trying to achieve.

# Answer
I found a solution in a different manner with the help of Enmanuel Reynoso a friend of mine, I divide it in a nested for loop, up into the amount of lines I want, and then iterate through the loop.

```
void setupplanetwaypoint()
{

    const int pointsInLine = 70; // how many points in a line
    const int lines = 180; // lines must be multiple of 30
    const int spaceBetweenLines = 360 / lines;
    waypointsVEC.resize(lines);

    for (int inc = 0; inc < lines; ++inc)
    {
        const float longitud = 90;

        const float rad = 3.14f / 180.0f;

        const float rotation = spaceBetweenLines * inc;

        float latitud = -90;

        for (int b = 0; b < pointsInLine; ++b)
        {
            // Laurent Help - remember wiki page Polar to Cartesian
            float x = 20 * sin(longitud * rad) * cos(latitud * rad);
            float y = 20 * sin(longitud * rad) * sin(latitud * rad);
            float z = 20 * cos(longitud * rad);

            // 2D rotation, we only move 2 axis, in this case X would be 'z' and Y would be 'x'
            float zr = z * cos(rotation * rad) - x * sin(rotation * rad);
            float xr = z * sin(rotation * rad) + x * cos(rotation * rad);

            latitud += 180.0f / pointsInLine;

            CWaypoint WP(xr, y, zr);
            waypointsVEC[inc].push_back(new CWaypoint(WP));

            // OLD CODE FROM WHEN WAYPOINTS WERE MODEL CUBES
            // region VV
#pragma region
        /*  model->LookAt(0, 0, 0);
            model->Scale(0.02);
            modelsLines[inc].push_back(model);*/
            //
#pragma endregion
        }

    }
}

```
> 0 votes

---
Tags: vector
---


# Question
Title: How can I reduce the performance impact of rendering trees?
I'm making a low poly stylized kind of game. I have a terrain with some water, and I want lots and lots of trees; I have 10,000 trees mass placed, at the moment. Each tree consists of no more than 200 triangles, so they aren't too taxing.

The main problem is that there are lakes, and the lakes are quite large. You can't actually see any trees on the other side of the lake, and that looks really bad, especially when you walk there and trees suddenly appear.

To fix this, I have to increase the tree distance so that you can see a decent amount of trees on the other side of the lake, but that reduces performance to 40-50fps, and there is hardly anything else in the game yet. I'm using a GTX 1080, if that helps.

What can I do to make my game run faster with more trees?

# Answer
Ok, so the problem was simply that I wasn't using pre-computed realtime GI. I check that on a little while ago but it didn't have an immediate effect so I left it and forgot about it, and the lighting processing time was so long too. However, it just finished processing it, and my word, my fps has jumped up by 3x. So for now, I'll leave it at that and in the future make sure I'm always using precomputer realtime GI!

If there still is anything else that I could be doing to further improve performacnce, please let me know, I would be most grateful!
> 13 votes

# Answer
There are couple of things you can do to increase drawing performance.

1. You said they were pretty far away. You could use LOD to decrease the vertex count of those trees, and thus decreasing time required to go through all the vertices being drawn. Even though this is most likely not the issue at hand (GTX1080 with just 10k trees with 200 tris each, puny numbers for the gpu) I still included it. Billboarding is an effective tool for the lowest LOD level, as it is essentially a flat plane always facing the camera with a rendered image of the tree on it. It loses sense of depth, which is why it is good for the lowest level as the player most likely won't notice the difference.
2. Have you enabled batching? Dynamic batching is usually done automatically if the vertex counts of the meshes are fairly low. Static batching can also be tried by making the trees static by checking the checkbox in the unity editor on the parent gameobject. This does not work well with animated objects. You need the objects to have shared material to make this work.
3. Custom batching lets you control the rendering by generating the chunks yourself instead of letting unity handle it, and it also enables batching for larger meshes. This is done easily by Mesh.CombineMeshes. This also does not work well with animated objects. You need the objects to have shared material to make this work. You probably want to divide your world in to some kind of chunks and create batches from those. How those chunks should be generated is really up to how your camera moves in the world.
4. Enable instancing on the shaders. Instancing enables the engine to draw multiple objects (with same mesh) with just one draw call. You need the objects to have shared mesh and shared shader for this to work. The material can vary, but the shader must support all the different varying properties.

To make the engine create instanced rendering batches better, you probably want to group the same meshes together in scene. Also playing with material render queue will give you good results if one mesh has always the same material. During the development the mobile game I currently am working on, I used this to reduce drawcalls by more than half in my testing scene. Also since Unity 5.6 make sure you check the `Enable Instancing` checkbox in the material.

5. Keep your drawcalls and SetPass calls down in general. These are the raw calls for your GPU to draw stuff, and they have a large overhead. Reducing drawcalls (which is what batching and instancing is doing) will increase the overall performance your CPU can provide as it is required to do so much less waiting. SetPass calls are changes to your current shaders, so if you have many different materials you will have multiple SetPass calls, which are also causing the CPU to wait a little bit.
6. If your scene is huge and your CPU time goes in to going through all the objects in the scene, try to reduce the objects in the scene. Group up some trees instead of placing them invidually and have them as a single object. Also make sure you're not moving the trees or the parent objects, as that makes Unity to discard cached transforms and to recalculate the whole scene tree.
7. If your scene is huge and your CPU time still goes mostly in to Unity walking through the scene tree to make lists to render all the objects, one thing you could do is to not let Unity to handle the rendering. If you have a better way to track drawable objects you could use CommandBuffer.DrawMeshInstanced or Graphics.DrawMeshInstanced to draw them by hand. I won't go in much detail about this as it's a lot more advanced and involves culling obects yourself and whatnot.
8. Dynamic lighting is not as fast to render as static lighting. You can pre-render your static lights to a lightmap. You should also reduce the number of dynamic lights if possible to make rendering the frame take less time. Forward lighting is harder to pull off if you have multiple light sources, where deferred lighting works a little bit better in that regard as it is able to reduce drawn pixels per light.

In case if the static or dynamic batching is not working properly (which you can see by checking the frame debugger), you need to make sure that you are indeed using shared material, and are not making copies of the material by accident with calling `meshRenderer.material`. Calling the `.material` will make copies of your materials and break batching. Use `.sharedMaterial` instead.

Since Unity 5.6 you can use the Frame Debugger to determine why certain drawcalls did not batch with the previous drawcalls. This will be really helpful while trying to reduce the drawcalls of your game.

Instancing has the following advantages over static/dynamic/custom batching:

* Uses less memory as the mesh does not have to be duplicated in memory
* Can use multiple materials, only shared shader is required
* Objects can be animated

Also as a downside it is rather new feature in Unity and might be a bit unstable. Also older or mobile device GPUs do not necessarily support instancing.
> 45 votes

---
Tags: unity, performance, terrain
---


title: Sampled texture renders dark

text:
# Question
Title: Sampled texture renders dark
I'm taking a texture from a shared texture handle and rendering it on the screen. I do this by creating a simple mesh that covers screen space, and then sampling the texture like so

```
float4 main(PixelInput pixelInput) : SV_TARGET
{
    return sourceTexture.Sample(textureSamplerState, pixelInput.uv);
}

```

However, the texture on the screen appears **significantly** darker than the source texture. I suspect this is because the type of the texture from which I am sampling is DXGI\_FORMAT\_R8G8B8A8\_UNORM\_SRGB but my back buffer is DXGI\_FORMAT\_B8G8R8A8\_UNORM. For technical reasons, I am unable to change the format of either.

I tried the following conversion to linear color space

```
    float4 sRGBA = sourceTexture.Sample(textureSamplerState, pixelInput.uv);
    float3 sRGB = float3(sRGBA.x, sRGBA.y, sRGBA.z);
    float3 RGB = sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);
    return float4(RGB, sRGBA.w);

```

But this seemed to make no difference at all (which I found surprising in and of itself).

There are no other shader effects or interesting pieces being applied.

What here might cause the effect of the darker rendering?

*Thanks in advanced, let me know if there is any additional interesting information!*

# Answer
> 2 votes
I'm thinking you got your targets mixed up in your question because now you are converting linear to gamma so I'm thinking the targets are around the other way.

When sampling from an none SRGB texture if your back buffer is an SRGB format then you need to do the conversion by hand.

Like this:

```
 // Converts from linear RGB space to gamma.
 float3 LinearToGamma(float3 color)
 {
 return pow(color,1/2.2);
 }

```

If your targets are the way you say they are then I would expect the conversion to be

```
// Converts from gamma space to linear RGB.
float3 GammaToLinear(float3 color)
{
return color * color;
}

```

because you are reading from an SRGB texture and outputting to a none SRGB target.

---
Tags: directx, directx11, hlsl
---


# Question
Title: How to create per-vertex normals when reusing vertex data?
I am displaying a cube using a vertex buffer object (gl.ELEMENT\_ARRAY\_BUFFER). This allows me to specify vertex *indicies*, rather than having duplicate vertexes. In the case of displaying a simple cube, this means I only need to have eight vertices total. Opposed to needing three vertices per triangle, times two triangles per face, times six faces. Sound correct so far?

My question is, how do I now deal with vertex attribute data such as color, texture coordinates, and normals when reusing vertices using the vertex buffer object?

If I am reusing the same vertex data in my indexed vertex buffer, how can I differentiate when vertex X is used as part of the cube's front face versus the cube's left face? In both cases I would like the surface normal and texture coordinates to be different. I understand I *could* average the surface normal, however I would like to render a cube. Also, this still doesn't work for texture coordinates.

Is there a way to save memory using a vertex buffer object while being able to provide different vertex attribute data based on context? (Per-triangle would be idea.)

Or should I just duplicate each vertex for each context in which it gets rendered. (So there is a one-to-one mapping between vertex, normal, color, etc.)

Note: I'm using OpenGL ES.

# Answer
Unfortunately, you can't -- you can't have differently-sized attribute streams (you'd need multiple index buffers, or some other kind of mapping to correlate them all).

You'll have to duplicate the vertices you want to participate in different triangles or otherwise have unique attributes other than position. This isn't actually as bad *in practice* as it seems in terms of duplication of the position data. A cube is actually a pretty pathological case for this scenario, and tends to make the amount of duplication you'll end up with *seem* much higher than it would be for "real" models. Unless you're game is all about cubes, in which case, well... sorry. :D
> 6 votes

# Answer
Interpolating the normal is fine for the vast majority of real cases.

Plus, cubes have their own special textures, cube maps, with 3D texture co-ordinates. In conjunction with a normal map, you shouldn't have any problems.
> 0 votes

# Answer
One way to 'solve' this is to use a normal texture and look up the normal for each pixel in the fragment shader. Hopefully this should be possible with OpenGL ES.

It might be a bit overkill to have normal mapping with cubes but for real models I suppose they work out just fine.
> 0 votes

---
Tags: opengl-es, normals, vertex-arrays
---


title: Creating VR Headset Video

text:
# Question
Title: Creating VR Headset Video
So I have a video stream of known resolution and I have a VR headset via HDMI at a known resolution.

Is there an existing library to create the slight fisheye and side-by-side layout for these single screen headsets? (It's a custom build, so no hardware locked API please)

Target: Win 7/8/10

# Answer
It is not easy to go through the entire way. There are no current libraries combining those stuffs you want. But you can make a custom design basing on open libraries and graphic languages(Let us leave aside argument that opengl and d3d is not languages). Firstly, you should begin with a Video decode library like FFmpeg. Then, assuming you good at one of opengl/gles/vulkan/d3d/mental or other graphic languages, you should build a scene for you video. slight fisheye and side-by-side layout are just little trick in graphics, you should achieve if you good for graphics principle.I think it is enough for you goals. Tial-and-error is a good method as XGundam05 says. Good lucky.
> -1 votes

---
Tags: software-engineering, graphics-programming, virtual-reality
---


title: LibGdx animation sequence

text:
# Question
Title: LibGdx animation sequence
In my game the character movement animations work fine but now I'm trying to do a sequence of programmatic animations, for an enemy character, and it's proving to be a pain.

I'm just doing it on Android.

I have the enemy character doing a walking animation till it reaches and end position, then I want it to do a three frame throw animation. It's walk animation is fine.

Since I only want to do the throw animation frames once, I tried to use `Animation.PlayMode.NORMAL`, and try to use `isAnimationFinished()`.

I also tried to get the frame number using `getKeyFrameIndex()` to try to detect when it showed the last frame.

But in both cases, when it reaches the end position, either I just see a flash of one of the throwing frames, or nothing at all, and it says it's "finished" with the animation, using one of the above ways to test it.

```
objectBatch.draw(
    animation.getKeyFrame(throwingSkeletonObject.fStateTime),
    throwingSkeletonObject.position.x,  // x
    throwingSkeletonObject.position.y,  // y
    1,      // width
    1);     // height

```

I'm using the `fStateTime` that was passed into the Object from the `update()` of the Object. For the walking animation I use:

```
 animation.setPlayMode(Animation.PlayMode.LOOP);

```

and for the throw animation:

```
 animation.setPlayMode(Animation.PlayMode.NORMAL);

```

The frameDuration for the walk animation is 0.7f and for the throw 0.3f.

So what do I need to do to be able to actually see all the frames of the throw animation, and then be able to tell when that's "finished", so I can go back to the walk animation going the other way or whatever?

I've tried lots of different combinations of things, including using a slower throw frameDuration, and nothing seems to really work.

Eventually I want to try to get the Boss animations going and those are much more complicated, so I want to get this fairly simple sequence to work.

UPDATE:

In the `update()` I'm doing:

```
throwingSkeletonObject.fStateTime += fDeltaTime;

```

The game is 2D, and I'm not using scene2D.

UPDATE SOLVED?:

I wrote a smaller test app in hopes of replicating the problem but it worked pretty well. When it did the throw animation I reset the StateTime back to zero, so as a test, I commented that out so it used the same StateTime as the walking animation and it only showed one frame of the throwing animation, so I think that was the problem. But I'm not sure about the throwing animation "end" test, I'm hoping that that will also work now.

# Answer
The problem with the throwing animation is quite simple: timing.

You set the frameDuration to 0.3f. This is (obviously) equal to 3/10f. When you set the frameDuration, it's in terms of seconds per frame. In this case, each frame lasts 0.3 seconds for a total of under a second.

Try setting the frameDuration to 2/3f. That will result in the throw animation lasting almost exactly 2 seconds.
> 0 votes

---
Tags: android, libgdx, animation
---


# Question
Title: How to select multiple frames from a sprite sheet in unity
I have a sprite sheet and cannot figure out how to select multiple frames in unity 5.5 I am watching a tutorial and it doesn't say how to do it. Is there a button I have to press while clicking or is it having to change some settings?

# Answer
I'm not sure about the timing when you need or want to select multiple frames at once. But as I read it, you may just want to press control (CTRL) while clicking on your frames to select several of them at once.
> 2 votes

---
Tags: unity, spritesheet
---


title: Component super class?

text:
# Question
Title: Component super class?
I have recently been programming an Entity Component System in Java for a small game that I am working on. From what I have tested, it works rather well however I question the component part. I currently have an *Entity* class that stores subclasses of *Component* in a *HashMap* which can be accessed by a *String*:

```
private Map<String, Component> components = new HashMap<String, Component>();

```

The problem is that my root *Component* class looks like this:

```
public class Component {

}

```

I feel as if I've headed in the wrong direction so my question is do I need a *Component* super class? If so, is there anything that needs to be put in it? If not, should I have a *HashMap* of *Objects* instead? Are there advantages to either methods?

# Answer
Your component base-class seems to be empty now, but it's just a question of time until you will find functionality to add to it. A good candidate might be an `update()` function which you likely want to have on almost any kind of component.

In the meantime you might want to change it to an interface. That would make it a pure marker interface: An interface which defines no functionality, but marks classes which fulfill some specific purpose or implement some contract, like in your case, being a component.

And by the way: If you want to allow one component per component-type on each entity, you might want to define your hash map as a `Map<Class, Component>`. You addComponent method would then do this:

```
public void addComponent(Component newComponent) {
     components.put(newComponent.getClass(), newComponent);
}

```

GetComponent looks like this:

```
public Component getComponent(Class type) {
    return components.get(type);
}

```

and would be called like this:

```
getComponent(PlayerControllerComponent.class);

```

This should be a bit faster and gives you the advantage of type-safety (you can no longer misspell your component identification strings).
> 1 votes

---
Tags: java, entity-component
---


title: Bartle taxonomy formula

text:
# Question
Title: Bartle taxonomy formula
Anyone knows the formula inside the Bartle Test of players taxonomy?

I need to do the test, but I need the weight of each question to make something more accurate and trustworthy to the real test...

Some links to the online test:

# Answer
> 3 votes
Erwin Andreasen, the co-author of the widely-taken questionnaire, links to the original question set (which seems to be the same one used on the sites you linked). Since the download link is somewhat hidden in an auto-redirect page, I'll just reproduce it in full here:

```
Are you more comfortable, as a player on a MUD:
+S Talking with friends in a tavern?
+A Out hunting orcs by yourself for experience?

Which is more enjoyable to you?
+A Killing a big monster
+S Bragging about it to your friends?

Which do you enjoy more in MUD quests:
+S Getting involved in the storyline
+A Getting the rewards at the end?

Which would you rather be noticed for on a MUD?:
+A Your equipment
+S Your personality

Would you rather be:
+S Popular
+A Wealthy

Which do you enjoy more on a MUD?:
+S Getting the latest gossip
+A Getting a new item

Which would you rather have, as a player on a MUD?:
+S A private channel, over which you and your friends can communicate
+A Your own house, worth millions of gold coins

Which would you enjoy more as a MUD player?
+S Running your own tavern?
+E Making your own maps of the world, then selling them?

What's more important in a MUD to you?
+S The number of people
+E The number of areas to explore

What's more important to you:
+S The quality of roleplaying in a mud
+E The uniqueness of the features, and game mechanic

You are being chased by a monster on a MUD.
Do you:
+S Ask a friend for help in killing it
+E Hide somewhere you know the monster won't follow

You're a player on a mud, and you want to fight a really tough dragon.
How would you approach this problem?
+S Get a big group of players to kill it.
+E Try a variety of weapons and magic against it, until you find its weakness.

You're a player on a mud, and about to go into an unknown dungeon.
You have your choice of one more person for your party.
Do you bring:
+S A bard, who's a good friend of yours and who's great for entertaining you and your friends
+E A wizard, to identify the items that you find there

Is it better to be:
+K Feared
+S Loved

Someone has PK'ed you. Do you want to:
+S Find out why, and try to convince them not to do it again
+K Plot your revenge

Which is more exciting?
+S A well-roleplayed scenario
+K A deadly battle

Which would you enjoy more?
+K Winning a duel with another player
+S Getting accepted by a clan

Would you rather
+K Vanquish your enemies
+S Convince your enemies to work for you, not against you

What's worse:
+K To be without power
+S To be without friends

Would you rather:
+S Hear what someone has to say
+K Show them the sharp blade of your axe

On a MUD, a new area opens up.
Which do you look forward to more?
+E Exploring the new area, and finding out its history
+A Being the first to get the new equipment from the area

On a MUD, would you rather be known as:
+E Someone who can run from any two points in the world, and really knows their way around.
+A The person with the best, most unique equipment in the game

Would you rather:
+A Become a hero faster than your friends
+E Know more secrets than your friends?

Would you rather:
+E Know where to find things
+A Know how to get things?

Which would you rather do:
+E Solve a riddle no one else has gotten
+A Getting to a certain experience level faster than anyone else

Do you tend to:
+E Know things no one else does
+A Have items no one else does

On a MUD, would rather join a clan of:
+E Scholars
+K Assassins

Would you rather win:
+E A trivia contest
+K An arena battle

If you're alone in an area, do you think:
+E It's safe to explore
+K You'll have to look elsewhere for prey

On a MUD, would rather be known for
+E Knowledge
+K Power

Would you rather:
+K Defeat an enemy
+E Explore a new area

You learn that another player is planning your demise.
Do you:
+E Go to an area your opponent is unfamiliar with and prepare there
+K Attack him before he attacks you

You meet a new player. Do you think of him as:
+E Someone who can appreciate your knowledge of the game
+K As potential prey

On a mud, would you rather:
+A Have a sword twice as powerful as any other in the game
+K Be the most feared person in the game

On a mud, would you be more prone to brag about:
+K How may other players you've killed
+A Your equipment

Would you rather have:
+K A spell to damage other players
+A A spell that increases the rate at which you gain experience points?

Would you rather have:
+A Two levels of experience
+K An amulet that increases the damage you do against other players by 10%.

Would you rather receive as a quest reward:
+A Experience points
+K A wand with 3 charges of a spell that lets you control other players, against their will. (charm person)

When playing a video game, is it more fun to:
+A Have the highest score on the list?
+K Beat your best friend one-on-one?

```

As you can see, there are no weights - each question has equal value, and simply chooses between two quadrants. Add up all the quadrants to get your final score.

Keep in mind that this questionnaire, and the taxonomy itself, is very simplistic and not rigorous at all. There are more accurate models for player psychology available. But as a simple way to understand that there can be different player motivations, this model is fine.

# Answer
> 1 votes
There is no real "formula".

The original presentation of a "Bartle Test" (as formulated by Erwin Andreasen) is to present the test-taker with a series of situations, and ask them to choose between two options, where each of the two options represents one of the types in Richard Bartle's Bartle Taxonomy of Player Types.

All you do to interpret the test is to add up the number of times the answer for each 'type' was selected. That's really all there is to it. There's no formula, no science, and there's no 'more accurate' or 'trustworthy' to be striven for. It's just a simple pop-culture personality test which gets you to say what you prefer to do, and then parrots back that you seem to be a person who prefers to do the things that you just said you prefer to do. Ooo, science-y.

The original question data, with the intended scoring for each answer, are available from the website of the test's creator, here. (it's the link labelled "original English question data set")

N.B.: In the original question set (which is used verbatim in both of the links posted in the question), 'Socialiser' and 'Killer' are each available 20 times, while 'Achiever' and 'Explorer' are each only available 19 times. This biases test results slightly towards producing higher 'Socialiser' and 'Killer' values. This may give you a hint at the lofty heights of scientific rigour under which this personality test was devised.

---
Tags: game-design, mmo, psychology
---


# Question
Title: Missing features from WebGL and OpenGL ES
I've started using WebGL and am pleased with how easy it is to leverage my OpenGL (and by extension OpenGL ES) experience. However, my understanding is as follows:

* OpenGL ES is a subset of OpenGL
* WebGL is a subset of OpenGL ES

Is this correct for both cases? If so, are there resources for detailing which features are missing?

For example, one notable missing feature is `glPushMatrix` and `glPopMatrix`. I don't see those in WebGL, but in my searches I cannot find them referenced in OpenGL ES material either.

# Answer
> 9 votes
The WebGL wiki contained a section in its FAQ hierarchy for "WebGL and OpenGL Differences" which seems to focus on differences in WebGL from "desktop" OpenGL implementations and, alas, isn't very detailed (mostly it's about behavior, not the API).

If that does not go into enough detail for you, you may need to compare the latest WebGL draft with the OpenGL ES or OpenGL specifications manually.

# Answer
> 9 votes
Have you checked the latestp WebGL draft?

According to the draft in case of a contradiction, the OpenGL ES 2.0 specification is the final authority.

Chapter 6 outlines the differences from OpenGL ES 2.0 to WebGL.

http://www.khronos.org/registry/webgl/specs/latest/

# Answer
> 1 votes
I found a great resource for comparing what specific APIs are available across different versions of OpenGL/WebGL/OpenGL ES.

I think you will find what you are looking for, here: http://web.eecs.umich.edu/~sugih/courses/eecs487/common/notes/APITables.xml

# Answer
> 0 votes
One way to look at it is WebGL is OpenGL ES 2.0 and OpenGL ES 2.0 is OpenGL with all the legacy cruft removed.

Since shaders were added all the legacy fixed function pipeline `glPushMatrix`, `glLight`, `glVertex` etc all made no sense to keep around.

So are those "missing" features or correctly and properly "deprecated" features?

What specific features are you looking for?

WebGL/OpenGL ES 2.0 is basic vertex and fragment shaders. There's limited support for non-power-of-2 textures and only a few texture formats (not really much of a limit is 99% of all textures are RGB8 or RGBA8). Support for floating point textures is optional but the majority of devices support them. Support for rendering to floating point textures is rarer though. Few if any mobile devices support rendering to a floating point texture.

WebGL2 (just shipped) and OpenGL ES 3.0 added a ton of new texture formats including integer based texture and 3D textures. It removed the non-power-of-2 texture limits. It added transform feedback (the ability for a vertex shader to write to a buffer). It also added occlusion queries. Vertex Array Objects are standard (they were optional in WebGL/ES 3.0). There's a bunch of other more minor features.

ES 3.1 (and probably the next version of WebGL) adds compute shaders (the ability for a fragment shader to do random access writes). Fragment shaders could only write to the fragment/pixel being requested of them at the moment whereas compute shaders and write anywhere they want.

What other features did you want to use?

---
Tags: opengl, opengl-es, webgl
---


title: A* Implementation broken?

text:
# Question
Title: A* Implementation broken?
I tried implementing Wikipedia's version of the A\* pathfinding algorithm, but when I run it in Unity the object which the script is applied to does nothing and Unity ends up taking 15% of my CPU. I feel like this is a stack overflow error, but I can't tell where it breaks down. Here's the entirety of the script:

```
public class Walker : MonoBehaviour {

    public int x { get; set; }
    public int y { get; set; }
    public MapView core { get; set; }
    public Node goal { get; set; }

    public float DistanceBetween(Node a, Node b) {
        return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
    }

    public List<Vector3> FindPath(Node goal) {
        Node start = new Node(x, y);

        List<Node> open = new List<Node>();
        open.Add(start);
        List<Node> closed = new List<Node>();

        Dictionary<Node, Node> cameFrom = new Dictionary<Node, Node>();

        Dictionary<Node, float> gScore = new Dictionary<Node, float>();
        gScore[start] = 0;

        Dictionary<Node, float> fScore = new Dictionary<Node, float>();
        fScore[start] = DistanceBetween(start, goal);

        while (open.Count != 0) {

            Node current = open[0];

            foreach (Node n in fScore.Keys)
                if (fScore[n] < fScore[current])
                    current = n;

            if (current == goal)
                return ReconstructPath(cameFrom, current);

            open.Remove(current);
            closed.Add(current);

            foreach (Node neighbor in Neighbors(current)) {

                if (closed.Contains(neighbor))
                    continue;
                float tempGScore = gScore[current] + DistanceBetween(current, neighbor);

                if (!open.Contains(neighbor))

                    open.Add(neighbor);

                else if (tempGScore >= gScore[neighbor])
                    continue;

                cameFrom[neighbor] = current;
                gScore[neighbor] = tempGScore;
                fScore[neighbor] = gScore[neighbor] + DistanceBetween(neighbor, goal);
            }
        }

        return new List<Vector3>();
    }

    public List<Vector3> ReconstructPath(Dictionary<Node, Node> cameFrom, Node current) {
        List<Vector3> path = new List<Vector3>();
        path.Add(current.GetVector());
        while (cameFrom.ContainsKey(current)) {
            current = cameFrom[current];
            path.Add(current.GetVector());
        }
        return path;
    }

    public List<Node> Neighbors(Node current) {
        int currx = current.x;
        int curry = current.y;

        List<Node> neighbors = new List<Node>();
        neighbors.Add(new Node(currx, curry - 1));
        neighbors.Add(new Node(currx, curry + 1));
        neighbors.Add(new Node(currx - 1, curry));
        neighbors.Add(new Node(currx + 1, curry));
        return neighbors;
    }

    public virtual void SetStartCoords() {
        x = (int)transform.position.x;
        y = (int)transform.position.z;
    }
}

public class Node {

    public int x;
    public int y;

    public Node(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Vector3 GetVector() {
        return new Vector3(x, 0, y);
    }
}

```

Could I be misusing the DistanceBetween() function incorrectly, since I'm using it to calculate both the gScore and fScore of each node?

Edit: I tried a new implementation, but Unity is still not even responding. @ratchet-freak @bálint

```
public class Walker {
    public List<Vector3> FindPath(Node goal) {
        Node start = new Node(x, y);

        SimplePriorityQueue<Node> open = new SimplePriorityQueue<Node>();
        open.Enqueue(start,0);

        List<Node> closed = new List<Node>();

        while (open.Count != 0) {

            Node current = open.Dequeue();

            foreach (Node neighbor in Neighbors(current)) {

                if (neighbor == goal)
                    return ReconstructPath(neighbor);

                neighbor.gScore = DistanceBetween(current, neighbor);
                neighbor.hScore = DistanceBetween(neighbor, goal);
                neighbor.fScore = neighbor.gScore + neighbor.hScore;

                bool skip = false;

                foreach (Node n in open)
                    if (n == neighbor && n.fScore < neighbor.fScore)
                        skip = true;
                foreach (Node n in closed)
                    if (n == neighbor && n.fScore < neighbor.fScore)
                        skip = true;

                if (!skip)
                    open.Enqueue(neighbor, neighbor.fScore);
            }

            closed.Add(current);
        }

        return new List<Vector3>();
    }

    public List<Vector3> ReconstructPath(Node current) {
        List<Vector3> path = new List<Vector3>();
        path.Add(current.GetVector());
        while (current.cameFrom != null) {
            current = current.cameFrom;
            path.Add(current.GetVector());
        }
        return path;
    }
}

```

# Answer
Doing a linear scan over the entire open set and then doing a `Remove` (which is also O(n)) is not going to help performance. A good implementation uses a heap of some sort for the open set where you can pop the next node in O(log n) and update the neighbours in the set also in O(log n).

`closed.Contains(neighbor)` where closed is a List means that this is a O(n) operation instead use a Set with a O(1) contains operation.

Related to this many implementations will create a

```
struct{
    Node cameFrom;
    float gScore;
    float fScore;
    bool closed;
}

```

So that you don't need 3 different dictionaries.
> 1 votes

---
Tags: unity, c#, algorithm, path-finding, search
---


# Question
Title: Unity Array Index Is Out Of Range Raycast triangleIndex
I just tried the script from the official unity documentation here https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html , the script is working at some point :

But unity throw error "Array index is out of range" more often than successful click if i click at random place in 1 gameobject ( Cylinder ) :

\[ i replay the game and do 5 click , see the error count at the debugger \]

This is my script ( not important it is almost same with the documentation , but i just put it , and i removed some part to make it shorter) :

```
    RaycastHit thehit;
    if (Input.GetMouseButtonDown (0) && methodoneenabled == true) {
        Ray theray = Camera.main.ScreenPointToRay (Input.mousePosition);

        if (Physics.Raycast (theray, out thehit)) {
            Debug.Log ("raycast work");
            if (thehit.collider != null) {
                string thedebug =  "Hit : " +   thehit.collider.gameObject.name + " ";

                 MeshCollider themeshhittwo = thehit.collider.gameObject.GetComponent<MeshCollider> ();
                if (themeshhittwo == null) {
                    Debug.Log (" | themeshhittwo == null ! | ");
                } else {

                    Debug.Log (" | " + thehit.triangleIndex + " | ");

                    Mesh mesh = themeshhittwo.sharedMesh;
                    Vector3[] vertices = mesh.vertices;
                    int[] triangles = mesh.triangles;
                    Vector3 p0 = vertices [triangles [thehit.triangleIndex * 3 + 0]];
                    Vector3 p1 = vertices [triangles [thehit.triangleIndex * 3 + 1]];
                    Vector3 p2 = vertices [triangles [thehit.triangleIndex * 3 + 2]];
                    Transform hitTransform = thehit.collider.transform;
                    p0 = hitTransform.TransformPoint (p0);
                    p1 = hitTransform.TransformPoint (p1);
                    p2 = hitTransform.TransformPoint (p2);
                    Debug.Log (" | " + p0 + " ; " + p1 + " ; " + p2 + " | ");
                    Debug.DrawLine (p0, p1);
                    Debug.DrawLine (p1, p2);
                    Debug.DrawLine (p2, p0);
               }
            }
        }
    }

```

My script can be run so tell me if i missed some part when copying and pasting .

Can anyone tell me what is the wrong part and the cause of the error at the script ? -,- though the script is official script ....

Edit : the script i shared is located at CameraScript.Update()
Edit : the error is located at

```
    Vector3 p0 = vertices [triangles [thehit.triangleIndex * 3 + 0]];

```

but mostly will available at here too

```
    Vector3 p1 = vertices [triangles [thehit.triangleIndex * 3 + 1]];
    Vector3 p2 = vertices [triangles [thehit.triangleIndex * 3 + 2]];

```

Edit : i found out that the error appear if i click the middle of the cylinder , and work well if i click near the corner of the cylinder ( not the corner ! ) , also it is work well at plane mesh without error , but what was causing it -,- .....

# Answer
> 6 votes
You've already printed all the info you need - it's right there in your console output.

**Your hit.triangleIndex is -1.**

Since C# arrays start at 0, this will always be out of range.

**So, why would Unity give you a value of -1 here? Because you didn't hit a triangle!**

You've set up your cylinder with two colliders on it: a CapsuleCollider and a MeshCollider. MeshColliders have triangles, but CapsuleColliders don't.

Your ray hits the CapsuleCollider most of the time (since it's round, it tends to stick out beyond the facets of the polygonal surface), but then instead of working with the collider you actually hit, you've changed the Unity example script to use GetComponent to grab the MeshCollider, even if it's not the one you hit. This is not a safe thing to do.

If you want to ensure you hit the MeshCollider, you can do a few different things (in order from simplest to most laborious...):

* Remove the CapsuleCollider
* Put the CapsuleCollider and MeshColider into separate child objects of the cylinder, and put each onto a different physics layer. Then you can use a layermask with your raycast to select just the mesh's layer.
* Use RayCastAll to tunnel through your first colision and hit the next one to (and the next, and the next...) then you can search through the results array for the first one that hit a MeshCollider

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


title: 2D Websocket WebGL game

text:
# Question
Title: 2D Websocket WebGL game
Inspired by BrowserQuest, I want to try my hand at making my own kind of game like this but I don't really know anything about game development other than the basics, like how the game loop works. Although, I feel more than confident with server-side/client-side JS so it's mostly just about learning concepts for me.

Some questions I've had so far when thinking about how I'll go about implementing it:

1. I understand there'll be unsynced client-side code and synced server-side code. If a player presses an arrow key on their keyboard, should it send that information to the server, then the server says it's ok, then the client does it? Or should the client just do it anyway then the server validate it after-the-fact and correct the client if they perform an invalid action?
2. The data going between server and client will initially be very simple. Currently I just have x and y positions for players. But how often is it ok for clients to send this data back to the server and the server to broadcast the data to all clients? I could do these things every 1ms which would make everything as smooth as possible, but wouldn't this kill the client/server or at least use a truck-load of bandwidth? I only have a very small VPS and wouldn't want to overload it by sending 1000 JSON objects to a bunch of clients every second when I don't have to. What's the sweet-spot here?
3. I want to include some PvP style combat in my game but am not sure if the websocket protocol is suitable for this. With UDP, data is sent back and forth super fast partly in thanks to its unreliable nature, right? With websockets, will the communication between clients/server be fast enough to process something like a player attacking another player?

Any other advice about this sort of thing would be great, even if it's just links to existing documentation/examples. Cheers.

# Answer
> 5 votes
**1: Should the client wait for confirmation before moving the player?**

Websockets use the TCP protocol, which can have very irregular latencies from time to time (which is usually why UDP is recommended for real-time games, but that's not available to browser-based Javascript). When the reaction to each input is not just delayed but delayed irregularly, your game will seem very unresponsive and laggy to the player. So if you can predict with reasonable sincerity that the server will confirm an action, you should execute it without waiting for that confirmation.

**2: How often to send data to the clients?**

Only send data when something has actually changed. Sending "Bob is still standing on 45:67" every millisecond is quite pointless. Only send a message when Bob started moving and another when Bob stops moving or changes direction.

Most online game servers run with a fixed number of ticks per second (usually something between 10 and 100). The ideal tick-rate depends on the game and is something you need to find out through test-play, but usually the more action-oriented a game the more does it benefit from a higher tick-rate.

**3: Is Websocket fast enough for PvP combat?**

I'm sorry, but that's impossible to answer. It depends too much on the combat system of your game and on how good the internet connections between your players and your server are. But considering that you seem to be on a tight budget and thus likely can't afford top-notch peering in local datacenters all around the globe, you might want to go for a combat system which emphasizes strategy and tactics over reaction speed and dexterity.

**Any other advice about this sort of thing?**

You want to build an MMORPG all by yourself? If you are just doing it for the learning experience, then go for it! There is a very wide variety of useful skills to pick up in the process. But don't expect it to be successful.

I also developed an MMORPG all by myself. And it actually worked quite well. After a few years of after-work and weekend development, the technology was practically feature-complete. I even had a bunch of working maps and a fully functional tutorial. But then I realized that if I want to manage an MMORPG the way it deserves, I don't just need to quit my day-job but also hire a whole bunch of people to create content and manage the community. I wasn't ready and willing for that kind of commitment. So I mothballed the project.

I don't regret the project at all. Most of what I know about Java, JavaScript, WebSockets (wrote my own implementation. It was as educating as it was painful) MongoDB and Linux server administration did I pick up in the course of that project. But just don't think that this project will make your rich or even financially independent, unless you are able and willing to invest a lot of money into it.

---
Tags: javascript, webgl, websocket
---


title: Java and Steam JVM deployment

text:
# Question
Title: Java and Steam JVM deployment
I am currently considering my options for game development and deploying to Steam Greenlight. I really like Java with libGDX, especially for its cross platform Android potential, and I understand that it is possible to deploy Java games on Steam. I am also very comfortable with having to create some sort of wrapper so that my Java game could call into the C++ Steamworks API.

My question is about what deployment problems I might run into. Specifically, with the client machine's installation of the JRE. I have seen many Steam installers check for the .NET runtime. Should I do a similar check and install for the JRE?

Are there any glaring reasons why Java deployment on Steam would be a nightmare to deploy and maintain vs something like C# using Monogame?

# Answer
As someone who has recently released a libGDX game on Steam, unlike .NET and DirectX, Steam does not provide an option with your application to automatically check and download the version you need of those libraries.

It's obtrusive to the user to make them install Java as a system library, as most still view the JRE, especially Oracle's, as some kind of adware/security hole and do not want to have it installed on their machine. There is still a stigma towards Java applications on the desktop, so you have to be considerate of the user.

What I recommend is using libgdx's packr application, which will automatically pack your jar and resources with an appropriate, private OpenJDK which is open to use and distribute with your software. Alternatively, you can do it manually by grabbing the unofficial OpenJDK build that they are using in packr and including it with your project.

I, personally, do that latter option as I have downloading the latest version and packing everything up, including distributing to steam, all included in my project's gradle build script.

Including your own JRE/JDK is lightweight, only adding about 80mb to your game, and is non-invasive. This also insures that the version of Java that you are running your application with is always the version that you need, instead of conflicting with what the system has.

**Edit: March 13, 2017**

For a little over a year now I've been using Azul's OpenJRE instead of the unofficial builds from alexkasko. They're widely used and supported even in enterprise environments. Additionally, they support Java 8 and up, where as at the time of my switch the unofficial build repository versions were stuck at Java 7.

Since I switched, there is now an open-source repository as well, that continues to provide community built versions of the openjdk/jre, if you wish to use that instead. Both are good.
> 16 votes

# Answer
I think that it is absolutely OK to check the user's runtime, given the language requires one. I think that in .NET, Java, Python, Lua, or other programming languages that require a runtime environment, simply because the game cannot run without it.

If you have UX concerns, don't worry, the JRE installer is not very intrusive, and many games get away with runtime installations, or even multiple dependencies.

In terms of legal concerns, I don't believe that you are in any grey or red zones of the law. According to the License FAQ, you can quite simply distribute the Java Environment with you're software, according to the item stating:

> **Can I distribute Java with my software?**
> Yes, you can provide Java with your software provided you abide by the terms and conditions of Java binary code license

That should be all the information you need to make an educated decision.
> 1 votes

# Answer
Some users may not have Java installed and I don't believe that Steam has a native way of checking for / installing Java as that would be irritating for the user and only a small minority of games on Steam require Java.

Try including a portable Java Runtime Environment so that you will always have a consistent build of Java to run the game on, I'm sure there are some around that will suit your needs.
> 0 votes

# Answer
Java development can be a nightmare as far as deployment; but, there are tools to make this easier.

For example, you can use a tool like `Launch4j` to package up your final game; optionally, you can tell it to include the JRE (or not) in order to create a fully self-contained binary.

This way, you don't care if or what JREs the client has installled; you just package up your app, and ship it. The downside is that your final binary will be significantly larger.
> 0 votes

---
Tags: java, libgdx, steam
---


# Question
Title: Where to update Player health text graphics? (C++)
I am trying to update the text rendered on the screen after the health of a player changes. The problem I am having is deciding where to update this. The player and health graphics are separate objects.

Currently,my code is organized like this: The main c++ has vectors:

* vector\< Players\>
* vector\< Renderables\>

"Renderables" is anything that can be rendered. It has a member function render() which is called for every object in the vector. A "Text" class inherits from it. It contains the string that is displayed on screen. "Text" has its own render function, and calls its member function getString() inside its render function.

The question is where do I update this string once the player's health has changed?

My current solution is actually to have a "PlayerHealth" subclass of "Text", which holds a pointer to the player. That way "PlayerHealth"can just redefine getString() as player-\>health converted to a string, and using "Text"'s render function. But I've been told this wasn't a very good method and was wondering what other approaches there were to this problem.

Thank you for your time

# Answer
> 1 votes
Fundamentally, you need to create some kind of association between a `Player` and the possibly-many sets of `Text` associated with that player. When you have that association, you can (depending on how you implement the association):

* push the new player health text to the correct `Text` from the `Player` or
* pull the new player text from the `Player` in the `Text`

There are several ways to establish this link; subclassing `Text` and creating a `PlayerHealth` that refers to a `Player` is on one way, but it doesn't scale well. You'll end up having to create lots of little subclass's, potentially, creating a maintainability problem.

A better option might be to give the `Player` a set of pointers to `Text` objects associated with the player in various ways. Perhaps they need a pointer to the `Text` representing their health, and one for their name, maybe one for debug information like position in the world, et cetera.

This allows you to easily push text updates from the `Player`, but doesn't really require any management of the `Text` on the player's part (except to know `Text` exists), so you preserve the separation you have.

A more general approach that's very common these days is to go for a full-on "component-based entity system" (or "ECS") and represent the player as a generic entity object with various components, such as components for each associated text. This option is more generic and puts more of an abstraction buffer between the two systems (potentially), but is also more work to implement and can be a source for design analysis paralysis. So if you go that route remember to focus on your concrete goals.

---
Tags: c++
---


# Question
Title: Is it wrong to be creating new objects in Update()?
I'm using Unity and sometimes I'm using th `new` keyword in `Update`, like `new Vector3()` etc...

I wonder is this causes memory leak? I mean in every frame a new Vector3 is created. If this is the way of working that means there are thousands of Vectors created in memory. Is it true or do I think wrong?

# Answer
> 15 votes
In C# there are two kinds of types, roughly: value types and reference types.

You use `new` when you create both, but value types are created on the stack (most of the time), and only reference types get created on the heap. Once created, reference types stick around until the garbage collector happens to come along, determine they are no longer needed, and collects them. Instances on the stack are destroy efficiently when the stack frame goes away (when the function they were created in ends).

`Vector3` is a value type in Unity, so almost all the instances you ever create will be stored on the stack and thus cheap to both create and destroy. So you're not likely doing anything wrong here. It certainly doesn't create a memory leak, and it almost certainly won't be a performance issue (you'd want to profile to be sure, anyhow).

Creating a lot of new *reference types* every frame can be problematic since that can induce the garbage collector to run more frequently, causing hitches as it pauses all your threads to do its work. But value types like `Vector3` are a pretty safe bet.

---
Tags: unity
---


# Question
Title: LibGDX Switching to fullscreen makes sprites blurry
I'm using LibGDX to develop/render my game and when I start the game in windowed mode, then switch to full screen, the sprites look blurry. Importantly(?), starting the game in full screen then switching to windowed mode doesn't have this problem.

Here's a section of a screenshot starting off windowed:

And after switching to fullscreen, the (roughly) same section of the screen:

The sprites are loaded from a `TextureAtlas` using LibGDX's `TexturePacker`. They're rendered using a normal `SpriteBatch` with the default settings/shaders. These are my `pack.json` settings:

```
{
    "pot": true,
    "paddingX": 2,
    "paddingY": 2,
    "bleed": true,
    "edgePadding": true,
    "maxWidth": 4096,
    "maxHeight": 4096,
    "duplicatePadding": false,
    "filterMin": "MipMapLinearLinear",
    "filterMag": "Linear"
}

```

I wondered if the filterMin/Mag might be having some effect but trying different settings is giving the same results.

To switch between fullscreen and windowed, I'm using the following code:

```
public static void toggleFullscreen() {
    if (DisplaySettings.isGamefullscreen && Gdx.graphics.supportsDisplayModeChange()) {
        // Switch to windowed
        Gdx.graphics.setWindowedMode(DisplaySettings.windowedWidth, DisplaySettings.windowedHeight);
        DisplaySettings.isGamefullscreen = false;
    } else if (Gdx.graphics.supportsDisplayModeChange()) {
        // Switch to full screen
        Gdx.graphics.setWindowedMode(DisplaySettings.desktopWidth, DisplaySettings.desktopHeight);
        Gdx.graphics.setFullscreenMode(Gdx.graphics.getDisplayMode());
        DisplaySettings.isGamefullscreen = true;
    }
}

```

So in this case the game starts off windowed then toggles to fullscreen after everything has loaded/been set up.

I am using some `FrameBuffer`s and `TextureRegion`s to draw to, but these are disposed and recreated on a resize.

I feel like there's some problems perhaps with the mipmaps being created and used incorrectly in this case but I'm a bit stuck at this point, any help much appreciated!

# Answer
> 3 votes
The problem is that you started the game with a specific resolution **Width** **x** **Height**. Next you tell you application to render that on the fullscreen, so it is taking that rendering and **upscaling** it, which causes you rendering to look blurry.

What you have to do is to call this first in your function: Gdx.graphics.setDisplayMode(**x\_width**, **y\_width**, DisplaySettings.isGamefullscreen), where **x\_width** and **y\_width** is the size you actually want the image rendered in (not upscaled to).

Then you might also have to send the new x\_width and y\_width to the camera, including updating the camera.

Hope that helps you.

---
Tags: opengl, java, libgdx, lwjgl
---


# Question
Title: how do you add W, A, S, D controls to unity 5.5
I have a character already in the game files and just need to know how he can move I have looked online in lots of places and it just doesn't make sense to me as I am sorta new to the game development scene please help. I think you can use C# or Javascript in Unity.

# Answer
> 0 votes
Here is the C# code you can use to make your character move using the W, A, S, D keys

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

public class movement : MonoBehaviour {

public float speed = 1f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetKey(KeyCode.D))
        transform.position += new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);

    if (Input.GetKey(KeyCode.A))
        transform.position -= new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);

    if (Input.GetKey(KeyCode.W))
        transform.position += new Vector3(0.0f, speed * Time.deltaTime, 0.0f);

    if (Input.GetKey(KeyCode.S))
        transform.position -= new Vector3(0.0f, speed * Time.deltaTime, 0.0f);
}
}

```

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


# Question
Title: Unity 2D sprite animation keep in sync after setting inactive
I am creating a 2D sprite-based game and the tile map contains many animated background tiles (such as water). The map contains many areas that can be transitioned between in a Zelda style (camera scrolls to new area). After scrolling, I set the previous area to inactive. Setting the area to inactive pauses the animations (which is what I want), but when I reenter a previous area the animations start from where they left off. Therefore, any animated tiles adjacent to each other between screens are out of sync and cause an obvious seam. I would like for all the background tile animations to run on the same time value even after they've been paused. The animations use an Animator Controller attached to each animated tile GameObject with an Animation that changes the sprite from an atlas.

Another idea I had would be to have a separate class modify my texture atlas (maybe using setpixel) to update the tiles to their next frame of animation (since I want all tile animations to be in sync and run at the same speed), but I'm not sure how updating the texture will affect performance.

I would like to hear people's ideas for any solutions to this problem.

# Answer
I've implemented a solution using my idea of actually modifying the texture that is being used by the tiles. It works perfectly for what I am trying to do, and doesn't affect performance in a meaningful way that I could see with the Profiler/stats.

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

public class TextureAnimator : MonoBehaviour {
    // The texture that will be modified.
    // Must have read/write enabled in the texture import settings.
    public Texture2D tilemap;

    // The texture containing each frame of the animated tiles.
    // For my example, each unique tile is laid out vertically,
    // and each frame of the tile is laid out horizontally.
    // Must have read/write enabled in the texture import settings.
    public Texture2D animations;

    // frames per second of the animation
    int samples = 5;
    int lastFrame = -1;
    float time = 0;

    void Update () {
        // the current frame of animation
        int frame = Mathf.FloorToInt (time * samples);

        // make sure we are on a different frame of animation before
        // updating the texture
        if (frame != lastFrame) {
            // first 4 params of SetPixels are the x,y,width,height of the region in the tilemap to change
            // first 4 params of GetPixels are the x,y,width,height of the region in the animations texture to read from
            // this animation has 4 frames, so we do frame%4
            tilemap.SetPixels (1, 1, 16, 16, animations.GetPixels (1+((frame%4)*17), 1, 16, 16));
            // actually applies the SetPixels calls to the texture
            tilemap.Apply ();
            lastFrame = frame;
        }

        time += Time.deltaTime;
    }
}

```
> 1 votes

---
Tags: unity, 2d, animation, tilemap
---


title: Minigame inside game in Unity

text:
# Question
Title: Minigame inside game in Unity
I am developing a 2D game, and using an option of the game, it will open a minigame. I planned to set it as a separate scene, but I don't know how could I load a Scene into another scene as a window.

To give you an example, it would be something like Mass Effect and Piracy puzzle (as you can see, the game opens another game in a separate window).

Example:

As you can see, the Minigame is in some kind of Window, and in the background is the main game.

Anybody knows how could I do that?

Thank you

# Answer
> 5 votes
You can load a scene without destroying anything in the current scene by using the method `SceneManager.LoadScene` with the `LoadSceneMode.Additive` flag.

Example: `SceneManager.LoadScene ("MinigameSceneName", LoadSceneMode.Additive);`

That way all the objects from the loaded scene get added to your current scene. Both scenes now coexist with each other in the same 3d space.

To close the minigame, use `SceneManager.UnloadSceneAsync ("MinigameSceneName");`

Note that all scripts from the "background scene" are still active, so you might want to set your input controller to inactive while the minigame is active.

The minigame scene won't get loaded "in a window", but you can fix that by the scene *being* a window in form of an own UI canvas.

If you don't want to implement your minigame with just the UI system, you can add a secondary camera to the scene which shows the minigame. To make that second camera render everything it sees on top of the output of the first camera, set it's "Depth" higher than that of the first camera and set its "Clear Flags" to "Depth Only". You can also edit the "Viewport Rect" of your minigame camera to only draw inside a defined rectangular area. Another feature which could be useful here is the "Culling Mask" which controls which camera renders which layers. When primary game and minigame use different layers, you can easily use culling masks to make sure that they don't interfere with each other visually. For more information, check the documentation of Camera.

---
Tags: unity, unityscript
---


# Question
Title: Efficient systems in an Entity Component System
I'm designing a simple Arcanoid game with ECS.

With ECS there are many systems that only update components once in a while. For example, Particle systems are animated sprites that can be used for collision effects or explosions. These kind of effects happen rarely.

`ParticleSystem` will only update `ParticleComponent` when they exist, which happens rarely, just on collisions, etc. The rest of the time it's polling to find entities with `ParticleComponent`.

Isn't this polling inefficient? If I have many more functions similar to the `ParticleSystem`, that only do work rarely, the update will be clogged with systems that do not update anything. Would it be good practice to "sleep" the system until an entity is assigned to the `ParticleComponent`?

For example (using EntityX):

```
class ParticleComponent : Component<ParticleComponent>
{
public:
    ParticleComponent(ParticleId id) : id(id), time(0.0){};

    ParticleId id;
    double time;
};

class ParticleSystem : System<ParticleSystem>
{
public:
    void update(EntityManager & entities, EventManager & events, TimeDelta dt)
    {
        // this list will be empty if there are no entities.. but there is still a search
        entities.each<ParticleComponent>([](Entity & entity, ParticleComponent & particle)
        {
            // update current animation time
            particle.time += dt;
        });
    }
};

class Game : public EntityX
{
public:
    Game()
    {
        systems.add<ParticleSystem>();
        systems.configure();
    }

    void update(TimeDelta dt)
    {
        // this is only useful when there are entities with ParticleComponents
        systems.update<ParticleSystem>(dt);
    }

    void onRareEvent()
    {
        auto entity = entities.create();
        entity.assign<PositionComponent>();
        entity.assign<ParticleComponent>(FIRE_PARTICLE);
        // destroy in 3 seconds
        timer.schedule(3, Game::destroyEntity, entity);
    }

    //void render()...
}

```

# Answer
> ParticleSystem will only update ParticleComponent when they exist, which happens rarely, just on collisions, etc. The rest of the time it's polling to find entities with ParticleComponent.
>
> Isn't this polling inefficient?

No, it's not efficient, but there's no reason to do it that way and no (good) ECS implementation will poll for components.

When a component/entity is created, add the component/entity to the systems's list of active objects if the object meets the appropriate requirements (some systems require a combination of components, sometimes called a "component signature" by hip youthful people). Then the system consistently has an accurate list of all objects it needs to update and the information it needs to access them efficiently, no polling required.

This is true in an ECS architecture or other component architectures. Our engine is a very far cry from ECS and yet we do the same thing: components call something like `game.SomeManager.addComponent(this)` in their initialization function and `game.SomeManager.removeComponent(this)` in their shutdown function. Fancier ECS architectures automate that, but it's the same idea.

I would have assumed that libraries like EntityX are actually doing this under the hood, but I could be wrong. Every single off-the-shelf open source entity library I've ever seen on GitHub (EntityX included) is hot flaming garbage and I'd recommend that you run screaming in the opposite direction, anyway. If you think you need a complex library to manage your game objects, that's a sign that you're massively over-complicating the problem. And if you're using some crazy template meta-programming nonsense (like EntityX) you're potentially shooting yourself in the foot (that stuff will have trouble scaling past the smallest and simplest hobby games, especially if you at all value the time lost waiting for your game to compile).
> 2 votes

# Answer
Particles is something that doesn't fit inside a component.

Instead you want spawning particles as a possible behavior of the collision component.

Then the particles themselves are in a flat array that you can loop over and update positions and render them all easily.

```
class ParticleSystem{

    std::vector<Particle> particles;

    public:
    void spawn(...); //push_back some new particles based on args

    void update(TimeDelta dt){

        for(auto it = particles.begin(); it != particles.end();++it){
            do{
            it->ttl -= dt;
            if(it->ttl < 0) {
                //particle died, remove from list;
                swap(it*, particles.back());
                particles.pop_back();
                if(it == particles.end())return;
            }
            while(it->ttl < 0);

            //update pos and vel of it*
            it->pos+=it->val * dt;
            it->vel+=it->accel*dt;
        }

    }

}

```

Particle system can always update and will usually have some particles to move but the `spawn` is only called from other components based on certain triggers.

This changes from poll notification to push notifications. Which if things are idle most of the time is much better for performance.
> 0 votes

---
Tags: c++, entity-system
---


title: Creating UI using Flixel

text:
# Question
Title: Creating UI using Flixel
I am new to game development but familiar with programming languages. I have started using Flixel and have a working Breakout game with score and lives.

What I am trying to do is add a **Start Screen** before actually loading the game.

I have a create function that adds all the game elements to the stage:

```
override public function create():void
   // all game elements
{

```

How can I add this pre-load **Start Screen**? I'm not sure if I have to add in the code to this create function or somewhere else and what code to actually add.

Eventually I would also like to add saving, loading, options and upgrades too. So any advice with that would be great.

Here is my main **game.as**:

```
package
{
    import org.flixel.*;

    public class Game extends FlxGame
    {
        private const resolution:FlxPoint = new FlxPoint(640, 480);
        private const zoom:uint = 2;
        private const fps:uint = 60;

        public function Game()
        {
            super(resolution.x / zoom, resolution.y / zoom, PlayState, zoom);
            FlxG.flashFramerate = fps;
        }
    }
}

```

# Answer
> 2 votes
So, while there might be several ways to do it, I've found it easiest to make a seperate State for each of my game 'sections' - so, the Main Menu, the Game Itself, and the Game Over/Scoreboard screens would each be their own state: `MenuState`, `PlayState`, and `EndState`, respectively.

So, make a new Class: `MenuState.as` and make sure it extends `FlxState`. In the `create()` method of `MenuState`, create and add all of your UI objects.

In your `game.as`, change this line:

```
super(resolution.x / zoom, resolution.y / zoom, PlayState, zoom);

```

Change it to:

```
super(resolution.x / zoom, resolution.y / zoom, MenuState, zoom);

```

In `MenuState`, somewhere (probably in a Button or KeyUp logic), you can use `FlxG.switchState(new PlayState);` to exit your Menu and start your game.

I recommend you have your game's logic in it's own state if possible, because it makes it easier to load, reset, and exit the game itself on demand.

# Answer
> 2 votes
If you want to add a screen **before** all assets are loaded you have to use a preloader. You can read about this here. Flixel provides simple preloader (FlxPreloader) that is easy to understand and to customize.

# Answer
> -2 votes
in the main.hx chang first State on MenuState (Its how Scenes in Unity man)

---
Tags: screen, ui-design, flixel
---


title: Pixel Perfect Camera

text:
# Question
Title: Pixel Perfect Camera
I'm trying to get the camera pixel perfect in my game. I have tried the solution described in this video: https://www.youtube.com/watch?v=eN1zV0hlkso&t=7s

I use the resolution 128 by 72.

1. Set the main camera to orthographic and the size to half of the screen height, 36
2. Duplicate the camera and make it a child of the main camera, set the value near to 0 and rename the camera to Virtual Camera.
3. Create a new layer called Virtual Screen and set the culling mask of the virtual camera to virtual screen.
4. Create a quad and make it a child object of Virtual Camera. Remove the Mesh Collider and turn ligt and reflection probes off. Rename the quad to virtual screen and set the layer to virtual screen. Set the size of the quad to the desired resolution, 128 by 72
5. Create a render texture, set the size to the desired resolution and the filter mode to point.
6. Create a material, set it to unlit/texture and the texture to the render texture created in step 5.
7. Set the target texture of the main camera to the render texture and the material of the virtual screen to the material created in step 6.

With these steps 1 pixel is 1 unit. Is it possible to get a pixel perfect camera with for example 16 pixels per unit?

# Answer
The orthographic projection (and the size of the quad) are giving you the number of units that appear in your screen.

If you set the size of the texture to match that size, then you get one pixel per unit. If you want more pixels per unit, make the texture bigger.
> 1 votes

---
Tags: unity
---


title: Loading settings files better?

text:
# Question
Title: Loading settings files better?
I have recently been working on a small game project and decided to implement settings loading at game startup. The problem is that my method seems to be too hard coded and not scalable without having a huge method:

```
public String loadSettings(String path) {
    String[] file = loadFileAsString(path);

    isFullscreen = Boolean.parseBoolean(file[0]);
    windowWidth = Integer.parseInt(file[1]);
    windowHeight = Integer.parseInt(file[2]);
    ...
}

```

As you can see, this method will get very large after a while and is at risk of crashing if someone edits the file incorrectly so what is a better way of loading this data?

# Answer
> 2 votes
> risk of crashing if someone edits the file incorrectly

If the configuration is invalid, then it should not work. You should verify if the data on the file is valid (e.g., It has all the fields, it does not have letters where numbers are expected, etc...) and either notify the user, load default settings or whatever is appropriate for your game.

> so what is a better way of loading this data?

If you want the user to be able to edit the configuration file by hand - and you do not want to worry about parsing the file - you should be using some well-known format.

Consider to use INI, JSON, YAML, XML or similar. There are libraries that will handle loading the file for you.

Which one to use is opinion based. You will have to pick considering, for example:

* Is there a library available your language and platform?
* How hard will it be to edit configuration by hand?
* How hard is to handle versioning the settings (e.g. loading a configuration file from an old version of the software that used different fields)?
* How fast is to parse the file?
* How easy is to validate the data types of the fields?
* How resilient is the format to corruption?

Alternatively, any other criteria relevant to your case.

If using a well-known format does not work for you, you could create a proprietary tool to edit the configuration file and use a binary format. It will read faster and will discourage messing with the file directly.

---
Tags: java, loading, file, settings
---