# Question
Title: How to know from which direction there is a collision with an object? In Unity C#
In the game, there is a ball, and moving objects that can hit it. I want the ball to move when an object hits it. But the ball should move to the right direction, the one which the collision was from. I looked for some answers on the internet, however, most codes were in Java script, and those that were in C# weren't helpful because it needed a Rigidbody. The ball is a rigidbody, but the objects that may hit it, aren't. Those are being moved by the CharacterController. The question is how can I detect the collision, to know from what direction it came, and move it to that direction. Thank you.

# Answer
> 1 votes
Use rigidbody.AddForce instead of transform.Translate so that the collisions are detected. For the direction create a variable with the difference between the target and the object itself and then normalize to find out the direction.

# Answer
> 0 votes
I think a normalized vector from the ball to the object.

direction = (ball.transform.position - kicker.transform.position).normalized;

I made a game doing kind of this thing you are doing. (source code link in the post) http://luigigarcia.byethost7.com/projects/goal-a-r-goal/

I think that your kicking object must do this work, not the ball. You need to know the ball someway:

* reference set in some component;
* through the OnCollision MonoBehaviour methods;
* etc..

You apply the direction with something like this:

```
  ball.theRigidbody.AddForce(direction * powerValue);

```

---
Tags: unity, c#, collision-detection, direction
---


# Question
Title: Unity3d change texture on terrain at specific vector3 at runtime
I need the terrain texture to change at certain positions depending on where trees etc. are randomly positioned at runtime. I'm struggling to find any solid information about how to take a particular vector3 and tell the terrain to paint a different texture of size x at that location. So far I have found a lot of information about how to change textures based on height map information. As my map is flat, that information doesn't seem very relevant.

EDIT: using the following code when each tree was randomly instantiated:

```
    public void ChangeTextureAtTreeLocation(Vector3 treePosition)
    {

        int mapX = (int)(((treePosition.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
        int mapZ = (int)(((treePosition.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
        float[,,] splatmapData = terrainData.GetAlphamaps(1, 1, 4, 4);
        terrainData.SetAlphamaps( mapX, mapZ, splatmapData);
        terrain.Flush();
    }

```

got me this result:

As you can tell, the results aren't great. There are two main deficiencies:

1. I don't know how to access the terrain texture array directly so I paint a portion of the map first (see the bottom left of the image), sample that portion, and then set that sample at the location of the trees. This is not ideal as I cannot change the shape, size, or opacity of the added terrain texture. There is also no blending between textures, which gives the texture a rabbit burrow look.
2. you cannot see it in the image, but the textures do not appear under the trees but are directly north east of them. Not sure why that is. I'm assuming it has something to do with how textures are drawn relative to their origin.

# Answer
> 3 votes
Terrain has a "setAlphaMaps" function you can use to modify the terrain splat maps at runtime.

You can find the documentation (along with an example) in the official unity documentation here: http://docs.unity3d.com/ScriptReference/TerrainData.SetAlphamaps.html

Just make sure you call Terrain.Flush when you're done.

As your target is a vector3 you will have to convert it into 2D space and scale the position relative to the origin of the terrain, but then you can just set pixels in the alpha maps around that point.

So lets address your issues.

1. The way splat mapping works is by additively blending 4 textures based on the floats in the Red, Green, Blue and Alpha channels in a bitmap. So you should be able to get half alpha of texture 1 by setting Red to 0.5. You're going to have to do some math to smooth the alpha value in a radius from your target point.
2. You're getting the pixels +4 in X and Z around your target point, try offsetting the point you index into the array by -half of the diameter you want the splat to be (make sure you clamp it).

I hope that solves your issues.

---
Tags: unity, textures, terrain
---


# Question
Title: How to create heat haze effect in Libgdx?
I would like to create a heat haze effect for a 2D game I am making.

Do You have ideas or suggestions, how to get that effect. I am using Libgdx(OpenGL 2.0).

Thank You in advance!

# Answer
> 3 votes
I used this solution to make a water distortion effect. You could use the sin waves vertically instead of horizontally to possibly achieve your effect. I draw what might get distorted onto a `FrameBuffer`. I make regions of the buffer texture that will be redrawn with a distortion shader applied. **GdxGame.java**

```
void create(){
    scaleX =  Gdx.graphics.getWidth() / gs.cam.viewportWidth ; //floats that convert the width and height in world
    scaleY =   Gdx.graphics.getHeight() / gs.cam.viewportHeight;//to width and height on screen
    //The above floats need to be recalculated on screen resize, and the frame buffer will also need to be recreated
    batch = new SpriteBatch();
    shader = new ShaderProgram(Gdx.files.internal("data/vertexShader.glsl").readString(),Gdx.files.internal("data/fragmentShader.glsl").readString());
    coords = new Vector3(0,0,0);
    heatRegions = new ArrayList<TextureRegion>();
    heatCoords = new ArrayList<Vector2>();
    heatDimensions = new ArrayList<Vector2>();
    idt = new Matrix4();
    time = 0f; //makes the effect move over time
    /*This is a bad way to store your regions. I assume some object generates heat waves,
    so use it's x and y and width and height, also have it store it's own distortionRegion
    instead of storing ArrayLists*/
    //Create a FrameBuffer to draw the objects that will be distorted to.
    try {//This try-catch block is because some Androids don't support Format.RGBA8888
            frameBuffer = new FrameBuffer(Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
        }catch (GdxRuntimeException e){
            frameBuffer = new FrameBuffer(Format.RGB565, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
        }

    heatRegions.add(new TextureRegion(frameBuffer.getColorBufferTexture()));
    heatCoords.add(new Vector2(0,0));
    heatDimensions.add(new Vector2(32,32));
}

public void render(){
    float dt = Gdx.graphics.getDeltaTime();
    time += dt ;
    float angle = time * (2 * MathUtils.PI);
    if (angle > (2 * MathUtils.PI))
        angle -= (2 * MathUtils.PI);

    Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl20.glEnable(GL20.GL_BLEND);
    shader.begin();
    shader.setUniformf("timedelta", -angle);
    shader.end();

    frameBuffer.begin();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    //Draw the objects that will be rendered BEHIND the heat wave to the FrameBuffer so that they will get distorted
    batch.end();
    frameBuffer.end();
    //Draw the buffer to screen
    g.setProjectionMatrix(idt);
    g.begin();
    g.draw(frameBuffer.getColorBufferTexture(), -1, 1, 2, -2); //IIRC, you need to vertically flip it. If I remembered wrong, then do -1, -1, 2, 2
    g.end();
    g.setProjectionMatrix(cam.combined);
    //Now we will actually use the effect by drawing our heat regions
    batch.setShader(shader);
    batch.begin();
    for(int i = 0; i < heatRegions.size(); i++){
        TextureRegion region = heatRegions.get(i);
        coords.set(heatCoords.get(i).x, heatCoords.get(i).y,0);//
        coords.project(cam.combined); //get screen coordinates for the coords
        region.setTexture(frameBuffer.getColorBufferTexture());
        //cut out the area to distort
        region.setRegion(coords.x, coords.y,
                        heatDimensions.get(i).x * scaleX,heatDimensions.get(i).y * scaleY);
        //draw it with the distortion shader applied
        batch.draw(region, coords.x, coords.y,
                        heatDimensions.get(i).x * scaleX,heatDimensions.get(i).y * scaleY);
  }
  batch.end();

}

```

**GLSL Shaders Formatted as Java Strings**

```
public static String waterFragmentShader = "#ifdef GL_ES\n"
        + "precision mediump float;\n"
        + "#endif\n"
        + "varying vec4 v_color;\n"
        + "varying vec2 v_texCoords;\n"
        + "uniform sampler2D u_texture;\n"
        + "uniform sampler2D u_texture2;\n"
        + "uniform float timedelta;\n"
        + "uniform vec2 sss;\n"
        + "uniform vec2 u_maxclamp;\n"
        + "void main()                                  \n"
        + "{                                            \n"
        + "  vec2 displacement = texture2D(u_texture2, v_texCoords/4.0).xy;\n" //
        + "  float t=v_texCoords.y +displacement.y*0.7-0.15+  (sin(v_texCoords.x * 40.0+timedelta) * 0.003); \n" //swap the x & y stuff here to make the waves vertical instead of horizontal
        + "  gl_FragColor = v_color * texture2D(u_texture, vec2(v_texCoords.x,t ));\n"
        + "}";

public static String vertexShader =
        "attribute vec4 a_position;    \n"
        + "attribute vec2 a_texCoord0;\n"
        + "uniform mat4 u_projTrans;\n"
        + "varying vec4 v_color;"
        + "varying vec2 v_texCoords;"
        + "void main()                  \n"
        + "{                            \n"
        + "   v_color = vec4(1, 1, 1, 1); \n"
        + "   v_texCoords = a_texCoord0; \n"
        + "   gl_Position =  u_projTrans * a_position;  \n"
        + "}";

```

---
Tags: shaders, libgdx, post-processing
---


# Question
Title: Are concurrent Update and Draw calls possible in XNA?
I am making a real-time game in XNA and I would like to reduce the `Update()` call frequency while getting as many `Draw()` calls as possible. This would enable the program to finish long calculations in the `Update()` method while `Draw()` is still regularly called to perform interpolation and rendering to have the game appear running smoothly.

But, it seems like `Draw()` is never invoked before `Update()` has finished. This creates stuttering.

Is it possible to achieve concurrent calls to `Draw()` before `Update()` has finished?

# Answer
XNA's update and draw methods do in fact happen in a single thread. In order to utilize other threads on the machine, or do long running calculations across multiple frames you can utilize C#'s asynchronous function calls. The basic idea is, you start a calculation by invoking an asynchronous function, this function will execute in a new context on the machine and won't block your main update thread. The trouble now is getting the result of the calculation back. Here's a quick example that I think is free of race conditions:

```
private volatile object Result = null;
private volatile bool CalculationInProgress = false;
private void AsyncCalculation() {
    Result = DoSomeStuffThatTakesAWhile();
    CalculationInProgress = false
}
public override Update(GameTime time) {
    if(Result == null) {
        if(!CalculationInProgress) {
            CalculationInProgress = true;
            ((Action)AsyncCalculation).BeginInvoke(null, this);
        }
    else {
        UseResult(Result);
        Result = null;
    }
}

```

I hope this gives a general idea of how .BeginInvoke could be used in your case. You're basically polling your result in each update call until it is completed.You don't need to use Action either, Action is a delegate that takes no parameters and returns void, if you need to pass parameters and have an output take a look at Func\<\>.

