# Question
Title: How do I achieve this glowing edge shader?
I came across this example, and wanted to know how to achieve a shader that will give me similar results, i.e. the glowing edges.

How do I achieve this sort of shader?

# Answer
> 4 votes
It looks like this particular effect is applied in texture space, rather than a runtime post-process effect. Here's one way to generate such a texture:

1. Set up a pair of RenderTextures of your desired texture resolution (or larger - you can always downsample the result later, which can help smooth out artifacts)
2. Use Graphics.DrawMeshNow to draw your model into the first RenderTexture, using a custom shader that...

* Has a vertex shader that transforms vertices to their UV coordinates, rather than using the typical model-view-projection matrices to project them from the camera's viewpoint. This will let you render a UV net of the object.
    * Has a fragment shader that outputs the face's object space normal as a colour, effectively rendering a normal map for the object.

    (This will let us distinguish coplanar triangles that are a part of a single larger polygonal facet, or triangles with a smoothed edge between them, versus triangles that meet along a sharply folded edge.
3. Use Graphics.Blit to copy the first RenderTexture into the second, with an image effect shader that performs edge detection (eg. using a Sobel-Feldman operator). With appropriate contrast & thresholds, this will give us a texture with bright lines at the UV seams and hard edges of the model.
4. Blit back and forth once or more, using a blur image effect shader to bloom out these bright lines.
5. Finally, do one last blit that reads both your bloomed edge RenderTexture and your model's texture, brightening the edges of the texture where the RenderTexture is bright (eg. using additive, screen, dodge, or overlay blending formulae, or creating your own variation).
6. Save the resulting texture to a file, so you don't need to re-generate it every time you want to use it.

Here's an example where I used a similar method to detect UV seams in a model and add "rails" to the texture along these lines.

# Answer
> 2 votes
This can be done with an edge detection shader. A simple one consists of a post processing fragment shader, which marks as edge all fragments that have normals too different from the neighborn ones in the input image. Your shader should change the fragment color when It is detected as edge. From that, you could also blur the edges' neigborhood in order to avoid aliasing.

---
Tags: unity, shaders
---


# Question
Title: How to implement Boids steering efficiently? (ie. find nearest neighbours of moving entities)
As I understand it, modern pathfinding uses ideas such as Boids steering on top of traditional A\* and Dijkstra's algorithm.

It's easy to find recommendations for implementing Dijkstra's algorithm efficiently in say C++. That is I can find out what are the typical data structures to use.

With Boids steering I cannot find anything that definitively says what is the recommended way to go. You have these moving units and you need to be able to find for each unit all the nearby units to apply steering or whatever else.

What kind of data structure can I use to perform these nearest neighbour queries efficiently?

# Answer
> 2 votes
It turns out there are *lots* of data structures that are commonly used for this, which might be why you've had trouble identifying a single canonical recommendation. Each one has different characteristics and trade-offs.

Check out the Wikipedia article on nearest neighbour search for an overview, and specifically the fixed-radius near neighbours flavour which is probably most relevant to what you want to do.

One relatively simple method suggested by the second link is to divide your world into a grid of square (2D) or cubic (3D) cells. Each cell becomes a "bucket" into which you record your entities, moving them to a new bucket as they travel around the world.

When you want to find the nearest neighbours to a given entity, then they must be either in the same bucket or one of the 8/26 adjacent buckets (assuming your search radius is less than or equal to the bucket spacing).

For a large world and with entities that aren't super-tightly concentrated, this can let you skip evaluating the vast majority of entity pairs when searching for neighbours.

Of course, even from this high-level description, there are many implementations possible. The bucket lookup device could be a hash table, which itself can be implemented multiple different ways. It's likely to be difficult to identify which implementation is objectively "best" for a given game, so instead I'd recommend focusing on implementing it in a way that you find clear and friendly to work with first. If that version turns out to be a performance bottleneck in practice, then you can post a new question with the specifics of your implementation and profiling results, either here or on the Code Review exchange, to get suggestions for how to eke out more performance.

---
Tags: ai, path-finding, data-structure, steering-behaviors
---


title: Blending between many materials

text:
# Question
Title: Blending between many materials
I am storing one material ID per vertex in my meshes. In the shader for the mesh, I have a texture array full of textures that the material ID can refer to. The fragment color is chosen using triplanar texturing. Unlike vertex colors, these material IDs cannot be blended.

For example, if a dirt texture had a material ID of 5, and a grass texture had a material ID of 1, fragments in between one vertex with material ID 5 and one with material ID 1 would potentially have a material ID between 2 and 4, which is not ideal. Another flaw with this method is the fact that there would be a hard transition in between materials, as the mix or lerp function in the shader is not used.

Is there a way to blend the textures of two neighboring vertices in the fragment shader? I can add additional per-vertex data if needed.

# Answer
> 3 votes
One way that this can be done is to divide your materials into layer slots. As one example, REDengine 3, powering the Witcher 3, uses a background layer and an overlay layer for its terrain materials.

You can store your material data in control map textures as in the case above, or in your vertex data. Either way, you end up storing the identity of the material in each slot, and a blending weight between them. This keeps the total amount of material data per point and total number of texture sampling operations tightly controlled: even if your library of materials is huge, only a fixed number of them are ever in play for a single triangle/fragment.

If storing this data in the vertices, then this means that any three vertices sharing a triangle need to agree on the materials in each slot. If a vertex sits at the junction of 6 triangles, 3 of which want "snow over rock," and the other 3 want "snow over dirt," then you can duplicate this vertex to handle each case - similar to how we create hard edges where a normal changes abruptly, or UV seams. For a control map, you can use point filtering for the material IDs so they never get interpolated.

This does place a constraint on how your materials are painted. In a 2-layer system, if two adjacent locations disagree about what material should go on layer 1, layer 2 needs to hit full opacity along their shared edge to prevent a texture seam being visible. Similarly for two locations disagreeing about what belongs on layer 2 - it has to hit zero opacity in between. In practice you can usually spread out material changes over a few triangles/cells to account for this, or stick a prop/some grass in the way so the seam isn't visible. ;)

# Answer
> 0 votes
The vertex value will indeed be interpolated when arriving to the fragment shader, so for example having two connected vertices, one with texture slot id=2 and one with id=17 will give the fragment shader everything in between 2 and 17 (including decimal values in between) depending on pixel position, causing lots of texture slots to be walked through on the way.

A quick though might be to actually describe the amount of *each* texture slot in each vertex, using a 0...1 style, ie. doing it "in parallel", in an order that is always fixed. A vertex typically connects to 6 other vertices (but can connect to more), so at most 6 textures would in that case be involved in the blending at any time. You'd however describe the amount of *all* textures in each vertex; those that are 0 you'd simply skip in the fragment shader and maybe count on doing at most 6 lookups.

A question that comes next is how many "floating point" channels can you allocate in the vertex data? Not too many, i guess, but at least a few, depending on what else you need to bake in the vertex data.

Having said that, i could point out that you maybe do not need a fine resolution of 1/256 for the "amount of each texture"? If you are willing to have for example 1/16 as resolution, you can bake in the texture amounts for 16 different textures in one 8-bit "float-part", since it can hold 256 different integer values. In that case, you could describe the blending of max 16 texture materials in for example normal.w. Or have 8 channels, each with a resolution of 1/32. Ofc you need to do some bit maths in the shader (and when building the mesh), but that's the fun part right? :-)

Edit:

About the segment above, i must admit a duration-of-a-shower amount of brainwork did not reveal any good solutions as to how to control the splitting of a single float so that one is able to grab individual segments of it's bit-sequence while GPU is interpolating it. This would be a question for the bit-guys, ie. a separate issue to ask the encryption and compression experts. Can you interpolate a 32-bit floating point value AAAA (4 bytes), so that individual bytes of it's bit representation remain decodeable along the interpolation and all become BBBB *separately* at the other end?

---
Tags: unity, shaders, blending
---


# Question
Title: Multiple instances of same sprite class showing different animation frames in libGDX and box2d
So here is my problem. I created an enemy class which extends Sprite in libGDX with a Box2d body in it for collision detection. My code calls the enemy class dynamically within the game in a loop, but the problem is that when after collision I use a different animation sequence to depict a defeated enemy, the animation sequence shows different frame rates for different instances of the same class**or just jumps to the last frame**. I don't know why that is happening.

Here is the class that is called in a loop.

```
public class Spearman extends Enemies {
    private Body spearman1;
    private TextureAtlas atlas;
    private Animation approaching,defeated;
    private float time;
    private TextureRegion spearmaninit;

    private int spearmanstate=0;

    public Spearman(Play_State state,float x, float y){
        super(state,x,y);
        atlas=new TextureAtlas();
        atlas=Lone_Warrior1.getAtlas(3);
        time=0f;

        Array<TextureRegion> frames=new Array<TextureRegion>();
        for(int i=0;i<3;i++)
        {
            frames.add(new TextureRegion(atlas.findRegion("Spearman"+i)));
        }
        approaching=new Animation(0.15f,frames);
        frames.clear();
        for(int i=0;i<5;i++)
        {
         frames.add(new                         TextureRegion(atlas.findRegion("Spearmandefeated"+i)));
        }
        defeated=new Animation(2.2f,frames);
        frames.clear();
        spearmaninit=new TextureRegion(atlas.findRegion("Spearman0"));
        setBounds(getX(),getY(),200/ Lone_Warrior1.PPM,170/Lone_Warrior1.PPM);
        setRegion(spearmaninit);

    }

    public void update(float dt){

        if(spearmanstate!=-1) {
            setPosition(spearman1.getPosition().x - getWidth() / 2,        (spearman1.getPosition().y - getHeight() / 2)+13/Lone_Warrior1.PPM);
            if (spearmanstate==0 && spearman1.getLinearVelocity().x>0)
                spearmanstate=1;
            if (spearmanstate==1 && spearman1.getLinearVelocity().x==0) {
                Play_State.bodiesToRemove.add(spearman1);
                Play_State.enemycounter++;
                spearmanstate = -1;

            }
            if(spearmanstate==0)
                spearman1.setLinearVelocity(-2f,0);
            setRegion(getFrame(dt));
        }
    }
    public boolean check(){
        if(spearmanstate!=-1)
             return true;
    else
        return false;
    }
    public TextureRegion getFrame(float dt){
        TextureRegion region=null;
        region=approaching.getKeyFrame(time,true);
        if(spearmanstate==1)
           region=defeated.getKeyFrame(time);
       /* if(!region.isFlipX())
        region.flip(true,false);*/
        time=time+dt;
        return region;

    }

    @Override
    public void defineEnemy() {
        BodyDef bdef=new BodyDef();
        bdef.position.set(getX(),getY());
        bdef.type=BodyDef.BodyType.DynamicBody;
        spearman1=Play_State.world.createBody(bdef);

        FixtureDef fdef=new FixtureDef();
        PolygonShape War1=new PolygonShape();
        War1.setAsBox(60/Lone_Warrior1.PPM,60/Lone_Warrior1.PPM);

        fdef.shape=War1;
        fdef.filter.categoryBits=Lone_Warrior1.BIT_APPROACHING;
               fdef.filter.maskBits=Lone_Warrior1.BIT_GROUND|Lone_Warrior1.BIT_RUN|Lone_Warrior      1.BIT_ATTACK;
        spearman1.createFixture(fdef).setUserData("spearman1");

    }

    }

```

The abstract class that calls the Spearman:

```
    public abstract class Enemies extends Sprite {
    World world;
    Body b2body;
    public Enemies(){

    }
    public Enemies(Play_State screen,float x, float y){
        this.world=screen.world;
        setPosition(x,y);
        defineEnemy();
    }

    public abstract void defineEnemy();
    public abstract void update(float dt);
    public abstract boolean check();
}

```

Here is the code that calls the class.

```
 switch (a) {
                case 1:
                    System.out.println("creating spearman");
                    spearman.add(new Spearman(screen, (Lone_Warrior1.V_Width /Lone_Warrior1.PPM) + (Lone_Warrior1.x+``(i*500/Lone_Warrior1.PPM)), 100 /       Lone_Warrior1.PPM));
                    break;
                   }

```

Here is the collision detection and things that are done on collision in the contact listener class:

```
 if(fb.getUserData()!=null&&fb.getUserData().equals("spearman1")){
            System.out.println("spearman attacked");
            if(fa.getUserData()!=null&&fa.getUserData().equals("warriorhighkick")){
                System.out.println("spearman lost!");
                //Spawner.berserkers.get(0).berserker1.applyForceToCenter(300,100,true);
                fb.getBody().applyForceToCenter(300,100,true);
            }
            else{
                System.out.println("spearman wins");
                //fa.getBody().applyForceToCenter(-300,0,true);
                if(!fa.getUserData().equals("Ground")&&!fa.getUserData().equals("spearman1")){
                Play_State.bodiesToRemove.add(fa.getBody());
                    Warrior.posture=-1;}
            }
        }

```

# Answer
> 0 votes
Solved!

Yes, the Sprite class is a little troublesome for frame by frame animation but I had already done much of my code and needed to find a patch job for this problem instead of having to rewrite the entire code.

So here is the answer:

```
 time=currentState==previousState ? time+dt : 0;
    previousState=currentState;

```

Whenever you update the time using delta time in the update method, make sure to check if the current animation sequence is equal to the previous one, if not then make time zero, then after collision the next animation would play out in the intended sequence.Just put a tracker for the state you are in.

```
int State=1://the default form for player
    State=2;//the state of animation when the player is hit`
`    currentState=State;

```

---
Tags: libgdx, collision-detection, animation, box2d
---


# Question
Title: Why do I have an uneven sprite line, when zooming and moving in libGDX?
I'm having trouble zooming in and moving my sprites. I made a simple drawing to demonstrate what happens.

---

No zoom:

Zoomed out:

---

Some lines disappear, when moving a sprite. If I use a filter, this effect improves, but the image is now blurred.

```
    textureParameter = new TextureLoader.TextureParameter();

    textureParameter.genMipMaps = true;
    textureParameter.minFilter = Texture.TextureFilter.MipMapLinearLinear;
    textureParameter.magFilter = Texture.TextureFilter.Linear;
    game.getManager().load(ResourcesString.image, Texture.class, textureParameter);

```

This is the way I deal with my camera:

```
//Code
private void zoomCamera(Vector3 origin, float scale){
    main.orthographicCamera.update();
    Vector3 oldUnprojection = main.orthographicCamera.unproject(origin.cpy()).cpy();
    if(scale > zoomMin) scale = zoomMin;
    if(scale < zoomMax) scale = zoomMax;
    main.orthographicCamera.zoom = scale;
    main.orthographicCamera.update();
    Vector3 newUnprojection = main.orthographicCamera.unproject(origin.cpy()).cpy();
    main.orthographicCamera.position.add(oldUnprojection.cpy().add(newUnprojection.cpy().scl(-1f)));
    main.orthographicCamera.update();
}

public void pan(float x, float y, float deltaX, float deltaY) {
    main.orthographicCamera.translate(deltaX * -2f, deltaY * 2f);
}

```

---

Why do my lines display as uneven when I zoom out, and how do I fix it?

# Answer
If you have a sprite that has a line that is one pixel wide and you're displaying that in a viewport that is the same as the resolution of the display/window the all is fine, but you'll get the artifacts you're describing if you (for example) zoom out so that the viewport is four times larger than the display. At that point the pixels in the sprite needs to be rendered at half their size which is impossible due to hardware limitations, instead the pixel on screen is rendered as the blend between two pixels, which is why it looks like a half line.

Setting the filtering to `Nearest` will combat this to a certain extent but comes with the drawback of things looking "pixely".

If what you really need us for the lines in the sprite to always be exactly 1 pixel in width, regardles of resolution, then look into using the `ShapeRenderer` instead.
> 0 votes

---
Tags: libgdx, textures, sprites
---


title: C++ turning towards mouse

text:
# Question
Title: C++ turning towards mouse
I'm creating an attack boat game in c++ and I have an issue with my boat following the mouse around the screen. My plan is to have the boat follow the mouse more like a boat (slow rotations, instead of instantaneous whilst taking about 4 seconds to do a 360 turn) and for the most part it does what it should.

The bug happens when the mouse is on the left side of the screen (as soon as my mouse crosses the -x axis), as the boat follows the mouse, the boat turns in the wrong direction and does a 360, instead of following the mouse.

This is the code i'm using to do my boat turning.

```
        angle = atan2(delta_y, delta_x) * 180.0 / PI;

        //Rotate the boat towards the mouse and
        //make the boat turn more realistically
        if (angle - rotate > 0) {
            rotate += 1.0f; // turns left
        } else if (angle - rotate < 0) {
            rotate -= 1.0f; // turns right
        }
        if (angle - rotate >= 360.0f) {
            rotate = 0.0f;
        }`

```

# Answer
> 1 votes
It looks like you want to compute the signed difference between your two angles, taking into account that angles "wrap around," so the fastest way to get from +170 to -170 is to keep increasing, even though on a number line you'd have to go the other way and decrease.

Try this trick:

```
  float angleDifference = fmod(destination - current + 900f, 360f) - 180f;

```

This gives us the signed difference between two angles in the range \[-360, 360\], correctly handling the rotation direction across the wrap-around point.

```
  current += clamp(angleDifference, -1f * turnRate, 1f * turnRate);

  current = fmod(current, 360f); // Keep current from wandering too far afield.

```

How this works is the fmod or modulo operator (also represented by a % for integers or in other languages) "wraps" the number back to 0 when it goes above 360, or below -360. Adding 900 (2.5 * 360) keeps the intermediate math positive for our given input range, and we subtract the 0.5 * 360 at the end so that clockwise rotations come out negative.

---
Tags: c++, rotation, glut
---


title: export c4d mesh

text:
# Question
Title: export c4d mesh
I am trying to export a mesh and his textures out of c4d. The mesh is a car that have multiple materials and multiple objects. It looks like this :

For straightforwardness reasons I would like to have only 1 mesh file, and 1 texture file after the export. Export the mesh is the easy part, I just have to connect every objects that compose the mesh and export is in the format I want. But I have problems with textures. After some research I found that I had to use the "Bake Object" tool. So after setting the texture size ( 2048x2048 ) and file format, I get this result with the single texture :

I'm not a big user of c4d. I just use it to convert objects and reduce objects numbers/merge textures, so I have no idea where the problem can be... I tried options like "keep uvs", that didn't worked. Since the connected object looks like the first image, the problem should be in the second part.

Is there a simpler way of doing that?

# Answer
Adjust the phong angle on the model, optimize points(Mesh -\> Commands -\> Optimize) and increase resolution of texture on material using the editor tag.
> 1 votes

---
Tags: export
---


# Question
Title: How to Store Design Data in Unity including Formulas?
My team is switching to Unity 3D for an upcoming project. I'm tasked with converting our game data system into Unity.

Our existing games use spreadsheet documents (Google Docs) for designers to set values and formulas. This is then exported into an XML doc (and obfuscated) and read in by our game client. I'm trying to figure out a way to accomplish this same thing but solely through Unity. Storing, exposing, and reading data through Unity is pretty straightforward but I'm not sure on supporting formulas.

I realize I can write a custom parser and interpreter which can handle formulas but I'm wondering if there is already a way to do this in Unity.

For example, let's say I have a unit with various stats: `Level`, `Max HP`, `HP`, `Damage`, `Victory Reward`, etc. That unit may receive a reward after combat which is based on its `Level` and remaining `HP`. A designer would be able to enter into the `Victory Reward` field either a flat value, like 3, or a formula such as "Floor({Level} * ({HP} / {Max HP}))", something like that.

My question is basically, is there an existing solution for handling data with formulas in Unity, via a downloadable asset or something in Unity itself, or is there a simple framework or technology which already can do something like this which can be easily integrated (example: some kind of JSON extension which supports self-referencing other values and basic mathematical/logical operations)?

# Answer
> 1 votes
The canonical way in Unity to create "data-assets" is by implementing ScriptableObject's. This allows you to create a custom type of asset which you can then create and maintain in the Unity editor (optionally using some custom editor controls which you also need to program). This would allow you to create a`UnitType` asset with all the fields mentioned in the question and then assign the `UnitType`s to units in the scene.

But you might have a hard time to create these automatically from Google Docs spreadsheets.

Formulas are game mechanics, not game data. So they should be hard-coded into scripts. If you prefer to have all your mechanical formulas in one place, you could do so by implementing them all as static methods in a stateless class.

---
Tags: unity, data
---


# Question
Title: Game Maker 8.0 - Can I simulate any collision event within the step event of an object including the "other" reference?
Let's say I have two objects. One is "obj\_wall" and the other is "obj\_player". For the sake of argument, let us assume that I cannot just add a collision event to obj\_wall (I truly cannot due to limitations embedded within the nature of the project itself).

Is there a function or block that allows one to write a collision event within obj\_wall's step event? I know there are various collision detection functions, but what I need is one that acts *identically* to the collision event and allows me to access the "other" property. If this is not possible, are there any suitable alternatives (such as a function that detects collision and returns the instance\_id of an object colliding the wall)?

My primary issue here is that I want to be able to use collision in one instance of an object without having to have the collision event added. I'd prefer it to be as close as possible to the collision event so as to avoid unnecessary extra checks.

# Answer
You can use the `instance_place()` function:

> `instance_place(x,y,obj)` Returns the id of the instance of type obj met when the current instance is placed at position (x,y). obj can be an object or the keyword all. If it does not exist, the special object noone is returned.

You can create a structure like this:

```
// Check collision
var oth = instance_place(x,y,my_obj);
if (oth!=noone)
{
    // compute collision
}

```

Here, the variable `my_obj` is an instance id or an object index you want to check and collision with; and the local variable `oth` is the instance id of the instance the collision occurred with. If `oth` is equal to `noone`, no collision was detected.
> 1 votes

---
Tags: collision-detection, game-maker
---


title: Unity wwwForm responce handle?

text:
# Question
Title: Unity wwwForm responce handle?
Is there any way to handle the response for the wwwform we are using add.form method and there is no way to validate the data insertion we cant say the values are entered into database or not is there any way to check the response?

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LoadOnClicktes : MonoBehaviour {
    public Text box1;
    bool ch=false;

    // Use this for initialization
    string url1="*******/index.php";

    // Update is called once per frame
    public void LoadScene(int score1)
    {
        string kill = box1.text;
        Debug.Log (kill);
        int sco = Player.score;
        Debug.Log (sco);
        WWWForm form = new WWWForm ();
        form.AddField ("name", kill);
        form.AddField ("score",sco);
        WWW WWW = new WWW (url1, form);
        Debug.Log ("Done");
        ch = true;

    }
    /*void OnGUI(){
        if(ch)
        GUI.Window (0, new Rect ((Screen.width / 2) - 150, (Screen.height / 2) - 75
        , 300, 250), ShowGUI, "");
    }
    void ShowGUI(int windowID)
    {
        // You may put a label to show a message to the player

        GUI.Label(new Rect(65, 40, 200, 30), "Score Submitted");

        // You may put a button to close the pop up too

        if (GUI.Button(new Rect(50, 150, 75, 30), "OK"))
        {
            ch = false;
            // you may put other code to run according to your game too
        }

    }*/

}

```

# Answer
> 0 votes
Of course you can check the response to your request, you just gotta know when the WWW request has finished. There are different ways to do it, but for your case you could do something like this:

```
public void LoadScene(int score1)
{
    string kill = box1.text;
    Debug.Log (kill);
    int sco = Player.score;
    Debug.Log (sco);
    StartCoroutine(PublishScores(kill, sco));
}
IEnumerator PublishScores(string kill, int score) {
    WWWForm form = new WWWForm ();
    form.AddField ("name", kill);
    form.AddField ("score",score);
    WWW requestWWW = new WWW (url1, form);
    yield return requestWWW;
    if (requestWWW.responseHeaders.Count > 0)
    {
        foreach (KeyValuePair<string, string> entry in requestWWW.responseHeaders)
        {
            Debug.Log(entry.Value + "=" + entry.Key);
        }
    }
    Debug.Log ("Done");
    ch = true;
}

```

I didn't test it, but it should work. There you can see all the response headers and do whatever you want with them. Try looking a little more at the documentation to understand how to use it: https://docs.unity3d.com/ScriptReference/WWW.html

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


# Question
Title: Efficient AI handling when you have bools (avoiding cache misses)
So I am trying to optimize my ai in my game i am working on in C++

This is an example of what ai will look like

```
    class EntityUnit : public CEntity
{
public:
    enum CUnitTypeEnum // Enumerator used for finding the type of entity
    {
        Infantry,
        Tank,
        Aircraft,
        Transport,
        Naval,
        BipedalTank,
        NA,
    };

    enum CUnitTypeState
    {
        Idle,
        AttackingUnit,
        Defend,
        SearchForStrategicPoint,
        GuardResource,

    };

    enum CUnitMoveType  // Controls how the units will move to an area
    {
        Normal,  // pathfinding will take into account influence map costs
        Aggressive, // pathfinding will not take into account influence map costs
        Evasive,  // Pathfinding will add extra cost to influence map where units have occupied
        NavalNormal,
        NavalAgressive,
        NavalEvasive,
        AircraftNormal,
        AircraftAggresive,
        AircraftEvasive,
        NUKE
    };
private:

    IModel* UnitModel;

    float unit_x;
    float unit_y;
    float unit_z;
    float height;
    float width;

    float maxhealth;
    float currenthealth;
    float strength;

    float speed;
    float util_timer_movedelay = 0; // TIMER - used for delaying movement per frame

    float buildtime;
    float cost;
    float unit_model_scale;

    string unitname;
    string unitdescription;

    CUnitTypeEnum CUnitType;

    vector<gen::CVector3*> pathfinding;
    Vector3 TargetWaypoint;
    Vector3 SourceWaypoint;

    // AI BOOLEAN & STATE
    bool underattack; // IS the unit under attack / do we wan't to perform combat()
    bool reachedwaypoint; // used to detect whether reached waypoint
    bool unitGarrisoned; // IS this unit inside a cities garrison ?
    bool unitInSquad; // is this unit in an ai control squad ?

    CUnitTypeState State = Idle; // Starts off idle, == not doing anything

    string NukeSource;
    string NukeTarget;
    gen::CVector3 VNukeSource;
    gen::CVector3 VNukeTarget;

```

Its a polymorphic entity, that will call in my game loop the AI polymorphic function update() now I understand some general concepts, and I have been told or am under the impression, that the reason for my large slowdown in performance, is because the CPU' tries to guess what a enum or bool will be when you use a lot of them in a tightly closed loop, can anyone explain why this is ? and also how to avoid this or what is the most efficient way to avoid this when my AI needs to be able to change through certain behaviours and know things about its world that is true and false.

# Answer
Have a look at this question on Stackoverflow: https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array

The top answer (ahead by a little over 20'000 votes, so unlikely to change) answers the why, while the question answers what you can do about it.

And to place the answer here: Branch prediction, and it can be improved by sorting. However, don't get your hopes up. I haven't seen your code, but this is unlikely to be the primary bottleneck.
> 0 votes

---
Tags: ai
---


# Question
Title: Problem with transitioning to previous state(State Stack)
I am using a state stack as the mechanism to transition through states in my game. Currently moving to a new state works correctly, but when I want to go back to a previous state(removing top state) the application crashes. The GameSelectState class is supposed to have a menu button that when clicked should go back to the MenuState.

Game.hpp:

```
#pragma once
#include <SFML/Graphics/RenderWindow.hpp>
#include "StateStack.hpp"
#include "TextureManager.hpp"

class Game
{
public:
    Game();
    void run();

private:
    sf::RenderWindow window;
    StateStack states;
    TextureManager textures;
};

```

Game.cpp:

```
#include <memory>
#include <SFML/System/Time.hpp>
#include "Game.hpp"
#include "SplashState.hpp"
#include "GameState.hpp"

Game::Game() :
    window(sf::VideoMode(1680, 1050), "Variadic-Poker"),
    states(),
    textures()
{
    this->states.pushState(std::make_unique<SplashState>(window, states, textures));
}

void Game::run()
{
    const sf::Time timePerFrame = sf::seconds(1.f / 60.f);

    sf::Clock clock;
    sf::Time elapsedTime = sf::Time::Zero;

    while (this->window.isOpen())
    {
        sf::Time deltaTime = clock.restart();
        elapsedTime += deltaTime;

        while (elapsedTime > timePerFrame)
        {
            elapsedTime -= timePerFrame;

            this->states.getState()->processEvent();
            this->states.getState()->update(deltaTime);
            this->window.clear(sf::Color::Black);
        }

        this->states.getState()->draw();
        this->window.display();
    }
}

```

StateStack.hpp:

```
#pragma once
#include <memory>
#include <stack>
#include "GameState.hpp"

class StateStack
{
public:
    StateStack();

    std::unique_ptr<GameState>& getState();

    void pushState(std::unique_ptr<GameState> state);

    void popState();

    void clearStates();

    void changeState(std::unique_ptr<GameState> state);

private:
    std::stack<std::unique_ptr<GameState>> states;
};

```

StateStack.cpp:

```
    #include "StateStack.hpp"

    StateStack::StateStack() :
        states()
    {
    }

std::unique_ptr<GameState>& StateStack::getState()
{
    return this->states.top();
}

void StateStack::pushState(std::unique_ptr<GameState> state)
{
    this->states.push(std::move(state));
}

void StateStack::popState()
{
    this->states.pop();
}

void StateStack::clearStates()
{
    while (!this->states.empty())
    {
        this->states.pop();
    }
}

void StateStack::changeState(std::unique_ptr<GameState> state)
{
    this->popState();
    this->states.push(std::move(state));
}

```

GameSelectState.hpp:

```
#pragma once
#include <SFML/Graphics/Sprite.hpp>
#include <SFGUI/Window.hpp>
#include <SFGUI/Button.hpp>
#include "GameState.hpp"
#include "TextureManager.hpp"

class StateStack;

class GameSelectState : public GameState
{
public:
    GameSelectState(sf::RenderWindow& window, StateStack& states, TextureManager& textures);

    virtual void processEvent() override;
    virtual void update(sf::Time deltaTime) override;
    virtual void draw() override;

    void transitionToMenu();
    void transitionToPlay();

private:
    sf::Sprite background;
    sfg::Button::Ptr menuButton;
};

```

GameSelect.cpp:

```
 #include <memory>
    #include <SFML/Window/Event.hpp>
    #include "StateStack.hpp"
    #include "GameSelectState.hpp"
    #include "MenuState.hpp"
    #include "PlayState.hpp"

    GameSelectState::GameSelectState(sf::RenderWindow& window, StateStack& states, TextureManager& textures) :
        GameState(window, states, textures),
        menuButton(),
    {

        menuButton = sfg::Button::Create("  Menu  ");
        menuButton->GetSignal(sfg::Widget::OnLeftClick).Connect( [this] { transitionToMenu(); });

        hud.Add(menuButton);
    }

    void GameSelectState::processEvent()
    {
        sf::Event event;

        while (this->window.pollEvent(event))
        {
            this->hud.HandleEvent(event);

            switch (event.type)
            {
            case sf::Event::Closed:
                this->window.close();
                break;
            case sf::Event::Resized:
                this->selectionWindow->SetPosition(sf::Vector2f(window.getSize().x / 2.5f, window.getSize().y / 3.1f));
                break;
            }
        }
    }

    void GameSelectState::update(sf::Time deltaTime)
    {
        this->hud.Update(deltaTime.asMilliseconds());
    }

    void GameSelectState::draw()
    {
        this->window.clear(sf::Color::Black);
        this->window.draw(this->background);
        this->sfgui.Display(this->window);
    }

    void GameSelectState::transitionToMenu()
    {
        this->menuButton->Show(false);
        this->states.popState();
    }

    void GameSelectState::transitionToPlay()
    {
        this->menuButton->Show(false);
        this->selectionWindow->Show(false);
        this->states.pushState(std::make_unique<PlayState>(this->window, this->states, this->textures));
    }

```

The transitionToMenu() method in the GameSelectState class is supposed to be called when the button gets clicked, this method pops the top of the stack and it is supposed to return to the menu of the game. Currently when I click the button the application crashes. I am not sure if issue is occurring because of some error with the unique pointer manipulations or if the problem is related to the reloading of the previous game state in the game loop. This is my first time making a game and first time implementing a state machine, I would appreciate any pointers or help with the implementation of state transitioning in the game.

# Answer
Do you remember these cartoons where the goofy character saw the branch of the tree, but realized too late that he was on the wrong side of the cut?

That's what you seem to be doing here.

```
void GameSelectState::transitionToMenu()
{
    this->menuButton->Show(false);
    this->states.popState();
}

```

Here, `this->states.popState();` goes into you statesStack, deletes the 'current' state, and returns.

...returns to where?

The state, presumably the one that called the function, is the cause of it self deletion. When the code continues, it continues on a deleted object, where all hell can break lose.

Now it might not be the 'best' way to fix this, but you could set up the state transition but actually perform it in your `while (elapsedTime > timePerFrame)` loop, *outside* of your stack.
> 1 votes

---
Tags: c++, sfml, game-state
---


# Question
Title: Aligning a weapon model with a first-person camera
The tools I am using are: *gcc*, *opengl es 2* and *glm*.

I am trying to align a weapon model with the first-person camera. The main issue is that I can not seem to figure out how to "*anchor the weapon to the camera*" by utilizing the camera space and offsetting and rotating the object so it fits like in an FPS-game. Instead I use the member variables of the `Camera` class to align and rotate the weapon accordingly.

With the help of GDN, I created this camera class:

```
#pragma once

#include <GLES2/gl2.h>

#include "deps/glm/glm.hpp"
#include "deps/glm/gtc/matrix_transform.hpp"

#define DEFAULT_YAW -90.f
#define DEFAULT_PITCH 0.f
#define DEFAULT_SPEED 15.f
#define DEFAULT_SCROLL_SPEED 0.04f
#define DEFAULT_SENSE .24f
#define DEFAULT_FOV_Y 45.f
#define DEFAULT_RATIO 16.f/9.f
#define DEFAULT_NEAR .1f
#define DEFAULT_FAR 1024.f

#define MIN_FOV 44.3f
#define MAX_FOV DEFAULT_FOV_Y
#define MIN_PITCH -89.f
#define MAX_PITCH 89.f

class Camera
{
public:
    Camera(glm::vec3 pos = default_pos, glm::vec3 up = default_up) :
        m_Position(pos),
        m_WorldUp(up)
    {
        UpdateVectors(); // Otherwise glm::LookAt will complain.
    }
protected:
    glm::vec3 m_Position; // Set by ctor.
    glm::vec3 m_WorldUp; // Set by ctor.

    glm::vec3 m_Target; // Set by UpdateVectors().
    glm::vec3 m_Right; // Set by UpdateVectors().
    glm::vec3 m_Up; // Set by UpdateVectors().

    GLfloat m_Ratio = DEFAULT_RATIO;
    GLfloat m_FOV = DEFAULT_FOV_Y;
    GLfloat m_FOVmin = MIN_FOV;
    GLfloat m_FOVmax = MAX_FOV;

    GLfloat m_Yaw = DEFAULT_YAW;
    GLfloat m_Pitch = DEFAULT_PITCH;
    GLfloat m_PitchMin = MIN_PITCH;
    GLfloat m_PitchMax = MAX_PITCH;

    GLfloat m_MovementSpeed = DEFAULT_SPEED;
    GLfloat m_ScrollSpeed = DEFAULT_SCROLL_SPEED;
    GLfloat m_MouseSenseX = DEFAULT_SENSE;
    GLfloat m_MouseSenseY = DEFAULT_SENSE;
public:
    glm::mat4 View() const { return glm::lookAt(m_Position, m_Target + m_Position, m_Up); }
    glm::mat4 Projection() const { return glm::perspective(m_FOV, m_Ratio, DEFAULT_NEAR, DEFAULT_FAR); }

    glm::mat4 ViewProjection() const { return Projection() * View(); }

    glm::vec3 const& Position() const { return m_Position; }
    void Position(glm::vec3 pos) { m_Position = pos; }

    glm::vec3 Target() const { return m_Target; }
    void Target(GLfloat x, GLfloat y, GLfloat z) { m_Target = glm::vec3(x, y, z); }

    glm::vec3 Right() const { return m_Right; }
    glm::vec3 WorldUp() const { return m_WorldUp; }
    glm::vec3 Up() const { return m_Up; }

    GLfloat const& GetRatio() const { return m_Ratio; }
    GLfloat const& GetFOV() const { return m_FOV; }
    GLfloat const& GetYaw() const { return m_Yaw; }
    GLfloat const& GetPitch() const { return m_Pitch; }

    void SetYaw(GLfloat yaw) { m_Yaw = yaw; }
    void SetPitch(GLfloat pitch) { m_Pitch = pitch; }

    void MoveForward(GLfloat time_delta) { m_Position += m_Target*m_MovementSpeed*time_delta; }

    void MoveBack(GLfloat time_delta) { m_Position -= m_Target*m_MovementSpeed*time_delta; }

    void MoveLeft(GLfloat time_delta){ m_Position -= m_Right*m_MovementSpeed*time_delta; }

    void MoveRight(GLfloat time_delta) { m_Position += m_Right*m_MovementSpeed*time_delta; }

    void MoveUp(GLfloat time_delta) { m_Position += m_WorldUp*m_MovementSpeed*time_delta; }

    void MoveDown(GLfloat time_delta) { m_Position -= m_WorldUp*m_MovementSpeed*time_delta; }

    void Yaw(GLfloat offset) { m_Yaw += offset*m_MouseSenseX; }

    void Pitch(GLfloat offset)
    {
        m_Pitch += offset*m_MouseSenseY;

        if (m_Pitch > m_PitchMax)
        {
            m_Pitch = m_PitchMax;
        }
        else if (m_Pitch < m_PitchMin)
        {
            m_Pitch = m_PitchMin;
        }
    }

    void Zoom(GLfloat y)
    {
        if (m_FOV >= m_FOVmin && m_FOV <= m_FOVmax)
        {
            m_FOV -= y*m_ScrollSpeed;
        }
        if (m_FOV > m_FOVmax)
        {
            m_FOV = m_FOVmax;
        }
        if (m_FOV < m_FOVmin)
        {
            m_FOV = m_FOVmin;
        }
    }

    void UpdateVectors()
    {
        glm::vec3 front;
        front.x = glm::cos(glm::radians(m_Yaw)) * glm::cos(glm::radians(m_Pitch));
        front.y = glm::sin(glm::radians(m_Pitch));
        front.z = glm::sin(glm::radians(m_Yaw)) * glm::cos(glm::radians(m_Pitch));

        m_Target = glm::normalize(front);
        m_Right = glm::normalize(glm::cross(m_Target, m_WorldUp));
        m_Up = glm::normalize(glm::cross(m_Right, m_Target));
    }
};

```

All my models inherit from the `Transformable` class, which I use to create the model matrix with `Transform()`, take a look:

```
#pragma once

#include <GLES2/gl2.h>

#include "deps/glm/gtc/matrix_transform.hpp"

class Transformable
{
public:
    Transformable() {}

    Transformable(glm::vec3 const& pos, glm::vec3 const& size)
    {
        Translate(pos.x, pos.y + size.y/2.f, pos.z); // Place on the y-coordinate.
        Scale(size); // Set initial size.
    }
protected:
    glm::mat4 m_TransformTranslation;
    glm::mat4 m_TransformScaling;

    glm::mat4 m_TransformRotationX;
    glm::mat4 m_TransformRotationY;
    glm::mat4 m_TransformRotationZ;

    glm::vec3 m_Orientation;
public:
    void Position(glm::vec3 const& pos) { m_TransformTranslation = glm::translate(glm::mat4(1.f), pos); }

    glm::vec4 const& Position() const { return m_TransformTranslation[3]; }
    glm::mat4 Rotation() const { return m_TransformRotationX * m_TransformRotationY * m_TransformRotationZ; }

    GLfloat X() const { return Position().x; }
    GLfloat Y() const { return Position().y; }
    GLfloat Z() const { return Position().z; }

    GLfloat Width() const { return m_TransformScaling[0].x; }
    GLfloat Height() const { return m_TransformScaling[1].y; }
    GLfloat Length() const { return m_TransformScaling[2].z; }

    void OrientX(GLfloat deg) { m_Orientation.x = deg; m_TransformRotationX = glm::rotate(glm::mat4(1), m_Orientation.x, glm::vec3(1, 0, 0)); }
    void OrientY(GLfloat deg) { m_Orientation.y = -deg; m_TransformRotationY = glm::rotate(glm::mat4(1), m_Orientation.y, glm::vec3(0, 1, 0)); }
    void OrientZ(GLfloat deg) { m_Orientation.z = deg; m_TransformRotationZ = glm::rotate(glm::mat4(1), m_Orientation.z, glm::vec3(0, 0, 1)); }

    void Translate(glm::vec3 const& vec) { m_TransformTranslation = glm::translate(m_TransformTranslation, vec); }
    void Scale(glm::vec3 const& vec) { m_TransformScaling = glm::scale(glm::mat4(1), vec); }

    void Translate(GLfloat x, GLfloat y, GLfloat z) { Translate(glm::vec3(x, y, z)); }
    void Scale(GLfloat x, GLfloat y, GLfloat z) { Scale(glm::vec3(x, y, z)); }

    glm::mat4 Transform() const { return m_TransformTranslation * Rotation() * m_TransformScaling; }
};

```

I do all the offsetting, yawing and pitching in the player class, which holds the model for the weapon.

```
#pragma once

#include "camera.h"
#include "model.h"

class Player
{
public:
    Player(Model *weapon) :
        m_Camera(new Camera),
        m_Weapon(weapon)
    {}

    ~Player()
    {
        delete m_Camera;
    }
private:
    Camera *m_Camera;
    Model *m_Weapon;

    glm::vec3 m_Position;
    glm::vec3 m_Rotation;

    GLfloat m_MovementSpeed = 100.f;
    GLfloat m_MouseSenseX = 1;
    GLfloat m_MouseSenseY = 1;
public:
    Camera* PlayerCamera() const { return m_Camera; }
    Model* GetWeaponModel() const { return m_Weapon; }

    void Update()
    {
        m_Camera->Position(m_Position);
        m_Camera->Update();

        glm::vec3 weapon_offset_y = glm::vec3(0, 10, 0);

        m_Weapon->Position(m_Position + weapon_offset_y);
        m_Weapon->OrientY(m_Camera->GetYaw() + 30);
        m_Weapon->OrientZ(m_Camera->GetPitch() + 30);
        m_Weapon->OrientX(20);
    }

    void Position(glm::vec3 pos) { m_Position = pos; Update(); }
    void SetYaw(GLfloat deg) { m_Camera->SetYaw(deg); Update(); }

    void MoveForward(GLfloat delta) { m_Position += m_Camera->Target() * m_MovementSpeed * delta; Update(); }
    void MoveBack(GLfloat delta) { m_Position -= m_Camera->Target() * m_MovementSpeed * delta; Update(); }
    void MoveLeft(GLfloat delta) { m_Position -= m_Camera->Right() * m_MovementSpeed * delta; Update(); }
    void MoveRight(GLfloat delta) { m_Position += m_Camera->Right() * m_MovementSpeed * delta; Update(); }

    void Yaw(GLfloat delta) { m_Camera->Yaw(m_MouseSenseX * delta); Update(); }
    void Pitch(GLfloat delta) { m_Camera->Pitch(m_MouseSenseX * delta); Update(); }
};

```

As you can see, I am also struggling with the model matrix, which is currently an *RTS-matrix* and the camera provides a `projection*view` matrix with ViewProjection(). I multiply both and pass it as a uniform to a shader.

Although It seems that I am doing the offsets and rotations wrong, because when I move the camera, the weapon model moves around *(up and down)*, instead of being glued to the view.

Any suggestions are much appreciated!

# Answer
> 2 votes
One old trick for FPS games is that the player's weapon is rendered separately. What that means in practice is that you render your scene in (at least) two parts: first the world, then the player weapon. The player weapon is matched exactly to the *camera* so that it always appears in the same position.

What about the weapons you see other players holding? It's a fake! If you think about it, to get the same look, the players would have to be holding their gun right under their eyes, about where their noses are.

It's a similar technique to skyboxes, which are also fixed (position, not rotation) to the camera but are rendered behind everything else, and makes them appear infinitely distant. This also means they don't have to be really large at all; I usually use something like a 1x1x1 cube.

I think changing your code to move the weapon to the camera's position will be enough to fix it. Just make sure that you don't completely divorce the weapon rendering to the world - you still want the lighting to make sense.

---
Tags: opengl, camera, opengl-es, opengl-es2, glm
---


title: Rigidbody2D loses speed on collisions

text:
# Question
Title: Rigidbody2D loses speed on collisions
I'm trying to create a simple Breakout-style game. In my game, the ball strikes a paddle that moves with the player's mouse. Depending on the position of the strike, the ball changes its direction. This allows the player to aim the ball.

The problem I'm having is that each time I set the position, the ball loses velocity. I've tweaked every Physics2D setting I could find, but I'm not seeing any changes. Here's what my `Ball` class looks like:

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

public class Ball : MonoBehaviour {

  public float initialVelocity;
  public float collisionAngleRange;
  public Paddle paddle;

  private Rigidbody2D body;

  public void Start() {
    body = GetComponent<Rigidbody2D>();
    body.velocity = VectorUtilities.AngleToVector2(135) * initialVelocity;
  }

  // When colliding with the paddle, use the position of the strike to adjust the ball's position.
  public void OnCollisionEnter2D(Collision2D collision) {

    // Ignore the object if it's not the paddle.
    if (!collision.gameObject.CompareTag("Paddle")) { return; }

    // Get the collision coordinates
    Bounds bounds = collision.gameObject.GetComponent<BoxCollider2D>().bounds;
    float left = bounds.min.x;
    float right = bounds.max.x;

    Vector2 contact = collision.contacts[0].point;

    // Interpolate the contact point and determine the angle.
    float interpolation = (contact.x - left) / (right - left);
    float angle = 90 - collisionAngleRange / 2 + collisionAngleRange * (1 - interpolation);

    // Change the direction of the ball without affecting its speed.
    body.velocity = VectorUtilities.AngleToVector2(angle) * body.velocity.magnitude;

    // Log what's happening with the velocity
    Debug.Log(body.velocity.magnitude);
  }
}

```

The `VectorUtilities` class looks like this:

```
using UnityEngine;

// A set of utility methods and extensions for Vector2 and Vector3.
public static class VectorUtilities {

  public static Vector2 AngleToVector2(float degrees) {
    return new Vector2(Mathf.Cos(degrees * Mathf.Deg2Rad), Mathf.Sin(degrees * Mathf.Deg2Rad));
  }
}

```

Here are my `Ball` game object's `Rigidbody2D` and `CircleCollider2D` settings:

The paddle's settings:

The material settings:

Physics2D settings:

I recognize I could solve this problem by multiplying the ball's normal vector by my desired speed, but it's more important to me to understand *why* this is happening and to fix the underlying problem. Why does the ball lose speed on every collision, and how can I prevent that from happening?

# Answer
I *finally* figured out what was going on here. Because the mass of the `Ball` and the mass of the `Paddle` are the same, the `Ball` was transferring some of its force into the `Paddle` when it collided with it. However, since the `Paddle` had its y position and its rotation frozen, I couldn't actually see the effect of the `Ball` striking it. Turning off those properties allowed me to see the problem.

The solution was to set the body type of the `Paddle` to `Kinematic`, which allows it to register collisions without being affected by them.
> 3 votes

---
Tags: unity
---


# Question
Title: Collision Detection and Bounding Box Creation
I am trying to create bounding boxes. My goal is not to create them with giving x,y and z coordinates. But rather, I will be loading a model or else rendering a shape - say an aeroplane. The algorithm then should be able to create efficient bounding boxes around it. I am coding in opengl.

Can you help me out with the same?

# Answer
I don't think writing such algorithm would be easy if you want it to be completely general and applicable to any whatsoever model.

The best way would be to create by hand your bounding boxes in the same 3D software that you use for creating your airplane. This way, you are able to create boxes which match accurately the model according to your needs. It's also very simple, you just need to draw rectangles.

Then, save those bounding boxes separately and load them into your game as you would with the model itself. Retrieve two opposing vertices of each box and there you have your bounding boxes.
> 1 votes

---
Tags: c#, opengl, collision-detection, bounding-boxes
---


title: Binary Serialization and Protocol

text:
# Question
Title: Binary Serialization and Protocol
i found this page Protocols. I'm currently working on a game similar to agario and i find that page is helpful for my game.

They using WebSocket for sending game messages which is mine too. But i'm use text message (JSON) instead of binary message and i'm planning to switch to binary message for minimizing bandwidth reason because JSON are verbose even it's easy to serialize/deserialize.

On the section server-\>client protocol and client-\>server protocol, they used term of opcode. I don't about what opcode is and what the purpose of those number, but i know in WebSocket protocol RFC 6455, they used term of opcode too like 1 for text message and 2 for binary message.

My Question is:

1. How to serialize/deserialize game messages in binary message?
2. What is those number in opcode used for? for now, my assumption is those number are used for serialization in binary message, maybe not i don't know
3. If my assumption in Q2 is right, how to implement those number to my protocol? maybe some code demonstration? it will be great if the code in javascript and golang because i'm use go for server and javascript for client.

Thanks

# Answer
> 1 votes
For Go/JavaScript may be a good solution to use MessagePack. And you can use it on client side with any platform.

You will save traffic, and you can use JavaScrtipt implementation as well.

Note: for Javascript, node.js, and browser, I suggest to use JSON. Because it simply faster for JSV8 (actually not really, see update), in case if your messages relatively small.

**UPD:** I was wrong. Serializing/Parsing large objects turns into serious performance issues for the browser and NodeJS server.

Also, origin object can be large and contains data I don't want to send with JSON. So in JSON-case, I need to clone an object, or create a new one, then serialize it.

So I decided to describe the serialize/parse functions for each type of messages and operating with a pre-defined structure for each message type.

Here is an example of my message processing (JS):

```
...
sight_ui: {
  pack: function (thing) {
    const slots = [];
    for (let slot in thing.inv)
        slots.push(slot);
    return [
        thing._id,
        thing.name,
        slots.join(SEP2)
    ].join(SEP1);
  },
  unpack: function (str) {
    let s = str.split(SEP1);
    return {
        _id: s[0],
        name: s[1],
        slots: s[2] ? s[2].split(SEP2) : [],
    }
  }
},
...

```

In this case, I detect serialization function by the first part of the message. It can be 1 character or a string separated from the message body by a specific symbol. Each function can be micro-optimized and easy to test. I'm using `wse` WebSocket wrapper, it allows to describe protocol separately. But it's poorly documented yet.

---
Tags: websocket, serialization, binary, protocol
---


title: Train-like movement in a 2D game

text:
# Question
Title: Train-like movement in a 2D game
I am developing a 2D game using Cocos2d-X in C++ language. In my game, I need to implement train movement.

Here is the image about the output I want to achieve:

I tried to do the above moment using Actions from Cocos2d-X. However on the curved part of the tracks, the train movement is not accurate.

I have following questions:

1. Is there a *right* method to create the train movement using Actions? If not, which alternate methods or algorithm can be used?
2. I wanted to achieve train movement similar to the game Mini Metro. How to create such train movement in Cocos2D-X?

I would appreciate any suggestions/thoughts on this topic.

# Answer
I'm not used to Cocos2D engine, but I can suggest this solution for you to apply to your game.

**Naive implementation**
The simplest way to implement a train wagon can be making an object which follows a given path, whose angle rotates according to the path direction. Given a path (as an open line or closed polygon) consisting of a finite number of points, the direction along the path can be computed with the inverse tangent (or any equivalent function) of the two vertices representing the current line segment the train is moving onto.

This leads to an issue: when turning, the wagons will be always centered to the railway track, because we are rotating every wagon object considering its sprite origin only, and we'll see wagons edges too unnaturally distant from one another. Also, if the path quality (aka the number of segments making up our line or polygon) is low, wagons sprite will abruptly change its rotation angle when moving from line segment to line segment.

**Improved implementation**
Real train wagons are usually bonded to the railway track by two or more couples of wheels; the rotation of every wagon when turning depends on the position of its wheels.

Instead of working with one point only, which represents the center of mass (or origin) of our wagons, we can consider two points per wagon, each one representing the midpoint of every couple of wheels. Such midpoints are here coloured blue:

This way, we force these midpoints to travel onto the railway track, making sure *their relative distance never changes*, and midpoints belonging to different wagons *always keep the same relative distance* as well.

The final touch is drawing the wagon sprites with origin in the midpoint between the two previous wheels midpoints, and its rotation angle will be the inverse tangent of the two wheels midpoints as well. The direction will be correct since the midpoints are forced to the path.

Hope that helps you solving your issue, or developing a more appropriate solution on your own.
> 11 votes

---
Tags: 2d, algorithm, ios, cocos2d-x
---


# Question
Title: SDL2 MOUSEBUTTONUP triggers more than once
I've been trying to figure this out all day. I'm trying to make a simple check box. But my MOUSEBUTTONUP event keeps firing until I trigger another event like moving the mouse or clicking again.

```
//If a mouse button was released
if (Sdl_Setup->GetMainEvent()->type == SDL_MOUSEBUTTONUP)
{
    //If the left mouse button was pressed
    if (Sdl_Setup->GetMainEvent()->button.button == SDL_BUTTON_LEFT)
    {
        //Get the mouse offsets
        SDL_GetMouseState(&mouseX, &mouseY);

        //If the mouse is over the button
        if ((mouseX > Button->GetX()) && (mouseX < Button->GetX() + Button->GetWidth()) && (mouseY > Button->GetY()) && (mouseY < Button->GetY() + Button->GetHeight()))
        {
                //Set the button sprite
                state = selected;
                Button->SetCrop(GetFrameX(), GetFrameY(), state);
                clicked = true;
                std::cout << clicked << std::endl;
        }
    }
}

```

This will just spam 1 in the console (if you keep the mouse still) when all I want is for it to trigger once. From what I've read MOUSEBUTTONUP is only supposed to be sent to the event queue once

I've tried adding a bool to stop it after it's clicked by putting it in an if statement and that works but the thing is I want to be able to toggle the box on and off so when I add an else statement that changes the bool back to false it spams 101010 instead of just one.

```
   //If a mouse button was released
if (Sdl_Setup->GetMainEvent()->type == SDL_MOUSEBUTTONUP)
{
    //If the left mouse button was pressed
    if (Sdl_Setup->GetMainEvent()->button.button == SDL_BUTTON_LEFT)
    {
        //Get the mouse offsets
        SDL_GetMouseState(&mouseX, &mouseY);

        //If the mouse is over the button
        if ((mouseX > Button->GetX()) && (mouseX < Button->GetX() + Button->GetWidth()) && (mouseY > Button->GetY()) && (mouseY < Button->GetY() + Button->GetHeight()))
        {
            if (clicked == false)
            {
                //Set the button sprite
                state = selected;
                Button->SetCrop(GetFrameX(), GetFrameY(), state);
                clicked = true;
                std::cout << clicked << std::endl;
            }
            else
            {
                //Set the button sprite
                state = noInteraction;
                Button->SetCrop(GetFrameX(), GetFrameY(), state);
                clicked = false;
                std::cout << clicked << std::endl;
            }
        }
    }
}

```

# Answer
> 1 votes
I suggest adapting your program to use a "mousedown" variable. Here's an example you can use as a reference:

```
bool mousedown=0;  // Declared outside the scope of functions that use it.
while(running) { // Main loop.
    SDL_Event event;
    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_MOUSEBUTTONDOWN:
                mousedown=1;
                break;
            case SDL_MOUSEBUTTONUP:
                if(mousedown) {
                    /* The SDL_MOUSEBUTTONUP event will be ignored if a
                       previous SDL_MOUSEBUTTONDOWN event has not occurred. */
                }
                mousedown=0;
                break;
        }
    }
}

