title: 3D on GBA, how was it done?

text:
# Question
Title: 3D on GBA, how was it done?
I've been wondering, how did game programmers make this: https://youtu.be/S6huq2G43Ls?t=4368 possible?

There seems to be some odd morphing of textures when you walk by objects, and the textures are much higher than should be possible for normal 3D on the GBA. I'm assuming that programmers were hired to create a completely new rendering platform like DX and OpenGL. but how were they able to make graphics look nearly as good as their console (ps2, Gamecube) counterparts?

# Answer
It most likely is a raycast engine. Keep in mind the processor in a GBA is 25mhz ARM7 processor. Close to late 386 early 486 intel processors. Combined with the relative low resolution, enough power to software render a raycast scene.

Raycasting is a technique where each pixel is projected on a simple definition of a scene. Consider Wolfenstein3D and the first Doom games: they, like this game, existed before opengl was mainstream.

Google for raycast engine and you can find examples of this thechnique in less than 1000 lines of code.
> 2 votes

# Answer
Basically the GBA has no builtin support for 3D. This is unlike the DS (and modern GFX cards).

This is similar to comparable platforms, like the SEGA Mega Drive and Nintendo SNES which both have *somewhat* of the same specs/power as the GBA.

On such platforms you need to calculate the 3D graphics yourself, paint it to a buffer in RAM and then "blit" that buffer to the 2D format which the console actually does understand.

There's of course several libraries for this, so you don't have to know 3D math to the core. However, for performance reasons, these libraries are likely replaced by game-specific routines, that are optimized specifically for your own game. Often this code is written in ARM assembly, which is the GBA's "fast" mode.

If you're interested in the source code for such stuff, check out the demo scene for GBA, by google-searching "gba homebrew".

You mention PS2 and Gamecube. Both of these have builtin 3D support - Like the PS1 and N64 before them.
> 1 votes

---
Tags: 3d, graphics, software-engineering, mobile
---


# Question
Title: Why do all my matrices end up with the same values in this code?
My programme reads a binary file. For that I made a `Dictionary<int, float[]>` where int is order number (ID) and float\[\] is an array of important values. Here's my code how I read the binary file to my dictionary:

```
        inv_bind_mats = new Dictionary<int, float[]>();
        float[] Farr = new float[16];

        string path2 = Application.StartupPath + "\\skeletons\\" + skeletonName + ".bone_inv_trans_mats";
        using (BinaryReader inv_trans_mats = new BinaryReader(File.Open(path2, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.ASCII))
        {
            inv_trans_mats.BaseStream.Seek(4, SeekOrigin.Begin);
            bonesCount = inv_trans_mats.ReadUInt32();
            for (int i = 0; i < bonesCount; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    if (j < 12)
                    {
                        Farr[j] = inv_trans_mats.ReadSingle();
                    }
                    else if (j >= 12)
                    {
                        Farr[j] = 0.0f;
                    }
                }
                inv_bind_mats.Add(i, Farr);
            }
        }

```

It doesn't matter which ID I choose all float\[\] values are same for each. This binary file is an inverse matrix of skeleton bones. Each bone has 12 float values when I need to get 16 so I just add 4 more '0' values to what I get from file.

But the problem is all float values from inv\_bind\_mats\[i\]\[0-16\] to inv\_bind\_mats\[i\]\[0-16\] are equal.

How I want it to work: each bone has it's own matrix (float array) instead of one matrix for all bones.

# Answer
> 3 votes
In C#, arrays are reference types. That means that when they are passed around, the data in them points back to the original array. In your case here, you are adding the same array as the value to each entry in the Dictionary. Because of that, they are all pointing at the same array, which you are changing during each iteration of the loop.

If you wanted to use different, unrelated arrays for each value in the dictionary you would have to create a new array each iteration of your for loop.

---
Tags: c#
---


# Question
Title: Interpolation UNITY taking longer than expected
I'm trying to do multiplayer interpolations with the lidgren network (UDP) but the interpolation is taking longer than expected and the message queue is getting full. It's been a week and I still can't find the issue.

Here's an approximate code:

```
    private void Update()
    {
        if (networkUpdates.Count > 0 && CurrentUpdate.Finished)
        {
            var update = networkUpdates.Dequeue();

            CurrentUpdate = NextVesselUpdate;
            NextVesselUpdate = update;

            StartupInterpolation();
        }
    }

    private void StartupInterpolation()
    {
        CurrentVesselUpdate.NextUpdate = NextVesselUpdate;
        StartCoroutine(CurrentVesselUpdate.ApplyUpdate());
    }

    //In the CurrentVesselUpdate class....

    public IEnumerator ApplyUpdate()
    {
        InterpolationDuration = NextUpdate.SentTime - SentTime;
        for (float p = 0; p <= 1; p += (Time.delta / InterpolationDuration))
        {
            ApplyInterpolations(p); //Several lerps here
            yield return null;
            Finished = true;
        }
        ApplyInterpolations(1);//Several lerps here
    }

```

# Answer
> -1 votes
OK I finally solved moving the StartupInterpolation() to the fixed update and the other logic to the LateUpdate

---
Tags: unity, multiplayer, interpolation, lerp
---


