# Question
Title: Game crashes when two objects of same class collide libgdx
I have a class named Meteor and I created a function that create Meteors all the time, and I have a Player class.

The collision between the Player and Meteor works fine, but the game crashes when a collision between two meteors occurs.

I don't know why the crash occurs and I want to fix it.

Meteor Class

```
public class Meteor  {

String[] meteorNames = new String[]{"meteorBrown_big1", "meteorBrown_big2", "meteorBrown_big3",
        "meteorBrown_big4", "meteorBrown_med3", "meteorGrey_big1", "meteorGrey_big2",
        "meteorGrey_big3", "meteorGrey_big4", "meteorGrey_med2"};

HashMap<String, Sprite> map;
    World world;
    public Body body;
    public Sprite meteorSprite;
    String name;
    public Boolean destroyed = false;

public Meteor(World world, HashMap<String, Sprite> map){

    this.world = world;
    this.map = map;
    Random random = new Random();
    name = meteorNames[random.nextInt(meteorNames.length)];
    meteorSprite = map.get(name);
    defineMeteor();

}

public void drawMeteor(SpriteBatch batch){
    if(!isDestroyed()){
        meteorSprite.setPosition(body.getPosition().x, body.getPosition().y);
        meteorSprite.setRotation((float) Math.toDegrees(body.getAngle()));
        meteorSprite.setOrigin(0, 0);
        meteorSprite.draw(batch);
    }

}

private void defineMeteor(){

    BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("data/meteors/meteors.json"));
    //Create the body
    BodyDef bodyDef =  new BodyDef();

    bodyDef.type = BodyDef.BodyType.DynamicBody;

    bodyDef.position.set(100, 200);

    //Set the physics properties
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.density = 4 * meteorSprite.getWidth();
    fixtureDef.restitution = 0.6f;
    fixtureDef.friction = 0.2f;

    body = world.createBody(bodyDef);

    //Random location to create a meteor in x axis
    Random r1 = new Random();

    int High = (int) ( Gdx.graphics.getWidth() * 0.5);
    int Low = (int) (-Gdx.graphics.getWidth() * 0.5);
    int r2 = r1.nextInt(High - Low) + Low;
    //body.setTransform(r2, Gdx.graphics.getHeight() * 0.5f, 0);
    body.setTransform(0, 50 * 0.5f, 0);
    body.setUserData(Meteor.this);

    //Random Vx and Vy
    r1 = new Random();
    r2 = r1.nextInt(3);
    r1 = new Random();
    int r3 = r1.nextInt(40);
    body.setLinearVelocity(0, -r3);
    body.setAngularVelocity(-r2);

    loader.attachFixture(body, name + ".png", fixtureDef, meteorSprite.getWidth());

    //Create sensor
    fixtureDef.isSensor = true;
    FixtureDef fDef = fixtureDef;
    fDef.isSensor = true;
    fDef.filter.categoryBits = MyGdxGame.METEOR_BIT;
    fDef.filter.maskBits = MyGdxGame.SHIP_BIT | MyGdxGame.METEOR_BIT;
    loader.attachFixture(body, name + ".png", fDef, meteorSprite.getWidth());
    //body.getFixtureList().get(body.getFixtureList().size-1).setUserData("meteorSensor");

}

public void setToDestroy(){
    destroyed = true;
}

public Boolean isDestroyed(){
    return destroyed;
}

```

ContactLisneter Class

```
public class ContactGameListener implements com.badlogic.gdx.physics.box2d.ContactListener {

@Override
public void beginContact(Contact contact) {

    Fixture fixA = contact.getFixtureA();
    Fixture fixB = contact.getFixtureB();

    int cDef = fixA.getFilterData().categoryBits | fixB.getFilterData().categoryBits;

    switch (cDef){
        case MyGdxGame.SHIP_BIT | MyGdxGame.METEOR_BIT:
            if(fixA.getFilterData().categoryBits == MyGdxGame.SHIP_BIT){
                ((Player)fixA.getBody().getUserData()).life -=1;
                ((Player)fixA.getBody().getUserData()).score +=1;
            }

            else {
                ((Player)fixB.getBody().getUserData()).life -=1;
                ((Player)fixB.getBody().getUserData()).score +=1;
            }
            break;
        case MyGdxGame.METEOR_BIT | MyGdxGame.METEOR_BIT:
            Gdx.app.log("Meteoro", "meteoro");
            fixA.getBody().setTransform(fixA.getBody().getPosition().x, fixA.getBody().getPosition().y, fixA.getBody().getAngle());
            fixB.getBody().setTransform(fixB.getBody().getPosition().x, fixB.getBody().getPosition().y, fixB.getBody().getAngle());
            break;

    }

```

Error found

```
A/art: art/runtime/check_jni.cc:70] JNI DETECTED ERROR IN APPLICATION: JNI CallVoidMethodV called with pending exception 'java.lang.ClassCastException' thrown in unknown throw location
A/art: art/runtime/check_jni.cc:70]     in call to CallVoidMethodV
A/art: art/runtime/check_jni.cc:70]     from void com.badlogic.gdx.physics.box2d.World.jniStep(long, float, int, int)
A/art: art/runtime/check_jni.cc:70] "GLThread 67293" prio=5 tid=14 Runnable
A/art: art/runtime/check_jni.cc:70]   at com.badlogic.gdx.physics.box2d.World.step(World.java:689)
A/art: art/runtime/check_jni.cc:70]   at com.mygdx.game.libgdx.Screens.GameScreen.stepWorld(GameScreen.java:248)
A/art: art/runtime/check_jni.cc:70]   at com.mygdx.game.libgdx.Screens.GameScreen.render(GameScreen.java:139)
A/art: art/runtime/check_jni.cc:70]   at com.badlogic.gdx.Game.render(Game.java:46)
A/art: art/runtime/check_jni.cc:70]   at com.mygdx.game.libgdx.Screens.MyGdxGame.render(MyGdxGame.java:101)

```

MyGdxGame.java:101:

```
@Override
    public void render() {
        super.render(); //101
    }

```

GameScreen.java:248:

```
world.step(STEP_TIME, VELOCITY_ITERATIONS, POSITION_ITERATIONS); // 248

```

# Answer
> 0 votes
When two meteors collide you set the transform of each body to the transform of the colliding fixtures, I am not sure why you would want to do that or what you hope to achieve.

Regardless, you're not allowed to mutate the state of the bodies or fixtures while the `World` step is being executed, which it still is when the contact listener call-back fires. You need to perform such actions outside the call to `step`.

---
Tags: libgdx, box2d
---


# Question
Title: In Unity, can I make a GameObject within a prefab disabled by default?
If I create a simple object hierarchy in my scene...

```
-ExampleGameObject
--Child1 [is active]
--Child2 [is not active]

```

...how can I accurately store this as a prefab? If I drag ExampleGameObject to a new prefab, then instantiate that prefab, both Child1 and Child2 will be active, which isn't what I want.

# Answer
Annoyingly, the simplest way is to attach a script to one of the prefab GameObjects that set the enabled flag manually when the object is dropped into the editor.

```
using UnityEngine;
using System.Collections;

#pragma strict

public class SetInactive : MonoBehaviour {

    #if UNITY_EDITOR

    void OnDrawGizmos()
    {
        this.gameObject.SetActiveRecursively(false);
    }

    #endif
}

#endif

```
> 3 votes

# Answer
You need to instantiate the Prefab while the Child is active, assign it to a variable and then set the Child inactive.

Otherwise there is no way to activate the Child since you can't assign a Prefab component to a variable before Instantiate to reach it later, and also you can't "Find" an inactive GameObject to make it active. Either way you won't be able to get any reference to activate a disabled Child in a Prefab.

*Pseudo Unity 3D C# code:*

Define a variable in a script attached to the main component of the prefab:

```
public class MyPrefab {
    public GameObject problemChild;
}

```

In your game code, while instantiating that prefab assign the child to the variable in the prefab and then disable the child:

```
Transform newTransform;

void InstantiateMyPrefab() {
    newTransform = Instantiate(myPrefab, position);
    newTransform.problemChild = newTransform.FindChild("ProblemChild").gameObject;
    newTransform.problemChild.SetActive(false);
}

```

So it will be instantiated with the child disabled by default and you'll have a reference to that child.

Later in the game you can call this to make the child active again.

```
void WhereIsMyChild() {
    newTransform.problemChild.SetActive(true);
}

```
> 2 votes

# Answer
Yes you can! If you uncheck the checkmark next to the name of the game object that you want disabled in the inspector. There is also a way to do it via code without checking, i think you just call the gameObject you want to be disabled and set .active to false
> 1 votes

---
Tags: unity
---


# Question
Title: Unity sprites rendering problems on Android
I'm creating a simple 2d game for android, with normal sprites and animations. The problem is that when I open the game on my smartphone (Samsung galaxy trend plus), The sprites are rendered this way:

Of course, this is not what should happen. Moreover, within the Unity editor everything works flawlessly. My settings for the export are:

* Texture compressions: ETC2 (GLES 3.0) - Tested also with "Don't override"
* Player settings
    + Default orientation: landscape
    + Use 32 bit display buffer: unchecked - tried also with this option checked
    + Rendering path: forward - tried also with Legacy Deferred
    + Static batching/Dynamic batching: both checked
* Camera settings
    + Clear flags: Solid color - tried also skybox

I don't have any other scene, and this one has only one camera (I saw some topics where people were having problems because they had two or more cameras). The sprites are all .png images with transparence, except for the background, that has no transparence, but is lagging. There are three sprites which are animated using the spritesheet, but they're terribly lagging, and almost can't be seen in this screenshot. I really can't understand why, I'll continue to try, waiting for your answers. Thank you in advance!

EDIT: If in the player settings the orientation is set to auto-rotate and the device is in portrait, all the sprites works perfectly!!! The problem is that my game is meant for landscape...

# Answer
I just received an answer from the Unity Answers forum. It pointed out that I should've tried to disable the mipmaps on the sprites. After disabling them everything worked flawlessly.
> 1 votes

# Answer
I recently encountered this problem 2nd time. I think it is a bug of Unity. Well, surprisingly the solution is out of the box. Solution is also like bug, silly bug silly solution.

Right now your camera is definitely at Z:-10 move it to -1.... something and change Clipping Planes to Near: 0.3 Far 3.

May be this exact solution may not resolve your problem, but solution does exist in this. Play with it if this exact settings not work.

**NOTE:** I hope your `Order in Layers` are properly set as the should be.
> 0 votes

# Answer
I had similar issue, then using the ordering of layers and changing the z value of the sprites to make them nearer or farther from the camera, it helped me.

Try making the objects closer to camera which as hidden or not seen clearly.

Hope this works.

Thanks
> 0 votes

# Answer
Setting camera's clearflags to solid color solved this for me.
> -1 votes

---
Tags: unity, android, rendering, sprites
---


# Question
Title: Fbx SDK Importer issue (texture / uv related)
I am using the latest autodesk FBX Importer SDK, but whatever I do, I am unable to get the uvs right. Some parts are textured properly while others are not.