```

# Answer
> 1 votes
In `Sdl_Setup` is where I make the window I'm using and stuff like that and the variable `mainEvent` is `= new SDL_Event();` so then when I was calling `GetMainEvent()` it was just sending that to `PollEvent()` over and over again. So all I did is create a quick `void` function in `Sdl_Setup` to set `mainEvent` to a blank `SDL_Event()` and then call that after `clicked = true;` and it works.

---
Tags: input, sdl2, events
---


title: "Here's money, make my game"

text:
# Question
Title: "Here's money, make my game"
Okay I know it is not as easy as the title implies but I was wondering: I have an idea of a game I want to play. I recognize it would take a pretty huge development but for the full version I would be willing to pay up to €800, which I know does not cover the development costs in the slightest.

What are my options?

ps: I am not sure if this is the right stackexchange site but I couldn't find a better fit.

# Answer
> 0 votes
With 800 euros, unless you want a crappy freelanced game, you have a couple of options:

The best surefire way of doing it is to do it yourself, as Kerrigan Fairbairn said in his answer, because those 800 euros won't get you much more than a laptop, Unity, and freelanced artwork. The game could be a hobby of yours that you spend multiple years developing, heck, open source it and random people might help develop it! It be an amazing learning and developing experience that you'd be sure to enjoy after you lasso the basics.

If you truly believe that this is a great game idea and you do not have the time or expertise to spend 6 years working on it, your best bet will be Kickstarter. Use the 800 euros to get some fancy drawings and animations, then have a couple freelancers make you a great Kickstarter video. Using the remaining cash, rent out a studio for a night for the video to demonstrate the low risk. If you're successful, you have just converted those 800 euros into 350,000 USD. Now partner with a moderately sized game company depending on the scale of the game and, make a game!

Or, you could just wait till the AI uprising occurs and by a robot to make your game. :)

# Answer
> -1 votes
Your options are to pick up an accessible development kit like UE4 or Unity and learn how to use them to make the game yourself, then you can use the €800 to pay for freelance artwork or cheap licensing costs. Nobody is going to make a game of the scale you implied in your response for as little as €800.

Alternatively you can wait for a game that's similar to your idea to crop up on the open market coincidentally.

# Answer
> -3 votes
Have you attempted using freelancers? They would most definitely be willing to work for cheap to make a game! Try using a website like freelance.com or upwork for higher end freelancers! Good luck and hire the right one!

---
Tags: game-industry
---


title: Crouching Up and Down XNA C# Controller

text:
# Question
Title: Crouching Up and Down XNA C# Controller
The game is a 2D platformer.

The problem I have is when I press the B button to crouch from standing, I do not know how to implement a function where B can be pressed again to move back to the standing sprite.

the issue is if i use the code presented below it will check every frame for B == Pressed, basically appearing as if the player never crouched at all. Could somebody help please?

```
if (facingRightSide == true)
        {
            if (currPad.Buttons.B == ButtonState.Pressed)
            {
                m_currState = AnimState.CrouchRight;
                isCrouchedRight = true;
            }
        }