# Question
Title: LibGDX - why are the shapes from my ShapeRenderer resizing with my viewport?
I have created a class called Node which I would like to (currently) contain a single Actor (later I will be adding additional actors, but for now I'm sticking with just one). The actor is called "body" and is just a container for the position/size of the "Node" actor.

I have also created a Label which I am drawing with a custom font file.

What I am having issues with is that when I RESIZE my app window (on desktop, I'm not currently using Android or any other targets), the LABEL works just fine (stays the same size on my screen), but the Node gets resized with the main window. That is, if I make the window twice as wide, the square stretches to be twice as wide as it was before. Why is this? The coordinates I am using work exactly as I expect UNTIL I resize the screen. Is there something else I have to do in the resize() method?

## App class:

```
public class App implements ApplicationListener {
    private Stage stage;
    private ShapeRenderer shapeRenderer;

    @Override public void pause() {}
    @Override public void resume() {}

    @Override
    public void create() {
        stage = new Stage(new ScreenViewport());

        shapeRenderer = new ShapeRenderer();

        //  FONT stuff  //  https://github.com/libgdx/libgdx/wiki/Gdx-freetype
        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/arial.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.color= Color.ORANGE;
        parameter.size = 24;

        BitmapFont arialFont = generator.generateFont(parameter);
        generator.dispose();

        Skin skin = new Skin();

        Label.LabelStyle labelStyle = new Label.LabelStyle();
        labelStyle.font=arialFont;
        skin.add("default", labelStyle);

        Label label = new Label("DOOT", skin);
        label.setX(110.5f);
        label.setY(110.5f);

        stage.addActor(label);

        stage.addActor(new Node(shapeRenderer));
    }

    @Override
    public void resize(int width, int height) {
        // See below for what true means.
        stage.getViewport().update(width, height, true);
        shapeRenderer.updateMatrices();
        System.out.println(""+width+"x"+height);
    }

    @Override
    public void render(){//} {
        Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void dispose() {
        stage.dispose();
    }
}

```

## Node class:

```
public class Node extends Group {
    private Actor body;
    private ShapeRenderer shapeRenderer;

    public Node(ShapeRenderer sr) {
        body = new Actor();
        body.setBounds(10.0f, 10.0f, 100.0f, 100.0f);
        shapeRenderer = sr;
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);

        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
        shapeRenderer.box(body.getX(), body.getY(), 0.0f, body.getWidth(), body.getHeight(), 0.0f);
        shapeRenderer.end();
    }
}

```

# Answer
You need to set the shapeRenderer projectionMatrix everytime you change your camera or viewport.

You could try to start by getting the projectionMatrix being used in the Batch.

`shapeRenderer.setProjectionMatrix(batch.getProjectionMatrix());`

Just like it's described here: https://github.com/libgdx/libgdx/wiki/Scene2d
> 3 votes

---
Tags: libgdx
---


# Question
Title: How should renderer class relate to the class it renders?
I am working on making a Pong clone as a practice project. I have a `PongState` class with members like `Ball`, `Paddle`, `Board` and `Score`. I want to structure my code so that each object doesn't have to know how to render itself, but a `PaddleRenderer` class will. I also want to create a `PongStateRenderer` class, which may use other classes like `PaddleRenderer`, as well.

How should I let `PongStateRenderer` know about the internals of `PongState` so that it can render it? The `Ball` object in `PongState` know's it's own position and size, does that mean `Ball` has to be a public member variable so that `PongStateRenderer` can also know the position, or is there a better way to do this without totally breaking encapsulation? Perhaps my architecture is totally wrong, and I should use a different method?

I'm working in C# as it says in the tag but a general answer that applies to many languages could also be helpful.

# Answer
> 4 votes
It sounds like you're just taking a baby step away from "objects render themselves" rather than moving all the way to an approach where something else renders the objects. When objects render themselves, every object (in this case a paddle, a ball, et cetera) has a `draw` method and some corresponding data. In your case you just appear to be moving that method and state into its own class, so you'd still have a `PaddleRenderer` and a `BallRenderer` and so on. I would argue this is inferior, as it doesn't really solve many of the problems associated with the "objects render themselves" approach.

Instead, I would encourage you to think more broadly: generally you can visually represent things in one of two broad classes: sprites or 3D meshes. Your renderer should know how to render sprites, and it should know how to render meshes. Let's say for simplicity everything in your game is represented and rendered as sprites. So you create a `Sprite` class that contains all the needed properties: references to textures, animation sequence information and current state, position, current sequence index, current frame index, et cetera.

Then you give your `Paddle` a `Sprite*`, and you give you `Ball` a `Sprite*`, and you configure the data on each sprite to be appropriate for the ball, or the paddle, or whatever else you want to put in the game. But the renderer just has this big homogeneous list of `Sprite` objects to render and that's all it concerns itself with.

Every tick of the game logic, you update the ball's position and the paddle positions and all of that. Once the logic tick completes, before you actually render, you can simply copy that position information into the appropriate sprite member before rendering. Likewise with any other state (for example maybe you update the sprite's tint color randomly every time the ball hits a paddle, for a psychedelic effect).

This approaches makes the "renderer" subordinate to the game logic, but that's reasonable. Generally in a game you'll have user input which directs the game logic, and then game logic which directs the rendering. Information (and responsibility) flows along those paths, but it *generally* does not flow in the other direction (the renderer usually does not influence the state of the game logic).

---
Tags: c#, architecture, rendering
---


# Question
Title: Drawbacks to an Octree and Quadtree hybrid?
I've implemented an octree to divide 3D space that contains several objects. I've noticed in certain octree nodes I could use more refinement in some axis, but splitting the node into 8 children is a bit overkill. Imagine a neighborhood full of buildings. At some point, it doesn't make sense in my case to further subdivide in height, but I need more precision in the other two axis.

Is there any major drawback to subdivide an octree cell into just 4 children, ie., subdividing in only two axis? This would create a hybrid between an octree and a quadtree.

I haven't found any documentation related to this, which seems strange to me, given it looks like a simple approach to a common problem.

# Answer
> 1 votes
A k-d tree like Philipp suggested would likely be a good solution, but certainly more complicated to implement. Your proposed solution should work fine, but you may need to be clever with how you store your child indices/pointers, if your goal is to save space.

If I were trying to solve this, given the limited information I have about your problem, I would create a different sort of hybrid. I'd use a quad tree along the horizontal plane, and then I'd use some other structure (an array of uniform buckets based on number of elements and extent, a binary tree, etc depending on need) to subdivide within a cell along the vertical axis.

# Answer
> 0 votes
Complexity and debugging would be the issue. Seems like a waste of time if you can avoid it. I made a spacial tree that was fairly complicated to make sure it could fit into one big array and query superfast and it was a giant pain.

I would consider instead to just use two quadtrees, one for everything at ground level and one a bit higher.

---
Tags: octree, quadtree
---


# Question
Title: How to convert applied torque or angular velocity angle to a positive 0 - 360 degree?
Objective

* To convert `body.getAngle()` to 4 direction (NSEW), when torque or angularvelocity is used

Because box2d body default angle is zero, I used it as reference to create my character direction. 0 degree means West, 90 degree North, 180 degree East and 270 is south, with a range of 45 degree. When I manually transform the body I get the right direction, but when I use the `body.setAngularVelocity()` or `body.applyTorque()` I get a different angle, which is more than 360 degree, assume `body.angle() * RADIAN_TO_DEGREE`. I am only expecting 0 to 360 degree without negative.

```
public static SteerDirection getDirection(float degreeAngle) {
    SteerDirection direction = SteerDirection.NONE;
    if(degreeAngle > 0 && degreeAngle < 22.5 || degreeAngle > 337.5 && degreeAngle < 360){
        direction = SteerDirection.WEST;
    }

    if(degreeAngle > 22.5 && degreeAngle <67.5) {
        direction = SteerDirection.NORTH_WEST;
    }

    if(degreeAngle > 67.5 && degreeAngle < 112.5){
        direction = SteerDirection.NORTH;
    }

    if(degreeAngle > 112.5 && degreeAngle < 157.5){
        direction = SteerDirection.NORTH_EAST;
    }

    if(degreeAngle > 157.5 && degreeAngle < 202.5){
        direction = SteerDirection.EAST;
    }

    if(degreeAngle > 202.5 && degreeAngle < 247.5){
        direction = SteerDirection.SOUTH_EAST;
    }

    if(degreeAngle > 247.5 && degreeAngle < 292.5) {
        direction = SteerDirection.SOUTH;
    }

    if(degreeAngle > 292.5 && degreeAngle < 336.5) {
        direction = SteerDirection.SOUTH_WEST;
    }

    return direction;
}

```

# Answer
You can convert angles that are beyond 0 and after 360 back to 0~360 by doing:

```
float angle = -180f;
angle %= 360f;
if(angle < 0) angle += 360;

```

That aside, I'm not really sure your cardinal directions are right. I'd assume you're better of forgetting about angles and converting them to vectors. Then you'll have a solid basis to work on. Take a look:

```
float angleInDegrees = 180f;
Vector2 direction = new Vector2(1, 0); //Put here your default direction with length 1. This usually is a vector. pointing right.
direction.rotate(angleInDegrees);
if(Math.abs(direction.x) > 0.707) { //a perfect diagonal in unit circle
    direction.x = Math.signum(direction.x);
} else {
    direction.x = 0;
}
if(Math.abs(direction.y) > 0.707) {
    direction.y = Math.signum(direction.y);
} else {
    direction.y = 0;
}

```

Now you have a vector pointing exactly to `(0, 1)`, `(1, 0)`, `(0, -1)`, `(-1, 0)`, `(1, 1)`, `(1, -1)`, `(-1, 1)` or `(-1, -1)`. The 8 cardinal points you described. You can easily convert this vector to your cardinal points if you wish.
> 1 votes

---
Tags: 2d, libgdx, rotation
---


# Question
Title: Generating grammatically correct MUD-style attack descriptions
I am currently working on a text based game, where the outcome of a combat round goes something like this

```
%attacker% inflicts a serious wound (12 points damage) on %defender%

```

Right now, I just swap %attacker% with the name of the attacker, and %defender% for the name of the defender. However, the description works, but don't read correctly. Since the game is just all text, I don't want to resort to generic descriptions (Such as "You use Attack on Goblin for 5 damage", which arguably solve the problem)

How do I generate correct descriptions for cases where %attacker% refers to

* "You", the player? "You inflicts..." is wrong
* "Bees", or other plural? I need somehow to know I should prefix the name with a "The "
* If %attacker% is a generic noun, such as "Goblin", it will read weird as opposed to %attacker% being a name. Compare "Goblin inflicts..." vs. "Aldraic Swordbringer inflicts...."

How does text-based games usually resolve such issues?

# Answer
The %attacker% approach can be extended to include some information other than just the names of the objects:

1. The verb may be singular or plural. This depends on the subject. "You **attack** X" (singular 2nd person subject) vs. "Extrakun **attacks** X" (singular 3rd person subject) vs. "The goblins **attack** X" (plural 3rd person subject). Most verbs just need an `-s` added but there are a few exceptions.
2. The noun may be a proper noun ("**Goblin** attacks X") or a common noun ("**A goblin** attacks X"). Common nouns starting with a vowel sound should use "an" instead of "a". It may be a common noun but having only one instance in the current context ("**The goblin** attacks X").
3. The noun may vary in number, from zero ("You hit **no goblins**") to one ("You hit **one goblin**") to many ("You hit **three goblins**"). Many nouns just need an `-s` or `-es` added but there are many exceptions.
4. Subjects and objects may be simple ("**A goblin**") or compound ("**A goblin and her brother**").
5. Common nouns at the beginning of the sentence need to be capitalized, but if the noun has an article or if it's compound you want to only capitalize the first word. Proper nouns are always capitalized.
6. The subject position ("**She** hit the goblin") and object position ("The goblin hit **her**") use different pronouns.
7. Possessives can be generated by adding `'s` if singular ("A **goblin's** axe"), `'` if plural ("Two **goblins'** axes"), but pronouns have their own rules ("**Your** axe").

For English, I wrote Python a text generation library derived from a MUD called JaysHouseMOO. Feel free to study or copy the code. It doesn't have a good library of exceptional cases; you'll have to add that with the words used in your game. I'm afraid my ported code isn't extensively tested. It might also need more cases added for games (it was designed for a social MUD, not a gaming MUD).

Your example would be written as `"%1I %1:(inflicts) a serious wound (%2n damage) on %3i"`. The numbers `%1`, `%2`, `%3` tell it which object is to be substituted; `I`/`i` tell it to add an indirect article ("a", "an") if needed; `n` tells it to display the noun without articles; `:(inflicts)` tells it to conjugate the verb for that object.

Here's the output to show to the attacker, the defender, and to everyone else:

```
$ python
>>> import msg
>>> m = "%1I %1:(inflicts) a serious wound (%2n damage) on %3i."
>>> attacker = msg.GenderedObject('Amit', 'm', 'proper')
>>> defender = msg.GenderedObject('goblin', 'm', 'unique')
>>> points = (12, 'point')
>>> msg.Msg().sub_parties({1: attacker, 2: points, 3: defender},
                          m, [attacker, defender])
(['You inflict a serious wound (12 points damage) on the goblin.',
  'Amit inflicts a serious wound (12 points damage) on you.'],
 'Amit inflicts a serious wound (12 points damage) on the goblin.')

```

Note if you had given it `(1, 'point')` it would have printed "1 point" instead of "1 points". That's something that bugs me in game text, so I made sure to include a feature to make it easy to print that properly.

Here's another example, with compound nouns, and "a" vs. "an":

```
>>> m = "%1I %1:(hits) %2'n %2'(head)."
>>> a1 = msg.GenderedObject('goblin', 'm', 'normal')
>>> a2 = msg.GenderedObject('orc', 'm', 'normal')
>>> d1 = msg.GenderedObject('Amit', 'm', 'proper')
>>> d2 = msg.GenderedObject('Extrakun', 'm', 'proper')
>>> msg.Msg().sub_parties({1: [a1, a2], 2: [d1, d2]}, m, [d1, d2])
(["A goblin and an orc hit your and Extrakun's heads.",
  "A goblin and an orc hit Amit's and your heads."],
 "A goblin and an orc hit Amit's and Extrakun's heads.")

```

These examples are in English, and only track male/female, pronouns, singular/plural verbs/nouns, and proper/common nouns. What you need to track will vary across languages and the type of text in your game. In Spanish there are formal and informal pronouns. Several languages have masculine and feminine forms of verbs. Japanese pronouns depend on the status of the subject relative to the object. In some languages the verb conjugation can implicitly include the subject. Determine all the kinds of text you want to generate and the languages you want to translate to, and that'll tell you what you need to track in your game objects. When you're creating the content, you can include the necessary annotations and exceptional cases.
> 15 votes

# Answer
Instead of having a single string, and trying to substitute into it properly, you could have a whole set of them. Start with the objects. You know, when creating the mob, what to refer to it as. You can give it a specific property, separate from it's name, for substituting into attack strings. Weapons can have multiple strings for variety, and can substitute in more detail. Instead of 'attacker', they can ask specifically for 'attacker-pronoun' or 'attacker-propername'. Mobs can have plural versions of these identifiers too, if your 'bees' are represented by multiple mobs and not just a single mob that happens to be called 'bees'.

So you would have a mob like

```
name = goblin
pronoun = he
plural = goblins
proper = goblin
common = a goblin
specific_common = the goblin
possessive = the goblin's
possessive_pronoun = his

```

Then your attack string asks for specific items like so..

%attacker-pronoun% hit %defender-specific\_common% for %damage%! %defender-pronoun% really felt that one!
> 6 votes

# Answer
There is a set of modules for Perl starting with Lingua::EN::Inflect that deals with these issues. Even if you're using a different language, the API choices made might help you frame your own design.
> 5 votes

# Answer
The way I handle this is through a large set of systemry that, among other things, involves modeling the message as a data structure rather than a string. The values for the attacker and the defender are their actual objects; the verb ("inflict" in your message) is marked as such, and knows the object for the person performing it, so that the message renderer knows that it needs to be displayed in first person to the actor and second person to everybody else. Objects also know whether their nouns are proper or not (and therefore, whether "the" or "a/an" should ever be applied to them), there are data models that allow me to specify that "the" or "a/an" would normally be expected to be applied to a non-proper noun in that position, and a lot more.

This thread on Mudconnector is very similar to your question, and I go into my system's details extensively there. Basically, the way I do it is what you would want if you want to be completely unconstrained by your messaging system's underlying capabilities and are willing to pay a price in learning curve for that. (Much like vi vs. nano.)
> 3 votes

# Answer
I would advise you to KISS (keep it stupidly simple), and exploit advantages of the text interface.

Simplify, simplify, simplify as much as you can. Remove complexity before you even start thinking about coding. Instead of one sentence, use two sentences to describe an event, like many games do. Do you remember Baldur's gate ? It's not a text game, but damage is described with text ;)