I am using Direct3D9 and Direct3D11 (same result in both).

Image:

360 image: https://i.gyazo.com/5a2e5f6e127521915508c9c300eb03e5.mp4

The model uses a single texture and a single material shared among 4 meshes.

Is there someone who sees immediately what the problem could be? Or is there someone who can replicate the issue for me and figure out what I am missing?

FBX Test File: http://www.4shared.com/rar/o\_WG0Crpce/Peach64FBX.html

My UV reading method:

```
int vertexCounter = 0;
for (int j = 0; j < nbPolygons; j++) {

    for (int k = 0; k < 3; k++) {

        int vertexIndex = pFbxMesh->GetPolygonVertex(j, k);

        Vector2 uv;
        _readUV(pFbxMesh, vertexIndex, pFbxMesh->GetTextureUVIndex(j, k), uv);

        pVertices[vertexIndex].uv.x = uv.x;
        pVertices[vertexIndex].uv.y = 1.0 - uv.y;
        vertexCounter++;
    }
}

void _readUV(fbxsdk::FbxMesh* pFbxMesh, int vertexIndex, int uvIndex, Vector2& uv) {

    fbxsdk::FbxLayerElementUV *pFbxLayerElementUV = pFbxMesh->GetLayer(0)->GetUVs();

    if (pFbxLayerElementUV == nullptr) {
        return;
    }

    switch (pFbxLayerElementUV->GetMappingMode()) {

        case FbxLayerElementUV::eByControlPoint:
        {
            switch (pFbxLayerElementUV->GetReferenceMode()) {

                case FbxLayerElementUV::eDirect:
                {
                    fbxsdk::FbxVector2 fbxUv = pFbxLayerElementUV->GetDirectArray().GetAt(vertexIndex);

                    uv.x = fbxUv.mData[0];
                    uv.y = fbxUv.mData[1];

                    break;
                }

                case FbxLayerElementUV::eIndexToDirect:
                {
                    int id = pFbxLayerElementUV->GetIndexArray().GetAt(vertexIndex);
                    fbxsdk::FbxVector2 fbxUv = pFbxLayerElementUV->GetDirectArray().GetAt(id);

                    uv.x = fbxUv.mData[0];
                    uv.y = fbxUv.mData[1];

                    break;
                }
            }

            break;
        }

        case FbxLayerElementUV::eByPolygonVertex:
        {

            switch (pFbxLayerElementUV->GetReferenceMode()) {

                // Always enters this part for the example model
                case FbxLayerElementUV::eDirect:
                case FbxLayerElementUV::eIndexToDirect:
                {

                    uv.x = pFbxLayerElementUV->GetDirectArray().GetAt(uvIndex).mData[0];
                    uv.y = pFbxLayerElementUV->GetDirectArray().GetAt(uvIndex).mData[1];

                    break;
                }
            }

            break;
        }
    }
}

```

I am doing V = 1.0 - uv.y because I am using Direct3D11.

NOTE: the MappingMode is always eByPolygonVertex and ReferenceMode is always eIndexToDirect

* Rendering Info:
    + Rendered as a Triangle List
    + Uv wrapping mode: Wrap (Repeat)
    + Culling: None

# Answer
> 1 votes
The solution was to split the vertices.

---
Tags: directx11, fbx, importing
---


# Question
Title: Unity 5.5 - Modify image of a button from an array of images via script - Logic Help
Right now i have this:

Is a placeholder for what i want to do. This blue circles are images in different buttons, i have a blue image circle for every letter. I have to display the correct letter image to create a word. For example: word: "DOG" and the word is created by the "D" "O" "G" images.

That is the logic i cannot get my head around.

**How can I, via script, select which image to show depending on the word given?**

**IDEAS:**

* I have an array of (INDEX, "letter") in my GameController.CS. Maybe i can add a number to the different images name. Separeate the word in characters. Look the position of this character in the Letters\[\] and that number turn it into a string and find the image with that number in the name.

I really need help to figure this out.

Thanks in advance for any help.

# Answer
> 0 votes
## I've created a simple solution to get you started.

Assuming you have 26 images of the letters (or a multi-image sprite which is what I used) do the following:

1. Create a project, include the images in the project as assets.
2. Create two empty objects, we'll call them `Letter` and `LetterMgr`
3. Add a sprite renderer to `Letter`. This will be our template object.
4. Add a script file called `LetterMgr.cs` and add it to the `LetterMgr` object.
5. Add the following code to the script:

```
public GameObject LetterTemplate;

public Sprite[] TheLetters;

void Start () {
    var theWord = "Lilo";
    var letters = theWord.ToUpper().ToCharArray();
    var position = Vector3.zero;
    var spacing = Vector3.right * 2;
    foreach (var letter in letters) {
        var letterIndex = letter - 65; // uppercase A is 65
        var letterObj = Instantiate(LetterTemplate, position, Quaternion.identity);
        letterObj.name = letter.ToString();
        letterObj.GetComponent<SpriteRenderer>().sprite = TheLetters[letterIndex];
        position += spacing;
    }

}

```
6. In the Scene editor, click the `LetterMgr` to show its properties.
7. Click the little lock icon at the top right of the inspector (this is **important** for the next steps).
8. select all the letter images (**order is important**, click the first one and then shift-click the last) and drag them to the "The Letters" property in the inspector.
9. Select the `Letter` object and drag it to the "Letter Template" property.
10. Run the project. You should get a result similar to this:

---
Tags: unity, logic, ui-design
---


# Question
Title: Generating circular bounding volume / AABB for bone animated object
I have the animated bounding boxes for the individual bones of an object which comes from a pre-computation of the bone's bounding boxes multiplied with the bone matrix. In this question I'm referring to the surrounding aka overall BB for the model. I get it by looping through the precomputed bounding boxes of the bones.

I'm able to get an OBB but not an AABB or circular volume because I can't get into the correct "space" for the center of the volume. I thought that getting an AABB would be very easy, but since I have the min/max points in bone space (?) I need to do some operation to disable rotation. All I can get is OBB :(

I figure that the aabbV4 vector is in "bone space". So, I have to take the inverse of that space somehow, but since I have the combined value of each bone, I need the AABB / circular volumes to follow tutorials on collision detection and not just OBB that I have now.

So, each object has multiple bones which have a bounding box which animate each frame according to a bone matrix. Then, the mvpGet() function creates the MVP matrix which moves / rotates / scales the whole thing.

I render the OBB / surrounding volume of the bones like this:

```
for (auto &i : myAbj.allObj)
{
    if (i->bb->val_b && i->anim->val_b)
    {
        i->aabbV4.clear();

        for (auto &j : i->bbSkelAll)
        {
            for (auto &k : i->aiGbones)
            {
                if (k.name == j.name)
                {
                    i->obbMVP = glm::transpose(k.animatedXform) * j.obbMVP; // precomputed obbMVP

                    //AABB - STEP 1 - GATHER / STORE
                    glm::vec4 bbSkelXformMin = glm::transpose(k.animatedXform) * glm::vec4(j.min, 1.f);
                    glm::vec4 bbSkelXformMax = glm::transpose(k.animatedXform) * glm::vec4(j.max, 1.f);
                    i->aabbV4.push_back(bbSkelXformMin);
                    i->aabbV4.push_back(bbSkelXformMax);

                    break;
                }
            }

            i->mvpGet();
            i->render();
        }
    }
}

 //AABB - STEP 2 - MIN / MAX
for (auto &i : myAbj.allObj)
{
    if (i->bb->val_b && i->anim->val_b)
    {
        glm::vec4 aabbMin = (i->aabbV4.empty()) ? glm::vec4(0.f) : i->aabbV4[0];
        glm::vec4 aabbMax = (i->aabbV4.empty()) ? glm::vec4(0.f) : i->aabbV4[0];

        for (uint j = 0; j < i->aabbV4.size(); ++j)
        {
            aabbMin = glm::min(i->aabbV4[j], aabbMin);
            aabbMax = glm::max(i->aabbV4[j], aabbMax);
        }

        glm::vec3 aabbSize = aabbMax - aabbMin;
        glm::vec3 aabbCenter = .5f * (aabbMin + aabbMax);
        i->aabbMVP = glm::translate(glm::mat4(), aabbCenter) * glm::scale(glm::mat4(), aabbSize);

        i->aabbTgl = 1;
        i->mvpGet();
        i->render();
        i->aabbTgl = 0;

        cout << "aabbCenter = " << glm::to_string(aabbCenter) << endl;
    }
}

```

# Answer
Maybe I am misunderstanding your question, but it seems like you have oriented bounding boxes and you want to get an axis aligned bounding box that contains all the OBBs.

The easiest way to get an AABB containing an OBB is to gather the min and max (x,y,z) coordinates of the corners of the OBB. When you have the min and max corners, that defines an AABB. That is the AABB which contains your OBB. If you want to contain more OBBs, just gather the min and max from every OBB's corners.

You can get a corner of an OBB by transforming a unit cube's corner by the OBB's World matrix.

There are probably more efficient methods though, but you could implement the simplest first and optimize when you find it too slow for your needs.

Good luck!
> 0 votes

---
Tags: opengl, c++, physics, skeletal-animation
---


# Question
Title: approach for the system that record player actions and imitate it
I am trying to implement some kind of system, that would allow `AI` to imitate player's action at certain points in similar cases. Case example

```
Player (hp: 10, mp: 5) used skill [BasicAttack] when in battle

```

When I set for a `bot` parameters like `hp: 10, mp: 5` and state `attack` it should use `BasicAttack` skill because in same case player used that action. (I'd like to have ability to define `similar` cases like when `hp: 11, mp: 6` then bot use `BasicAttack` too because it is similar to `hp: 10, mp: 5` case but whatever)

The question is that what are the basic approaches for such cases? Leaving aside `snapshotting` of player's state, how can such system be implemented?

So far I have two ideas. My ideas are

```
1. order player parameters by priority and states and create tree where every node would be
corresponding parameter value. For example node with name [hp] and value [10] will have a
child note [mp] with value [5] thus I can create required paths to actions

2. I have event log with recorded player events. It keeps its record ordered. I iterate over
it and using pattern matching I compare player parameters and retrieve corresponding player
action

```

The first approach seems much faster though.

But I'd like to know if there already exist approaches for such systems, in order not to reinvent the wheel as I used to do. Are any?

# Answer
What you want is to measure frequency of the actions the player performs.

**Abstract**: Every time the player you want to imitate does an action you take a copy of the (relevant) player state and for that player state, make a counter for the action and add 1 to it. Then use that as probability distribution for the AI agents.

---

## Data structures

What you want is a data structure that provides fast lookup on complex data (the player state).

Below I suggest using locality sensitive hashing, the idea is to take all the variables of the data (the player state) and use them to compute a single value that you can then use as key to lookup in such way that similar items will result in a similar key if not the same.

A simple approach to do this is to keep the order of relevance of the bits of information, perhaps removing a few. For example, if you have hp = 10 and mp = 5, you have (in binary) hp = 1010\_2 and mp = 101\_2, if we combine by simple XOR we have 1111\_2 (15), by removing the last two bits we have key = 11\_2 (3).

Other similar values will have the same key, such as (hp = 11, mp = 5), (hp = 11, mp = 6), (hp = 10, mp = 4), (hp = 11, mp = 4), etc... but will also other values that are not that close such as (hp = 15, mp = 0), or even (hp = 70, mp = 75).

Of course, there could be better hashing algorithms, yet, in general this shows that you can't take the collision as a guarantee of proximity, but it will reduce the search space considerably, improving your performance.

Therfore, I'd suggest to combine locality sensitive hashing with the custom search tree which you have already considered.

---

## General Solution

**When the player is playing**

For example, when the player is battle, with hp 10 and mp 5 and does a basic attack...

1. Take a copy of the player state (in battle, hp = 10, mp = 5, etc...)
2. Look if there is a recorded player state close enough※ to that and select it. if there isn't, create a new recorded player state with an associated action dictionary and select that
3. On the action dictionary for selected recorded player state, look for the action the player performed※※, if it is there add 1 to its counter, if it isn't add the action with value of 1

※: You will need your own definition of close enough. In general, you can think of the player state as a vector space (where each variable you consider is a dimension) then each state is a point and you can measure distance from point to point. You may consider using locality sensitive hashing on the player state to map similar player states. You may also want to consider to represent variables in a uniform scale (for example, instead of taking at hp = 10, take hp = 20%).

※※: You will need to abstract your actions. You cannot consider attack each enemy as a different action, but you may consider distinguishing attacking the weakest enemy, attacking the stronger enemy, etc... Or you may just have attack. There will be a sweet spot of granularity for your game.

---

**When the AI is playing**

The AI agent will take its own "player state", look up for similar recorded player states of the player it has to mimic, select the closest one available... and then use the action dictionary as probability distribution to decide what to do.

For example, if the counter says that the player in that recorded state has attacked 20 times, and has healed 10 times and has run away 10 times, then the AI will add a weight of 20 to attack, 10 to healing and 10 to run away, that will result in the AI selecting between attack with a chance of 50%, healing with a chance of 25% and running away with a chance of 25%.

You will need to add the counters to get the total (20 + 10 + 10 = 40), use that to get the probabilities (20/40 = 50%, 10/40 = 25%, 10/40 = 25%), then use the accumulate values (50%, 50% + 25% = 75%, 75% + 25% = 100%) of that as stop marks to a uniform random number generators giving you a number from 0 to 1 (which should be available in your language). Depending on what range the result falls (\[0, 0.5), \[0.5, 0.75), \[0.75, 1)) you choose the corresponding action.

Further reading: Darts, Dice, and Coins: Sampling from a Discrete Distribution.

---

## Inspiration from Drivatars

The method I explain above is based on the talk "Drivatar and Machine Learning Racing Skills in the Forza Series" from nuclai15. In which it is explained that the Drivatar (that mimic real players in games of other players) use a frequency map of the tracks, so the AI will know for each part of the tracks where the player has been how often the player passes over there and how fast. The AI also records other actions such as bumping into other cars which helps to reflect aggressive players.

That will provide information on (for example) what type of curves the player will take on the inner side and what type of curves will take on the outer side, it may also provide information on what parts of the track the player will accelerate, etc...

When the Drivatar needs to play on a track where the player it mimics has not played, it will look for tracks with similar features and use those to model the behavior.

---

**Harmonic Mean**

Another interesting thing about Drivatar is that they will give more weight to recent behavior. This allows the Drivatar to improve as their player counterparts improve... it also means that when the player has had a bad performance, it is reflected in the Drivatar.

You may accomplish that by changing the information stored in the dictionaries and how the weights are computed... To do that, you could use the harmonic mean of the time since the action happened it will naturally give more weight to more recent actions (instead of what I suggested above).

In that case you will not store the number of times the action is performed but instead store what action was performed when... although it will mean to store more data and require more computing power to compute the weights.

To alleviate that you can: 1) remove old actions from the record as they will have low weight anyway (perhaps a data structure organized by chunks of time will ease this process) and 2) pre-compute the weights on the client on a natural exit points (e.g.: when the player saves, when a match completes, when the player goes to the peaceful part of the map, etc..) instead of doing it just in time.