if (isCrouchedRight == true)
        {
            if (currPad.Buttons.B == ButtonState.Pressed)
            {
                m_currState = AnimState.FacingRight;
                isCrouchedRight = false;
            }
        }

```

Thank you for your time.

# Answer
> 1 votes
Try implementing a property to keep track of your previous pressed state.

So then you can do something like this instead:

```
ButtonState PreviousButtonState;

// Only action button press once
if (PreviousButtonState.Buttons.B != ButtonState.Pressed && currPad.Buttons.B == ButtonState.Pressed)
{
    if (m_currState == AnimState.FacingRight) {
        m_currState = AnimState.CrouchRight;
    } else if (m_currState == AnimState.CrouchRight) {
        m_currState = AnimState.FacingRight;
    }
}

//Store the previous button state for next iteration
PreviousButtonState = currPad;

```

---
Tags: c#, xna-4.0, input, platformer, controllers
---


# Question
Title: Unity movie texture behaviour when hidden
I have a UI with a button and a panel. Clicking the button toggles the panel on and off :

```
GameObject.SetActive();

```

Now the panel element has a child which is a plane. This plane has the following components :

* mesh renderer
* videoPlay, a script I've written
* an audio source

The videoPlay script basically applies the MovieTexture to the plane's material, sets the plane's audioSource to the movie's audio clip, and starts audio and video.

```
public MovieTexture movie;