---

**Split the information between the source of the event and its consequence.**

For example :

* Merlin cast a spell of fireball.
* Madmax is hit with 3 damages of fire.
* A goblin is hit with 2 damages of fire.
* A goblin is hit with 10 damages of fire.
* etc...

---

**I would also advise to always use the third person singular, would it be either proper or common noun.**

Moreover, though English is an important international language, if you want to have more emotional impact, and touch a bigger market, you may need to translate your game in to other languages.

If you intend to do so, be aware that the sentence structure may be different in other languages. According to Wikipedia, 45% of the available languages build the sentence in the SOV (subject-object-verb) order, where 42% (like English) build the sentence in the SVO order; like english.
> 0 votes

---
Tags: mud, text-based
---


# Question
Title: Can I make color data not render as gradient?
I would like for the color between my vertices to not be rendered as a gradient, but as a hard break. Is there any way to accomplish this in OpenGL/GLSL?

# Answer
You can try doing this with `flat` attribute qualifier in shaders, like so:

```
flat vec3 surfColor;

```

It tells GLSL to pass values from vertex to fragment without interpolation.

From GLSL Interpolation qualifiers:

> Interpolation qualifiers control how interpolation of values happens across a triangle or other primitive. There are three basic interpolation qualifiers.
>
> **flat** The value will not be interpolated. The value given to the fragment shader is the value from the Provoking Vertex for that primitive.
> ...

Additional read on SO: https://stackoverflow.com/questions/27581271/flat-qualifier-in-glsl
> 7 votes

# Answer
These are two options I know:

1. **Define each triangle seperate with the color you want in each vertex**. Usually vertices are shared between neighboring triangles. If you make each triangle unique you can set the color of each vertex to the color you want the triangle to be. It increases the number of vertices, but unless you have a huge number of objects this is likely not a issue.
2. **Texture it**: make the texturemap of solid colors line up with the vertices and edges. Adds the benefit that you can recolor the model simply by changing the texture.

Both are often used in the 'flatshaded' look.
> 1 votes

# Answer
http://www2.imm.dtu.dk/pubdb/views/publication\_details.php?id=4884 "Single-pass wireframe rendering" describes a technique for rendering models in wireframe using barycentric coordinates.

http://codeflow.org/entries/2012/aug/02/easy-wireframe-display-with-barycentric-coordinates/ gives related code for the technique.

Barycentric coordinates are giving you the distance to each vertex, which could in turn be used to choose the color belonging to the vertex with the closest distance.

https://en.wikipedia.org/wiki/Barycentric\_coordinates\_(mathematics) describes how to compute the barycentric coordinates.

Once we have the barycentric coordinates of the point on the triangle, we compare the dimensions of the point and determine which one is the smallest. We use this information to index a uniform which holds the vertex colors.
> 0 votes

---
Tags: opengl, glsl, lwjgl
---


# Question
Title: What are the best practices when colaborating with an audio engineer?
I am talking with various audio engineers and each has pretty much their own rates and way of colaborating. Since I am pretty foreign to their world and work process, I want to have a healthy relationship, and a fair money/work exchange.

Thus I want to inquire on the copyright use of the music. Naturally, the first would be the right to use all the sountracks in the game, for trailers, promotional material, conventions.

Secondary, I am thinking explicit permission for streamers and youtubers & the like to use the music for their edited videos and as background music while playing or streaming, as long as they give credit and link to the website or game page.

Thirdly, the right to sell the music, as an addon, on the game page.

Different sound engineers expressed explicit fobidding the second and/or third bulletpoint, and I am sure there is a fourth and fith, sixth...etc. that I am missing. So my question is a bit more complex.

I am open to suggestions on improving my question, perhaps I failed to get the message through.

# Answer
> 1 votes
Copyright really is a nightmare. There are very possessive sound engineers with their work, but not all are like that. I am a sound engineer and to avoid me that problem. I prefer to charge for all the work, once, including license to resell (With a contract between), and the developer is responsible to use it as he wants.

---
Tags: audio
---


# Question
Title: How to use Actors/Groups with ShapeRenderer instead of Batch?
I am intersted in using Actors and Groups on a Stage so that I can make components and subcomponents which draw relative to their parents, but I intend to do my drawing with a ShapeRenderer instead of a Batch. From what I understand of an Actor, the batch which is passed in to the draw() method has all of its matrices set up properly so that I can just use a coordinate system WITHIN THE PARENT to lay out the subcomponents. But it seems that this coordinate system is focused on Batches, and I want to draw using a ShapeRenderer.

What do I have to do to get the child Actors to draw themselves RELATIVE TO THEIR PARENT (rather than in global coordinates) when drawing them with ShapeRenderers?

Also, one other question: How should I be managing begining/ending the ShapeRenderer? I am currently passing in a reference to a global ShapeRenderer when I construct my parent object, and this parent object passes in references to each of its children. Should I be calling begin() end() separately in the draw method of each parent/child actor? Or should I call it in my main app's draw() method, so I'm only calling it once each frame?

# Answer
> 5 votes
Here is my `HorizontalLine` class. If you create one, set it's width and weight (height) and you can add it to a container like `Table` or so. It will use it's `getX()` and `getY()` methods to draw itself on coordinates relative to it's parent.

This answer will also help you to understand: https://stackoverflow.com/questions/18075414/getting-stage-coordinates-of-actor-in-table-in-libgdx

```
public class HorizontalLine extends Actor {

    private ShapeRenderer sr;

    public HorizontalLine(float width, float weight, Color color){
        setSize(width,weight);
        setColor(color);

        sr = new ShapeRenderer();
        sr.setAutoShapeType(true);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);

        batch.end();

        Vector2 coords = new Vector2(getX(),getY());

        Color color = new Color(getColor());
        sr.setProjectionMatrix(batch.getProjectionMatrix());
        sr.setColor(color.r, color.g, color.b, color.a * parentAlpha);

        Gdx.gl.glEnable(GL20.GL_BLEND);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        sr.begin(ShapeRenderer.ShapeType.Filled);

        sr.rectLine(coords.x,coords.y,coords.x + getWidth(), coords.y, getHeight());
        sr.end();
        Gdx.gl.glDisable(GL20.GL_BLEND);
        Gdx.gl.glLineWidth(1f);
        sr.setColor(Color.WHITE);

        batch.begin();
    }
}

```

Also, you should end the batch, begin the renderer, end it, and begin the batch again in each actor cause otherwise it will mess up in future. Remember that `ShapeRenderer` calls are expensive. Remember to set `SR` and `Batch's` color back to white when you finish.

---
Tags: libgdx
---


# Question
Title: Best Way To Make Responsive UI Buttons in Unity
I've been stuck on this for quite some time. I'm trying to make a platformer game for android so I need some touch buttons. I made some buttons in Photoshop but I can't figure out how to make them move the player right. I've tried implementing the `IPointerDownHandler` interface but once I get the player moving I can't stop it, even if I call a function in `OnPointerUp` to set the players velocity to a new vector3 where all values are zero. I've also tried attaching event triggers to the buttons I made, but it's the opposite the player only moves for one frame and then I have to press the button again. I don't want to import any assets from the asset store and I don't want to use gui system. I want to learn how to do it myself. Thanks in advance. Here is the script in which I call functions from my PlayerController.

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

public class LeftButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public Image leftButton;

    private PlayerController player;

    private void Start()
    {
        leftButton = GetComponent<Image> ();
        player = FindObjectOfType<PlayerController> ();
    }

    public virtual void OnPointerDown(PointerEventData ped)
    {
        Debug.Log("LeftButton Pressed!!");
        player.moveLeft (-2);
    }

    public virtual void OnPointerUp(PointerEventData ped)
    {
        player.stopMoving ();
        Debug.Log ("Button Lifted!!");
    }
}

```

Here is my PlayerController script.

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    private Rigidbody2D myrb;

    // Use this for initialization
    void Start ()
    {
        myrb = GetComponent<Rigidbody2D> ();
    }

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

    }

    public void moveLeft(float moveSpeed)
    {
        myrb.velocity = new Vector3 (moveSpeed, myrb.velocity.y, 0f);
    }

    public void moveRight(float moveSpeed)
    {
        myrb.velocity = new Vector3 (moveSpeed, myrb.velocity.y, 0f);
    }

    public void stopMoving()
    {
        myrb.velocity = new Vector3 (0f, 0f, 0f);
    }
}

```

# Answer
You can simply do it by adding two `Event Trigger` with the UI buttons. One calls a public method for `PointerEnter`. Another calls a public method for `PointerExit`.

In the `PointerEnter` trigger call the method that moves the object and in the `PointerExit` trigger call the method that stops the movement.
> 1 votes

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


# Question
Title: Unity3d wheelcollider falling through terrain
I have created simple project with 3D car and terrain. I have added 4 Wheel Colliders on model wheels. But when I run project wheels falling through terrain.

Before run:

After run:

I am sure that at start wheel colliders above the terrain and not intersect it. Configuration is:

In what problem is? I have tried a lot of different things but I can't find a solution.

# Answer
> 3 votes
Do "not rotate" the WheelCollider components. WheelColliders are implemented as ray casted down, you can see the direction of the ray on selecting the same in the editor. To get more accuracy try tweaking Physics.minPenetrationForPenalty and Time.fixedTimeStep.

Edit: Noticed the rotation in your inspector window.

# Answer
> 0 votes
I had a similar issue, on a model imported from Blender. Blender uses a different axis than Unity, so the imported model had an x-rotation of -90 degrees and the wheel collider ray-casts forwards, instead of downwards.

To fix it, in Blender:

> In object mode, set the X rotation of your model to -90. Press `Ctrl` \+ `A` and apply rotation, X rotation appears to be 0 now in Blender, set it to 90 and save/export it. You'll see that it will appear both correct and at 0 rotations now.
> **<sub>\- Unity Answers: Rotation when importing from Blender</sub>**

---
Tags: unity, 3d, terrain
---