There may be a more simple way, I would very much enjoy seeing a simpler solution in C#. Hope this gives you a bit of a starting point though.
> 2 votes

---
Tags: xna
---


# Question
Title: How can I apply a glow filter in Phaser?
I'm trying to get the following effect, but as far as I know, a filter is the only sensible way.

Imagine some objects and background, and a fire ball passing through. The fireball glows. All objects (not the background) become brighter in color where they are under that glow. The glow effect could be described as a glow around a missile's fire.

This should be built-in to Phaser, as pixi.js has it.

# Answer
It may be achieved by following: add a glow sprite with additive blending mode (since it was introduced in Phaser 2.0 on March 13) and combine it with masking (you can find article on PIXI about masking here). So, the workflow: \- you render all your foreground objects, that need to be affected by glow to mask graphics \- render background and all foreground objects to real graphics \- use the mask graphics to set the mask of the glow sprites (set additive blending mode for them) and render the glows Result: you get untouched background, and all foreground objects now are lit by glow sprites.
> 2 votes

# Answer
Look in pixi.js/src/filters or try pixi-extra-filters/src/filters/glow.

```
fireball.filters = [ new PIXI.filters.GlowFilter(viewWidth, viewHeight, distance, outerStrength, innerStrength, color, quality) ];

```
> 0 votes

---
Tags: javascript, special-effects, phaser
---


# Question
Title: Unity: why game app on Android takes up much more memory than Unity Profiler reports?
We are profiling a game app on Android 4.4.2 device via Unity’s ADB profiling.

We have set up ADB profiling following the official guide: http://docs.unity3d.com/Manual/Profiler.html

The ADB profiling works fine, when the app is running, Unity Profiler reports its memory usage as following:

Used Total: 100.4 MB Unity: 40.5 MB Mono: 10.1 MB GfxDriver: 34.9 MB FMOD: 3.9 MB Profiler: 14.8 MB Reserved Total: 112.8MB Unity: 47.0 MB Mono: 15.4 MB GfxDriver: 34.9 MB Profiler: 15.5 MB

Meanwhile, we are also running another performance test tool (i.e. Emmagee, https://github.com/NetEase/Emmagee) to monitor the app, which can monitor CPU, memory, network traffic, battery current and etc. However, the memory usage of the app reported by Emmagee tool is much larger:

As shown above, Unity Profiler reported 112.8M memory is totally reserved for running the app, but Emmagee tool reported \>200M PSS memory is used. Obviously, more than 90M memory taking up is happened somewhere by something that Unity Profiler does not take into account.

(We also tried other performance monitoring tool for Android apps, e.g. APT, and the result is similar to what Emmagee reported. The extra memory usage problem remains.)

We noticed that the Unity Profiler itself would take up ~15M memory, which is included in the profiler’s report. Also, we knew that PSS memory includes proportional shared libraries with other processes, but 90M+ extra is such large amount considering that Unity Profiler only reported 112.8M totally.

Our puzzle remained: Where does the 90M+ memory come from? How are they used by the app? Why Unity Profiler does not report the extra memory? What can we do for reducing the extra memory and the total PSS memory of the running app, and/or get it close to what Unity Profiler reports?

Any help could be appreciated!

# Answer
> 1 votes
I have almost zero unity experience, but I have developed android games in other platforms, and I believe I know what is going on because I had a similar experience.

Probably it is video memory. Many mid to low end Android devices use RAM to allocate video memory. Uncompressed textures take up a lot of space.

---
Tags: unity, android, memory
---


# Question
Title: Animating a Sprite After Mouse Release - SFML
I'm working on a game where the user can drag and release sprites. After the sprite is released it should interpolate (animate) back to its original position. So I researched on the math relevant to implement the concept in the game. To demonstrate my point, here's the code of a console app I wrote:

```
#include <iostream>
#include "vec2.h"
#include <cmath>

using namespace std;

int main()
{
    m::vec2 posA { 0.f, 0.f };
    m::vec2 posB { 10.f, 10.f };

    m::vec2 B_to_A = posA - posB; // (-10, -10)

    float length = m::length(B_to_A); // 14.1421

    m::vec2 normalizedVec = B_to_A / length; // (-0.707107, -0.707107)

    float lengthOfUnitVec = m::length(normalizedVec); // 1

```

I tried to emulate the update function of the game:

```
    float loopLength = length;

    size_t i = 0;
    while(loopLength > 0)
    {
        posB += normalizedVec;
        cout << posB << endl;
        cout << i << endl;
        ++i;
        loopLength -= lengthOfUnitVec;
    }

```

The loop executes 14 times when `loopLength` is negative. As you can see my plan was to defined a variable for the distance until point A is reached. Also, the position of B is changing as the distance decreases.

The problem is that when I release the sprite it doesn't return exactly to where it was originally.

My guess is that it has to do with floating-point numbers but I just can't come up with a solution. Another speculation is it is because the user can release at any position. Therefore, there's always an extra offset.

Notice, here I used a simple case where the distance is (-10, -10) and a normalized velocity. When I try to scale the velocity `normalizedVec` for moving faster the gap is larger. Maybe I will post Part 2 when I try to implement using your advices in SFML. I appreciate any help.

**Solution in SFML:**

```
#include "Game.h"
#include "ResourcePath.hpp"
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Window/Event.hpp>

using namespace std;

Game::Game()
: window(sf::VideoMode(640, 480), "SFML")
, frameRate(sf::seconds(1.f / 60.f))
, sprite{}
, shape{}
, isAnimating{ false }
, isSelected{ false }
, texture{}
, speed{ 0.1f }
, targetPos{sf::Vector2f{ 30.f, 30.f} }
{
    window.setVerticalSyncEnabled(true);

    texture.loadFromFile(resourcePath() + "sprite.png");
    shape.setPosition(targetPos);
    shape.setOutlineColor(sf::Color::Red);
    shape.setOutlineThickness(1.f);
    shape.setFillColor(sf::Color::Transparent);
    shape.setSize(static_cast<sf::Vector2f>(texture.getSize()));
    sprite.setTexture(texture);
    sprite.setPosition(targetPos);
}

void Game::draw()
{
    window.clear();

    window.draw(shape);
    window.draw(sprite);

    window.display();
}

void Game::processEvents()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::Closed)
        {
            window.close();
        }

        if (event.type == sf::Event::MouseButtonPressed)
        {
            if (sprite.getGlobalBounds()
                .contains(event.mouseButton.x, event.mouseButton.y))
            {
                isSelected = true;
                isAnimating = false;
            }
        }

        if (event.type == sf::Event::MouseButtonReleased)
        {
            isSelected = false;
            isAnimating = true;
        }

        // Escape pressed: exit
        if (event.type == sf::Event::KeyPressed
            && event.key.code == sf::Keyboard::Escape)
        {
            window.close();
        }
    }

}

void Game::update(sf::Time dt)
{
    if (isAnimating)
    {
        sprite.move((targetPos - sprite.getPosition()) * speed );
    }

    if (isSelected)
    {
        sprite.setPosition(static_cast<sf::Vector2f>(sf::Mouse::getPosition(window)));
    }

}

void Game::run()
{
    sf::Clock clock;
    sf::Time dt = sf::Time::Zero;
    while (window.isOpen())
    {
        processEvents();
        dt += clock.restart();
        while (dt > frameRate)
        {
            dt -= frameRate;
            processEvents();
            update(frameRate);
        }
        draw();
    }
}

```

# Answer
How about this algorithm? It also provide a smooth movement. First declare the animaton speed and the previous position of the sprite (where it should go after the mouse release):

```
float Speed = 0.1f; //animation speed, adjust as you like
Vector2 TargetPos; //The previous position of the sprite or just the position where the sprite should move after mouse release
TargetPos.x = PreviousPosition.x; //or some test values, e.g. 300
TargetPos.y = PreviousPosition.y;
// I dont know your vector class. Imagine this:
/*
struct Vector2
{
  float x;
  float y;
};
*/

```

Update in each frame (in the update loop) the animation (the actual sprite position), but only if the mouse button is released (or whenever you like):

```
//Pseudocode
if(Mouse.leftBtnReleased)
{
    Sprite.Position.x += (TargetPos.x - Sprite.Position.x) * Speed;
    Sprite.Position.y += (TargetPos.y - Sprite.Position.y) * Speed;
}

```

What it actually does is that the sprite is moving constantly (if the mouse button is released) towards the `TargetPos`-position but the further the sprite is away from this point the faster it moves. This creates a smooth animation. Also quite useful for camera zooming and follow camera movement e.g. in platformer games. You can adjust the `Speed` value as you like.
> 1 votes

---
Tags: c++
---


# Question
Title: How many threads should I have, and for what?
Should I have separate threads for rendering and logic, or even more?

I'm aware of the immense performance drop caused by data synchronization (let alone any mutex locks).

I've been thinking of taking this to the extreme and doing threads for conceivable every conceivable subsystem. But I'm worried that may slow things too. (For example, is it sane to separate the input thread from rendering or game logic threads?) Would the data synchronization required make it pointless or even slower?

# Answer
The common approach for taking advantage of multiple cores is, frankly, just plain misguided. Separating your subsystems into different threads will indeed split up some of the work across multiple cores, but it has some major problems. First, it's very hard to work with. Who wants to muck around with locks and synchronization and communication and stuff when they could just be writing straight up rendering or physics code instead? Second, the approach doesn't actually scale up. At best, this will allow you to take advantage of maybe three or four cores, and that's if you *really* know what you're doing. There are only so many subsystems in a game, and of those there are even fewer that take up large chunks of CPU time. There are a couple good alternatives that I know.

One is to have a main thread along with a worker thread for each additional CPU. Regardless of subsystem, the main thread delegates isolated tasks to the worker threads via some sort of queue(s); these tasks may themselves create yet other tasks, as well. The sole purpose of the worker threads is to each grab tasks from the queue one at a time and perform them. The most important thing, though, is that as soon as a thread needs the result of a task, if the task is completed it can get the result, and if not it can safely remove the task from the queue and go ahead and perform that task itself. That is, not all tasks will end up being scheduled in parallel with each other. Having more tasks than can be executed in parallel is a *good* thing in this case; it means that it is likely to scale as you add more cores. One downside to this is that it requires a lot of work up front to design a decent queue and worker loop unless you have access to a library or language runtime that already provides this for you. The hardest part is making sure your tasks are truly isolated and thread safe, and making sure your tasks are in a happy middle ground between coarse-grained and fine-grained.

Another alternative to subsystem threads is to parallelize each subsystem in isolation. That is, instead of running rendering and physics in their own threads, write the physics subsystem to use all your cores at once, write the rendering subsystem to use all your cores at once, then have the two systems simply run sequentially (or interleaved, depending on other aspects of your game architecture). For example, in the physics subsystem you could take all the point masses in the game, divide them up among your cores, and then have all the cores update them at once. Each core can then work on your data in tight loops with good locality. This lock-step style of parallelism is similar to what a GPU does. The hardest part here is in making sure that you are dividing your work up into fine-grained chunks such that dividing it evenly *actually* results in an equal amount of work across all processors.

However, sometimes it's just easiest, due to politics, existing code, or other frustrating circumstances, to give each subsystem a thread. In that case, it's best to avoid making more OS threads than cores for CPU heavy workloads (if you have a runtime with lightweight threads that just happen to balance across your cores, this isn't as big of a deal). Also, avoid excessive communication. One nice trick is to try pipelining; each major subsystem can be working on a different game state at a time. Pipelining reduces the amount of communication necessary among your subsystems since they don't all need access to the same data at the same time, and it also can nullify some of the damage caused by bottlenecks. For example, if your physics subsystem tends to take a long time to complete and your rendering subsystem ends up always waiting for it, your absolute frame rate could be higher if you run the physics subsystem for the next frame while the rendering subsystem is still working on the previous frame. In fact, if you have such bottlenecks and can't remove them any other way, pipelining may be the most legitimate reason to bother with subsystem threads.
> 65 votes

# Answer
There's a couple things to consider. The thread-per-subsystem route is easy to think about since the code separation is pretty apparent from the get go. However, depending on how much intercommunication your subsystems need, inter-thread communication could really kill your performance. In addition, this only scales to N cores, where N is the number of subsystems you abstract into threads.

If you're just looking to multithread an existing game, this is probably the path of least resistance. However, if you're working on some low level engine systems that might be shared between several games or projects, I would consider another approach.

It can take a bit of mind twisting, but if you can break things up as a job queue with a set of worker threads it will scale much better in the long run. As the latest and greatest chips come out with a gazillion cores, your game's performance will scale along with it, just fire up more worker threads.

So basically, if you're looking to bolt on some parallelism to an existing project, I'd parallelize across subsystems. If you're building a new engine from scratch with parallel scalability in mind, I'd look into a job queue.
> 31 votes

# Answer
That question has no best answer, as it depends upon what you are trying to accomplish.

The xbox has three cores and can handle a few threads before context switching overhead becomes a problem. The pc can deal with quite a few more.

A lot of games have typically been single threaded for ease of programming. This is fine for most personal games. The only thing you would likely have to have another thread for is Networking and Audio.

Unreal has a game thread, render thread, network thread, and audio thread (if I remember correctly). This is pretty standard for a lot of current-gen engines, though being able to support a seperate rendering thread can be a pain and involves a lot of groundwork.

The idTech5 engine being developed for Rage actually uses any number of threads, and it does so by breaking down game tasks into 'jobs' that are processed with a tasking system. Their explicit goal is to have their game engine scale nicely when the number of cores on the average gaming system jumps.

The technology I use (and have written) has a seperate thread for Networking, Input, Audio, Rendering, and Scheduling. It then has any number of threads which can be used to perform game tasks, and this is managed by the scheduling thread. A **lot** of work went into getting all the threads to play nicely with each other, but it seems to be working well and getting very good use out multicore systems, so perhaps it is mission accomplished (for now; I might break down audio/networking/input work into just 'tasks' that the worker threads can update).

It really depends upon your final goal.
> 25 votes

# Answer
A thread per subsystem is the wrong way to go. Suddenly, your app won't scale because some subsystems demand a lot more than others. This was the threading approach taken by Supreme Commander and it didn't scale beyond two cores because they only had two subsystems that took up a substantial amount of CPU- rendering and physics/game logic, even though they had 16 threads, the other threads just barely amounted to any work and as a result, the game only scaled to two cores.

What you should do is use something called a thread pool. This somewhat mirrors the approach taken on GPUs- that is, you post work, and any available thread simply comes along and does it, and then returns to waiting for work- think of it like a ring buffer, of threads. This approach has the advantage of N-core scaling and is very good at scaling for both low and high core counts. The disadvantage is that it's quite hard to work the thread ownership for this approach, as it's impossible to know which thread is doing what work at any given time, so you have to have the ownership issues locked down very tightly. It also makes it very hard to use technologies like Direct3D9 which don't support multiple threads.

Thread pools are very hard to use, but they deliver the best possible results. If you need extremely good scaling, or you have plenty of time to work on it, use a thread pool. If you're trying to introduce parallelism into an existing project with unknown dependency problems and single-threaded technologies, this isn't the solution for you.
> 13 votes

# Answer
You are right that the most critical part is to avoid synchronization wherever possible. There are a few ways to achieve this.

1. Know your data and store it in memory according to your processing needs. This enables you to plan for parallel calculations without the need of synchronization. Unfortuantely this is most of the time quite hard to achieve as the data is often accessed from different systems at unpredictable times.
2. Define clear access-times for data. You could separate your main-tick into x phases. If you are sure that Thread X reads the data only in a specific phase, you also know that this data can be modified by other threads in a different phase.
3. Double-Buffer your data. That is the most simple approach, but it increases the latency, as Thread X is working with the data from the last frame, while Thread Y is preparing the data for the next frame.

My personal experience shows that fine grained calculations are the most effective way, as these can scale far better than a subsystem-based solutions. If you thread your subsystems, the frame-time will be bound to the most expensive subsystem. This can lead to all threads but one idling until the expensive subsystem has finally finished it's work. If you are able to separate large parts of your game into small tasks, these tasks can be scheduled accordingly to avoid idling cores. But this is something that is hard to accomplish if you have already a big code-base.

To take some hardware constraints into consideration, you should try to never oversubscribe your hardware. With oversubscribe, I mean having more software threads than your platform hardware threads. Especially on PPC architectures ( Xbox360, PS3 ) a task-switch is really expensive. It's of course perfectly okay if you have a few threads oversubscribed which are only triggered for an small amount of time ( once a frame, for example ) If you target the PC, you should keep in mind that the number of cores ( or better HW-Threads ) is constantly growing, so you would want to find a scalable solution, which takes advantage of the additional CPU-Power. So, in this area, you should try to design your code as task-based as possible.
> 12 votes

# Answer
General rule of thumb for threading an application: 1 thread per CPU Core. On a quad core PC that means 4. As was noted, the XBox 360 however has 3 cores but 2 hardware threads each, so 6 threads in this case. On a system like the PS3... well good luck on that one :) People are still trying to figure it out.

I would suggest designing each system as a self contained module that you could thread if you wanted. This usually means having very clearly defined communication pathways between the module and the rest of the engine. I particularly like Read-Only processes like Rendering and audio as well as 'are we there yet' processes like reading player input for things to be threaded off. To touch on the answer given by AttackingHobo, when you are rendering 30-60fps, if your data is 1/30th-1/60th of a second out of date it really is not going to detract from the responsive feel of your game. Always remember that the main difference between application software and video games is doing everything 30-60 times a second. On that same note however, input may be one of the things you want to keep on the main thread so the rest can react to it as soon as it appears :)