void Start() {
    GetComponent<Renderer>().material.mainTexture = movie as MovieTexture;
    GetComponent<AudioSource>().clip = movie.audioClip;
    movie.Play();
    GetComponent<AudioSource>().Play();
}

```

Now when at runtime I click the button (which hides the panel which is the plane's parent element), the audio and video stop as the plane disappears - which is expected behaviour.

When I reopen the panel though, the sound restarts right away but as if it were catching up for the time it was hidden (so it starts really fast and then comes back to regular speed) ; and the video is just frozen for - empirically and approximately - the same time the panel was hidden.

I've tried in the script - in Update() - messing with

```
if (!transform.parent.gameObject.activeSelf && movie.isPlaying)
    {
        movie.Pause();
        GetComponent<AudioSource>().Pause();
    }

```

for example, (and the same with Play() when it shows back up) but it doesn't seem to change anything.

# Answer
> 1 votes
As @jgallant stated, it was a matter of pausing the A/V before deactivating the panel.

I rearranged the scripts and works fine, still with a small delay though.

---
Tags: unity
---


# Question
Title: My money will only save for one game run
I am trying to make a money system my problem is that the money value only saves for 1 game run then the value returns to 0. Here is my code. What should I do.

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

public class Money : variables {

    public Text cash;

    // Use this for initialization
    void Start () {

        if (counter < 9 && counter > 1)
        {
            money = money + 2;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 10 && counter < 20)
        {
            money = money + 5;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }

        else if (counter > 21 && counter < 30)
        {
            money = money + 15;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 31 && counter < 40)
        {
            money = money + 25;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 41 && counter < 70)
        {
            money = money + 50;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 71 && counter < 100)
        {
            money = money + 75;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 101 && counter < 200)
        {
            money = money + 100;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);
        }
        else if (counter > 201)
        {
            money = money + 150;
            PlayerPrefs.GetInt("money", money);
            PlayerPrefs.SetInt("money", money);

        }

        cash.text = "Credits: " + PlayerPrefs.GetInt("money", money);
    }
}

```