# Question
Title: Sprite loses quality when converted to texture in unity
So I have a sprite that is 750 (width) by 210 (height). I have put it in the game and adjusted the pixels per unit to match the scene size. But soon I realized that I need to use a texture to make the sprite appear to be scrolling.

When I did this I noticed a loss in quality when I made a quad and applied the texture to it. It seems that the sprite changes resolution when I make it a texture. It goes from (750px x 210px) to (512px x 256px) as seen in pic below:

As a sprite:

As a Texture:

I am a complete beginner to unity and need all the help I can get.

Let me know if you need any more info.

Thanks!

# Answer
> 1 votes
You are using the DXT1 compression settings after you changed it to a texture. Try using TrueColour or Automatic TrueColour option in the inspector, which will maintain the image quality. But it will also require more space

# Answer
> 1 votes
all textures in Unity are expanded into a power of 2 square. So your texture would be expanded to 1024x1024, which will cause ugly effects.

You should modify the texture into 1024x256, for example, so it expands cleanly to 1024x1024.

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


title: How do I roll a ball with a Rigidbody?

text:
# Question
Title: How do I roll a ball with a Rigidbody?
I have a ball in a game that rolls around just fine with `Rigidbody.AddForce()`. I have other non-physics balls, however, that I control directly with `Rigidbody.MovePosition()`.

It seems that no matter what I do, no matter how interpolation and collision detection are set, the ball does not "roll" when moved with `Rigidbody.MovePosition()`. It teleports, but `IsKinematic` is *not* set , as instructed by the documentation.

How do I get the ball to roll properly with `Rigidbody.MovePosition()`? Alternatively, if that's not possible, how do I calculate the rotations manually?

# Answer
> 1 votes
To make the ball move naturally, you should use `AddForce` (to make to move in a straight line) and `AddTorque` (to make it roll).

---
Tags: unity, physics
---


# Question
Title: movement control with the 2D driving game
I am working on a 2D driving game.I have a button(forward).I need to move the vehicle by pressing on the button. When the button is pressed the vehicle should accelerate upto its maximum speed and when the button is release the vehicle should gradually slow down.

```
float rotateSpeed=0.1f;
float speedForce = 15f;
float torqueForce = -200f;
float driftFactorSticky = 0.9f;
float driftFactorSlippy = 1;
float maxStickyVelocity = 2.5f;
float minSlippyVelocity = 1.5f;

bool moveForward=false;
bool moveBackward=false;
bool turnLeft=false;
bool turnRight=false;

Vector3 myRot;
void FixedUpdate () {
    Rigidbody2D rb = GetComponent<Rigidbody2D>();
    float driftFactor = driftFactorSticky;
    if(RightVelocity().magnitude > maxStickyVelocity) {
        driftFactor = driftFactorSlippy;
    }
    rb.velocity = ForwardVelocity() + RightVelocity()*driftFactor;

    //Move rover forward and backward
    if(Input.GetKey(KeyCode.UpArrow) || moveForward==true ||  Input.GetButton("Accelerate") ) {
        Debug.Log ("Uparrow....................................................");
        rb.AddForce( transform.up * 0.3f);

    }
    if(Input.GetKey(KeyCode.DownArrow) || moveBackward==true || Input.GetButton("Brakes")  ) {
        Debug.Log ("break....................................................");

        rb.AddForce( transform.up * -speedForce/30f );

    }
    float tf = Mathf.Lerp (0, torqueForce, rb.velocity.magnitude / 2);
    rb.angularVelocity = Input.GetAxis ("Horizontal") * tf;

    if (Input.GetKey (KeyCode.RightArrow) || turnRight==true) {

        transform.Rotate(0,0,-0.5f);
    }
    if (Input.GetKey (KeyCode.LeftArrow) || turnLeft==true) {
        transform.Rotate(0,0,0.5f);

    }

}

Vector2 ForwardVelocity() {
    return transform.up * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.up );
}

Vector2 RightVelocity() {
    return transform.right * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.right );
}

```

this is working fine but the problem is that when I release the forward button the speed of vehicle is not getting slow down.

Can anybody help me please

# Answer
> 1 votes
To make the vehicle slow down, you can use physics properties like drag and friction, or you can add a negative force (less strong than braking).

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


title: OpenGL Fast-Object Instancing Error

text:
# Question
Title: OpenGL Fast-Object Instancing Error
I have some code that loops through a set of objects and renders instances of those objects. The list of objects that needs to be rendered is stored as a std::map\>, where an object of class MeshResource contains the vertices and indices with the actual data, and an object of classMeshRenderer defines the point in space the mesh is to be rendered at.

My rendering code is as follows:

```
glDisable(GL_BLEND);
    glEnable(GL_CULL_FACE);
    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    for (std::map<MeshResource*, std::vector<MeshRenderer*> >::iterator it = renderables.begin(); it != renderables.end(); it++)
    {
        it->first->setupBeforeRendering();
        cout << "<";
        for (unsigned long i =0; i < it->second.size(); i++)
        {
            //Pass in an identity matrix to the vertex shader- used here only for debugging purposes; the real code correctly inputs any matrix.
            uniformizeModelMatrix(Matrix4::IDENTITY);
            /**
             * StartHere fix rendering problem.
             * Ruled out:
             *  Vertex buffers correctly.
             *  Index buffers correctly.
             *  Matrices correct?
             */
            it->first->render();
        }
        it->first->cleanupAfterRendering();
    }

    geometryPassShader->disable();
    glDepthMask(GL_FALSE);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);

```

The function in MeshResource that handles setting up the uniforms is as follows:

```
void MeshResource::setupBeforeRendering()
{
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    glEnableVertexAttribArray(3);
    glEnableVertexAttribArray(4);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); // Vertex position
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 12); // Vertex normal
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 24); // UV layer 0
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 32); // Vertex color
    glVertexAttribPointer(4, 1, GL_UNSIGNED_SHORT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 44); //Material index
}

```

The code that renders the object is this:

```
void MeshResource::render()
{
    glDrawElements(GL_TRIANGLES, geometry->numIndices, GL_UNSIGNED_SHORT, 0);
}

```

And the code that cleans up is this:

```
void MeshResource::cleanupAfterRendering()
{
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    glDisableVertexAttribArray(4);
}

```

The end result of this is that I get a black screen, although the end of my rendering pipeline after the rendering code (essentially just drawing axes and lines on the screen) works properly, so I'm fairly sure it's not an issue with the passing of uniforms. If, however, I change the code slightly so that the rendering code calls the setup immediately before rendering, like so:

```
void MeshResource::render()
{
    setupBeforeRendering();
    glDrawElements(GL_TRIANGLES, geometry->numIndices, GL_UNSIGNED_SHORT, 0);
}

```

The program works as desired. I don't want to have to do this, though, as my aim is to set up vertex, material, etc. data once per object type and then render each instance updating only the transformation information.

The uniformizeModelMatrix works as follows:

```
void RenderManager::uniformizeModelMatrix(Matrix4 matrix)
{
    glBindBuffer(GL_UNIFORM_BUFFER, globalMatrixUBOID);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(Matrix4), matrix.ptr());
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}

```

# Answer
> 2 votes
First of all, OpenGL is full of weird things so a driver bug, however unlikely it may be, is still an option - consider testing the app on different setups (nVidia vs. AMD, older drivers) and other tiny modifications of code. For example, you could start with removing the "glBindBuffer(GL\_UNIFORM\_BUFFER, 0);" line - it appears to be doing nothing useful anyway.

Since everything here appears to be correct, the problem is most probably not here. There are two options: gDEBugger and stepping through the code in the C++ debugger. It appears that something is being reset just before drawing. In gDEBugger, there's a "call history" feature which could help you see which calls were made before the draw call and in what order.

By the way, I strongly suggest you to wrap every error-returning call with a macro that checks for all possible errors and throws them. It has to be a macro to support extended debugging (printing file, line and the faulty line of code itself) that can be disabled in release builds. If some secret rule is broken, such setup should warn you of that immediately.

# Answer
> 0 votes
I am pretty sure the attribute should bind to the current buffer so there is no reason to be redoing this business with the attributes every frame unless you rebuild the buffer every time....

So you should probably do it one way or the other - either leave it be or rebuild the whole thing every frame.

# Answer
> 0 votes
TL;DR: Driver bugs.

In my tests as of today (Oct 2016) uniform buffers are **not supported properly** by most drivers out there.

Some don't respect `glUniformBlockBinding` some don't update the uniform data (`glBufferSubData` and `glBufferData`) properly, where the shaders' / GPU cached internal copies of said buffers are not kept coherent.

---

The way I understand it (and the way Nvidia also understands it)

* Bind/Map your Uniform Buffer Object to a **global table shared by all shaders** inside the OpenGL driver/GPU using `glBindBufferBase` or `glBindBufferRange`.
* Map the shader's uniform buffer accesses to an entry into that global table using `glUniformBlockBinding(shader_id, shader_ubo_index, global_ubo_index);` this setting is **per shader program**, not shared globally.

Note: global\_ubo\_index is NOT the name of the uniform buffer object but an index into that global table.

This "complexity" (which is a great feature to share UBOs between different shaders, such as lighting values) seem to be what most OpenGL drivers get wrong. To be fair the wording in the OpenGL documentation isn't the most unambiguous it could be either.

I had to resort back to using plain old uniforms for other drivers.

Both screenshots using uniform buffer objects, two different drivers:

---
Tags: c++, opengl, 3d, rendering, instancing
---


title: Unity XCode build linker error

text:
# Question
Title: Unity XCode build linker error
We are trying to build a Unity game in Xcode but keep getting this error:

> ld: '/Users/Pero/Documents/GitHub/MyGame/XCodeProject/Pods/GooglePlayGames/gpg-cpp-sdk/ios/gpg.framework/gpg(libgpg.a-armv7-master.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE\_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture armv7 clang: error: linker command failed with exit code 1 (use -v to see invocation)

We are using:

* Unity 5.1.1f1
* Xcode Version 7.1 (7B91b)

We have these frameworks included in the Xcode project:

* gpg.framework
* GooglePlus.framework
* GoogleOpenSource.framework
* GoogleMobileAds.framework
* CoreText.framework
* AdSupport.framework
* AudioToolBox.framework
* AVFoundation.framework
* CFNetwork.framework
* CoreGraphics.framework
* CoreLocation.framework
* CoreMedia.framework
* CoreMotion.framework
* CoreVideo.framework
* Foundation.framework
* iAd.framework
* MediaPlayer.framework
* OpenAL.framework
* OpenGLES.framework
* QuartzCore.framework
* SystemConfiguration.framework
* UIKit.framework
* StoreKit.framework
* CoreTelephony.framework

We also have Cocoapods installed and this is in our Podfile:

```
platform :ios, '7.0'
pod 'GooglePlayGames'
pod 'Google/SignIn'

```