In this scenario you would then go over the list of timestamp for each action. For each timestamp subtract it from last time the player was seen. Convert the result to standard units (e.g. seconds). Compute the inverse. Add all the results together (that is the summation of all the inverse values). And finally take the inverse of the summation, and use that as weight... you would then proceed to get the total, accumulate and use the random number generator in the same fashion as described before.

---

**Further Research**

Since we want elements that were added long ago to fade away, and since we will be using random anyway, and since we will never get a perfect imitation of a player... We may as well use probabilistic data structures to store the actions such as Bloom filters, Count-min sketch and HyperLogLog.
> 1 votes

---
Tags: ai
---


# Question
Title: difficulty with final admob configuration/implementation libgdx
I've been trying to include some ads in my app using AdMob. It all launches ok so i assume i have the library added correctly etc. I followed a tutorial that was over a year old (Brent Aureli on youtube) becoz that was all i could find relative to LibGDX.

It seems to try to pull the ad in , but can't display it. I can't make much more sense out of the log and would love if someone can help me out.

As a note, my game is in debug version (of course as i'm still developing it in Android Studio - but v1.0 is available on Play Store), i've added the Test Device as per the log. Usually (ie. before i added the adView code) the intro music plays right from the start. This still happens but as soon as i get the message on phone saying "signing into Google..." and the subsequent failure message (which is normal as its in debug) the music now stops and doesnt start again until i press my Play Game button.

I'm currently doing everything inside AndroidLauncher.

Here is the log: V/WebViewChromiumFactoryProvider: Binding Chromium to main looper Looper (main, tid 1) {d618180} I/LibraryLoader: Expected native library version number "",actual native library version number "" I/chromium: \[INFO:library\_loader\_hooks.cc(104)\] Chromium logging enabled: level = 0, default verbosity = 0 I/BrowserStartupController: Initializing chromium process, singleProcess=true W/art: Attempt to remove local handle scope entry from IRT, ignoring W/chromium: \[WARNING:resource\_bundle.cc(304)\] locale\_file\_path.empty() I/chromium: \[INFO:aw\_browser\_main\_parts.cc(65)\] Load from apk succesful, fd=61 off=43108 len=3029 I/chromium: \[INFO:aw\_browser\_main\_parts.cc(78)\] Loading webviewchromium.pak from, fd:62 off:229484 len:1089587 W/AudioManagerAndroid: Requires BLUETOOTH permission W/chromium: \[WARNING:data\_reduction\_proxy\_settings.cc(331)\] SPDY proxy OFF at startup W/art: Attempt to remove local handle scope entry from IRT, ignoring W/AwContents: onDetachedFromWindow called when already detached. Ignoring W/art: Attempt to remove local handle scope entry from IRT, ignoring W/art: Attempt to remove local handle scope entry from IRT, ignoring W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection W/art: Attempt to remove local handle scope entry from IRT, ignoring W/AwContents: onDetachedFromWindow called when already detached. Ignoring W/art: Attempt to remove local handle scope entry from IRT, ignoring W/art: Attempt to remove local handle scope entry from IRT, ignoring I/Ads: Ad finished loading. I/AndroidLauncher: ad loaded... I/chromium: \[INFO:CONSOLE(0)\] "Document was loaded from Application Cache with manifest https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.appcache", source: https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.html (0) I/chromium: \[INFO:CONSOLE(0)\] "Application Cache Checking event", source: https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.html (0) I/chromium: \[INFO:CONSOLE(0)\] "Application Cache NoUpdate event", source: https://googleads.g.doubleclick.net/mads/static/mad/sdk/native/sdk-core-v40-loader.html (0) D/GameHelper: GameHelper: onActivityResult: req=RC\_RESOLVE, resp=SIGN\_IN\_FAILED D/GameHelper: GameHelper: onAR: responseCode=SIGN\_IN\_FAILED, so giving up. W/GameHelper: disconnect() called when client was already disconnected. D/GameHelper: GameHelper: Notifying LISTENER of sign-in FAILURE (error) I/AndroidInput: sensor listener setup I/Ads: Scheduling ad refresh 60000 milliseconds from now. I/AndroidGraphics: resumed I/Timeline: Timeline: Activity\_idle id: android.os.BinderProxy@36075376 time:451983293 I/Ads: Ad is not visible. Not refreshing ad. I/Ads: Scheduling ad refresh 60000 milliseconds from now. I/AndroidGraphics: paused I/AndroidInput: sensor listener tear down I/AndroidGraphics: Managed meshes/app: { } I/AndroidGraphics: Managed textures/app: { } I/AndroidGraphics: Managed cubemap/app: { } I/AndroidGraphics: Managed shaders/app: { } I/AndroidGraphics: Managed buffers/app: { } I/AndroidGraphics: destroyed W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection D/GameHelper: GameHelper: onStop D/GameHelper: GameHelper: Client already disconnected when we got onStop.

and my code:

```
public class AndroidLauncher extends AndroidApplication implements GameHelper.GameHelperListener, GoogInterface{
private final String TAG = "AndroidLauncher";
private GameHelper gameHelper;
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
FlapTurdGame game;

protected AdView adView;

@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    game = new FlapTurdGame(this);
    if (gameHelper == null) {
        gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
        gameHelper.enableDebugLog(true);
    }
    loginGPGS();

    // make a new relative layout (as per Brents tutorial) for AdMob
    RelativeLayout layout = new RelativeLayout(this);
    View gameView = initializeForView(game, config);
    gameView.setMinimumHeight(200);
    layout.addView(gameView);

    // create the new AdView and pass it this (it takes an activity but calls it context - i dunno why yet!)
    adView = new AdView(this);

    // set the adListener for the adView:
    adView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            Log.i(TAG, "ad loaded..." );
        }
    });

    // set size and Ad Id for banner ad
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId("ca-app-pub-9900639686681371/7970613041");

    // create an adrequest builder
    AdRequest.Builder builder = new AdRequest.Builder();
    builder.addTestDevice("42BC38E35388C24799529CF0FA59830A");
    // sets layout of advert to wrap to width and height:
    RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    // add the banner ad to our layout with the adParams:
    layout.addView(adView, adParams);

    adView.loadAd(builder.build());

    setContentView(layout);

    gameHelper.setup(this);
    initialize(game, config);

}

@Override
public void onStart(){
    super.onStart();
    gameHelper.onStart(this);
}

@Override
public void onStop(){
    super.onStop();
    gameHelper.onStop();
}

@Override
protected void onPause() {
    adView.pause();
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    adView.resume();
}

@Override
public void onActivityResult(int request, int response, Intent data) {
    super.onActivityResult(request, response, data);
    gameHelper.onActivityResult(request, response, data);
}

@Override
public boolean getSignedInGPGS() {
    return gameHelper.isSignedIn();
}

@Override
public void loginGPGS() {
    try {
        runOnUiThread(new Runnable(){
            public void run() {
                gameHelper.beginUserInitiatedSignIn();
            }
        });
    } catch (final Exception ex) {
    }

}

@Override
public void submitScoreGPGS(int score) {
    Games.Leaderboards.submitScore(gameHelper.getApiClient(), getString(R.string.leaderboard_top_scorers_world), score);
}

@Override
public void unlockAchievementGPGS(String achievementId) {
    Games.Achievements.unlock(gameHelper.getApiClient(), achievementId);
}

@Override
public void getLeaderboardGPGS() {
    if (gameHelper.isSignedIn()) {
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), getString(R.string.leaderboard_top_scorers_world)), 100);
    }
    else if (!gameHelper.isConnecting()) {
        loginGPGS();
    }
}

@Override
public void getAchievementsGPGS() {
    if (gameHelper.isSignedIn()) {
        startActivityForResult(Games.Achievements.getAchievementsIntent(gameHelper.getApiClient()), 101);
    }
    else if (!gameHelper.isConnecting()) {
        loginGPGS();
    }
}

@Override
public void onShowAchievementsRequested() {

}

@Override
public void onSignInFailed() {

}

@Override
public void onSignInSucceeded() {

}

```

}