# Answer
> 2 votes
In the example code, your setting a value to your `PlayerPrefs` file under `"money"` *immediately* before you retrieve it. In turn, it *does* save, but your code overrides the value *before* you retrieve it.

```
PlayerPrefs.SetInt("money", money);
cash.text = "Credits: " + PlayerPrefs.GetInt("money", money);

```

No matter what, your not going to notice any form of persistent data, in this way. You set a value just before you retrieve it, and thus, the value you retrieve will always be the value you start from. If you have not set a value to `money`, it will default as 0. In turn, your setting the `"money"` value of your `PlayerPrefs` as 0 immediately before you attempt to retrieve it.

---

While *a lot* of your context is *still* very unclear, you can break your logic into some basic methods. From there, it is only basic organisational logic to ensure you do not call the method to set your value while it is still a default value.

```
/// <summary>The string used to tag money in the PlayerPrefs.</summary>
/// <remarks>Hard coding a string once ensures we do not make mistakes, later.</summary>
string moneyTag = "money";
/// <summary>The current value for money</summary>
int money;

void Start()
{
    money = GetMoney();
}

/// <summary>Retrieves the value of money from the PlayerPrefs</summary>
int GetMoney()
{
    // Passing money in as the second value ensures it will be retained,
    // should there be no PlayerPrefs value. Otherwise, the default will
    // always be 0, voiding inspector-side values.
    return PlayerPrefs.GetInt(moneyTag, money);
}

/// <summary>Saves the value of money to the PlayerPrefs</summary>
void SetMoney()
{
    PlayerPrefs.SetInt(moneyTag, money);
    PlayerPrefs.Save();
}

/// <summary>Increments money by a value according to tapCount, and saves it.</summary>
/// <params name="tapCount">The amount of taps, used to increment money.</params>
void ProcessTapCount(int tapCount)
{
    if (tapCount < 9 && tapCount> 1)
    {
        money = money + 2;
        SetMoney();
    }
    else if (tapCount> 10 && tapCount< 20)
    {
        money = money + 5;
        SetMoney();
    }
}

```