We have tried searching the issue and none of the solutions we found did work. We have tried enabling and disabling the bitcode, Build Active Architecture Only, setting or deleting Search Paths… Here are some links:

xcode-5-1-missing-required-architecture-arm64

new-warnings-in-ios9

impact-of-xcode-build-options-enable-bitcode-yes-no

error-after-updating-to-xcode-7

xcode-7-and-enable-bitcode-yes-setting-does-not-work

apple-llvm-6-0-error-clang-failed-with-exit-code-1

It is our first time using Xcode. We have built the Android version from Unity with no problems.

There was also a problem with creating the Xcode project from Unity on a Mac (Unity kept crashing), so the Xcode project was created on a PC.

Thank you in advance

# Answer
I would suggest upgrading to the latest Unity 5 patch release (5.2.2p3) at the time of writing this and build your XCode project from the Mac. If Unity is crashing at that point chances are there is something inherently wrong with your project.

I would also suggest a clean of the Library and Obj folders, and even deleting your entire Xcode project and trying again.

If you have made sure you are using the latest version of the Google Play Game Services plugin, and you still get the error, I'm wondering if you are using the C/C++ version of the plugin from here? https://developers.google.com/games/services/ios/quickstart

If so, see if people have gotten it working with Unity, if not, perhaps look at the Prime31.com plugin for GPGS, as that definately works with Unity.
> 2 votes

# Answer
I was stuck with this same problem until 5 hours ago all you have to do is go to build setting in ur project and scroll down to build options when u see (enable bitcode) change it to no and there you go this worked for couple people if it does not work for you let me know i got a different idea
> 0 votes

---
Tags: unity, ios, xcode
---


title: Calculate experience for each kill

text:
# Question
Title: Calculate experience for each kill
I need a formula to calculate experience of players on each kill. It's based on the value of armor of the 2 opponents. For example if i kill the opponent and i've a total armor of 4000 gold and the opponent has a total of 450, i get less experience than if i had armor of 450 and opponent of 4000. I was thinking to something like ((my armor/opponent armor) / 100) + total damage, but doesn't give the result i would. I tried to search some good formula but i haven't found nothing. Thanks.

# Answer
If you're calculating based on the ratio of the armor values as in your formula, this means that if your opponent has armor twice as good as you, you get twice as much Xp

To do this, you would have a formula such as following:

(Enemy Armor)/(My Armor)\*Xp

Here the Xp is a base amount that you can choose. This is the Xp you get when you kill someone with armor just as good as yours.

In your formula you had the enemy armor and your armor switched. This means that if your opponents armor is twice as *good*, you would get twice as *less* Xp.

Also, you use Damage in your formula, I am however not sure why. Do you get Xp based on the damage you deal and not on kills? Because if that is the case, you can also give Xp based on solely the damage given. This way, if your opponents armor makes you have to give twice as much damage to kill him, you also get twice as much Xp. The formula would then be something like:

Damage/(Normal damage) * Xp

Where normal damage is the damage you have to deal to an armorless opponent and Xp is once again te 'base Xp'
> 1 votes

---
Tags: game-mechanics, mathematics
---


title: Buying music from an independent artist

text:
# Question
Title: Buying music from an independent artist
I have a concern regarding buying a song from an independent/amateur music artist. How can I demonstrate, if needed, that he actually sold that song to me and agreed to let me use his work for commercial purposes?! What if he decides, for a reason or another, to screw me saying that he didn't gave me authorizations?

The transaction etc. is made entirely online.

Thank you.

# Answer
You will need a written contract signed by both him and you. Print it, sign it, send it to him by snail mail, tell him to sign it, and have him send it back by snail mail.

Ask your lawyer to write such a contract.

When you don't want to use snail mail and stay completely electronic, ask your lawyer if it might work in your jurisdiction to print the contract, sign it and scan it with the signature.

You don't have a lawyer? Get one. The moment you start making business with 3rd parties you need one.

When you really want to avoid paying a lawyer (a decision which might bite you back later) you can still try to draft your own contract. Contracts are still valid when not written by legal professionals. But they will be treated as if they were, so you need to be really careful with what you write. When anyone decides to sue the other party, the contract will be interpreted word-for-word not by what you actually meant. Important information it requires:

* When, how, and how much do you pay him?
* Which song exactly do you get the rights to?
* What rights exactly?
    + For what purposes?
    + Just this project or any further projects?
    + For how long?
    + Exclusive / non-exclusive?
    + Are you allowed to edit it?
* (important!) What happens when the artist doesn't actually have the full rights to the song and a 3rd party sues you which claims the song violates their rights?
> 5 votes

# Answer
You have to state you will become owner of tracks and all copyrights and creative rights will be assigned to you. In such case the producer will transfer all his'/her' rights to you. Very important is that you agree on a flat fee and there will be no payments afterwards as all rights are bought by you in this deal.
> 0 votes

# Answer
I've worked on a lot of projects, online, with 8 years of experience making music for video games and as a music producer. Most of the time, I sign a contract where I scan my signature, and send the document back with my signature. I've never had any problems.
> -1 votes

---
Tags: music, commercial
---


title: 2D collision not working

text:
# Question
Title: 2D collision not working
I'm new to game programming and my first project is a platformer.

All things are going well, I draw the map, got the scrolling working, there's only one problem. I can't get the collision to work, I tried several things but can't find my own mistake.

It's probably a beginners mistake, could anyone help me out ?

My .cpp

```
// Include
#include "Application.h"
#include "FrameworkTest.h"
#include "Tile.h"
#include <iostream>

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/ext.hpp>

// Define
APPLICATION_ENTRY(FrameworkTest);
#define DEFAULT_SCREENWIDTH 1280
#define DEFAULT_SCREENHEIGHT 720
#define TileSize 64  // 64 x 64 tiles (pixels)

using namespace std;

// Vector with tiles
vector <Tile*> TileList;

FrameworkTest::FrameworkTest()
{

}

FrameworkTest::~FrameworkTest()
{

}

bool FrameworkTest::onCreate(int a_argc, char* a_argv[])
{
    // Background color
    setBackgroundColor(NHTV::SColour(0x204, 0x255, 0x255, 0xFF));
    AddFont("./fonts/invaders.fnt");

    // Player sprite
    m_iPlayerSprite = CreateSprite("./images/Player.png", 76, 68, false);

    // Store the screen size
    GetScreenSize(m_iScreenWidth, m_iScreenHeight);

    // Position the player
    MoveSprite(m_iPlayerSprite, m_iScreenWidth * 0.1f, m_iScreenHeight * 0.3f);

    // My Tiles, (9 tiles for now...)
    // 1 Corner left grass
    // 2 No corner grass
    // 3 Corner right grass
    // 4 Mud left corner
    // 5 No corner mud
    // 6 Mud right corner
    // 7 Crate (later on I want this to increase the score.)
    // 8 Direction
    // 9 Plain blue tile

    // Corner left grass tile
    // Create the sprite, give it dimensions, don't draw from center.
    unsigned int TileHandle = CreateSprite("./images/1.png", 64, 64, false);
    Tile* Temp = new Tile();
    Temp->TileHandler = TileHandle;
    // Put tile in TileList (vector)
    TileList.push_back(Temp);

    // No corner grass tile
    TileHandle = CreateSprite("./images/2.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Corner right grass tile
    TileHandle = CreateSprite("./images/3.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Mud left tile
    TileHandle = CreateSprite("./images/4.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Mud central tile
    TileHandle = CreateSprite("./images/5.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Mud right tile
    TileHandle = CreateSprite("./images/6.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Crate tile
    TileHandle = CreateSprite("./images/7.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Arrow Tile
    TileHandle = CreateSprite("./images/8.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    // Blue .png file (...)
    TileHandle = CreateSprite("./images/9.png", 64, 64, false);
    Temp = new Tile();
    Temp->TileHandler = TileHandle;
    TileList.push_back(Temp);

    return true;
}

void FrameworkTest::onUpdate(float a_deltaTime)
{
    // Position of player
    float xPos = 0; float yPos = 0;
    // Store position in xPos and yPos.
    GetSpritePosition(m_iPlayerSprite, xPos, yPos);

    // Collision

    float testX, testY;
    GetSpritePosition(m_iPlayerSprite, testX, testY);
    int test = TMap[(int)(yPos / TileSize)][(int)(xPos / TileSize)];

    if (test != 8)
    {
        xPos = testX;
        yPos = testY;
        cout << "TEST"<< endl;
    }

    // Scrolling
    GetSpritePosition(m_iPlayerSprite, MainScreenXpos, MainScreenYpos);
    MainScreenXpos = MainScreenXpos - (m_iScreenWidth / 2);
    MainScreenYpos = MainScreenYpos - (m_iScreenHeight / 2);

    if (MainScreenXpos < 0)
    {
        MainScreenXpos = 0;
    }

    if (MainScreenYpos < 0)
    {
        MainScreenYpos = 0;
    }

    if (MainScreenXpos >(30 * TileSize) - m_iScreenWidth)
    {
        MainScreenXpos = (30 * TileSize) - m_iScreenWidth;
    }

    if (MainScreenYpos > (30 * TileSize) - m_iScreenHeight)
    {
        MainScreenYpos = (30 * TileSize) - m_iScreenHeight;
    }

    // Stable movement
    float deltaTime = GetDeltaTime();
    float moveSpeed = 400.0 * deltaTime;

    // Player input
    // Right
    if (IsKeyDown(NHTV::KEY_RIGHT))
    {
        MoveSprite(m_iPlayerSprite, xPos + moveSpeed, yPos);
    }

    // Left
    if (IsKeyDown(NHTV::KEY_LEFT))
    {
        MoveSprite(m_iPlayerSprite, xPos - moveSpeed, yPos);

    }

    // Up
    if (IsKeyDown(NHTV::KEY_UP))
    {
        MoveSprite(m_iPlayerSprite, xPos, yPos + moveSpeed);
    }

    // Down
    if (IsKeyDown(NHTV::KEY_DOWN))
    {
        MoveSprite(m_iPlayerSprite, xPos, yPos - 4.0f);
    }

    // ESC
    if (IsKeyDown(NHTV::KEY_ESCAPE))
        destroy();
}

void FrameworkTest::onDraw()
{
    clearScreen();
    float fDeltaT = GetDeltaTime();
    int XscreenOffset = MainScreenXpos / TileSize;
    int XcellOffset = (int)MainScreenXpos % TileSize;

    // Draw my tiles,
    // column and row, loop, loop

    for (int ROW = 0; ROW < (m_iScreenHeight / TileSize) + 1; ROW++)
    {

        for (int COLUMN = 0; COLUMN < (m_iScreenWidth / TileSize) + 1; COLUMN++)
        {
            MoveSprite(TileList[TMap[ROW][COLUMN + XscreenOffset]]->TileHandler, (COLUMN*TileSize) - XcellOffset, m_iScreenHeight - (ROW*TileSize));
            DrawSprite(TileList[TMap[ROW][COLUMN + XscreenOffset]]->TileHandler);
        }

    }

    // tmap = 24248523854835
    //TileHandle = CreateSprite("./images/2.png", 64, 64, false);
    //Temp = new Tile();
    //Temp->TileHandler = TileHandle;
    //TileList.push_back(Temp);

    //Draw player
    DrawSprite(m_iPlayerSprite);

    // Draw HUD
    SetFont("./fonts/invaders.fnt");
    DrawString("SCORE", m_iScreenWidth * 0.725f, m_iScreenHeight - 2, 1.0f, NHTV::SColour(0x204, 0x255, 0x255, 0xFF));          // I want to use this later on to display my score.
    DrawString("Platformer", m_iScreenWidth * 0.8f, 38);                                    // Name of the game.

                                                                                // Deltatime frame
    std::string timeFrame = "DeltaTime: ";
    timeFrame.append(std::to_string(fDeltaT));
    SetFont(nullptr);
    DrawString(timeFrame.c_str(), 10, 720, 0.75f, NHTV::SColour(0x204, 0x255, 0x255, 0xFF));

}

void FrameworkTest::onDestroy()
{

}

```