If you design your engine's systems well enough any of them can be moved from thread to thread to load balance your engine more appropriately on a per-game basis and the like. In theory you could also use your engine in a distributed system if need be where entirely separate computer systems run each component.
> 4 votes

# Answer
I create one thread per logical core (minus one, to account for Main Thread, who incidentally is responsible for Rendering, but otherwise acts as a Worker Thread too).

I collect input device events in realtime throughout a frame, but don't apply them until the end of the frame: they will have effect in the next frame. And I use a similar logic for rendering (old state) versus updating (new state).

I use atomic events to defer unsafe operations until later in the same frame, and I use more than one event queue (job queue) in order to implement a memory barrier that gives an iron-clad guarantee regarding order of operations, without locking or waiting (lock free concurrent queues in order of job priority).

It is noteworthy to mention that any job can issue subjobs (which are finer, and approach atomicity) to the same priority queue or one that is higher (served later in the frame).

Given I have three such queues, all threads except one can potentially stall exactly three times per frame (while waiting for other threads to complete all outstanding jobs issued at the current priority level).

This seems an acceptable level of thread inactivity!
> 2 votes

# Answer
I usualy use one main thread (obviously) and I'll add a thread every time I notice a performance drop of about 10 to 20 percent. To loacte such an drop I use visual studio's performance tools. Common events are (un)loading some areas of the map or make some heavy calculations.
> 0 votes

---
Tags: performance, multithreading
---


# Question
Title: How can I protect my save data from casual hacking?
What options are there for saving game data in a secure manner? I'm interested in solutions specifically tailored for C++.

I'm looking for something that is fast and easy to use. I'm only concerned about storing simple information such as

* Which levels are and are not unlocked
* The user's score for each level

I'm curious again to know what's out there to use, any good libraries to use that give me nice, secure game data files that the average player can't mess with.

I just found this here which looks very nice, but it would be great to get some opinions on potential other libraries/options out there.

# Answer
> 24 votes
first lets say since you have a very simple save file, you can use text file.

one of the simplest ideas is to use a string key to lock/unlock data:

```
void encrypt(string& data,string key)
{
    for(unsigned i=0;i<data.size();i++)
        data[i] += key[i%key.size()];
}

void decrypt(string& data,string key)
{
    for(unsigned i=0;i<data.size();i++)
        data[i] -= key[i%key.size()];
}

```

but after a little google search I've found these links, which might be useful:

## Edit:

Based on signed char being "Undefined behavior" as @v.oddou mentioned, I guess using XOR or casting to unsigned char will result in safer/more-cross-platform code. something like this:

```
void encrypt(string& data,string key)
{
    for(unsigned i=0;i<data.size();i++)
        data[i] ^= key[i%key.size()];
}

void decrypt(string& data,string key)
{
    for(unsigned i=0;i<data.size();i++)
        data[i] ^= key[i%key.size()];
}

```

# Answer
> 24 votes
**Nothing can be considered secure client side; anyone who tells you it is, is lying.**

You can use any encryption and scramble method you want, but since the client must be also able to decode it, and the user has access to the client itself, if he is resourceful enough he'll have access to the decryption key / algorithm.

You can only add layers of annoyances to someone willing to crack it, but given enough time it *will* be cracked, and you can't do anything about that.

# Answer
> 10 votes
You can definitely leave your save file unencrypted but add a checksum that is calculated through all the values that you want to "guard".