---

When you want to save the value, you *do not* retrieve it. When you want to retrieve the value, you *do not* save it. When you call a `Start` method, for example, you may want to retrieve the value from the `PlayerPrefs` file. You would *not* want to *set* the value, because we will not have a value for `money` at the start, unless we actually *retrieve* it from the `PlayerPrefs` file.

# Answer
> 0 votes
At game launch, your money variable will always be 0. you should save the pref with the new value at the game end, and retrieve it in the game init part.

```
int money; // it's surely initialized somewhere

// your Manager in it's Start()

if(!PlayerPrefs.HasKey("Money")){
    PlayerPrefs.SetInt("Money", 0); // save the pref for the first time
} else {
    money = PlayerPrefs.GetInt("Money"); // grab the value that is set in the prefs
}

// After the game loop ends, where you show the win/lose condition. you should update the prefs to store the new value
PlayerPrefs.SetInt("Money", money);

```

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


title: Make objects flip Box2D?

text:
# Question
Title: Make objects flip Box2D?
I'm working on a shooter, platformer and everything is going okay so far, but I want to make some enemies that fly over top of the player and swoop around him. How can I make them fly? I've seen people suggest to change the world Gravity but that'd mess up the player. What's the best solution?

# Answer
> 1 votes
Just use the right combination of forces through applyForceToCenter()