My .h

```
#ifndef __Tutorial1_H_
#define __Tutorial1_H_

#include "Application.h"
#include <glm/glm.hpp>

// Application class wrap
class FrameworkTest : public NHTV::Application
{

    // Make public
public:

    FrameworkTest();
    virtual ~FrameworkTest();

    // Scrolling
    float MainScreenXpos, MainScreenYpos;

    // Level (14 height, 50 width.)
    int TMap[14][50] =
    {
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 1, 1, 1, 1, 2, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 1, 1, 1, 1, 2, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 },
        { 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8 },
        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
        { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 },
        { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 },
        { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 3, 4, 4, 4, 4, 5, 8, 8, 8, 8, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 },
    };

protected:

    virtual bool onCreate(int a_argc, char* a_argv[]);
    virtual void onUpdate(float a_deltaTime);
    virtual void onDraw();
    virtual void onDestroy();

private:
    // ScreenSize
    int m_iScreenWidth;
    int m_iScreenHeight;

    // Player
    unsigned int m_iPlayerSprite;
    unsigned int m_Enemy;
    unsigned int m_Coin;
};

#endif // __Tutorial1_H_

```

My game looks like this right now, don't be fooled by the players position, there's no gravity and the starting point is above a tile, no collision happening here.

# Answer
As far as I can see you are first of all testing what block your sprite position is in, so not what block you're standing next to or on top of. This means that if you want to stop the player if it collides, it will be already in the block.

If this position is the corner of your sprite, it is important to keep in mind that this means that you only test collision on one corner and not the opposite one. This means that if you're xpos and ypos are in the bottom left corner, you are not testing for the other side. This means that your entire right side can be inside a block, and you still won't detect collision. This can be solved by simply also checking collision for the other corner(s).

If you want the code to reset the position of the sprite when colliding, based upon your code, you will get something like this:

```
float testX, testY;
GetSpritePosition(m_iPlayerSprite, testX, testY);

//for Y (with original X)
int test = TMap[(int)(yPos / TileSize)][(int)(originalX / TileSize)];

if (test != 8)
{
    yPos = originalY;
    cout << "TEST_Y"<< endl;
}

//For X (with original Y)
int test = TMap[(int)(originalY / TileSize)][(int)(xPos / TileSize)];

if (test != 8)
{
    xPos = originalX;
    cout << "TEST_X"<< endl;
}

//For X and Y
int test = TMap[(int)(yPos / TileSize)][(int)(xPos / TileSize)];

if (test != 8)
{
    xPos = originalX;
    yPos = originalY;
    cout << "TEST_XY"<< endl;
}

```

Where originalX and originalY are the xPos and yPos before the movements.

Note that you will have to do x and y separately, otherwise the x position will also reset if you collide with a block below you because gravity wants to move you down. In the end you do test for both, but if in one of the former the xPos or yPos has already been reset, this code will be the same as one of the first two sets. The last test is only necessary of you move diagonally from one block to another.

If you want to test for the other corners, you just add the sprite width to xPos and/or add the sprite height.
> 0 votes

---
Tags: opengl, c++, collision-detection, platformer, glfw
---


title: Multi touch gesture terminology

text:
# Question
Title: Multi touch gesture terminology
What term would you use to describe the type of touch gesture whereby the user touches a point on screen, and an object moves (ease-out) to the location where the finger is touching the screen?

Can you tell me the names of the different types of multi-touch gestures (screen-based) such as tap, swipe, etc.?

# Answer
> 0 votes
### You seem to be describing a *single press* gesture.

I would call it a ***single press***. I believe your understanding of *touch gestures* might be wrong, as I would not call the event you describe a *touch gesture*. I would call it a *response* to a particular touch gesture.

---

### Let's break down your description into the *action* and the *reaction*.

> the user touches a point on screen

That, in itself, completely describes the event where the user interacts with the screen. This describes the interaction where a user simply touches the screen; a ***single press***.

> an object moves (ease-out) to the location where the finger is touching the screen

This is your *reaction* to the gesture of touching the screen. If you wish to describe the *event*, I would call it a "mouse follow" or "beacon follow", where your element follows the *mouse cursor* (excuse the analogy) or a *beacon* that you place down during your input.

---

### Gesture terminology

> Can you tell me the names of the different types of multi-touch gestures (screen-based) such as tap, swipe, etc.?

To me, this appears to be a difficult question, especially given the lack of context. Do you simply wish to know of the *alternates* available to you through a multi-touch input device, or do you actually wish to know for the purpose of deliberately implementing them? Different platforms can have different names for the same gesture, and as a result, names you hear might be *correct* but not actually *work* if taken literally in implementation.

* Slide
* Drag
* Swipe
* Press
* Long press
* Multi-press
* Press and hold
* Pinch in
* Pinch out

---
Tags: mobile, terminology, multitouch
---


# Question
Title: how are the vertex properties of meshpart decided based on model format in xna
Exactly how the question says , how does the vertex properties like vertex stride and the data stored in the mesh part decided based on the format of a model and how would i determine that and then decide which vertexdeclaration to be used properly

For ex - a .obj model might or might not have vt data , vn data based on which it may have a different data in the meshpart . How would i go about deciding which vertex declaration to use to properly decode the data in that mesh's vertex buffer

# Answer
What I do in cases like this is just use the same vertex declaration but just set the missing elements to zero.

I use assimp for all my mesh importing so it will be a bit different but I just check like this:

```
  Dim hasTexCoords As Boolean = mesh.HasTextureCoords(0)
  Dim hasColors As Boolean = mesh.HasVertexColors(0)
  Dim hasNormals As Boolean = mesh.HasNormals
  Dim hasTangents As Boolean = mesh.Tangents IsNot Nothing
  Dim hasBitangents As Boolean = mesh.BiTangents IsNot Nothing
  Dim hasBW As Boolean = mesh.Bones IsNot Nothing

        Dim Verts As New List(Of PCTNTBNSkinned_ImportType)
                For i As Integer = 0 To mesh.VertexCount - 1
                    Dim Vertex As New PCTNTBNSkinned_ImportType
                    Vertex.Position = FromVector(mesh.Vertices(i))
                    If hasColors Then
                        Vertex.Color = FromColor(mesh.VertexColorChannels(0)(i))
                    End If
                    If hasNormals Then
                        Vertex.Normal = FromVector(mesh.Normals(i))
                    End If
                    If hasTangents Then
                        Vertex.Tangent = FromVector(mesh.Tangents(i))
                    End If
                    If hasBitangents Then
                        Vertex.BiNormal = FromVector(mesh.BiTangents(i))
                    End If
                    If hasTexCoords Then
                        Vertex.TexCoord = New Vector2(mesh.TextureCoordinateChannels(0)(i).X, mesh.TextureCoordinateChannels(0)(i).Y)
                    End If
                    Verts.add(Vertex)
                 next

```

that way if my shader needs an element its there and I can just add another processing step to my mesh importing to add the missing data.

You end up with a bit of waist if the shader u are using doesn't need all that vertex data u are sending but at lest it gets u up and running.

90% of my meshes use the same shader so for me its not an issue
> 1 votes

---
Tags: xna, graphics-programming
---


# Question
Title: How would I make my Python game Moddable?
before you mark it as duplicate, I want to say I have read this: I want to make a moddable game. How does this affect my programming language choice?

And it did not help me. Just for proof of concept, what would I add to

```
# main.py
import turtle as t
screen = t.Screen()
turt = t.Turtle()
for i in range(8):
    t.forward(100)
    t.right(45)
    t.backward(75)
screen.exitonclick()

```

to make it so that in another file, you could add something like

```
import main
main.t.color("red")

```

to make the turtle a different color.

Basically, what would I add to `main.py` to make it run the mod settings?

# Answer
> 1 votes
Haha. Solved my own problem in less than 10 minutes.

So what I really wanted to do was to make a simple game modifiable.

So I created this (not necessarily smart or safe) method of making a configuration file that could be used for "modding".

This is what it looks like:

```
# main.py
import turtle as t
screen = t.Screen()
turt = t.Turtle()
cfg = open("mods.py","r")
cfg = cfg.read()
cfg = cfg.split("\n")
for i in range(len(cfg)):
    if i < len(cfg):
            exec(cfg[i])

for i in range(8):
    turt.forward(100)
    turt.right(45)
    turt.backward(75)
screen.exitonclick()

```

and in mods.py:

```
turt = t.Turtle()
turt.color("red")

```

Now before everyone gets all up in my face for using `exec`, let me just say that for a solution that was thought of quickly, I am okay with it. Plus, it wouldn't be that hard to add some sort of portection, ie `if "os" not in cfg[i]: exec(cfg[i])` and all of that would really just be a matter of time consumption.

I had to add `if i <len(cfg):` because when I split at the `\n` that was adding a blank element at the end of the list it generated. I doubt that would raise an error, but no harm in being a little extra cautious.

Overall, I'm glad with my solution... I'll add security detection and stuff but as of right now it will work, because the game I am working on will not be a public game.

---
Tags: python, modding
---


# Question
Title: How do I implement the functionality of Game Makers point_direction() function?
I am trying to understand the logic behind Game Maker's `point_direction(x1, y1, x2, y2)` function, which takes the vector from `(x1, y1)` to `(x2, y2)` and returns the counter-clockwise angle it forms from the positive x-axis, in degrees.