The cracker would therefore be able to re-produce the hashing (which you off course will use with proper salt) and therefor will have a happy time trying to re-produce.

This would still not be %100 secure but, probably the best time effective solution.

# Answer
> 2 votes
This provided some simple XOR encryption:

```
#include <iostream>

using namespace std;

string encryptDecrypt(string toEncrypt) {
    char key[3] = {'K', 'C', 'Q'}; //Any chars will work
    string output = toEncrypt;

    for (int i = 0; i < toEncrypt.size(); i++)
        output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];

    return output;
}

```

And how to use it:

```
int main(int argc, const char * argv[])
{
    string encrypted = encryptDecrypt("kylewbanks.com");
    cout << "Encrypted:" << encrypted << "\n";

    string decrypted = encryptDecrypt(encrypted);
    cout << "Decrypted:" << decrypted << "\n";

    return 0;
}

```

The output of this code is this:

```
Encrypted: :=.43*-:8m2$.
Decrypted:kylewbanks.com

```

---
Tags: security, data, savegame
---


# Question
Title: Unity5x GetComponent<Animation>().Play("sequence".StopAll) not working
I'm working with Unity3D 5x using C#. I've attached collision detection to the character controller script that plays a "gothit" animation clip (using legacy animations).

Here are the code snippets, the first is for the collision:

```
void OnTriggerEnter (Collider other)
{
     if(other.gameObject.CompareTag ("dmgEnvironment")||other.gameObject.CompareTag ("dmgPlayerHit"))
    {
        GetComponent<Animation>().Play("gothit", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        print("hit damage");
    }
}

```

The attack animation call:

```
public void AnimatePunch()
{
    DidAttack ();
    //play animation
    if (canHit && lastAttackTime < lastAttackButtonTime + attackTimeout) {
        SendMessage("DidAttack", SendMessageOptions.DontRequireReceiver);
    }
    GetComponent<Animation>().Play("punch", PlayMode.StopAll);
    GetComponent<Animation>().wrapMode = WrapMode.Once;
}

```

The problem I'm running into is that the "gothit" sequence won't play on collision but will do so when wired to the AnimatePunch().

I'm not sure why this is happening. Any help is greatly appreciated.

# Answer
> 0 votes
It's a fairly simple fix...just had to add animation speed & it worked.

---
Tags: unity, c#, collision-detection, animation
---


# Question
Title: OpenGL picking performance: ray casting vs. color picking
I am curious of how the performance of color picking compares to ray casting. I am looking at the scenario when the mouse is clicked which means only then the scene is rendered in a backbuffer for color picking or ray-cating has to be applied.

Note: I have found this question which unfortunatly does not give any indication.

# Answer
It depends on multiple factors including...

1. How much geometry you are raycasting against (more = slower)
2. The resolution you are rendering your color picking at (higher = slower)
3. How you've implemented either solution (CPU raycasting? vs GPU color picking? or something else?).
4. Resource constraints -\> if your application is already CPU bound, and has plenty of GPU power to spare, doing a super efficient CPU ray cast is still going to be slower than doing an inefficient operation on the GPU.

There is a way to get an answer for your particular situation though - profile it and find out!

It's also important to note, either solution is a reasonable solution in many cases, so going one way or the other is likely not going to be a huge deal. If you aren't having performance problems, don't spend too much thought trying to choose between reasonable answers IMO!
> 5 votes

---
Tags: opengl, picking
---


# Question
Title: Cannot link SFML to my project in code::blocks
If anybody uses SFML, could you tell me how to add it to a project in code::blocks? Any technique will do.

# Answer
> 1 votes
Well, If you did a basic google search, you would find lots of answers to your question. Here is a good website to answer your question, straight from SFML itself: SFML and Code::Blocks

This is based off of windows, but I'm sure it will work for all platforms.

Hope this helps.

---
Tags: c++, sfml
---


title: Unity3d seamless level loading

text:
# Question
Title: Unity3d seamless level loading
I've read that application.loadLeveAdditiveAsync is a pro only feature. I'm looking for an asset that can do something similar. I would like to load assets based on the camera/player position. Ideally, it would be great to dispense with scenes entirely and just load information based on some distance value. This asset seems to be doing just that: https://www.assetstore.unity3d.com/en/#!/content/8015 however I'm not sure if the author is active anymore, and recent customers are complaining about a serious bug.