# Answer
> 0 votes
You can change the gravity for a singe body using

```
body.setGravityScale(0);

```

You could then move the bodies with ApplyForce or directly change their position.

---
Tags: libgdx, physics, box2d
---


# Question
Title: Using Volumes to reveal secret doors in UE4 C++ project
I'm working on a maze project and I would like to have secret doors. My basic idea is to have the walls be destroyed when the player is both within the bounds of a trigger volume, and presses a button. I know the basic way to implement the code, but my main concern is how to handle the volumes. Should I create a class, maybe called "SecretController" that holds the code that says:

"if player is in box\[i\] and presses fire, destroy door\[i\]"

This seems like it would work, but I'd rather know before I go create a ton of stuff I'll just have to delete later. Thanks for the help folks!

# Answer
> 1 votes
Your plan is sound. As to script complexity, this would be a tiny amount of blueprint nodes: one bool for volume, one bool for button, and boolean AND node, a branch node, a Destroy node. That should get you running.

I mention Blueprint because, although you have a C++ proejct, Blueprint has a much faster iteration time and was designed specifically for prototyping gameplay. When it works how you want, *then* transfer it to code.

---
Tags: c++, unreal-4
---


title: Base64 Decoding In Unity

text:
# Question
Title: Base64 Decoding In Unity
I am trying to decode a map file for Unity which I believe was compressed using Base64 encoding.

The actual data looks like this:

> H4sIAHah5VgA/z2PvQ7CMAyEXyXyjASsXStGeAHEkBRTivJTOQlKW/XdSYKc7dOd7+Tb4CrnmzQIHQzRB2eExi9qOAiQMbwdZeOFdiyCUx/o7mKD6ZnVc5EIfca+JnPTRaNBG459VFjslM1TgYVhZfCJO/zSaG29LUktSi1LfDYyKAbJEDCFSGVXbR5omkP51UZd19n/6PrpLh77D92WFGkKAQAAAA=

And I am expecting an output that looks like:

> custom,cuboid,default,1,1,1,0,1,1,1,1.0,1.0,0,0,0,0,0,0,0;

While Base64 decoding should be an easy feat, this particular case is giving me trouble. I've tried decoding it into several different formats, but all my attempts resulted in garbled messes. I am fairly certain that the file is in a Base64 format, but it shouldn't be this difficult to decode.

Does anyone have an idea of how the file was encoded and how I might go about decoding it?

# Answer
> 2 votes
Converting your base64 string to hex shows it starts with `1F 8B` which is the magic number for GZIP compressed data. This code works as expected:

```
byte[] data = Convert.FromBase64String("H4sIAHah5VgA/z2PvQ7CMAyEXyXyjASsXStGeAHEkBRTivJTOQlKW/XdSYKc7dOd7+Tb4CrnmzQIHQzRB2eExi9qOAiQMbwdZeOFdiyCUx/o7mKD6ZnVc5EIfca+JnPTRaNBG459VFjslM1TgYVhZfCJO/zSaG29LUktSi1LfDYyKAbJEDCFSGVXbR5omkP51UZd19n/6PrpLh77D92WFGkKAQAAAA==");
using (var compressedStream = new MemoryStream(data))
using (var gZipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
    gZipStream.CopyTo(resultStream);
    string map = Encoding.UTF8.GetString(resultStream.ToArray());
}

```

---
Tags: unity
---


# Question
Title: How do I get an object from a .osg file in OpenSceneGraph?
I decided instead of using a really heavyweight engine like unreal that I am going to use SDL and Openscenegraph.

I would expect it to be something like:

```
osgObject* box = file->GetObject("Box");

```

# Answer
> 2 votes
To read a file, you need to use functions from osgDB::ReadFile.

```
osg::ref_ptr<Node> myNode = osgDB::readNodeFile(myFileName);

```

You can use that right away if the 'object' you want to use is at the root of your .osg database.

If you know that the node at the top is a group, and that group contains the 'object' you want, you do something like this:

```
osg::ref_ptr<Group> myGroup = osgDB::readNodeFile(myFileName).asGroup();
osg::ref_ptr<osg::Node> myNode;

for ( int i = 0; i < myGroup->getNumChildren(); ++i )
{
  if ( myGroup->getChild( i )->getName() == "box" )
    myNode = myGroup->getChild( i );
}

if ( !myNode )
{
  std::cout << "Error: object not found()\n";
  return;
}

```

And you could be fancy and write a visitor that does it:

```
class SearchNode : public osg::NodeVisitor
{
public:
  SearchNode( const std::string& name ) :
    osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
    mName(name),
    mNode(nullptr) {}

  osg::Node* getNode() { return mNode; }

  void apply( osg::Node& node ) {
    if ( node.getName() == mName)
      mNode = &node;
    else
      traverse( node );
  }

private:
  std::string mName;
  osg::Node* mNode;
};

```

---
Tags: openscenegraph
---


# Question
Title: Have body resume constant velocity after collision
I want to have a body move at a constant velocity, but react to collisions.

My example game is a train, I want it to move at 1 meter a second. If an obstacle appears on the tracks, I want it to react by smashing through it (which will normally slow it down). But when the obstacle is cleared, I want the train to accelerate back to 1 m/s and continue on.

It seems like the applyLinearImpulse() and applyLinearForce() methods are the place to start, but those are one-shot methods.

Thanks

# Answer
> 0 votes
If you apply a linear impulse to your train body every frame your train will speed up. You can then check if the velocity of the train exceeds the maximum velocity and scale down the speed.

```
body.getLinearVelocity();
body.applyLinearImpulse((body.getLinearVelocity()), body.getPosition(), true);

// limit max speed
Vector2 vel = body.getLinearVelocity();
float speed = vel.len();
if ( speed > MAX_SPEED ) {
    body.setLinearVelocity( vel.scl(MAX_SPEED / speed));
}

```

---
Tags: physics, box2d, jbox2d
---


# Question
Title: LibGdx table with label children at fixed positions
I'm trying to make a table containing three labels in each row.

Something like this:

Label1 Label2 Label3

Text1 Text2 LongerText

LongTextLoremIpsum LongTextLoremIpsum LongTextLoremIpsum

Is there a way to fix the position of the labels so that they will be at the same position horizontally regardless of the length of the text in the label?

So far I'm using a table as the root container, and then HorizontalGroup for each row.

# Answer
> 1 votes
Have you tried using a table?

```
Table table = new Table();
// add items to first row
table.add(label1);
table.add(label2);
table.add(label3);
table.row(); // start next row
table.add(text1);
table.add(text2);
table.add(longerText);
table.row(); // last row
table.add(reallyLongText).colspan(3); //span last row over 3 columns

```

---
Tags: libgdx, scene2d
---


# Question
Title: All scripts in Unity game can not be loaded
I can not provide a "why" here, because as far as I can tell it happened spontaneously - after saving an edit to one of my scripts, it just started happening. But here's the problem:

Every single one of my scripts, while still in the same Scripts file, can no longer be found and loaded. All the Script Components (take the Game Manager component for example) now look like this:

or like this:

Attempting to locate the scripts by going Add Component \> Scripts \> \[Desired Script\] doesn't work, because there isn't even a Scripts item in the Add Component menu. I have already looked this up, and none of the answers I found were applicable:

* Yes, every script's file name is the same as the Class name within them
* I have tried reimporting all assets (Assets \> Reimport All), no success.
* Taking all scripts out of the project, restarting unity and then reimporting the scripts. Nothing
* Removing all script components, then reapplying them. It didn't work because, as I said, there was no Script item in the Components menu.

This is a pretty game-breaking, literally, because this is a hobby game (I'm not doing this as a job, it's just in spare time). If I can't restore the game as it was, I won't be able to bring myself to restart it. So any help is greatly appreciated.

# Answer
## **What to do:**

Essentially, the answer is to make sure all script files have line endings consistent with your development system. If you don't know how to do that, this is what I did (albeit accidentally, at first):

1. On Monodevelop, save each open file, close each one, then finally close Monodevelop itself.
2. In Unity, there should be a `parsing error message`. Double click the error message to reopen Monodevelop and open the problem file. Now, at the bottom of the page, a message should pop up:

3. Hit OK. Nothing will visibly change on the page.
4. Go back to Unity, the parsing error message should clear. However, some Script Components will have lost their Script references. These will show up in warning messages when you attempt to play (most likely alongside actual errors stemming from the lost scripts. Just go to each of the listed GameObjects and reattach the appropriate script. It should now be back to normal, with no painful side effects

* Note: If multiple files have messed up line endings, you will have to repeat this process for all the corrupted scripts. This problem can also occur to Shaders, which are slightly harder to detect.
    * Note 2: Remember to check the script references on your prefabs, or anything that isn't in the scene right when you hit play. For example, laser bolts, bullets and arrows

## Why It Happens:

This, I'm less sure of. If I can find out why, I'll edit this to include why. If anyone knows why or has a suggestion, comment it. I didn't do anything abnormal when it happened to me.
> 1 votes

---
Tags: unity, scripting, bug
---


# Question
Title: How should I store dynamic game entities for efficient area-based selection?
In my 2d block-based game I'm trying to implement a data structure that would store entities entities in a way that's capable of:

* Direct selection based on coordinate.
* Iteration
* Iteration limited to an area

I thought of these solutions:

For 1,3 I thought that a 2 dimensional array of entities' coordinates would be suitable but I already have a 2 dimensional array of blocks' coordinates and don't want to have another one too. And this solution is not suitable with 2, there will be too many gaps when iterating the array and this is a performance loss.

The next solution I thought was simply using an array and adding new entitys simply by arr\[length\], this is performance wise for 2 but it is hard to perform 1 and 3 (use a for loop everytime to check if I'm colliding with an entity (duh)).

The last solution is simply adding entity data to my (already exists) blockList 2 dimensional array, this one has nearly the same pros and cons with first solution.

And there is always the alternative of using first and second solutions together by making them refer to the same object.

---

Which one of these solutions should I use, cause all of them have their pros and cons and I have to something uses less space, cause the game map is not fixed.

# Answer
> 1 votes
Another option may be using a quadtree structure or if you have many moving objects a spatial hashing aproach.

# Answer
> 0 votes
In the game I'm making I store the entities (actually their components) in an array (structure of arrays) and then I create a spatial grid containing, in each cell, the array index of the entities that belong to that area; and yes, you have to rebuild it every frame for dynamic objects, but the tutorials I've seen (that I remember) do this, especially for quad/octrees. That's fast for simple iteration and for area selection and in the case of rebuilding the grid is just one 'array.push\_back' per entity each frame.

You may consider ordering the entities in the array based on their position, to avoid cache misses when selecting them by area (if you have all the data grouped together you avoid jumping here and there on the RAM). But you don't need to do that each frame, maybe keep a index of the 'chaos of the system', based on how much the entities move, how many die and so on, and perform the sorting when it's too high (try and profile if that is needed)

Creating different arrays for different areas I think is not a good idea, both in terms of maintaining your code and performance, due to the continue swapping of entities betweens one area and the other (and so a lot of moving data). Maybe, I've never tried this approach, you can go this way if you have large different areas which don't communicate too much, but i don't think it's your case.

# Answer
> 0 votes
I have used 2 simple dirty tricks.

1 - Level divided by "chunks". Let's say 10x10 (CHUNK\_SIZE = 10) abstract units. So your level near 10x10 chunks. Let's say chunks array - it's a sort of low-detailed map when few enities can be in one cell. Every time when entity move (or every 10 game ticks), I recalculate new chunk chunk position ( like enity.chunk\_x = enity.x / CHUNK\_SIZE ). After, if chunk-position for entity has been changed (we moved to another chunk), I remove link from previous chunk, and put link on entity.

Now, let's say, your characted can see for 2 chunks around. Much more faster to look at near chunks, than go through hude array of entities.

2 - observation list: each playable character who can observe entities around, may keep and manage observation list. (using 1st dirty trick).

For javascript this techique is more that enough.

---
Tags: 2d, javascript, performance, data-structure, picking
---


# Question
Title: Calculate evenly distributed points along a curve
I'm using this equation to calculate a series of points along a quadratic curve:

```
// Returns a point on a quadratic bezier curve with Robert Penner's optimization of the standard equation
result.x = sx + t * (2 * (1 - t) * (cx - sx) + t * (ex - sx));
result.y = sy + t * (2 * (1 - t) * (cy - sy) + t * (ey - sy));

```

Sadly the points are unevenly distributed, as you can see in the dashed-line rendering below. The points are denser in the middle of the curve, and are further spaced apart near the edges. How can I calculate a evenly distributed set of points along a quadratic bezier curve?

Please note that I'm using this for rendering a dashed line, so a slow solution in MATLAB or something will not do. I need a fast solution that will fit inside a renderer. This is not for research or a one-off calculation!

**Edit:** I'm not asking how to accomplish the above. The above is MY RENDERING! I already know how to estimate the length of a bezier, calculate the number of points, etc, etc. What I need is a **better bezier point interpolation algorithm** since the one I have calculates points unevenly distributed along the curve!

**Edit:** Code in any language will do! My game runs in JS but I can port anything.

# Answer
I don't think there's a closed form for a point a certain fraction of the distance along a quadratic curve.

A solution that's often good enough for rendering is to traverse the curve at a fixed rate, keeping track of the distance traveled. When the distance to the current point becomes greater than the desired distance between points, use linear interpolation to choose a point between the previous and current points.

If you want the points to exactly fill the curve (that is, not have the last segment possibly be shorter than the rest), you first will have to find the length of the curve by traversing it a second time.

In code-like form (obviously not tested):

```
total_distance = 0

previous_point = start_point
t = 0
while t < 1
    t = t + STEP_SIZE
    current_point = bezier(t)
    total_distance = total_distance + length(current_point - previous_point)
    previous_point = current_point

ideal_distance = total_distance / NUM_POINTS

previous_distance = 0;
previous_point = start_point
t = STEP_SIZE
while t < 1
    current_point = bezier(t)
    current_distance = previous_distance + length(current_point - previous_point)

    if current_distance >= ideal_distance
        distance_interp = (ideal_distance - previous_distance) /
                          (current_distance - previous_distance)
        t_interp = t - STEP_SIZE + distance_interp * STEP_SIZE
        output_point(bezier(t_interp)
        current_distance = current_distance - ideal_distance

    previous_distance = current_distance
    previous_point = current_point
    t = t + STEP_SIZE

output_point(bezier(1))

```

I recommend starting with `STEP_SIZE = 1 / NUM_POINTS`. If the result isn't accurate enough, cut `STEP_SIZE` in half.

If you don't require the final segment to be the same length as the others, you can simply set `ideal_distance` to a length that you like, then run the second loop. In this case, `STEP_SIZE` should be set quite small to ensure that one iteration of the loop doesn't step past two of the desired points. Alternately, in the condition where `current_distance >= ideal_distance` you could check and output multiple points.
> 2 votes

---
Tags: javascript, geometry
---


# Question
Title: What is the correct way to get the starting point of a Box2D body?
when I use `getPosition()` I get the center point of the body. The fixture's position in the body is relative to the body. However if the body is inclined and has an angle do I need to calculate the starting point of the body? I need this point to draw a sprite on it. Is there an easy way to do this?

# Answer
> 0 votes
Say that you want the vertex at `L = (-w/2, -h/2)`, where `w` is the width of the rectangle and `h` is the height. Say that your box is at point `P`, rotated of an angle `theta` with respect to the axis orthogonal to the 2D plane.

First, get `L' = R(theta) L`, using the rotation matrix `R(theta)`. This is the vector pointing at the desired corner, rotated according to the orientation of the box. Second, translate it with `P`, so that your desired point is `X = P + L'`.

---
Tags: box2d
---


title: Changing speed of an object

text:
# Question
Title: Changing speed of an object
Is there a way of changing speed of an object at certain time? I want to change my speed to my initial speed after colliding with any object. I have already added bounce Physics to my colliding objects and player object with Friction set to 0. Please help.

# Answer
Get the Rigidbody component. Then change the velocity value.

```
Rigidbody rb;

void Start()
{
     rb = GetComponent<Rigidbody>();
}

void ChangeSpeed()
{
     rb.velocity = new vector3(x,y,z); //place your value in xyz
}

```

For further reference: Unity Physics Rigidbody Velocity
> 1 votes

# Answer
You could apply a force opposite to it for decceleration or a force in the movement direction for acceleration.

## Example:

for acceleration:

```
GetComponent<Rigidbody>().AddForce(transform.forward * FORCE_CONSTANT);

```

or for desceleration:

```
GetComponent<Rigidbody>().AddForce(-transform.forward * FORCE_CONSTANT);

```
> 0 votes

---
Tags: collision-detection, physics, rigid-body-dynamics, rigidbody
---


# Question
Title: Obtaining vector representing local z axis orientation
I've been trying to get the vector that represents the local rigid body's true forward pointing (z axis, or blue colored) vector. I've been using `Debug.DrawLine(...)` to try and find out which position vector to use.

```
Debug.DrawLine(_rb.position, new Vector3(_rb.position.x, _rb.position.y, _rb.position.z + 10), Color.red, .01f, true);
Debug.DrawLine(_tf.position, new Vector3(_tf.position.x, _tf.position.y, _tf.position.z + 10), Color.green, .01f, true);

Debug.DrawLine(transform.forward, new Vector3(transform.forward.x, transform.forward.y, transform.forward.z + 10), Color.blue, .01f, true);
Debug.DrawLine(transform.forward, new Vector3(transform.forward.x, transform.forward.y, transform.forward.z + 10), Color.yellow, .01f, true);

```

`rb.position` and `tf.position` appear to be equivalent, while `transform.forward` and `Vector3.forward` are equivalent but are in the world's `(x,y,z)` 0 position. **All four have the same orientation when I change the orientation of the `Rigidbody` via it's angular velocity property.**

---

## Why do you need the local z axis orientation?

I'm implementing a Vehicle in unity without using Wheel Colliers because they don't have the level of control that I want, and their physics are extremely wonky. Being able to obtain a vector representing the z axis orientation makes it very easy to turn the car, since I only have to modify the `Rigidbody.angularVelocity` function to get it to turn.

---

## Code for reference

For reference, my driving controller code consists of three steps within the `FixedUpdate()` method.

First is the simple Turning algorithm, which creates a triangle relationship with the front and back wheel of the car and the requested steering angle and then factors this relationship into a rate of change of angular velocity:

```
if (Input.GetButton("Right")) {
  _steerAngle = 45;
  var l = Mathf.Abs(Vector2.Distance(new Vector2(BL.position.x, BL.position.z), new Vector2(FL.position.x, FL.position.z)));
  turningCircleRadius = l / Mathf.Sin(_steerAngle);
  _rb.angularVelocity = new Vector3(_rb.angularVelocity.x, new Vector2(_rb.velocity.x, _rb.velocity.z).magnitude / _turningCircleRadius, _rb.angularVelocity.z);
} else if (Input.GetButton("Left")) {
  steerAngle = -45;
  var l = Mathf.Abs(Vector2.Distance(new Vector2(BR.position.x, BR.position.z), new Vector2(FR.position.x, FR.position.z)));
  _turningCircleRadius = l / Mathf.Sin(_steerAngle);
  _rb.angularVelocity = new Vector3(_rb.angularVelocity.x, new Vector2(_rb.velocity.x, _rb.velocity.z).magnitude / _turningCircleRadius, _rb.angularVelocity.z);
} else {
  _steerAngle = 0;
  _rb.angularVelocity = new Vector3(0, 0, 0);
  _turningCircleRadius = 1 / 0f;
}

```

Then the force exerted by the engine is calculated and then converted into change in velocity:

```
var latSpeed = new Vector2(_rb.velocity.x, _rb.velocity.z).magnitude;
  if (Input.GetButton("Accelerate")) {
    var force = _rb.mass * 10;
    latSpeed += force / _rb.mass * Time.fixedDeltaTime;
  } else if (Input.GetButton("Brake")) {
    var force = -1 * 1000 * _rb.mass;
    latSpeed += force / _rb.mass * Time.fixedDeltaTime;
    if(latSpeed <= 0) latSpeed = 0;
  }

```

Finally, the velocity is modified:

```
_rb.velocity = new Vector3(transform.forward.x * latSpeed, _rb.velocity.y, transform.forward.z * latSpeed);

```

As you can see this driving algorithm would work fine on a completely flat surface, but would start to have wonky interactions with hills if the vehicle's pitch were to change.

# Answer
`transform.forward` already gives you exactly this.

It looks like you might just be confused about how to visualize the vectors. You're repeatedly visualizing the vector (0, 0, 10) with different start points, not visualizing the facing direction of transform.forward.

Try this:

```
// Start our drawn line at the object's position in world space.
Vector3 lineStart = transform.position;

// From here, extend 3 units in worldspace along the object's local forward direction.
Vector3 lineEnd = lineStart + 3.0f * transform.forward;

// Draw the resuting line.
Debug.DrawLine(lineStart, lineEnd, Color.blue, Time.deltaTime);

```

You can verify that the blue line drawn exactly tracks the blue z+ axis of the local transform gizmo for the GameObject to which this script is attached.

There are similar bits of odd-looking math in the rest of your code. A couple of examples:

* You wrap a `Vector2.Distance` call inside an absolute value function, which is a no-op since the returned distance is already non-negative by definition.
* You both multiply and divide the `force` value by `rb_mass`, which neutralizes its effect, so your code ends up ignoring the object's mass.

With this in mind, you might want to consider re-evaluating Unity's built-in wheel collider. It's possible that the issues you had with it were a result of misinterpreting the vectors & math you were using. Physics libraries are strange and it's easy to make them behave badly, but the vast majority of troubles I've seen with them (including the majority of the problems I've had myself) turn out to be a result of using these tools incorrectly, and not an intrinsic flaw in the provided physics classes. They're just very easy to misconfigure.
> 2 votes

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