(Diagram from the YoYo Games documentation of `point_direction`)

How do I implement this functionality in my own code?

Here's my attempt so far:

```
//custom_point_direction script

var x1 = argument0;
var y1 = argument1;
var x2 = argument2;
var y2 = argument3;
var targetAngle;

targetAngle = radtodeg(arctan2(y2,x1));

return -targetAngle;

```

Here's an example of how I want to use this function. This is the step event of an object that should face/point towards the player object:

```
direction = custom_point_direction(x,y,player_obj.x,player_obj.y);
image_angle = direction;

```

This does not work like GameMaker's `point_direction()` function. How do I make my `custom_point_direction()` work similar to `point_direction()`?

# Answer
> 2 votes
You missed `y1` and `x2` which not used in your formula, it must be

```
arctan2(y1 - y2, x1 - x2)

```

For same with GM you can use this formula:

```
-radtodeg(arctan2(y1 - y2, x1 - x2)) + 180;

```

See a small example.

---
Tags: game-maker
---


# Question
Title: libgdx calculate vector to find new points
I am working with vector2 in libgdx. I have (x1,y1) and magnitude 'M' with an angle 'D'. How could I calculate (x2,y2) using vector2.

Thank You

# Answer
If you want to create a box structure from a point, just take that point and add the width and height to the corresponding values to find the other points.

You'll need 4 points so:

```
top-left: (x1, y1)
top-right: (x1 + boxWidth, y1)
bottom-left: (x1, y1 + boxHeight)
bottom-right: (x1 + boxWidth, y1 + boxHeight)

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: how to create an outlined polygon with vector3 coordinates?
I have a set of vector3 coordinates and I use them to draw a polygon in another app, my question is: how can I calculate a second set of coordinates to make it look like the line is outlined.

in the above picture, the blue dots are the vector3s I have and the red dots are the one I need, can anyone help me with an algorithm or formula to calculate them?
thanks

# Answer
> 3 votes
**1)Find barycentric coordinates**

```
for(int i = 0; i < verticesInPolygon; i++)
{
    bary.xyz += vertices[i].xyz;
}
bary.xyz /= verticesInPolygon;

```

**2)Create new vertices using this formula**

```
newVertex.coord = (vertices[desiredVertexInPolygon].coord - bary.coord)*offset+bary.coord;

```

Where `coord` is a desired coordinate(`x`, `y` or `z`) and `offset` is a scalar determining how far from the barycenter and how close to the original vertex a new vertex will be, i. e. 0.5 would make it appear right between, making new polygon being a half size of the original.

UPDATE: So, you need a constant offset to make outline, right? Here is a way to do it.

**1)Find barycentric coordinates**

We already know how to do this.

**2)Find a unit direction vector from barycenter to the original vertex**

```
dir.xyz = normalize(vertices[desiredVertexInPolygon].xyz - bary.xyz);

```

**3)Create new vertices with a following formula**

```
newVertex.xyz = vertices[desiredVertexInPolygon].xyz + dir.xyz * offset;

```

Where `offset` is now a real distance rather than scalar.

Note that in your case you should use a negative offset value, because you want outline to be inside the polygon.

---
Tags: unity, c#, algorithm, coordinates, mathematics
---


title: Feasibility of nested voxels

text:
# Question
Title: Feasibility of nested voxels
Out of curiosity, does anyone know how feasible it would be to have a voxel engine that allowed for voxels within other voxels? For example, you would have the usual chunks filled with voxels, but instead of stopping there each voxel could become a chunk of it's own to store more, smaller voxels. The first use case that comes to mind would be for showing damage to voxels, but there could be others, such as smoother terrain. Thoughts?

# Answer
> 1 votes
It's absolutely feasible. Go and look up octrees and KD-trees. These are just two ways of nesting voxels. These were already used in the 1990s in certain voxel applications. You could also use uniform grids and thus restrict the recursion depth to 1 or 2 levels, which may lead to better cache performance with simpler code. Good luck!

---
Tags: performance, voxels, data-structure
---


# Question
Title: Creating a 2D sidescroller with different behavior in each level
I'm creating a game with levels built from tilemaps in LibGDX. I've created the logic for the game that adds entities based on object layers, however, many levels have different behaviors. Do I need to create a separate class for every single level, or should I build in logic to handle every possible scenario in the class that loads levels?

# Answer
That depens on what exactly changes. If for example variabels change, such as the acceleration for Gravity, you could run a short piece of code to change this variable. You then store this variable in the class where you start a new level from. This way is pretty fast, so if you can make it that the behavior depends on a variable, you can try this.

If entire formulas change, you can deal with it by making a for loop which chooses the formula based on the level, but then this needs to be run every game loop. A more efficient way would be to use different classes like you said. This does not decrease preformance, but it does increase the size of your game.
> 0 votes

---
Tags: 2d, libgdx, platformer, levels
---


# Question
Title: Why is perlin noise generating flat terrain in Unity?
I am trying to generate terrain using perlin noise however the terrain being generated is a plateau. Here is the code that I'm using:

```
var xlength = 65.0;
var ylength = 65.0;
var scale = 4.1f;
var heights = new float[xlength, ylength];
function Start () {
    for (var i = 0; i < xlength; i++)
        for (var j = 0; j < ylength;j++)
            heights[i,j] = Mathf.PerlinNoise(Time.time * i / xlength * scale/1000,Time.time * j / ylength * scale/1000)*i*j;
    gameObject.GetComponent(Terrain).terrainData.SetHeights(0,0,heights);
}

```

What am I doing wrong here?

# Answer
> 1 votes
If you want seamless 'chunks', then you should evenly sample between whole integers.

```
 heights[i,j] = Mathf.PerlinNoise(i / xlength, j / ylength);

```

And resulting data must be between 0..1 (so don't scale it here).

> heights: Array of heightmap samples to set (values range from 0 to 1, array indexed as \[y,x\]). **<sub>\- Unity Documentation: TerrainData.SetHeights</sub>**

---
Tags: unity, procedural-generation, unityscript, perlin-noise
---


# Question
Title: LibGDX - Rendering things in different classes
thanks for your time!

I'm really new to LibGDX (and Java itself).

Which approach should I use to render my different game parts? I want to show a background, the main character, a bunch of enemies and an HUD. The playable area will be bigger than the screen so the camera has to move following the main character (top view). Also everything has to be procedurally generated.

For example, I have the code to generate the map (background) but I don't know how to render it if it's in another class (not the core entry point one). I can think of calling a custom background.draw() method from my main.render() class and pass a batch to draw onto but probably there are better ways. I've tried to use Stages (scene2D) aswell but I can't get my camera to move (are they mostly made for UI?).

I'd like to be pointed towards the best solution performance-wise since it's gonna be called every frame :P

# Answer
just send a reference to the other class with the main class.

like this:

```
Otherclass(myGame game) {... code}

```

Now you can access render here.
> 1 votes

# Answer
Using SpriteBatch is likely going to be the best option. Passing your batch as an argument to another class' method is generally not going to have any noticeable performance impact. This is also a very easy way of going about the problem because you can just call batch.draw() on your textures inside the desired method.
> 0 votes

# Answer
To render in a seperate class create a Renderer.java file with a single method named render and create an instance of it in the create() method of your main game class called Renderer renderManager = new Renderer() (filling in any constructors you need).

In the render() method of your main game class call renderManager.render(). Now any code that would normally go in the main render method can be placed in the render method of your Renderer. It will be executed as it would if it were in your main class.

As for HUDS, well, I have never had need to use them, so I have no clue. This might be of use to you. You can probably find a few tutorials online with a simple Google search and I know there are multiple StackOverflow pages on it. Check out the api docs also.

This tutorial on the libGdx wiki teaches you how to use the Orthographic camera to use world coordinates instead of pixels and to avoid the headache that comes with using pixels. Since it is described so well on the linked page I will not even attempt to explain it better.

# EDIT:

To create a HUD, you can use a seperate camera and overlay it. Do your game drawing first, then your HUD drawing. You could alternatively create a second `SpriteBatch` and not set the projection matrix to that of the camera. See below:

```
public void create()
{
    OrthographicCamera cam = new OrthographicCamera();

    SpriteBatch gameBatch = new SpriteBatch();
    SpriteBatch hudBatch = new SpriteBatch();

}

public void render()
{
    gameBatch.setProjectionMatrix(cam.combined);

    gameBatch.begin();
    //Draw using camera matrix
    gameBatch.end();

    hudBatch.begin();
    //Draw using the hud
    hudBatch.end();
}

```

You could alternatively use the `camera.project(Vector3 coords)` to draw to screen coordinates what you want. This will achieve the same results.
> 0 votes

---
Tags: java, libgdx, rendering, scene2d
---


# Question
Title: Updating an XML Document to Match New Save Data?
**The Problem**

I'm developing a game and using the *XmlSerializer* to store some user data.

While it isn't an immediate problem, I'm trying to conceptualize what would happen if I needed to update Save Data to a newer version of my game. Since the XmlSerializer reads as a Type, if I update my class with more variables, the save file becomes unreadable.

After doing some research, I discovered the XmlDocument class, which is able to read XML files as that type. This allows the data stored to be arbitrary, allowing me to read and write data accordingly.

What's confusing me is how exactly I would go about this. Is there an easy way to populate an XmlDocument with the Nodes/Elements of a custom class? And how can I detect when data is missing and needs to be added to the XML file?

**Example**

If you were confused by the question, here's a simple example of what I would like to accomplish:

```
<FileData version="Original File">
  <foo>14</foo>
</FileData>

```

Several versions later, I update my class to look like this:

```
class FileData {
    var foo = 14;
    var bar = 4;
}

```

Now I need the XML file to look like this before I can use XmlSerializer:

```
<FileData version="Updated File">
  <foo>14</foo>
  <bar>4</bar>
</FileData>

```

# Answer
> 0 votes
As it happens, the XMLSerializer (and most likely DataContract and JSON as well) will add in data that is missing when Deserializing. So in my example above, the XML Serializer will actually give you this when trying to read the outdated file:

```
<FileData version="Updated File">
  <foo>14</foo>
  <bar>0</bar>
</FileData>

```

Since "Bar" is a type *int*, it will default to 0. This is a huge step forward, but it doesn't completely solve the issue. We still need "bar" to default to 4 when running the game.

However, since we've now learned the XMLSerializer doesn't throw an exception when reading outdated files, we can stick a version number in the file like this:

```
<FileData version="Original File">
  <VERSION>1.0</VERISON>
  <foo>14</foo>
</FileData>