# Answer
> 0 votes
ok i actually found the answer. I had to move my initialize(game, config); call in AndroidLauncher to be BEFORE the call setContentView(layout);

---
Tags: java, android, libgdx, google-play-services, admob
---


# Question
Title: Can GPU overload cause rendering inaccuracies?
It was supposed to be a continuous tube, made out of 5000 instanced rings of 60 cubes each (12 triangles each) on my integrated laptop intel GPU card using OpenGL 3.3.

That was what I got. The distortions you see can also be seen when rendering 1000 or 500 rings, albeit at much lower quantity and severity.

What is causing it? I've disabled polygon smoothing, and it helped immensely, but didn't eliminate the problem. I've also found out that vertex shader variables are `highp` by default. There is no front culling either.

Here it is how it is supposed to look (same rendering, but from front, where it is not distorted).

The FPS is about 10. NearZ is 0.01, FarZ is 100, also tried 1..1000, didn't change much, if anything.

Can this possibly be just because I render too many triangles and the solution would be to make less of them?

Shader codes:

```
const char *VERT_SRC_FSTR =
"#version 330 core\n"
"in vec3 pos;\n"
"flat out int vertexID, instanceID;\n"
"uniform vec3 mov[%d], eye;\n" // %d - RENDERER_MAX_INSTANCE_COUNT
"uniform mat4 proj, view;\n"
"void main(void)\n{\n"
"    vertexID = gl_VertexID;\n"
"    instanceID = gl_InstanceID;\n"
"    vec4 p = proj * view * vec4(pos - eye + mov[gl_InstanceID], 1);\n"
"    p.x *= %f;\n" // %f - inversed aspection ratio (9/16)
"    gl_Position = p;\n}\n";
const char *FRAG_SRC_FSTR =
"#version 330 core\n"
"flat in int vertexID, instanceID;\n"
"out vec3 clr;\n"
"void main(void)\n{\n"
"    clr = vec3(vertexID %% 2, 1, instanceID %% 2);\n}\n";

```

Is there anything else I can try? Could this be an issue with my driver/graphics card?

Edit: `glxinfo` excerpt:

```
Extended renderer info (GLX_MESA_query_renderer):
    Vendor: Intel Open Source Technology Center (0x8086)
    Device: Mesa DRI Intel(R) Bay Trail  (0xf31)
    Version: 12.0.6
    Accelerated: yes
    Video memory: 1536MB
    Unified memory: yes
    Preferred profile: core (0x1)
    Max core profile version: 3.3
    Max compat profile version: 3.0
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.0
OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Intel(R) Bay Trail
OpenGL core profile version string: 3.3 (Core Profile) Mesa 12.0.6
OpenGL core profile shading language version string: 3.30
OpenGL core profile context flags: (none)
OpenGL core profile profile mask: core profile

```

Rendering code:

```
// Rendering draw function:
void rendererDraw(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUniform3fv(renderer.eyeLoc, 1, rendererInput.eye);
    glUniformMatrix4fv(renderer.projLoc, 1, GL_FALSE, rendererInput.proj);
    glUniformMatrix4fv(renderer.viewLoc, 1, GL_FALSE, rendererInput.view);
    for (struct RendererDrawable *d = rendererInput.drawables; d->vao!=0; ++d)
    {
        glUniform3fv(renderer.movLoc, d->instanceCount, d->mov);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBindVertexArray(d->vao);
        glDrawArraysInstanced(d->drawMode, 0, d->pointCount, d->instanceCount);
        glfwSwapBuffers(win);
    }
    glfwSwapBuffers(win);
}

```

Renderer header:

```
// Renderer public data:
extern struct RendererInput
{
    Vector eye;
    Matrix proj, view;
    struct RendererDrawable *drawables; // terminated by (drawable->vao == 0)
} rendererInput;

extern struct RendererOutput
{
    GLint posLoc;
} rendererOutput;

struct RendererDrawable
{
    GLenum drawMode;
    GLuint vao, pointCount, instanceCount;
    Vector *mov;
};

```

Drawable setup in engine.c:

```
void engineInit(void)
{
    rendererInput.drawables = calloc(2, sizeof(*rendererInput.drawables));
    // rendererInput.drawables[0] - the RING, which is being
    // drawn instanced multiple times with different offset (mov)
    rendererInput.drawables[0] = drawableCubeCircle();
    rendererInput.drawables[0].instanceCount = RENDERER_MAX_INSTANCE_COUNT;
    rendererInput.drawables[0].mov[0][0] = 0;
    rendererInput.drawables[0].mov[0][1] = 0;
    for (int i = 0; i < RENDERER_MAX_INSTANCE_COUNT; ++i) rendererInput.drawables[0].mov[i][2] = i;
    cameraInit();
    timerFrameReset();
}

```

A single ring being renderered correctly:

The issue here is not the ring itself, but their "chaining". As you can see in the pictures, most of the time it works correctly, but sometimes there are distortions. Since I'm not generating a mesh and instantiating them instead, the problem could only lie within:

`for (int i = 0; i < RENDERER_MAX_INSTANCE_COUNT; ++i) rendererInput.drawables[0].mov[i][2] = i;`

but I don't see it there.

# Answer
I forgot to initialize other offset vector array fields (x and y), leaving them undefined.

Before:

```
void engineInit(void)
{
    rendererInput.drawables = calloc(2, sizeof(*rendererInput.drawables));
    rendererInput.drawables[0] = drawableCubeCircle();
    rendererInput.drawables[0].instanceCount = RENDERER_MAX_INSTANCE_COUNT;
    rendererInput.drawables[0].mov[0][0] = 0; // <--- all other values undefined
    rendererInput.drawables[0].mov[0][1] = 0; // <--- all other values undefined
    for (int i = 0; i < RENDERER_MAX_INSTANCE_COUNT; ++i)
    {
        rendererInput.drawables[0].mov[i][2] = i;
    }
    cameraInit();
    timerFrameReset();
}

```

Fixed:

```
void engineInit(void)
{
    rendererInput.drawables = calloc(2, sizeof(*rendererInput.drawables));
    rendererInput.drawables[0] = drawableCubeCircle();
    rendererInput.drawables[0].instanceCount = RENDERER_MAX_INSTANCE_COUNT;
    for (int i = 0; i < RENDERER_MAX_INSTANCE_COUNT; ++i)
    {
        rendererInput.drawables[0].mov[i][0] = 0; // <--- fixed
        rendererInput.drawables[0].mov[i][1] = 0; // <--- fixed
        rendererInput.drawables[0].mov[i][2] = i;
    }
    cameraInit();
    timerFrameReset();
}

```
> 4 votes

---
Tags: opengl, 3d, instancing
---


# Question
Title: How to make a variable remain false after release of a button?
```
left_click = mouse_check_button_pressed (mb_left)

battleMode = true

if (left_click) battleMode = false

if battleMode = false then {
  if (key_right) then {
  x= x+5
  sprite_index= spr_walking
  image_speed = 0.5
  }
}

```

`battleMode` becomes `true` again once left click is not being held. I tried changing `mouse_check_button_pressed` to `mouse_check_button_released` and `mouse_check_button`, but `battleMode` becomes `true` again when `left_click` has done its job.

# Answer
> 1 votes
i dont know GM really, but from the code snippet it looks like you are setting battleMode to true once every frame in the game loop.

is battleMode a member variable or is it inside a method being called every frame?

Make sure battleMode is set to true only once when it is instantiated at the point of creation, and then your logic should work

# Answer
> 1 votes
```
left_click = mouse_check_button_pressed (mb_left)

~~battleMode = true~~

if (left_click) battleMode = false

if battleMode = false then {
  if (key_right) then {
  x= x+5
  sprite_index= spr_walking
  image_speed = 0.5
  }
}
```

I assume that the code you have pasted is used in a step event. Therefore whenever you are not pressing the mouse button battleMode will be true. Be sure to instantiate battleMode in a **Create event**

---
Tags: game-maker
---


title: LibGDX touchDown event continues

text:
# Question
Title: LibGDX touchDown event continues
I'm using libGdx to create a simple platformer.

I used a set of images as an onScreen controller for Android, and use this code to fire a shot -\>

```
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            downPressed = true;
            return true;
            //return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            downPressed = false;
            //super.touchUp(event, x, y, pointer, button);
        }

```

But when I keep the button pressed, the player continues to shoot which I don't want, I want the player to tap-to-shoot.

What am I doing wrong?

# Answer
The reason why the player continues to shoot is once you press the button **downPress=true**. It will stay true until you release the button. You could just call the shoot method from the touchDown event.

```
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            ~~downPressed = true;~~
            **ShootNow();**
            return true;
            //return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            ~~downPressed = false;~~
            //super.touchUp(event, x, y, pointer, button);
        }

```
> 1 votes

# Answer
You could use Gdx.input.justTouched() in your input loop to check for a tap event, then check if the Gdx.input.getX() and .getY() coordinates are within the bounds of any of your 'controller' images and respond accordingly.
> 0 votes

---
Tags: libgdx, android-studio
---


# Question
Title: Calculating position to position B with speed
I am trying to find out a formula that calculates the actual position of a player using his speed and a destination position.

These are the informations I have:

* Vector3 (X,Y,Z) : Current position
* Vector3 (X,Y,Z) : Destination position
* float : Speed

I can manage to calculate the angle between these two vectors, but I can't find an efficient formula to calculate the exact position using the speed at each loop. Do you have an idea?

**EDIT\***

I finally found a formula, but it's not really working as I want...