Any recommendations about assets that allow for seamless, open world style transitions between scenes would be great. (using Unity 3D 5, basic version, and writing in c#).

# Answer
Application.LoadLevelAdditiveAsync is not a pro feature anymore.
> 1 votes

---
Tags: unity, loading, scene
---


# Question
Title: How to deal with overlapping black parts of Light mask textures?
I am using this masking texture for a dynamic lighting effect in my game:

It looks beautiful until two lights begin to overlap:

This is obviously because the textures are overlapping when I draw them to the light map `FrameBuffer`.

```
lightFbo.begin();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            g.begin();

                for(Entity ent : entities){
                    if(ent instanceof Fireball)g.draw(light,ent.x - tlightSize / 2.5f,ent.y - tlightSize * 0.25f, tlightSize, tlightSize);
                }
            if(p instanceof FireCharacter){
                g.draw(light,p.x - lightSize / 2.5f,p.y - lightSize * 0.25f, lightSize, lightSize);

            }
g.end();
lightFbo.end();

```

I use the buffer texture from this map when I draw my actual game:'

```
g.setShader(lightingShader);
g.begin();
lightFbo.getColorBufferTexture().bind(1); //u_lightmap
light.bind(0)//u_texture
//draw things
g.end();

```

I don't want these to overlap, I want the light circles to merge without the border cutting in front of them. I tried making the black transparent in GIMP on the light texture but that made no difference. Here is the lighting shader:

**Vertex Shader**

```
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec4 vColor;
varying vec2 vTexCoord;

void main() {
    vColor = a_color;
    vTexCoord = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}

```

**Fragment Shader**

```
#ifdef GL_ES
#define LOWP lowp
precision mediump float;
#else
#define LOWP
#endif

varying LOWP vec4 vColor;
varying vec2 vTexCoord;

//texture samplers
uniform sampler2D u_texture; //diffuse map
uniform sampler2D u_lightmap;   //light map (frame buffer texture)

//additional parameters for the shader
uniform vec2 resolution; //resolution of screen
uniform LOWP vec4 ambientColor; //ambient RGB, alpha channel is intensity

void main() {
vec4 diffuseColor = texture2D(u_texture, vTexCoord);
vec2 lighCoord = (gl_FragCoord.xy / resolution.xy);
vec4 light = texture2D(u_lightmap, lighCoord);

vec3 ambient = ambientColor.rgb * ambientColor.a;
vec3 intensity = ambient + light.rgb;
vec3 finalColor = diffuseColor.rgb * intensity;

gl_FragColor = vColor * vec4(finalColor, diffuseColor.a);
}

```

My only ideas are using Gdx.gl.glSetBlendFunc(); and changing the blending source and dest values.

# Answer
> 1 votes
Okay so I solved it:

**1.** Make sure `glEnable(GL20.GL_BLEND_COLOR);` is on and the blend function is `Gdx.gl.glBlendFunc(GL20.GL_BLEND_SRC_ALPHA,GL20.GL_ONE_MINUS_SRC_ALPHA);`

**2.** Edit the light texture in something like GIMP to double check that your background is transparent.

**3.** ***MOST IMPORTANT*** Make sure the lightFramebuffer is `Format.RGBA4444` or `Format.RGBA8888` to support transparency.

---
Tags: opengl, java, libgdx, glsl, opengl-es2
---


# Question
Title: Polar movement towards cursor sfml and c++
I got smooth movement down moving based on the window but I wanted to see if I could move my sprite to my cursor when I pressed w instead of just in the -y direction but everything went wrong right away. Here is the function I'm trying to make work:

```
    void Ship::MoveShip(float ShipAccel, float deltaTime)
{
    float movementY;
    float movementX;
    m_ShipVel += ShipAccel * deltaTime;
    if (m_ShipVel > m_ShipMaxVel)
    {
        m_ShipVel = m_ShipMaxVel;
    }
    else if (m_ShipVel < -m_ShipMaxVel)
    {
        m_ShipVel = -m_ShipMaxVel;
    }
    movementX = m_ShipVel * (cos(m_ShipAngle * 180 / PI));
    movementY = m_ShipVel * (sin(m_ShipAngle * 180 / PI));

    m_SpriteShip.move(movementX, movementY);
}

```

Just made a video of what's happening with this code: Video

# Answer
I had the reciprocal of what I should have been using. The math.h class's sin and cos function want the arguments in radians and m\_ShipAngle is in Degrees. I was doing

```
   movementX = m_ShipVel * (cos(m_ShipAngle * 180 / PI));
   movementY = m_ShipVel * (sin(m_ShipAngle * 180 / PI));

```

When I should have been doing:

```
  movementX = m_ShipVel * (cos(m_ShipAngle * PI / 180));
  movementY = m_ShipVel * (sin(m_ShipAngle * PI / 180));

```

Sorry everyone who's time I wasted! I should have thought little harder.
> 1 votes

---
Tags: c++, game-design, sprites, movement, sfml
---


# Question
Title: Why are my Hello World Box2D project's collisions off by twice the size of my boxes?
I've been implementing Box2D into my engine but have run into a snag. I decided to rebuild the helloworld project inside of my own engine (it is almost identical), of which I will snip here in a moment. Firstly, **the problem:**

The dynamic body collides too early on the ground body. The ground body is much larger than is being rendered.

**Code:**

*GameHandler.cpp*

```
#include "GameHandler.h"

gameHandler::gameHandler()
{
    world_ = new b2World(gravity); //Gravity = 0, -10

    gfx = graphics(ResourceManager::getShader("main"));

    enter();
}

void gameHandler::update()
{
    float32 timestep = 1.0f / 60.0f;

    int32 velocityIts = 6;
    int32 positionIts = 2;

    world_->Step(timestep, velocityIts, positionIts);

    std::cout << "bodyx: " <<
    body_->GetPosition().x << " \t\tbodyy: " <<
    body_->GetPosition().y << " \tgroundx: " <<
    ground_->GetPosition().x << " \tgroundy: " <<
    ground_->GetPosition().y << "\n";

    input.update();

    if (input.isKeyDown(SDL_SCANCODE_RIGHT))
    {
        body_->ApplyForce(b2Vec2(20, 0), b2Vec2(0, 0), true);
    }
    if (input.isKeyDown(SDL_SCANCODE_LEFT))
    {
        body_->ApplyForce(b2Vec2(-20, 0), b2Vec2(0, 0), true);
    }

}

void gameHandler::render()
{
    gfx.drawSprite(Texture(), ground_->GetPosition(), groundSize, 0.0f, glm::vec3(1.0f, 1.0f, 0.0f));
    gfx.drawSprite(Texture(), body_->GetPosition(), bodySize, body_->GetAngle(), glm::vec3(0.0f, 1.0f, 0.0f));
}

void gameHandler::enter()
{

    groundSize = b2Vec2(10.0f, 10.0f);
    bodySize = b2Vec2(2.0f, 2.0f);

    // Define the ground body.
    b2BodyDef groundBodyDef;
    groundBodyDef.position.Set(0.0f, -20.0f);

    // Call the body factory which allocates memory for the ground body
    // from a pool and creates the ground box shape (also from a pool).
    // The body is also added to the world.
    ground_ = world_->CreateBody(&groundBodyDef);

    // Define the ground box shape.
    b2PolygonShape groundBox;

    // The extents are the half-widths of the box.
    groundBox.SetAsBox(groundSize.x, groundSize.y);

    // Add the ground fixture to the ground body.
    ground_->CreateFixture(&groundBox, 0.0f);

    // Define the dynamic body. We set its position and call the body factory.
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0.0f, 4.0f);
    body_ = world_->CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape dynamicBox;
    dynamicBox.SetAsBox(bodySize.x, bodySize.y);

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &dynamicBox;

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density = 1.0f;

    // Override the default friction.
    fixtureDef.friction = 0.0f;

    // Add the shape to the body.
    body_->CreateFixture(&fixtureDef);
}

```

*Projection:*

```
float lowerX = -25.0f, upperX = 25.0f, lowerY = -15.0f, upperY = 25.0f;
glm::mat4 projection = glm::ortho(lowerX, upperX, lowerY, upperY, -1.0f, 1.0f);

```

**Gif:**

##

The box falls off after reaching the end of what seems to be the ground box scaled to about double it's size to the left. The same thing happens going to the right but the invisible ledge is much shorter.

The same thing does happen inside of the helloworld.cpp project provided in the examples:

Strangest thing, any help?

Thanks in advance for any help!

# Answer
I was playing around a little and rereading the manual again. It noted that the size of the actual box is 2x the given size. Half-widths.

So I continued to play around inside my graphics system and continued to see where the box was colliding and not and ended up with:

Negate the (untouched) size from the position. Double the size of the boxes.

```
glm::vec2 position(pos_.x - size_.x, pos_.y - size_.y);
glm::vec2 size(size_.x * 2, size_.y * 2);

```

It seems to be working

I could also have done all of this in the matrix operations, but this might use less ops.
> 1 votes

---
Tags: 2d, physics, box2d
---


# Question
Title: Unity 3D - Rotate towards object with random offsets
Title is a little confusing, but let me explain:

I want to make the enemies look at the player, and shoot at him, with random precision, meaning that one time the enemy will shoot a little bit to the left of the player, next time a little bit to the right of him, and sometimes exactly at him.

Currently I have this scene:

The turret rotates, and when the green direction spots the player, it shoots a bullet facing the player (the green arrow).

Now I need where the rotation is passed for the `Instantiate`, to have some random precision, and I don't know how to do it. Here's what I have so far

```
Vector3 pos = new Vector3(firingPoint.transform.position.x, firingPoint.transform.position.y, firingPoint.transform.position.z);

float playerX = playerObject.transform.position.x;
float playerY = playerObject.transform.position.y;
float playerZ = playerObject.transform.position.z;

float randomX = Random.Range(playerX - 1f, playerX + 1f);
float randomY = Random.Range(playerY - 1f, playerY + 1f);
float randomZ = Random.Range(playerZ - 1f, playerZ + 1f);

Quaternion aimPrecision = Quaternion.LookRotation(new Vector3(randomX, randomY , randomZ));

Instantiate(bulletPrefab, pos, aimPrecision);

```

How can I do this?

EDIT: Right now, the enemy shoots like this:

but never towards me, or backwards

# Answer
> 3 votes
I found the solution myself. Here's what I've done:

I took the default forward rotation of the `firingPoint` object, and split it into it's parts - `x, y, z, w`.

Then from these floats, I create a new `Quaternion` using the constructor method:

```
float randomX = Random.Range(-0.1f, 0.1f);
float randomY = Random.Range(-0.1f, 0.1f);
float randomZ = Random.Range(-0.1f, 0.1f);
float randomW = Random.Range(-0.1f, 0.1f);

Quaternion oldRot = firingPoint.rotation;
Quaternion newRot = new Quaternion(oldRot.x + randomX, oldRot.y + randomY, oldRot.z + randomZ, oldRot.w + randomW);

```

Then every time this code get's called, the object will be instantiated with random rotation facing the player.

---
Tags: unity, rotation, vector, quaternion
---


# Question
Title: Rotation before scaling image/Lower resolution rotation? (XNA/C#)
Currently, when I rotate the image using SpriteBatch.Draw() the image is rotated after it is scaled. Resulting in:

Which is using the code

```
public override void Draw(GameTime gameTime) {
    sprite_batch.Draw(
        texture,
        parent.position,
        new Rectangle(0, 0, (int) 25, (int) 25),
        Color.White,
        rotation,
        new Vector2(texture.Width/2, texture.Height/2),
        new Vector2(2, 2),
        SpriteEffects.None,
        0f);
}

```

However what I would like to see is more on the grounds of

I've tried to directly edit the texture itself instead of rotating using spritebatch, only I have found that it was incredibly inefficient.

### Edit 1:

I am currently looking around at RenderTarget2D and such. Possible solution to my problem.

# Answer
> 1 votes
An easy way to do this would be to use transformation matrices. So you need to define a transformation matrix like so.

```
Matrix transform = Matrix.Identity;

```

Then to create the transformations do something like this but with your values in there.

```
transform = Matrix.CreateTranslation(X, Y, 0f) * Matrix.CreateRotationZ(rotationInRadians), Matrix.CreateScale(X, Y, 0f)

```

Now matrices are non-commutative meaning A * B != B * A and with transformation matrices changing the order you multiply them in will change which one happens first. For you I suggest Rotation * Scale * Translation or Rotation * Translation * Scale whichever you are looking for.

Then apply the transform in the spriteBatch. It will apply it for every sprite in that batch.

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, transform);

```

Lastly, note that in that overload for spriteBatch.Begin most of those are defaults except transform and samplerstate. A point clamp will prevent your objects from being sampled smoothly that way you can retain the rough edges you are looking for.

More information on transformation matrices can be shown by this picture. Although you don't need to fully understand them to utilize them.

# Answer
> 0 votes
Using a rendertarget may be a solution if you only have that one sprite. If your game requires a lot of those rotated, scaled sprites, you might want to look into a pixelshader. You might calculate the occurence of a color within your intended pixel size (your spritepixels may be 3x3 screen pixels) and color the resulting screen pixels accordingly.

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


# Question
Title: How do I calculate the position of a vehicle moving between tiles, over time?
I'm working on a small multiplayer game where players can create cities, and these cities will be placed on what's called the "world map." The world map is basically a giant coordinate plane made up of tiles, and the server will load the "world map" in chunks from the database relative to a player's position on the world map.

Now, I want players to be able to send planes from their city to another spot/tile anywhere on the world map. Say for instance player who owns **City 1** at position **10,10**, wants to create an **oil\_well** at position **70,30**. I want a plane to fly from the departure point to arrival point, and client that loads the chunk will see that plane flying across the map.

*How can I make the server calculate where the plane is?* I have the following information:

`departure_time`, `origin_x`, `origin_y`, `arrival_x`, `arrival_y`, `speed`. `speed` is the time in seconds that a plane can cross a tile on the world map.

I also have `distance`, which is simply calculated as (distance formula):

```
var distance = Math.sqrt(Math.pow( data.arrival_x - data.origin_x , 2) + Math.pow( data.arrival_y - data.origin_y , 2));

```

Again, how can I calculate the current position of a moving plane on this world map? Because the plane can fly at many different angles, depending on the angle of **departure point → arrival point**.

# Answer
> 2 votes
Scalar multiplication.

Assuming the plane moves at constant speed, you can determine how far along it is (0 meaning at `departure_point` and 1 meaning at `arrival_point`)

```
progress = distance / speed * time_elapsed

```

You can also compute a vector *(x,y)* representing the translation of the airplane from its departure point to its arrival point, by subtracting one position from the other.

```
x = arrival_x - departure_x
y = arrival_y - departure_y

```

Then simply multiply that translation vector `x`,`y` by the proportion of `progress` that has been made.

```
moved_by_x = x * progress
moved_by_y = y * progress

```

You can then add that vector to the departure point to find the point where the plane should be.

```
plane_x = departure_x + moved_by_x
plane_y = departure_y + moved_by_y

```

<sup>**departure point** red, **arrival point** blue, **plane position** orange</sup>

---
Tags: movement, tilemap, interpolation
---


# Question
Title: How to make the capsule collider that comes with character controller follow the animations
I'm making a 3D endless running game like subway surf. When I swipe/press down arrow the slide animation starts but the capsule collider isn't following along as it doesn't slides along with the character. Searched a lot on this on the forums, one possible answer is to attach the collider with some bone. I tried doing so, but couldn't make it. As I'm fairly new to Unity please provide some insights to how to overcome this situation. Here are the screen shots of the collider not following the sliding animation

# Answer
> 1 votes
I used a trick instead, just in case anybody else also has a similar problem: when the sliding animation starts I change the character controller's dimensions to just fit the slit. As soon as the sliding animation is over I reset the character controller's dimensions back to normal using the invoke method.

# Answer
> 0 votes
You could try animating the collider as well.

---
Tags: unity, animation, bones
---


# Question
Title: Processing through multiple shaders (LWJGL/Java/OpenGL)
Very simple question: Is it possible to process a vbo through different shaders? If so, how? What I want is sth like this:

```
reflectionShader.bind(); //starts shader
reflectionShader.load(some_values); //loads uniform vars into shader
process(vbo); //"renders" vbo using bound shader
reflectionShader.unbind(); //stops shader
refractionShader.bind();
refractionShader.load(some_other_values);
process(vbo);
refractionShader.unbind();
render(vbo); //output to screen

```

# Answer
The way to do this is with a FBO (Frame Buffer Object).

You can render each pass to a FBO and use it as a texture input in the next stage, any kind of deferred shading and post processing is reliant upon this functionality.

https://www.opengl.org/wiki/Framebuffer\_Object
> 1 votes

---
Tags: opengl, java, shaders, glsl, lwjgl
---


# Question
Title: How to correctly pass multiple light structures to shader stage?
I'm having some problems when passing multiple light structures to a shader stage. I'm using an array of point lights that is updated each frame.

This is my code for creating the buffer

```
D3D11_BUFFER_DESC lbDesc;
lbDesc.ByteWidth            = sizeof( PointLightData ) * NUM_LIGHTS;
lbDesc.Usage                = D3D11_USAGE_DYNAMIC;
lbDesc.BindFlags            = D3D11_BIND_CONSTANT_BUFFER;
lbDesc.CPUAccessFlags       = D3D11_CPU_ACCESS_WRITE;
lbDesc.MiscFlags            = 0;
lbDesc.StructureByteStride  = 0;

hr = mDevice->CreateBuffer( &lbDesc, nullptr, &mLightBuffer );

```

And this is how I update it

```
D3D11_MAPPED_SUBRESOURCE mappedResource;
hr = mDeviceContext->Map( mLightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );

if( SUCCEEDED( hr ) )
{
    memcpy( mappedResource.pData, &mPointLightData[0], sizeof(PointLightData) * NUM_LIGHTS );
    mDeviceContext->Unmap( mLightBuffer, 0 );
}

```

`mPointLightData` is declared like this

```
mPointLightData = new PointLightData[NUM_LIGHTS];

```

In my shader I declare the light

```
struct PointLight
{
    float4  positionAndRadius;
    float4  ambient;
    float4  diffuse;
    float4  specular;
    float3  attenuation;
};

cbuffer CB_LIGHT : register(b1)
{
    PointLight  pointLight[2];
};

```

I can only access the first light object in the buffer successfully. Rendering the second light results in a pitch black scene.

**However**, if I change the starting address at the mapping stage from `&mPointLightData[0]` to `&mPointLightData[1]` the second light works but obviously not the first.

So my guess is that I'm doing simething wrong at either the mapping stage or at the creation of the buffer..

Any suggestions? Thank you!

# Answer
There are additional alignment and layout rules for constant buffers. The `float3` probably needs padding on the CPU side to get the right stride.

Roughly paraphrased, things need to be on 16-byte boundaries.
> 4 votes

---
Tags: c++, directx11, hlsl, lighting
---


# Question
Title: Instantiation of multiple objects with varying velocities
I am looking to multiple objects of the same prefab at the same time with varying velocities.

```
public GameObject prefab;
public float xDirection;
public float yDirection;
void Update () {
        GameObject prefab1 = Instantiate
        (prefab,transform.position,quaternarion.identity) as GameObject;
        GetComponent<RigidBody2D>().velocity = new Vector2 (xDirection,yDirection);
}

```

I want to create three instances at once, but have the x/y direction be different. I am looking at creating an instance at three separate velocities. I know I can do something like this using

```
void Update () {
if (Input.GetKey(KeyCode.space)){
    xDirection = 1f;
    yDirection = 1f;
    shootObject();
    xDirection = 2f;
    yDirection = 2f;
    shootObject();
    xDirection = 2f;
    yDirection = 2f;
    shootObject();
    }
}
void shootObject () {
    GameObject prefab1 = Instantiate
        (prefab,transform.position,quaternarion.identity) as GameObject;
        GetComponent<RigidBody2D>().velocity = new Vector2 (xDirection,yDirection);
}

```

but I feel like there is something else that I should be able to do to simplify this even further since this seems to be very messy code.

(I apologize if something seems a little odd. Have only been coding for around a few weeks.)

Thank you for the help!

# Answer
There's not too much wrong with your code except you don't seem to be aware of how to use method parameters. I don't expect I need to explain much more than to show you the code...

```
void Update () {
    if (Input.GetKey(KeyCode.space)){
        shootObject(1.0f, 1.0f);
        shootObject(2.0f, 2.0f);
        shootObject(2.0f, 2.0f);
    }
}
void shootObject(float xDirection, float yDirection) {
    GameObject prefab1 = Instantiate(prefab,transform.position,quaternion.identity) as GameObject;
    GetComponent<RigidBody2D>().velocity = new Vector2(xDirection, yDirection);
}

```
> 1 votes

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


# Question
Title: Calculation correct position of object after collision (2d)
I have a circle, that bounces of walls. The circle is traveling at the speed defined by px/s for x and y. I have collision detection implemented and I use vectors to calculate the new x/y speed (and direction) after the collision. My problem is, that is some cases the circle gets stuck in or is consumed by the wall.

The reason for this is, that when the collision occurs, the circle is actually *x* pixels inside the wall (as illustrated by the image below) and not just at the "border" of the wall. This occurs because the circle might move multiple pixels on each redraw (tick). The circle doesn't move enough pixels during the next redraw in order to get loose from the wall, thus triggering a new collision. Direction changes again towards the wall leading to a shaking motion of the circle, either finally getting loose of the wall or being consumed by the wall.

The solution for this is to reposition the circle so that it is loose from the wall after the collision has occurred. My problem is, that with my rusty mathematics, I can't figure out how to calculate the correct position of the circle and that's where I need your help.

I also wonder, how exact I need to be with the position, I mean, I know the minimum distance of the middle of the circle to the wall (and thus also know how much the circle has penetrated the wall), let's call this value *d*. I could of course move the circle d pixels perpendicular to the wall, this might be a close enough approximation of the position, although not 100% accurate. If you guys think this is a good enough solution, is there a way to achieve this with vectors or do I need to calculate the angles and new position "manually" using cos and sin?

Side note: I'm not using SAT for collision detection because I have concave polygons.

# Answer
You are right in your assumptions of what needs to be done! In physics engines, after a collision was detected but before the collision is resolved (The changing of the objects velocity) there are a few steps which need to be done.

One of these steps is what I call decoupling: The process of separating two intersecting objects. This is the stage you are at. You have seen the results of neglecting to decouple intersecting objects when a collision is detected, and you have a good gage on what must be done to perform this decoupling.

You mention a value `d`, the penetration depth of the circle into the wall. You can actually calculate this depth pretty simply.

1. Take two points on your wall as vectors, `A`, and `B` and the center of your circle to be `C`.
2. Get the direction vector of the wall `dir = normalize(B - A);`. Then, get the vector from a point on your wall to the center of the circle `toCenter = C - A;`.
3. Now, you can use the projection to figure out the penetration depth! The projection of `toCenter` onto `dir` will give you the component vector of `toCenter` parallel to the wall. If you take this parallel component, and subtract it from the total, you are left with the vector which is perpendicular to the wall.

`perpVec = toCenter - projection(toCenter, dir);`

4. At this point, your penetration depth will be the radius of the circle minus the magnitude of the `perpVec`!

`d = radius - mag(perpVec)`

5. And if you move the circle `d` units in the direction of `perpVec` you can be left with your decoupled objects!

If you have trouble with the mathematics behind these operations, or their meaning and why exactly this gives you the proper solution, please let me know in the comments I would be happy to help.

To wrap it up and put a bow on it for you:

```
Vector dir = normalize(B - A);
Vector toCenter = (C - A);

Vector perpComponent = toCenter - dot(toCenter, dir) * dir; //toCenter - Projection

float penetrationDepth = radius - mag(perpComponent);

Vector mvmtToCorrectPosition = penetrationDepth * normalize(perpComponent);

```

**Edit**

A co-worker of mine, and myself have been continuing work on a slew of game programming examples. In the repository we actually have an explicit example of this but with two circles instead of a circle and a line:

https://github.com/MrNex/Game-Programming-Examples/tree/master/GLFW/Collision%20Resolution/Decoupling%20Intersecting%20Objects%20%28Circle%20-%202D%29/Decoupling%20Intersecting%20Objects%20%28Circle%20-%202D%29

Check out the main.cpp file. And if you are interested in the same example but with more complex convex polygons as colliding objects:

https://github.com/MrNex/Game-Programming-Examples/tree/master/GLFW/Collision%20Resolution/Decoupling%20Intersecting%20Objects%20%28Convex%20Hull%20-%202D%29/Decoupling%20Intersecting%20Objects%20%28Convex%20Hull%20-%202D%29

If you find these examples helpful please check the rest of the repository for a slew of stand alone game/graphics/physics programming examples in both 2D and 3D.
> 6 votes

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


title: Diversified Game Object List

text:
# Question
Title: Diversified Game Object List
Recently I started creating a game in java to hone my rusty java (I work primarily with cpp) and because I thought it to be a neat idea. To better illustrate the problem, let me explain a part of the game. The details aside, the game is in essence a dungeon builder and the problem pertains to the blocks you place down to create the maze adventurers have to travel through. Each block is a corridor and on each wall/floor/ceiling of a block you can place objects such as traps etc. However, while finishing up the game engine I realized I still lacked a list for blocks/objects that are special. Blocks or items that need a special animation (some extend spikes, some shoot fire, some contain a chest with inventory, etc). They're hard to bring together in one class and as we all know they can't be together in one list with different classes unless we want code-bloating. So my question is, what is the most efficient way to make collection of diversified game objects and how do other games do it?

Presently I have the following methods thought out.

* I reduce all objects to instances of one class. They all fit in one list. However, to induce special methods I need a long list of methods that each do something else. Frankly, this method is inefficient, unpleasant and unpractical to work with.
* I reduce all object to instances of one class. They all fit in one list. However, they each have an ID of a special action. If the need arises the ID gets compared with another list that's much shorter in length and uses generics or reflection to store the different effect. If it needs a special action it simply activates the effect (such as fire plume) on the given vector. The problem with this is that it does not allow for direct manipulation of the object such as a block that moves out to squash adventurers. Or if it could, it would be messy code, unnecessary throughput of code etc. I'd rather avoid it.
* I make a list of the base class/interface and add the different child classes to it. Each child class can thus have a different implementation. However, to access it, I need to know to use reflection and for that I need to know the initial class, which, in many cases, I don't since I want a dynamic system. The result is that I need to store the child class name in the 'block' parent class and then when the need arises, use that name to reflect the new class. Once again, it is inefficient and far too slow.
* I create a list of the block class and access it every time a generic block needs to be checked. However, if a creature/person walks over a tile it checks if the child class name in the block class is empty. If not, convert it to that class and execute the special function. This seems the best option as it gives the least code-bloating, is the most efficient, etc. However, it still needs to reflect and convert every time a creature goes onto a special block.
* I create an event driven list in which each block instance has his own special event that links to a certain animation. This is very tedious, very inefficient and because it is so detached it is once again difficult to animate the basic block.
* I use generics. Sadly, this causes far too much code-bloating and the accessing of the classes themselves gets difficult and messy.
* I create a huge switch method and each block instance has a number. The number corresponds with the correct animation in the switch it needs to execute. I don't think I need to say why I don't want to do this.

And there are a few more, but each of them is still as inefficient as the next. Furthermore, every time I look around this site or another people say "use a base interface/class in a list" however they never say what the most efficient way is to get the class out of the list again. Am I missing something obvious? How should I tackle this?

# Answer
> 2 votes
I will try to help you a litlle bit, in the way I can.
Correct me If I am wrong.
If I got it, then your game is about creating a dungeon, in wich, you can place block's to build it, like floor, ceiling's and such., and not only block's but you have other object's as well, like chest's and spikes.
So If I where to create a game like that, first, I would make an abstract class, wich is a father of all kind's of block's, or "Placeable's", these can be placed on dungeon's to build the stage.
So, the essential part of code wich manage placing thing's on stage, will be in this class.
Everything that you will put on the stage to build it, will be, in essence, for example an "Enviroment" Object., this object should be like an "Actor" as well, because, It's an object that is going to be drawn on screen, and (I least that's what I think) he should know how to draw himself, every Actor should have a Draw method that say's how he behave's when need's to be represented on screen. That said, father class, would be like:

```
    public abstract class Enviroment extends Actor{}

```

So a Floor block, Its just floor, and does not need to be animated, you will only need to place it somewhere, and give him a look, (asuming you are making a 2D game), that, would be just drawing a sprite and... done.
Then a floor, a wall, a door should be allright just extending of Enviroment:

```
    public class Floor extends Enviroment{}

```

Different It's the case, in wich, you have like a candle or spike kind of Enviroment. Those need to be animated, so, you need more like an "Animated Enviroment". Every thing that's going to be animated, in your world, should have an animation., then you can force any object who's gonna be animated, to actually do it., when you say that many different object's could share a behavior, then, they implement an interface.

```
    public interface Animable
    {
      InitializeAnimations(ASpriteSheet);
    }

```

So, then your AnimatedEnviroment that, is an abstract class, will implement this interface.

```
    public abstract class AnimatedEnviroment extends Enviroment implements Animable
    {
    }

```

Then, the way AnimatedEnviroment draws himself, It's not the same as Enviroment, cause he's an animation., every AnimatedEnviroment Object will draw an animation, cause you will override the Draw function in Enviroment.
Then a candle object will be:

```
    public class Candle extends AnimatedEnviroment{}

```

In any case, you will have a Candle, that knows how to animate itself, and not only that, this Candle will know how to place itself, cause It's an Enviroment too.
In case of a chest it will surely implement an interface that would be like a "Lootable", this will asure you that every lootable object will open a window to choose wether you want to pick items from it or not, it will extend AnimatedEnviroment, Cause It's gonna animate Himself when it open's, or maybe you just don't want to animate it at all, and just extend it from Enviroment. Anyway a Chest object, will be an Enviroment, and can be placed in Stages., because he already has all the behavior of an enviroment that he inherited and know's how to do it.
Same with spikes, you want them to harm when you step on them, and they get out and in, they are animable and they are hazardous, so It's HarmfullEnviroment that implements Hazardous and extends from AnimatedEnviroment., It make's you add a behaviour that, when you step on them, they make lose the hp of an aventurer object., and know's how to place himself in stages.

So when you check that an adventurer object step's on an enviroment object, you can ask wich kind of Enviroment he stepped on.
(This is an aproximation of a code that I just thougt, I don't know if this would be cool to implement, but for explanation pruposses, it should be ok)

```
    public void VerifyEnviroment(Adventurer[] MyAdventurers)
    {
       For (Adventurer CurrentAdventurer : MyAdventurers) <----''this is a list.
       {
          Enviroment = GetEnviromentHeSteppinOn(CurrentAdventurer.getX(),CurrentAdventurer.getY());

            If (Enviroment instanceof HazardousEnviroment)
            {
                CurrentAdventurer.setHp(CurrentAdventurer.getHP() - (HazardousEnviroment)Enviroment.DoHarm());
            }
       }
    }

```

When you make a list, you are making an Enviroment one, and you are adding Enviroment, you don't really care what kind of Enviroment, you just know that they are going to be placed.
I think that a game is complex enough for not-to-be organized with code, so, this is how I would do it.
Sorry if I extend it too much or If I gave you bad practices, but at least is a point of view; Im curious of what kind of platform you are aiming for, if your objective are smartphones I would start from here and then see what I can do to ease method calls or drawing, for example, floor's, don't necessary need to be a lot of block's, but just a large sprite with a certain pattern that cover's all the screen, different would be the case with other Enviroments that could be smaller.
A solution could be just store in a list where the HazardousEnviroments Are placed, so you just ask if any adventurer I'ts on any of them, and if possible, limit the amount of those according to your adventurer's level, should help you save the amount of check's.
Hugs.

---
Tags: architecture, gameobject
---


# Question
Title: Collision Detection/Response Issues in Unity
Sprite A: Box Collider 2D and Rigidbody 2D.

Sprite B: Box Collider 2D.

Both sprites have a Sprites/Default material with Pixel Snap enabled. The textures being used are set to Truecolor Format and Point Filter Mode. No Mip Maps and 1 Pixels Per Unit (higher PPU seems to make the issue more obvious, but lower value does nothing but scale the problem down).

I put Sprite A above Sprite B, hit play. I see Sprite A fall into Sprite B and hover slightly above it. I think this is horrible, so I look it up. I find I can lower Min Penetration For Penalty to help.. but not fix.. this issue. It's barely noticeable now.

After a while, I noticed Sprite A sometimes overlaps Sprite B briefly during collisions. I can't seem to find a clean fix to either of these issues.

Is Unity's physics engine just not designed for the level of accuracy I'm wanting? It seems the whole way the physics engine works is by allowing overlap (minPenetrationForPenalty) before pushing objects out of each other. I've been coding for many years as a hobbyist, so no professional experience, but this seems.. wrong. Are there options that don't involve overlapping of objects?

Thanks for any and all help.

# Answer
> 1 votes
You could try changing the collision detection to Continuous or Continuous Dynamic. See the Unity Manual: Rigidbody for further info.

# Answer
> 1 votes
This will occur in Unity, if a GameObject is too small. The colliders will end up being either too far or overlapping, as the physics get unstable if the GameObjects are too small.

Try making the gameobjects much larger (change the pixel per unit size), and you will see that it will more than likely fix your problem.

# Answer
> 1 votes
Sounds like a simple rigidbody setting. Change from interpolate to extrapolate, or vice versa.

http://docs.unity3d.com/ScriptReference/Rigidbody2D-interpolation.html

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


# Question
Title: PhysiJS and objects on top of moving objects
Using Physijs which uses ammo.js.

I am attempting to simply place a sphere on top of a box, the box is moving back and forth and I want the sphere to move with it while also being able to move on top of it.

I am already handling moving the object with `setLinearVelocity` but even with max friction the sphere doesn't "stick" to the box. I've tried increasing sphere velocity based on box speed but it doesn't seem to work.

Should this be working or am I on the wrong track? I've been stuck on this for quite a while and have tried every solution I can think of or find (and you can't find much on physijs). Perhaps I should try to get rid of Physijs entirely and just use ammo.js if I am trying to do these more advanced physics? (there will be much more to be added)

Hope my question is clear, and please let me know if you need code samples but it will be difficult to provide a good sample since my code is all modular and split up.

# Answer
I discovered that I needed to do the following:

Set the moving cube with weight of 1 and then `setLinearFactor` to `x,0,x` and `setLinearRotation` to `0,0,0`. This allowed me to use `setLinearVelocity` as expected and then increase the velocity of my sphere on top of the cube accordingly.
> 1 votes

---
Tags: physics, three.js
---


title: Alternatives to the GPL

text:
# Question
Title: Alternatives to the GPL
I made a game, and I am currently making a game engine. I want them both to be completely free and open source. What license should I choose? I was reading a bit on GPL, but that seems to be more suited for system code and libraries, AFAIK, as it doesn't permit the use of code for proprietorial software - which, in turn, implies that the code can be *used* in the first place. I can see that, obviously, game engines can be considered libraries, and therefor be *used*, but what about game code?

Is there an alternative to GPL?

# Answer
First off, this isn't legal advice and I'm not a lawyer.

There are tons of opensource licenses: http://www.opensource.org/licenses/alphabetical, and you have many different licensing options. Here's a super brief run down of popular license options... I may have gotten some details wrong.

**GPL** doesn't allow your code to be used in a project that is closed source (proprietary). You should only use the GPL license when you want to force anyone else who uses your code to have an open source project as well. Specific to your question, licensing your engine under the GPL would probably turn a lot (the majority) of people away from using it.

**LGPL** allows your code to be used in a project that's closed as long as they don't directly include your code in their project, but link to your code as a dynamic library instead. The project maintainers are also required to make any changes they make to your library available (so any bug fixes, etc need to be made available as open source). The linking issue has important consequences -- afaik technically you shouldn't be using LGPL'd code in a closed project on iOS for example, since they only allow static linking.

**BSD** allows your code to be used in a closed source project as long as proper attribution is maintained. There are some other specifics as well that try and absolve the author of the code from being liable for its use. This is a much more liberal license than any of the GPL ones.

**MIT** is very similar to BSD. Both BSD and MIT basically allow anyone to do practically whatever they want with your code. They aren't obligated to make any changes/fixes they apply back to you and can include your code in their project in any way they deem fit.

There are tons of other licenses. I suggest you check out the **Apache** license, **Mozilla** license, and the **zlib** license as they're in common use as well. Also check out the **WTFPL** :)

There are also important details between license versions, especially with the GPL licenses... so make sure you read up on those before choosing between LGPLv3 and LGPLv2.1 for example.
> 13 votes

# Answer
There are many alternative to the GPL. For starters, there is the LGPL.

However, there are several other more permissive and straightforward open-source licenses such as MIT and BSD. OpenSource.org has a large collection of open-source appropriate licenses available for perusal.

*In my opinion* you would do well to avoid the GPL and its derivatives (LGPL), instead opting for the MIT or BSD licenses. The GPL family of open source licenses are extremely complex as well as viral, and as a consequence are hard to use correctly, by both licensees and licensors.
> 3 votes

# Answer
The GPL is perfectly suitable for game engines, and data/content can be put under the GPL as well. In the case of data, the GPL simply has some clauses that don't apply.

Note that the GPL *does not* ban the use of your code/data in commercial projects. It is 100% legal to sell copies of modified GPL software - you simply must provide the source to the modifications or any other modules linked to the GPL code.

You might consider the more content-oriented Creative Commons licenses for your data. The CC licenses let you pick the exact "features" you want, including true non-commercial usage clauses if you want them. It's also feasible to use these licenses for code, as well.

All that said, purely in my own opinion I find it "anti-social" to use non-commercial or even GPL licenses. Projects like Lua, zlib, libpng, Box2D, Bullet, and so on are pretty key to the games industry and happily exist (and some even get funding) despite being very liberally licensed. Restricting what people can do with code only results in them rewriting something they might not have to; you don't get a dime from them either way, and at least with a liberal license you have a chance of building a reputation as being the author of critical components in popular games (which leads to great job offers).
> 2 votes

# Answer
*Please* use the Zlib license, or something similar, instead of the GPL. The Zlib is very liberal and allows developers to use your code in closed-source projects.

This will bring benefits for you, as developers will be more likely to use your engine if they know they can make money off of their project. You won't be losing anything by letting them profit, and they'll be more grateful and richer; thus, more likely to donate.

I'm currently using the Zlib license for a library I developed.
> 2 votes

# Answer
Mozilla Public License Version 2.0(MPLv2) is a FSF-approved open source license. It prohibits changes to the MPLv2 licensed code without redistribution of the MPLv2 code but is non-viral. It can be likened to a more reasonable LGPL.
> 2 votes

# Answer
You may also want to take a look at the Apache License v2.0. It is similar to the BSD and MIT licenses in that there is no copyleft. It's differs in that it spells out its conditions EULA-style that the BSD and MIT licenses mostly imply, such as the grant of patent rights.

Google also recommends the Apache License v2.0 in this post about license proliferation (and GPL v3 if you want copyleft).

An overview on OSS Watch
> 1 votes

# Answer
The GPL is a so called "coypleft license" that means, everyone who uses it will have release their source code as well under the same license.

The GPL does not, in any way prevent commercial use, it does however prevent DRM and restrictions on "sharing" it. And most commercial entities won't even consider sacrificing that.

There is the LGPL which only applies to modified code and not to the whole project, e.g. a game could use your engine but still not be avaible under the LGPL.

There are many people who prefer non-copyleft licenses such as the MIT license, the BSD license or the zlib license. These make almost no restrictions, aka "Do whatever you want as long you keep this license note"

There is also a middle way: dual licensing. There are companies which release their library under the GPL or the LGPL (example: Qt) but for a little fee also give out a different more liberal license. So everyone can use it under the terms of the GPL, but if they need more they can pay for it.
> 0 votes

---
Tags: legal, licensing
---


# Question
Title: How can I rasterize 3D triangles in software?
I am creating a 3D software renderer, and I have a wire frame cube rendering. Now I am working on solid color rendering and I am wondering what an efficient algorithm for shading the contents of the triangles would be?

# Answer
Let's call the vertices of a single triangle **v1, v2, v3**, and the colours of those vertices **c1, c2, c3**.

The general start to filling in your polygons is as follows:

1. iterate over every pixel of your screen
2. for every x/y coordinate calculate the barycentric coordinates **b1, b2, b3** with respect to the triangle you are trying to draw. You can find formulas on how to calculate these on the wikipedia page: https://en.wikipedia.org/wiki/Barycentric\_coordinate\_system

(If you want you can derive these formulas yourself, it's good practice and not that hard.)

The thing about barycentric coordinates is that whenever all of the coordinates are between 0 and 1, the x/y point that corresponds with it lies in the triangle. Whenever some of the barycentric coordinates are 1 or 0, and the others are between 0 and 1, the x/y point lies on the edge or corner of the triangle.

3. So now you simply check if the barycentric coordinates are between 0 and 1 inclusive, and if they are you draw a pixel there. If you want colour then you simply multiply **b1 * c1 + b2 * c2 + b3 * c3**, which will result in a Gouraud shaded triangle interpolation.

=========================================================================

There are many optimisations to be made to this algorithm, as well as some problems to be solved. I'll briefly describe the problems and solutions here:

**Edge pixels:**

If two triangles are drawn on each other, to which triangle does the edge between them belong?

You need a homogeneous way to solve this for all triangles. A solution would be to pick an off-screen point and assign the edge to the triangle that is closest to the off-screen point.

**Incremental calculation:**

The barycentric coordinates currently are being calculated freshly every new iteration, this is slow. We really want to do this incrementally, so we take every calculation out of the loop that we can, and we calculate the delta changes in the barycentric coordinates. We then add those to the starting coordinates every iteration to get the final barycentric coordinates.

**Early return:**

If we step through the whole screen and while iterating a row we find a section of triangle.
**X**
0 - 472 = no triangle
472 - 582 = triangle
582 - 640 = no triangle

Then after we found the triangle we know there is not going to be anything after that in the same row, so we simply go to the next row.

**X**
0 - 472 = no triangle
472 - 582 = triangle... STOP

**End notes** By now you should be getting well over a 100,000 triangles drawn per second on a modern computer. There are multiple different ways to determine in which order to draw these triangles. The easiest is the painters algorithm where you simply draw them from back to front. A z-buffer is another option you can employ.
> 4 votes

---
Tags: 3d, software-rendering, rasterization
---


# Question
Title: What kind of issues should I watch out for or avoid when using JOGL(OpenGL Java bindings)?
I am completely new to OpenGL, but have a very good basic foundation in Java. I've set up Eclipse with the most recent version of JOGL recently, having found it to be, of what I as a beginner programmer, feel as very easily adaptable from the original OpenGL code. By simply using a replace all command to change the C++ native library commands from gl to gl.gl, and GL\_ETC to glu.GL2\_ETC, and so on and using a website with OpenGL tutorials on nehe.gamedev.net that I recently found, I was wondering if there are any huge problems or things I should avoid for instance using awt or swing as a frame or window for a viewport program. Maybe I'm trying to ask a more specific question before I even try it on my own, and that is, "Do I use windows from both languages consecutively or would it just create two windows, whilst trying to only open one window?", as they both have similar methods and objects aside from OpenGL being much more centered on 3D graphics. The reason I ask is that the 3D graphics of OpenGL usually must be built on a frame as far as I know, or linked to the main method of course like anything.

# Answer
> 1 votes
You generally use a window provided with the library that supports OpenGL. I don't have any experience with JOGL but it seems it works with Swing, although apperantly with a small performance penalty.

LWJGL, another alternative for OpenGL in Java provides a window library with it which is native to C/C++ and is normally used for OpenGL rendering.

---
Tags: opengl, java, jogl
---


# Question
Title: Rotate coordinates back after rotating game context (geometry)
To achieve something similar to the image below using HTML5 canvas one can simply write the following:

```
var TO_RADIANS = 0.0174532925;
context.translate(30, 20);
context.rotate(30 * TO_RADIANS);
context.drawImage(img, 0, 0);

```

My problem comes when I want to convert the coordinates from inside the translated/rotated context back to the main context. For example, if a missile were shot from 0,0 inside the translated/rotated context along the X axis, what formula would you use to then convert its position to the outer context?

# Answer
> 2 votes
Note the following important identity for *augmented **isometric** affine matrices*:

$$ \begin{pmatrix} cos\theta & sin\theta & -(xcos\theta + ysin\theta)\\ -sin\theta & cos\theta & -(-xsin\theta + ycos\theta)\\ 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} cos\theta & -sin\theta & u\\ sin\theta & cos\theta & v\\ 0 & 0 & 1\\ \end{pmatrix} \begin{pmatrix} x\\y\\1\\ \end{pmatrix} = \begin{pmatrix} x\\y\\1\\ \end{pmatrix} $$

where the ***isometric*** condition is recognized from: \\$cos^2\theta + sin^2\theta=1\\$ and \\$\begin{pmatrix}u\\v\end{pmatrix}\\$ is the translation in world coordinates of your original transformation.

In vector terms, if you think of your original transformation as being $$ \begin{pmatrix} R & T\\ 0 & 1\\ \end{pmatrix} $$

then the inverse transformation, to return to World Coordinates is simply

$$ \begin{pmatrix} R^{-1} & -R^{-1}T\\ 0 & 1\\ \end{pmatrix} $$
where because of *isometry* the *inverse* of **R** is simply the *transpose* of **R**, as noted above.

In vector form the initial identity is just
$$ \begin{pmatrix} R^{-1} & -R^{-1}T\\ 0 & 1\\ \end{pmatrix} \begin{pmatrix} R & T\\ 0 & 1\\ \end{pmatrix} \begin{pmatrix} v\\1 \end{pmatrix} = \begin{pmatrix} v\\1 \end{pmatrix} $$

which is readily proved by multiplying out to get first
$$ \begin{pmatrix} R^{-1} & -R^{-1}T\\ 0 & 1\\ \end{pmatrix} \begin{pmatrix} Rv + T\\1\\ \end{pmatrix} = \begin{pmatrix} v\\1 \end{pmatrix} $$

and then reducing the left hand side as $$ \begin{pmatrix} R^{-1}Rv + R^{-1}T-R^{-1}T\\1\\ \end{pmatrix} = \begin{pmatrix} R^{-1}Rv\\1\\ \end{pmatrix} = \begin{pmatrix} v\\1 \end{pmatrix} $$

Q.E.D.

Note also that the vector form of the identity is not specific to only a 2D space, but applies to any number of spatial dimensions.

# Answer
> 0 votes
You basically found out about transforms and spaces in 2D!

If you enter this "new missile space" via translation followed by a rotation then you have to do the same thing in reverse, multiplied by -1.

```
missile.rotate(-30 * TO_RADIANS);
missile.translate(-30, -20);

```

Now your missile is in "world space".

---
Tags: 2d, mathematics, javascript, geometry
---


# Question
Title: EXE-ifying custom levels/scripts/graphics/music
My game is pretty much just a game-builder, where you create your own levels, scripts, graphics, music etc. and the game just loads them from a file you tell it. But how would I make it so the user could generate an exe that would just load the game files and act like a standalone game but actually be made with the game-builder thing? I'm using C++.

# Answer
A straightforward approach could be to produce a folder which contains always the same executable, copied, and different files next to it. The executable would look for data files relative to itself.

```
.../MyNewThing/
    MyNewThing.exe <-- renamed but identical
    resources/ <-- files with known names or name-patterns
    MyNewThing.data <-- alternatively

```

So, it's not a single self-contained file, but should be quite clear that you need to copy the whole folder.
> 1 votes

---
Tags: c++, data, user-generated-content
---