```

Now whenever we read a file, we can compare it's version number to our current version, and if it's outdated, we know that "Bar" now exists as 0. Now we can easily set "Bar" to 4 before returning the deserialized data.

SIDENOTE:

If we were to now go back to version 1.0, after saving a file with extra data, the XMLSerializer will actually just ignore the new data and simply return the correct version of FileData. So if our Type doesn't include "Bar", the Serializer will just ignore it in the inputted String.

# Answer
> 1 votes
You could use a datacontract.

So below is how to use a datacontract with two versions of FileData ( v1 & v2 ). Comment in filedata version 1 and call testV1(). This will cause filedata version 1 to be saved

Then comment in filedata version 2 and call testV2() this will cause filedata version 1 to be loaded as filedata version 2

```
using System.Runtime.Serialization;
using System.IO;
using System.Xml;

class Program
{
    // filedata version 1
    [DataContract]
    public class FileData
    {
        public FileData()
        {
            setDefaults();
        }

        private void setDefaults()
        {
            foo = 14;
        }

        [OnDeserializing]
        private void DeserializationInitializer(StreamingContext ctx)
        {
            setDefaults();
        }

        [DataMember]
        public int foo { get; set; }

    }

    /*
    // filedata version 2
    [DataContract]
    public class FileData
    {
        public FileData()
        {
            setDefaults();
        }

        private void setDefaults()
        {
            foo = 14;
            bar = 4;
        }

        [OnDeserializing]
        private void DeserializationInitializer(StreamingContext ctx)
        {
            setDefaults();
        }

        [DataMember]
        public int foo { get; set; }

        [DataMember]
        public int bar { get; set; }

    }
     * */

    static void Main(string[] args)
    {

        // run testv1 once. Ensure filedata version 1 is commented in
        testV1();

        // now comment out above testv1(). Ensure Filedata version 2 is commented in and run testv2()
        //testV2();

    }

    static void testV1()
    {
        FileData saveFd = new FileData();
        saveText(serialiseToString<FileData>(saveFd), fileName());
        FileData fd = deserialiseFromString<FileData>( loadText(fileName()) );
    }

    static void testV2()
    {
        FileData fd = deserialiseFromString<FileData>(loadText(fileName()));
    }

    static String fileName()
    {
        return UserPath() + "filedata.xml";
    }

    public static String UserPath()
    {
        return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\" ;
    }

    public static String serialiseToString<T>(T obj)
    {
        String ret = "";
        DataContractSerializer ser = new DataContractSerializer(typeof(T));
        var settings = new XmlWriterSettings { Indent = true };

        MemoryStream ms = new MemoryStream();
        var w = XmlWriter.Create(ms, settings);
        using (ms)
        {

            ser.WriteObject(w, obj);
            w.Close();
            ms.Position = 0;

            System.IO.StreamReader reader = new System.IO.StreamReader(ms);
            using (reader)
            {
                ret = reader.ReadToEnd();
            }
        }

        return ret;
    }

    public static T deserialiseFromString<T>(String text)
    {
        T p;
        DataContractSerializer ser = new DataContractSerializer(typeof(T));

        byte[] byteArray = Encoding.UTF8.GetBytes(text);
        MemoryStream ms = new MemoryStream(byteArray);
        using (ms)
        {
            p = (T)(ser.ReadObject(ms));
        }

        return p;
    }

    public static String loadText(String filename)
    {
        TextReader tw = null;
        String text = null;

        try
        {
            FileStream fs = System.IO.File.OpenRead(filename);
            tw = new StreamReader(fs);
            text = tw.ReadToEnd();
            tw.Close();
        }
        catch (Exception ex)
        {
            //deal with ex
            ex.ToString();
        }
        finally
        {
            if (tw != null)
            {
                tw.Dispose();   // same as tw.Close() btw
            }
        }

        return text;
    }

    public static bool saveText(String text, String filename)
    {
        bool success = false;
        TextWriter tw = null;

        String fd = Path.GetDirectoryName(filename);
        try
        {
            if (Directory.Exists(fd) == false)
            {
                Directory.CreateDirectory(fd);
            }

            tw = new StreamWriter(filename);
            tw.Write(text);
            tw.Close();
            success = true;
        }
        catch (Exception ex)
        {
            // deal with e
            ex.ToString();
        }

        finally
        {
            if (tw != null)
            {
                tw.Dispose();
            }
        }

        return success;
    }

}

```

---
Tags: savegame, xml, serialization
---


title: Project 3d lines onto plane

text:
# Question
Title: Project 3d lines onto plane
I'm trying to wrap my head around coordinate projection, and can't seem to solve the problem I am having. Here is an illustration of it:

The cubes represent 3d space, and the 2 red lines represent the positions of 3 points (which could be `n` points). I'm then trying to project these lines onto the green plane shown on the second cube.

My code so far for this is the following:

```
private List<Vector3> ProjectPoints(List<Vector3> points, Vector3 axis1, Vector3 axis2)
{
    var projectedPoints = new List<Vector3>();

    // first point is already on plane
    projectedPoints.Add(points[0]);

    // blue line
    axis1.Normalize();
    // yellow line
    axis2.Normalize();

    var planeNormal = Vector3.Cross(axis1, axis2);

    float totalRotationAngleSoFar = 0;

    // project remaining points
    for (int i = 1; i < points.Count; i++)
    {
        // get point relative to origin (prev point)
        Vector3 pointRelativeToOrigin = points[i] - points[i - 1];
        Vector3 pointDir = Vector3.Normalize(pointRelativeToOrigin);

        // rotate point by all the angles from previous points, this is so if we had
        // a curve where the points went in on themselve, this rotation would see the
        // curve 'unfolding' into a straight line on the plane
        Vector3 rotationAxis = Vector3.Cross(pointDir, planeNormal);
        Vector3 rotatedPoint = Vector3.Transform(pointRelativeToOrigin, Matrix.CreateFromAxisAngle(rotationAxis, totalRotationAngleSoFar));

        // get rotation axis and min angle between point and plane.
        float minAngleBetweenPointAndPlane = TODO_GetAngleBetweenPointAndPlane();

        // add to total rotation for the next point to use (TODO minus or plus?)
        totalRotationAngleSoFar -= minAngleBetweenPointAndPlane;

        // rotate point in line with plane
        Vector3 projectedPoint = Vector3.Transform(rotatedPoint, Matrix.CreateFromAxisAngle(rotationAxis, minAngleBetweenPointAndPlane));
        projectedPoint += projectedPoints.Last();
        projectedPoints.Add(projectedPoint);
    }

    return projectedPoints;
}

```

I 'think' this is the right approach, though not 100% sure. Also I've no idea how to calculate `TODO_GetAngleBetweenPointAndPlane()` with the data I have. I expect you can use the dot product, but I'm not sure what data I would plug in.

# Answer
I figured it out. Answer to my question was this:

```
// get rotation axis and min angle between point and plane.
var dot = Vector3.Dot(planeNormal, rotatedPointDir);
float angle = (float)Math.Acos(dot);
float minAngleBetweenPointAndPlane;
if (angle >= MathHelper.PiOver2)
    minAngleBetweenPointAndPlane = angle - MathHelper.PiOver2;
else
    minAngleBetweenPointAndPlane = MathHelper.PiOver2 - angle;

```

As well as storing the rotation matrices (instead of just angle), and also using the signed angle when using `CreateFromAxisAngle`.
> 0 votes

---
Tags: 3d, mathematics, rotation, projection, linear-algebra
---


# Question
Title: Java/Libgdx Pixel game with individual pixel changing
I am currently trying to make a game with pixelated graphics. The game is supposed to run with as few textures as possible. Instead of this it is supposed to generate the levels randomly, and fill in the pixels accordingly.

I would like to change pixels individually, since this way, I only can change the pixels that have to be changed, which seems to me to be the most efficient way.

What would be the fastest way in which I could achieve individual pixel updating/changing?

I have tried Pixmaps but they seem to be very slow and in order to draw them as far as I could find you have to create a new texture from the pixmap for every frame.

Drawing each 'pixel' as a square texture also seems to be a very inefficient way.

Does java/Libgdx have a 'fast' way of doing this?

I also saw a lot of people in other Posts recommending to use bufferedimage from the Java2D library. However, I am not sure if this can be combined with Libgdx functions and textures, which I will need for some entities. As far as I could see it requires you to use a Java2D graphics window.

Can you still use some textures in java2D?

# Answer
> 1 votes
I just post this here as i don't have enough reputation to comment; maybe you could use GL\_POINTS when doing a

```
glBegin(GL_POINTS);

```

if you use Libgdx (which is more or less based on OpenGL) ? Note this is just an hypothesis here.

Hope it helped :)

EDIT : Sarge Borsch who commented under is right. You shouldn't use the fixed function pipeline technique I suggested above, but, when rendering with VBOs and VAOs, you should do something like this :

```
glDrawArrays(GL_POINTS, 0, size);

```

with size being the number of vertices you draw (36 in the case of a cube without using indices).

---
Tags: java, libgdx, pixel, per-pixel
---


# Question
Title: Physics for movement in a topdown 2d game?
I'm implementing player movement for a simple topdown game, how would I handle more "advanced" concepts in physics to make my player movement feel more natural? Right now I have something like this:

```
void update(double delta) {
    dx = dy = 0;

    if (left) {
        dx -= 1;
    }
    if (right) {
        dx += 1;
    }
    if (up) {
        dy -= 1;
    }
    if (down) {
        dy += 1;
    }

    if (dx != 0 || dy != 0) {
        x += dx * delta;
        y += dy * delta;
    }
}

```

How would I go about implementing things like friction, acceleration, drag, and so on?

# Answer
> 1 votes
I recommend you to check on box2d physics library and steering-behavior concept and also iforce2d will give you a better examples. These will help you to bring characters to life. I assume that you are using java.

This is how you create the world. This will provide you automatically the physics you want, force, impulse, gravity, velocity, acceleration, angle, torque etc.

```
// earth gravity
Vector2 gravity = new Gravity(0, -9.8f);
World world = new World(gravity, true);

```

This is how to update the world. Read more if you have questions

```
world.step(POSITION_ITERATION, VELOCITY_ITERATION);

```

This is how you create the body.

```
BodyDef bodDef = new BodyDef();

bodDef.position.set(x, y);
bodDef.type = BodyType.DynamicBody;

Body body = world.createBody(bodDef);

FixtureDef fixDef = new FixtureDef();

fixDef.filter.categoryBits = categoryBits;
fixDef.filter.maskBits = maskBits;
fixDef.density = density;
fixDef.friction = friction;
fixDef.restitution = restitution;
fixDef.isSensor = isSensor;
fixDef.shape = shape;

body.createFixture(fixDef);

// also don't forget to dispose shape
shape.dispose();

```

This is how you use the body.

```
body.applyForce(...)
body.setLinearVelocity(...)
body.setTransform(...)
// and so on...

```

---
Tags: physics
---