```
private void WalkNew()
{
    float speed = 0.1f;
    float distX = this.DestinationPosition.X - this.Position.X;
    float distZ = this.DestinationPosition.Z - this.Position.Z;
    float distance = (float)Math.Sqrt((distX * distX) + (distZ * distZ)); // distance between A and B positions

    float time = distance / speed;
    float currentTime = Time.GetTickFrom(this.lastMoveTime);
    this.lastMoveTime = Time.GetTick();
    float percentage = currentTime / time;

    if (this.Position.IsInCircle(this.DestinationPosition, 0.1f))
    {
        // We arrived
    }
    else
    {
        this.Position.X += distX / percentage;
        this.Position.Z += distZ / percentage;
    }
}

```

Any thoughts about this formula ?

Thanks

# Answer
You subtract the current position from the destination position, this way you get a vector pointing to the destination.

You need to normalize this vector (divide it with it's length) and multiple with the speed. You get a velocity vector this way.

Finally you add this to the current position to get the new position.

In pseudo code:

```
currPos += normalize(dest - currPos) * speed

```

This way you don't need to uses that many costy function, such as atan2, cos or sin, only a square root.
> 1 votes

---
Tags: c#, mathematics
---


# Question
Title: Should I use retained mode or immediate mode
I'm trying to make a opengl wrapper for winforms(.net). Basically you code in gdi+ syntax but it gets rendered for opengl(using glcontrol of opentk).

Which mode should I use for rendering ui? It has to be fast enough to support lagless animations and image-drawing. Direct mode (glBegin, glEnd) is easy but I've read there are performance issues. On the other hand, retained mode will be relatively much complex to implement.

My preference is first make for immediate mode then move to retained as I progress. Are there any issues with immediate mode(like missing functionality

# Answer
**Immediate mode** in OpenGL consists of `glBegin`/`glEnd` calls, with one or more `glVertex` calls (the minimum legal number depending on the *mode* param of your `glBegin` call), and optionally other vertex attribute specification calls (`glColor`, `glTexCoord`, etc), between them.

* `glBegin` instructs the GL driver that you're starting to draw a point, line or polygon.
* `glTexCoord`, `glColor`, `glNormal`, etc just set a "current value" for the texture coordinate, colour, normal, etc.
* `glVertex` takes those "current values", together with the position information that you supply with the `glVertex` call, and transfers the lot to the driver.
* `glEnd` completes the point, line or polygon.

The major advantage to immediate mode is that you need to plan absolutely nothing up-front. You can just issue a `glBegin` call and start sending aribtrary geometry to your driver and hardware.

The major disadvantages to immediate mode include that it incurs a *lot* of function call overhead into the GL driver, and that vertex data must *always* be sent to the graphics hardware, even if that vertex data is unchanged from last time it was used.

These disadvantages can combine to make immediate mode slow. How slow? Well, faster than you might think (and definitely faster than some people might give you the impression it is). Quake and Quake II both used immediate mode so it's clearly quite capable of handling certain workloads with acceptable performance.

**The first disadvantage** was addressed in OpenGL 1.1 (1997) by the addition of **vertex arrays**, which allowed for the number of GL calls to specify a point, line or polygon, which could easily get into double figures, to drop to one (not including some setup calls).

**The second disadvantage** was addressed in OpenGL 1.5 (2003) by the addition of **vertex buffer objects**, which built on the vertex array specification and which allowed for data that didn't need to change to be kept in GPU memory.

I draw attention to these dates and version numbers because, and once again contrary to information you may see elsewhere, these are actually *very old* additions to OpenGL (both were in fact added *before* shaders were) and are widely available even on low-end commodity hardware.

What you are calling **retained mode** is primarily use of vertex buffer objects as a source for vertex data rather than just specifying it on-the-fly via immediate mode.

**Modern OpenGL** is the term typically used to refer to a usage of OpenGL in which vertex buffer objects and shaders are the *only* way of drawing available, being constrained by what is known as a "core profile". It is also possible to create what is known as a "compatibility profile" giving you the ability to mix certain features of modern and old-style OpenGL; mixing immediate mode with shaders would be one example.

---

**Which should you use?**

There's no clear-cut answer to this; it's really going to depend on the needs of your program.

Immediate mode, because of it's on-the-fly nature, is *great* for prototyping and fast iteration of new code.

The performance penalties of immediate mode primarily mount up as the polygon count increases, but yet we have seen from the examples of Quake and Quake II that there is a point at which it's still plenty fast enough.

Immediate mode, being older, might seem as though it's more compatible but that's not actually the case. It's not available on mobile devices *at all* for example; these primarily use OpenGL ES which has no immediate mode.

Immediate mode has been removed from OpenGL core profiles, so if you're using a GL core profile you won't have it available either.

Using vertex buffer objects requires a certain amount of up-front investment; you need to plan out your buffer usage and update strategy, and a poorly thought-out buffer object implementation can actually run *slower* than immediate mode (primarily by introducing multiple CPU/GPU sync points). On the other hand, get it right and if your workload is heavy enough you'll go 10s or 100s of times faster.
> 13 votes

---
Tags: opengl, graphics, opentk, ui-design
---


# Question
Title: openGL Vertex Projection does not work as expected
I try to render a simple grid using `glBegin(GL_LINES)`. I have a `class Camera`, which provides values like this:

```
float farPlane = 100.0f;
float nearPlane= 0.1f;

float screenRatio = 1,42857; //width/height = 1000/700
float frustum = 70.0f;

glm::vec3 position = glm::vec3(3.0f, 3.0f, 3.0f);

glm::vec3 UP = glm::vec3(0.0f, 1.0f, 0.0f);
glm::mat4 view = glm::lookAt(position, position - glm::normalize(position), UP); // makes the lookAt vector always point towards (0, 0, 0)
glm::mat4 projection = glm::perspective(frustum, screenRatio, nearPlane, farPlane);

```

using the `view` and `projection` matrices, i transform every vertex from my Grid model and render it.

```
glm::mat4 viewProjectionMatrix = Graphic::camera->getViewProjectionMatrix(); // returns Camera::projection * Camera::view
glBegin(GL_LINES);
for (unsigned int i = 0; i < vertexNum; ++i) {
    glColor3f(vertexArray[i].normal.x, vertexArray[i].normal.y, vertexArray[i].normal.z); // normal vector is used for color in this case
    glm::vec4 translatedPosition(viewProjectionMatrix*gridTransformationMatrix*(glm::vec4(vertexArray[i].position, 1.0f)));
    glVertex3f(translatedPosition.x, translatedPosition.y, translatedPosition.z);
}
glEnd();

```

but this is what i see when i move the camera along the line: (0,0,0) + u\*(1,1,1) http://i.imgur.com/PrcDcLs.gifv (you can see the camera cooridnates in the console)

# Answer
Could it be that your screenRatio is 1,42857 instead of 1.42857? Sorry in advance, I don't have enough rep to comment yet.
> 1 votes

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


# Question
Title: Libgdx: How to draw the score on the top left?
I want to keep the score visible on the top left corner of the screen. I have the score talking care of. I just want to display it.

`Score: x`

The comment on the accepted answer on Stackoverflow suggests that `BitmapFontCache` is the best way to do it, inside the render method.

* `BitmapFontCache.draw()` doesn't accept strings, so I cannot pass `Score:`
* `BitmapFontCache.draw(batch, x, Align.topLeft);` doesn't work either.
* Do I have to keep updating the score position?

**EDIT**

```
  game.batch.begin();
        cache.setText("Score: " + score, 500,500);
        cache.draw(game.batch);

```

.........

or even if I placed it outside `batch.begin`, if I place it directly in, I get

```
E/AndroidRuntime: FATAL EXCEPTION: GLThread 172645
                  Process: com.mygdx.game, PID: 16727
                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.badlogic.gdx.graphics.g2d.GlyphLayout com.badlogic.gdx.graphics.g2d.BitmapFontCache.setText(java.lang.CharSequence, float, float)' on a null object reference
                      at com.mygdx.game.GameScreen.render(GameScreen.java:129)
                      at com.badlogic.gdx.Game.render(Game.java:46)
                      at com.mygdx.game.Gam.render(Gam.java:20)
                      at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:459)
                      at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1647)
                      at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1352)
E/AndroidGraphics: waiting for pause synchronization took too long; assuming deadlock and killing

```

Even if I remove `score` variable and put everything outside batch.begin but inside render I keep getting the same error.

```
 public void render(float delta) {
        cache.setText("Score: " + 12, 500,500);
        cache.draw(game.batch);

```

# Answer
1. To set the text you have to use

```
BitmapFontCache.setText(text, x, y);
```
2. In the render method you just do

```
BitmapFontCache.draw(batch);
```
3. You only have to update the score position once in the render method.
> 1 votes

# Answer
Thanks for `Klemmensen` I ended up doing

```
game.font.setColor(Color.WHITE);
game.font.draw(game.batch, "Score: " +score, x, y);

```
> 0 votes

---
Tags: java, android, libgdx, ios
---


# Question
Title: JAVA -- Should I use a float or double for 1.5 speed for my player's speed? What should I use in general for positions, etc.?
The title says it all, but I would like to know if I should use a double 1.5 for my velX and velY factor, or a float 1.5 for my velX and velY factor. Also, I would like to know if I should use a double or float for everything such as positions of entities, etc.. Thanks in advance!

# Answer
> 1 votes
A double has a wider range than a float and use more memory. In your case it properly doesn't matter but the double is often the default option.

You can read more about it here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

# Answer
> 3 votes
Both the single-precision 32-bit `float` type and double-precision 64-bit `double` type can represent numbers like 1.5 exactly, with no rounding error.

(ie. as 1 * 2^0 + 1 * 2^-1, followed by 22 zeroes in the case of a `float`, or 51 zeroes in the case of a `double`)

Neither one can exactly represent a number like one-fifth, 0.2, because its denominator is not a power of two. The closest you can get with a `float` will be off by about 0.000 000 004, or four-billionths of a unit, and `double` will get even closer.

Now I don't know about you, but I don't usually tune my game's meshes/colliders/speeds to tolerances of billionths of units, so in practice the precision limits of `float` don't cause many problems in day-to-day game development calculations, *as long as we're working within a few kilometers of the origin of our coordinate system* \- since both `float` and `double` use a sliding scale of precision, staying more precise for values close to zero, and trading-off some precision to represent bigger numbers. You can consult the table in this answer for the precision available in each range.

There are a few cases where the limits do crop up though:

* **Exact comparisons.** Whether you're using `float` or `double`, don't use `if(myValue == thisTargetValue)` \- because even a difference of billionths of a unit like we saw above is enough to make this comparison fail. Compare using ranges instead, so your code is tolerant to some fluctuation in the tiny final digits.
* **Time.** If you measure your time in seconds with a single-precision `float`, then if your game is left running for a day you'll be in a range where you start to lose millisecond precision, and that's usually enough to make sensitive timing code go haywire. `float` is fine for accumulating time deltas like "how long has the player held the jump button," but don't use it for your global time. `double` should be more than sufficient for games played over human lifespans though. This type of error has led to the failure of missile defense systems, so take it seriously. ;)
* **Big Spaces.** Once you go further than a few thousand units from the 0 point of your coordinate system, the precision limits of `float` tend to become significant. You can see this in Minecraft versions before Beta 1.8 - if you walk far enough in one direction, movement becomes jumpy and the terrain starts getting weird, as the errors grow to reach the sensitivity thresholds of the algorithms being used.

3D rendering and physics engines usually work exclusively in single-precision `float` types, so changing absolutely everything over to `double` is generally not feasible. Instead, games with huge worlds usually solve this by breaking the world into chunks, and working with coordinates relative to the center of each chunk, rather than always in reference to the origin of the whole universe. Kerbal Space Program uses a `float` coordinate space with a "floating origin" that moves to keep the player centered, while an underlying orbital mechanics simulation uses `double` values for computing the large-scale trajectories.
* **Accumulated Error.** An error of billionths in one calculation isn't much. But if you use that as input into another calculation, then use that output as another input, on and on in a feedback loop, then the errors can accumulate and snowball out of proportion.

A common way this can happen is if you store a transformation matrix for each object, and accumulate changes to the transformation directly into that matrix, without any error-correction. This often manifests as a spinning object gradually flattening or distorting.

Switching to `double` only delays the issue a little, because it's really a problem with our algorithm, allowing small errors to self-reinforce and magnify up to visible scales. Maintaining a separate, authoritative source value, or applying error-correction as you go, like normalizing direction vectors, can stop these errors from piling up to visible scales.

# Answer
> 1 votes
It pretty much boils down to how precise you want your world to be. Do you need to be able to move exactly 1 mm at a time or are you fine with just a rough estimate? In most cases I would go with floats as they get the job done most of the time, while also allowing for your game to potentially run faster because you only need half the amount of data in cache. If your game is very physics oriented(think Kerbal space program) then I would suggest using doubles instead.

# Answer
> 0 votes
It may also depend on 3rd party framework, engines & libraries. I.E. if you use doubles on your data structures, but your library uses floats, you may find that your doing a lot of casting. In turn, this may impact:

* Performance: This SO post suggests (down) casting isn't likely to degrade performance. That being said, sometimes microbenchmarks don't accurately portray what happens in actual production code - always profile before & after attempts to optimize.
* Precision & Accuracy: Down casting involves a loss of data. Up casting floats essentially fabricates data. Depending on your needs, this may result in precision &/or accuracy problems.
* Readability: Unless you've tweaked your compiler / IDE settings, down casts must be explicit, which can clutter up your code & reduce its readability.
* Safety: If you have tweaked your settings to permit implicit down casts, you run the risk of allowing unwanted &/or dangerous down casts to slip through.

---
Tags: java
---


# Question
Title: Errors attempting to use Assimp in DirectX 12
I am trying to load a 3D model within a DirectX 12 project by means of Assimp, but even when I write only the importer function, I get errors I can not fix. How do I fix this?

---

Here is my code:

```
void Model::LoadModel(const std::string& FileName)
{
    Assimp::Importer importer;

    const aiScene* scene = importer.ReadFile("coso.fbx",
        aiProcess_CalcTangentSpace |
        aiProcess_Triangulate |
        aiProcess_GenSmoothNormals |
        aiProcess_SplitLargeMeshes |
        aiProcess_ConvertToLeftHanded |
        aiProcess_SortByPType |
        aiProcess_PreTransformVertices);

    if (scene == NULL)
    {

    }
}

```

---

Here are the errors I get:

> Error LNK2001 unresolved external symbol "public: struct aiScene const * \__cdecl Assimp::Importer::ReadFile(char const \*,unsigned int)" (?ReadFile@Importer@Assimp@@QEAAPEBUaiScene@@PEBDI@Z) Model.obj 1
>
> Error LNK2001 unresolved external symbol "public: \__cdecl Assimp::Importer::~Importer(void)" (??1Importer@Assimp@@QEAA@XZ) Model.obj 1
>
> Error LNK2001 unresolved external symbol "public: \__cdecl Assimp::Importer::Importer(void)" (??0Importer@Assimp@@QEAA@XZ) Model.obj 1

# Answer
> 1 votes
You need to add `assimp.lib` into the list of linked libraries. In Visual Studio's project properties it's in **Linker -\> Input -\> Additional Dependencies**. Also add its directory to `Additional Library Directories` in `General`.

---
Tags: directx, assimp
---


# Question
Title: LibGDX player movement on X axis is very limited
I'm making a side-scroller game using LibGDX, where player can move only on X axis. The problem is that the player can only move on positive X value, so he can't go to negative X. This is not that big of a problem, but the main problem is that where-ever I choose his initial position, he will never move right, so he basically can't extend his initial X value. I'm making movement with Gdx.graphics.getDeltaTime(), but when I don't use it, strangely everything works right. Other things work alright, the animation change works, test outputs worked, the problem always occurs only in the part of adding delta time to the x axis.

Player's initial position:

```
private Actor hiro;
hiro = new Hiro("Hiro", 106, 4, 32, 32);

```

(I'm not using LibGDX's Actor class, I made my own which uses animations)

Player's constructor:

```
public Hiro(String name, int x, int y, int width, int height) {
    super(name, x, y, width, height);
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    standingRightTexture = new Texture("hiro_standing_right.png");
    standingLeftTexture = new Texture("hiro_standing_left.png");
    walkingRightTexture = new Texture("hiro_walking_right.png");
    walkingLeftTexture = new Texture("hiro_walking_left.png");
    standingRight = new Animation(standingRightTexture, 1, 10f, true);
    standingLeft = new Animation(standingLeftTexture, 1, 10f, true);
    walkingRight = new Animation(walkingRightTexture, 8, 0.6f, true);
    walkingLeft = new Animation(walkingLeftTexture, 8, 0.6f, true);
    setAnimation(standingRight);
    state = State.STANDING_RIGHT;
    facingRight = true;
}

```

Player's movement:

```
if(Gdx.input.isKeyPressed(Input.Keys.D)){
        x += Gdx.graphics.getDeltaTime() * 6f;
        facingRight = true;
        state = State.WALKING_RIGHT;
        System.out.println(x);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.A)){
        x -= Gdx.graphics.getDeltaTime() * 6f;
        facingRight = false;
        state = State.WALKING_LEFT;
        System.out.println(x);
    }

```

Playing Screen's render method:

```
@Override
public void render(SpriteBatch spriteBatch) {
    cam.update();
    spriteBatch.setProjectionMatrix(cam.combined);
    spriteBatch.begin();
    hiro.getAnimation().update(Gdx.graphics.getDeltaTime());
    spriteBatch.draw(hiro.getAnimation().getFrame(), hiro.getX(), hiro.getY());
    moveCamera();
    spriteBatch.end();
}

```

If you want other segments of code, I'll provide it.

I greatly thank everyone whiling to help.

Edit: SOLVED! All I had to do was to use float axis instead of integer. Silly me!

# Answer
If you encounter a similar problem, be sure to always use float axis, not integer ones. When using integer, the game probably had problem with grounding the change of axis, since the Delta Time itself is float. Changing axis to float solved the problem perfectly.
> 0 votes

---
Tags: libgdx, movement, side-scroller
---


# Question
Title: How should I setup a vector class for a 2D game engine?
I'm at the beginning stages of building my first 2D game engine, and I'm not sure if I should setup my base 2D vector class as a `vec3(x, y, z)` or a `vec2(x, y)`

I might want to use a `vec3(x, y, z)` for adding z values, for ordering which objects would overlap other objects and still be visible. I'm also not sure if it's just easier to have a `vec3` for working with the transformation matrices and graphics libraries like OpenGL. This is my first game engine project, and I don't really know what is required for the long haul, in a 2D game.

How should I setup a vector class for a 2D game engine?

# Answer
> 2 votes
It would take less space in memory to use a Vec2 for things like game object position or scale (2 floats, instead of 3) which could be a win, but since this is your first 2D game engine I would just go with what feels best to you until you absolutely need to optimize. As far as rendering goes, it isn't that much of a hassle to move your x and y components into your graphics calls. As you mentioned, layering can become an issue. For a 2D engine I would probably have a separate field on my sprites for which render layer to use, and then draw each layer separately from back to front with a z value associated to that layer. Ex:(background z=-3, world z=-2, foreground z=-1, etc..)

Best of luck. Cheers :)

---
Tags: opengl, 2d, vector
---


# Question
Title: How to add a JSON object / model into your whitestorm world / scene?
I am loading the object from my json file.

```
var loader = new THREE.ObjectLoader();
loader.load("blue-car.json",
function ( car ) {
  car.position.set(2, 0, 0);
  car.addTo(world);
 }
);

```

How can I add the object to my world? In regular three.js it works when I load the json file, but how do I do it in whitestorm?

Update: I tried using the importScene whitestorm method. No errors but it still doesn't show up. Here is an image of logging out a regular plane in whitestorm and the car that is loaded from the json file.

Thank You!

# Answer
> -1 votes
Don't use the `THREE.ObjectLoader`, use `JSONLoader`, instead.

---
Tags: models, three.js, objects
---


# Question
Title: Why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix?
I'm working on a 2D game engine project, and I want to implement matrices for my transformations. I'm going to use the GLM library.

Since my game is only 2D, I figured I only need a 3x3 matrix to combine the translation, rotation and scale operations. However, `glm::translation` is only overloaded to return a 4x4 matrix, and never a 3x3.

I thought a translation could be performed by using a 3x3 matrix; why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix?

# Answer
You still need 4x4 for the projection matrix, even in 2D.

Typically you will use a combined MVP matrix in your shaders rather than separate matrices, so the calculations are easier (and faster - 4x4 is SIMD-friendly whereas 3x3 is not) throughout the pipeline if you just use 4x4 matrices everywhere.
> 3 votes

# Answer
Because GLM (as well as OpenGL) is designed to work for 3D graphics in the first place, and you need `mat4` to perform translations in 3D.

You could write a 2D translation function yourself. It's as simple as returning the following matrix:

```
1 0 x
0 1 y
0 0 1

```

Keep in mind that to use it you will need to have a `1` as the last component of your vectors (you don't need to actually store it, you may just add it temporarily before doing multiplication).
> 2 votes

---
Tags: opengl, matrix, glm
---


# Question
Title: If I purchase game assets from an artist, should I ask them to explicitly sign over all rights to the art?
To cover all worst-case scenario legal bases, does a developer need any form of written communication from an artist confirming both the purchase of, and explicit transfer of all rights to, the art assets used in a game?

It may be unlikely, but I wondered if a hypothetical vengeful artist could later decide to accuse a developer of unauthorized use of their art/copyright infringement if the art sale wasn't more explicit and "formal."

**Example**: A developer commissions an artist online, and receives an email containing game sprites in return for a PayPal payment to the artist. Would the developer have full legal rights to the art at that point, or are they still vulnerable to legal jabs?

# Answer
> A developer commissions an artist online, and receives an email containing game sprites in return for a PayPal payment to the artist.

In that statement, what would imply that the developer has now full rights over the art?

In that statement, what would imply that the artist has still full rights over the art?

It's not said that the artist wants the dev to only use the assets in a specific context, and since there is a transaction, it could be assumed that the artist allows the dev to use them... but it does not say anything about how they could use them.

My point is, if there is no formal agreement, it's easy for things to go wrong.

So to be on the safe side, agree on the license of the art, specifically the ownership of copyrights to the art, **before** anything else. Agree on what's going to be delivered (.psd, .png?), agree on the price, and agree on the dates, and agree on how the assets can be used (e.g. "I'd like to use it in game X, but also in game Y/you can use it in any of the game that *you* develop, but you can't resell the assets, unless you sell the whole IP."), again, **before** any work is done.

And have that written. Don't delete your emails. Store them so you can easily retrieve them. If you can have a written contract, that would be the best.

So yes, ask the artist to sign over all the rights to the art, but do it before they start to work.
> 0 votes

# Answer
By default, it is always the creator of the work, may it be art or program code, who owns it. By no means do you by default get more than a right to use it, if you purchase it without any further agreements. Additionally, that right may be limited to a particular way of use, if nothing else was stated.

If there is no separate agreement whatsoever, **do not expect to get "full rights" to the artwork just because you payed for it, even if it was custom-made solely for you**. That is not how it works. Any rights that extend over the (originator-favouring) default rights need to be agreed upon with at least something in writing, as Alexandre wrote in another reply. However, even a short text may change the constellation radically.

Open, honest and clear (in advance is not a bad idea either) communication is the absolutely best way to handle this. Both parties will easily understand each other if both for example are self-employed. After all, us freaks here *want* to do the work and have the fun.

---

Edit: Came to my mind, when speaking indies, that one could aim for a **parallel right** to the work. The word "exclusive" is always tricky. Parallel is good for the artist, who still holds his/her right to for example further develop he work, while you have all the freedom to do the same.
> 0 votes

---
Tags: assets, legal, art, copyright
---


title: XY rotation directions

text:
# Question
Title: XY rotation directions
I have a simple `W``A``S``D` controller to rotate the player, but if I press `W` and the player has been rotated by 20 degrees, it will only rotate around the x axis.

Yes, it's logical, but how I should I calculate rotation around the x and y axis?

# Answer
> 0 votes
You just have to use the trigonometric ratios. Lets say that you have rotated the character 20 degrees and you have a speed of 2 pixels per update.

```
PosX += cos(20)*2
PosY += sin(20)*2

```

In this example the x would increase with 1.88 pixels and the y would increase with 0.68 pixels per update.

---
Tags: mathematics, rotation
---


# Question
Title: Making an indie with friends: Legal considerations
I am close to finishing a game I am making with 3 friends. 1 other coder, and 2 graphic designers. We agreed from the start to split revenue (40/40/10/10).

However we have no contract, and I know that I don't own the graphics/sounds in my game just because "my friend made it". What steps should we take to make sure that all graphics/sounds that were provided by my friends, are actually owned by me (the company).

We have a budget of $0 so hiring a lawyer is not an option, should we draft our own contract regarding the revenue share?

# Answer
Verbal agreements are usually considered valid contracts. But there is an old saying among lawyers:

> A verbal contract isn’t worth the paper it’s written on.

The problem with verbal contracts is that when push comes to shove and someone goes to court, you have a word-against-word situation where everyone can claim that you agreed on something different and nobody can prove what you really agreed on. That's why it is usually a good idea to write your agreement down.

A few of the things you need to agree on:

* How do you split revenue?
* How do you split costs? And yes, if you want to promote your game, you will have to invest a bit of money sooner or later, even if it is just the subscription fee for the distribution platform.
* How much work is each of you expected to invest into the game in the future?
* Who owns what copyright? Keep in mind that you don't necessarily need to transfer copyright. You can agree to grant a non-exclusive perpetual license for using the work in the game.
* Who owns the trademark? Or in other words, if you decide to part ways, which one of you has the right to create a sequel?
* Games are never finished, just abandoned. What if some of you want to invest more work into the game to make it even more successful, but others don't feel like contributing anymore? Does that affect your revenue splitting agreement in any way?
* How do you make creative decisions about the game? When you come to a disagreement about a major mechanic, narrative or aesthetic aspect of the game, how do you resolve that conflict?
* How do you make business decisions about the game? Like where and when to release it, how to promote it, if you sell it to a publisher, to recruit more people, etc.
* What do you do if you decide to recruit more people for further development of the project? Do they also get a share (which would reduce the share of the others)? Or do they get paid a fixed amount?
* What happens when one of you wants out?
* What happens when two of you want the third person out?
* ...and a couple hundred more things I am not thinking about right now...

A lawyer's contribution is not required for a contract to be valid. But getting a lawyer to write that contract with you might still be a good idea. Legal writing requires a lot of attention to detail. It is easy to write something into a contract which doesn't actually mean what you all think it means. When you get into an argument and one of you decides to sue the others, the contract will be interpreted as written, not as what you thought it meant.
> 90 votes

# Answer
This response only addresses the revenue share aspect of the question.

I have found Back of a Napkin useful in the past. The (free) website is sponsored by a New Zealand law firm and steps you through five questions:

1. Who is in your team?
2. What are you building?
3. If your project makes money, what percentage stake do you each take home?
4. How will you make decisions?
5. What happens to the project if you break up?

You end up with a lightweight written agreement, which can be signed by the various team members. It is super-minimal as far as contracts go, but might work in the early stages of your company.
> 15 votes

# Answer
I think you should take a look at vesting.

It protects the other founders in case one (or more) of the founders isn't working as hard to achieve their goals on the project. It does that by not giving everything upfront, so you decide the milestones each one of you will have to achieve and when you achieve them, you get some of the shares you're entitled, so for example, you'll work your way to your 40%.

Let's say your first milestone is to deliver the first beta (extreme simplification here), and you agree that it will get you 1% of your shares. If one of you walk away before a certain period (this is defined by the founding team), say 2 years, then you get nothing. This stimulates everyone to dedicate to the project.

If you don't do this, someone could leave after one month and get their full share, while the other founders will have to keep working and this person who left will get the fruits of all your effort without doing a thing.

> What is founder vesting? Vesting means that at the very beginning each founder gets his or her full package of stocks at once to avoid getting taxed for capital gains; but, the company has the right to purchase a percentage of the founder’s equity in case he or she walks away. \[...\]
>
> In essence, vesting protects founders from each other and aligns incentives so everybody focuses towards a common goal: building a successful company.

This was in the first link I found when googling **vesting for startups**.

This article says:

> Note: The legal aspect of vesting varies significantly from country to country. So, contacting a lawyer to make a consultation is generally a good idea.

I'm not giving any legal advice. In my country you don't need a lawyer to do that. I think it's good if you structure a written agreement based on vesting, just check your local laws.
> 7 votes

# Answer
First, IANAL

With that out of the way I suggest that you create an entity. In the US a LLC would do. Then give all the assets (code, graphics, etc) to that entity. That way, no one can claim that the "duck model is theirs" and that you have to remove it from the game at some later date. Same with IP issues. If someone sues your LLC because your duck-crossing-the-road game is too much like theirs, the LLC is at risk, and not the one person that make the duck in blender.

With your assets in the LLC you just need a simple letter/contract of intent.

> Gross Revenue will be split with 40% going to Joe, 40% going to Jane, 10% going to Jack and 10% going to Bill. Liabilities will be shared in the same manor. If a time comes that investments need to be made, investments will be made at the same percentages. All works will belong to LLC Name Here. If any members of the group wish to stop participating in LLC Name Here, they will no longer receive revenues.

That should do what you want and offer "pretty good" protection. Keep in mind, that at some point you will want to hire a lawyer and accountant to help with these matters. But this should cover you for the short term.

You want to make sure you list your splits, the people involved, what happens if one of them wants out, and who is going to pay the bills.
> 2 votes

# Answer
The key thing is to get a written agreement of what everybody is expected to get out of the project and what they are required to contribute. This should also consider what happens if things go either better or worse than expected.

this does not necessarily have to be written in legalese, indeed the simple process of writing down how each person sees the project working may forestall any problems in the future. Often dispute happen not because any individual is being unreasonable but because peopel had different expectations and simply didn't realise that other people had made different assumptions.

Really important things to cover are :

* who owns the rights to copyright work produced by individuals ? Does it belong to the company or is it licenced to the game ? What happens of one copyright owner pulls out ?
* How are expenses paid for and how are profits distributed ? How is 'profit' defined ? Do you need to keep a pool of cash to cover ongoing expenses ? When can individuals take out their share of the value of the business in cash ?
* Who is responsible for any debts or liabilities ?
* How are creative and business decisions made ? How is the final decision made if there is a dispute ?
* How will you manage your accounts ? How do you verify that revenues and expenses are legitimate ?

As I have said simply having this sort of discussion and writing down what you decide is a lot better than nothing. Try to anticipate what potential problems and disagreements you might have and plan for them.

For example what happens if one of your team meets someone and decides to get married and move to the other side of the country ?
> 0 votes

---
Tags: legal
---


# Question
Title: How to create custom inspector to display generic Stack<T> class
I have a member that I would like to expose:

```
[Serializable]
private sealed class InputGameObjectStack: Stack<GameObject> {
    public InputGameObjectStack(): base(_InputGameObjectStackSize) {
    }
}

```

Inside the `MonoBehaviour`, I have:

```
[SerializeField]
private InputGameObjectStack _inputGameObjectStack;

```

Inside the editor script, I'm able to fetch the property from the `MonoBehaviour` object (as `SerializedProperty`), but there is *nothing* usable that allows me to traverse through the elements.

Is there any way of showing the constents of the stack in the inspector as immutable (no functionality to push/pop)?

# Answer
> 5 votes
# Use CustomEditor to display the content of your stack

## For Example

Assume we have the following class `TestScript`

**TestScript**

```
public class TestScript : MonoBehaviour {
    private Stack<GameObject> myStack = new Stack<GameObject>();
    void Start() {
        myStack.Push(new GameObject("Red Arrow"));
        myStack.Push(new GameObject("Green Ball"));
        myStack.Push(new GameObject("Blue Cake"));
    }
}

```

Create another class **inside the existing class** so it could access the private members, like so:

**StackPreview added *inside* TestScript**

```
public class TestScript : MonoBehaviour {
    private Stack<GameObject> myStack = new Stack<GameObject>();
    void Start() {
        myStack.Push(new GameObject("Red Arrow"));
        myStack.Push(new GameObject("Green Ball"));
        myStack.Push(new GameObject("Blue Cake"));
    }

    // This class is inside the TestClass so it could access its private fields
    // this custom editor will show up on any object with TestScript attached to it
    // you don't need (and can't) attach this class to a gameobject
    [CustomEditor(typeof(TestScript))]
    public class StackPreview : Editor {
        public override void OnInspectorGUI() {

            // get the target script as TestScript and get the stack from it
            var ts = (TestScript)target;
            var stack = ts.myStack;

            // some styling for the header, this is optional
            var bold = new GUIStyle();
            bold.fontStyle = FontStyle.Bold;
            GUILayout.Label("Items in my stack", bold);

            // add a label for each item, you can add more properties
            // you can even access components inside each item and display them
            // for example if every item had a sprite we could easily show it
            foreach (var item in stack) {
                GUILayout.Label(item.name);
            }
        }
    }
}

```

Now, in the editor you can see just the header (because we're adding items in the start function) - when you run the scene you get a nice list:

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


title: Position vs Destination Rectangle

text:
# Question
Title: Position vs Destination Rectangle
I'm new to programming, and I finally delved into XNA/MonoGame for wanting to practice coding game logic.

I'd like to know what the difference is between a Position (Vector2) and a Destination Rectangle (Rectangle), when it comes to positioning a sprite.

# Answer
> 5 votes
The simple answer is: the Vector2 positions the sprite at the X,Y coordinates, while Destination rectangle fills the sprite to *fit* that rectangle.

More advanced answer:

Sprites are in reality quads made up of two triangles, since underneath all this graphics stuff 3D routines are used. So both Draw methods transfer the sprite to a quad. This quad is basically a rectangle.

So what the Vector2 variant does is *create* a DestinationRectangle internally like this when calling SpriteBatch.Draw():

```
destrect = new Rectangle((int)V2.X, (int)V2.Y, Texture.Width, Texture.Height);

```

---
Tags: c#, xna, monogame
---


title: Java 3D Bounding box fixing

text:
# Question
Title: Java 3D Bounding box fixing
My player keeps sinking into objects when in right angle and when going to right way. It is hard to explain so I uploaded video about it on youtube. I am using min and max points to detect collision.

```
if(minX1 <= maxX2 && maxX1 >= minX2 && minY1 <= maxY2 && maxY1 >= minY2 && minZ1 <= maxZ2 && maxZ1 >= minZ2) {

        return true;

}

```

That code should be fine but somehow it doesn't work with my other stuff. Is there better easy way that I could detect collision using min and max points?

I am checking collision on every update.

# Answer
> -1 votes
I can't answer to you because I wasn't logged in while posting this. I am updating all bounding boxes on every update as you see it is working fine (except that one thing). And yes I use rotation matrix to calculate new min and max after rotation.

Please use https://stackoverflow.com/questions/42325860/3d-bounding-box-not-working-always and go ahead and delete this.

---
Tags: opengl, java, collision-detection, lwjgl
---


# Question
Title: How to change FPS during runtime in LibGDX?
I would like to be able to change the desired fps (`foregroundFPS`) during runtime without having to restart the game. I know how to set it before launch with `LwjglApplicationConfiguration` but I have no clue how to set it during runtime.

An example use would be in a menu where the player can select his FPS.

How can I do that ?

# Answer
So you want to change a member of a class in your desktop launcher from the code in your game. A very easy (but not scalable) way is to override a method of your game class in your launcher. So in your game class you add a method:

```
public class MyGame extends ApplicationAdapter {
    ...
    protected void setForegroundFPS(int value) {}
    ...
}

```

Then in your desktop launcher you override that method:

```
public class DesktopLauncher {
    LwjglApplicationConfiguration config
    public static void main (String[] arg) {
        config = new LwjglApplicationConfiguration();
        config.width = 1024;
        config.height = 768;
        new LwjglApplication(new MyGame() {
            @override
            protected void setForegroundFPS(int value) {
                config.foregroundFPS = value;
            }
        }, config);
    }
}

```

When you find yourself overriding a lot of method this way, then it's better to add an interface instead. See also: https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code
> 3 votes

---
Tags: java, libgdx, frame-rate
---


# Question
Title: Got garbage when getting shader compile log
I got garbage when trying to compile shader and get error log. I checked my code against some sample code, and could figure out where I did wrong.

Below is my code:

```
bool LoadShader(GLuint ShaderType, char const* ShaderFileName)
{
    os_file ShaderFile = OSReadFile(ShaderFileName);
    GLint ShaderHandle = glCreateShader(ShaderType);
    DebugPrint("Shader source: %s\n%.*s\n", ShaderFileName, ShaderFile.Length, ShaderFile.Contents);

    GLchar* ShaderSource = (GLchar*)&ShaderFile.Contents;
    GLint ShaderSourceLength = ShaderFile.Length;
    glShaderSource(ShaderHandle, 1, &ShaderSource, &ShaderSourceLength);
    glCompileShader(ShaderHandle);

    OSFreeFile(&ShaderFile);

    GLint Success;
    glGetShaderiv(ShaderHandle, GL_COMPILE_STATUS, &Success);
    if (!Success)
    {
        GLchar CompileLog[512];
        glGetShaderInfoLog(ShaderType, 512, NULL, CompileLog);
        switch (ShaderType)
        {
#define SHADER_TYPE_ERROR(ShaderType) case ShaderType: { DebugPrint(#ShaderType " Compile error!\n"); } break;
            SHADER_TYPE_ERROR(GL_VERTEX_SHADER);
            SHADER_TYPE_ERROR(GL_FRAGMENT_SHADER);
#undef SHADER_TYPE_ERROR
        }
        DebugPrint("%s\n\n", CompileLog);
        return false;
    }
    return true;
}

```

Below is some output:

```
Shader source: shader/fragment.glsl
#version 330 core

out vec4 Colour;

void main()
{
    Colour = vec4(1.0, 0.5, 0.2, 1.0);
}

GL_FRAGMENT_SHADER Compile error!
p��R�

```

# Answer
Change

```
glGetShaderInfoLog(ShaderType, 512, NULL, CompileLog);

```

To

```
glGetShaderInfoLog(ShaderHandle, 512, NULL, CompileLog);

```

Also consider using

```
GLint len = 0;
glGetShaderiv(ShaderHandle, GL_INFO_LOG_LENGTH, &len);

```

and allocating your text buffer using `len`.
> 1 votes

---
Tags: opengl, shaders
---


# Question
Title: Second glBindBuffer() call crashes program on Draw call
Background/Issue: I'm pretty new to openGL and I'm trying to create a game engine (for learning purposes) and my program keeps crashing on my glDrawElements() call but only after trying to set glBindBuffer a second time.

Code: Below is some of my code in my engine. Basically, I have two possible objects I can draw with my engine, a triangle and a square. I'm trying to first send initial shape data down to GPU buffers within my RenderSystem's Initialize function like so:

RenderSystem.cpp

```
bool RenderSystem::Initialize()
    {
        //Send triangle shape data down to GPU
        MyOpenGL::InitializeBuffers(ShapeData::Triangle().vertices.size(),
                   &ShapeData::Triangle().vertices.front(),
                   ShapeData::Triangle().indicies.size(),
                   &ShapeData::Triangle().indicies.front(),
                   triangleVertexBufferID , triangleIndexBufferID);

        //Send square shape data down to GPU
        MyOpenGL::InitializeBuffers(ShapeData::Square().vertices.size(),
                   &ShapeData::Square().vertices.front(),
                   ShapeData::Square().indicies.size(),
                   &ShapeData::Square().indicies.front(),
                   squareVertexBufferID, squareIndexBufferID);

        return true;
    }

```

The MyOpenGL::InitializeBuffers() function code is next:

```
void InitializeBuffers(int64 sizeOfGeometry, const void* GeometryDataFirstElement, int64 sizeOfIndicies, const void* indicieDataFirstElement, uint32 vertexBufferID, uint32 indexBufferID)
    {
        glGenBuffers(1, &vertexBufferID);
        glGenBuffers(1, &indexBufferID);

        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);

        glBufferData(GL_ARRAY_BUFFER, (sizeof(Vector2D) * sizeOfGeometry), GeometryDataFirstElement, GL_DYNAMIC_DRAW);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, (sizeof(uint16) * sizeOfIndicies), indicieDataFirstElement, GL_DYNAMIC_DRAW);

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 2, nullptr);
    }

```

Now, I want to call a draw function within my RenderSystems update() function which basically just calls this MyOpenGL::Draw() function:

```
 //Passing in which ever BufferID's I want to draw (square or triangle)
 void Draw(uint32 vertexBufferID, uint32 indexBufferID, uint16 numOfIndices)
    {
        glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);

        glDrawElements(GL_TRIANGLES, numOfIndices, GL_UNSIGNED_SHORT, 0);
    );

```

However, after the glDrawElements call my program crashes. If I remove the glBindBuffer functions then it works, calling the last buffer object I bound everything to. Why is my program crashing when trying to rebind to whatever object I want to draw?

# Answer
> 2 votes
Well I figured it out if anyone else has a similar problem in the future. I was passing in my triangle and square vertex and index bufferID's by value instead of by reference in my initializeBuffers() funciton. So temporary ID's where being used and then destroyed at the end of the function, leaving my global triangleBufferID's and squareBufferID's set to a default value of 0.

---
Tags: opengl, graphics-programming
---


title: How to move empty colliders?

text:
# Question
Title: How to move empty colliders?
I have 2D background in unity on which I would like to add multiple circle, box colliders. Assets are not separated. I have drawn assets on background.

How to move circle colliders with mouse or keyboard shortcut on the background? It's not very pleasant to define x,y position wherever needs to go for every collider.

# Answer
> 1 votes
# Use Custom Editor

Add the following code to the background game object:
**Important**: Must be named `MoveGizmo`

**MoveGizmo**

```
using UnityEditor;
using UnityEngine;

public class MoveGizmo : MonoBehaviour {

    [CustomEditor(typeof(MoveGizmo))]
    public class ColliderMove : Editor {
        private float moveSize = 0.2f;

        public override void OnInspectorGUI() {
            Collider2D[] cols = ((MoveGizmo)target).GetComponents<Collider2D>();
            moveSize = EditorGUILayout.FloatField("Move Size", moveSize);
            foreach (var col in cols) {

                // a header for each collider, stating its current offset (location)
                GUILayout.Label(col.offset.ToString());

                // horizontal group is for placing the buttons on the same row
                GUILayout.BeginHorizontal("", GUIStyle.none);

                // repeat button allows you to hold the mouse on the button
                // to continuously move the collider
                if (GUILayout.RepeatButton("<")) {
                    col.offset += new Vector2(-moveSize, 0);
                }
                if (GUILayout.RepeatButton(">")) {
                    col.offset += new Vector2(moveSize, 0);
                }
                if (GUILayout.RepeatButton("UP")) {
                    col.offset += new Vector2(0, moveSize);
                }
                if (GUILayout.RepeatButton("DOWN")) {
                    col.offset += new Vector2(0, -moveSize);
                }
                GUILayout.EndHorizontal();
            }

        }

    }
}

```

Note that I've also added a **Move Size** field so you can control the sensitivity of the move.

Adding this code to a gameobject will add the following buttons for each collider on that object:

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