# Question
Title: Android Game-Loop (rendering & logic removed, but still 'skipping frames')
**Overview**

Guys really hoping for some help here. My game loop is based on code from Fix Your Timestep!.

I've read the article more than a few times, but I can't quite work out what *exactly* is supposed to be going on within the loop.

I'm running my code on a Nexus 10 tablet which has VSync set to 60fps.

**Playing catch up**

When I run my code, I'm getting caught quite often in the while loop, ie it runs my logic more than once - so runs logic twice in a row before rendering).

With my understanding of the loop, this should happen when rending takes too long to fit into the time slice (which is 16.66666666666667ms).

So, maybe in 'normal circumstances', I would expect this to happen occasionally).

However, I've tried removing **all rendering and logic updating** and just running a skeleton loop and I'm still getting caught regularly and constantly within the 'while-loop'.

Therefore, when I'm running my game (with rendering and logic), I'm getting a lot of stuttering because I *know* the loop is going to skip frames. **The logic updates *are* however being capped at 60 which is exactly what I want**.

Obviously whether or not my rendering or physics update could be more efficient is not the issue here and is a question for another day as I've already removed that from the equation.

I can smooth things out somewhat with interpolation and it really does make a difference, however, it's not as smooth as some of the games I download from the Play Store and I really need to make it better.

So, what am I missing or not understanding? I would think it should (certainly with no rendering or logic updating to create a bottleneck):

* Enter the while-loop
* Exit the while-loop
* Wait for next VSync
* And repeat

Here is the loop I'm testing with:

```
@Override
public void onDrawFrame(GL10 gl) {

    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime; //Amount of time this entire frame took
            if ( frameTime > (0.25))
                frameTime = (0.25);

            currentTime = newTime;
            accumulator += frameTime;

            //Update logic
            while (accumulator >= dt){
//              saveGameState();  //Removed for testing
//              updateLogic(dt);  //Removed for testing
                accumulator -= dt;
            }

            //Get the amount to interpolate by
//              interpolation = (float) (accumulator / dt);  //Removed for testing
//              render(interpolate);                         //Removed for testing

}

```

# Answer
**Fix your Timestep does *not* deal with graphical stuttering even in a correct implementation.** Assume a working implementation where the only game logic is physics. If physics is at 50Hz, and render can run at 200Hz, you're only going to see 50Hz *unless* you implement visual interpolation. Likewise, if your framerate varies, *expect* stuttering.

The rest of this answer is largely a re-explanation of the above, with some extra points.

**Possibility 1: Cost too high - missing updates**

If you're often missing frames per se, i.e. not even getting a single frame in a given update then your per-frame logic is too costly and you need to reduce it, e.g. have fewer physics bodies active.

**Possibility 2: Cost reasonably low against a fluctuating frame period**

> I'm getting caught quite often in the while loop, i.e. it runs my logic more than once

Therein lies your problem. When the system is running your code on true fixed-rate vsync, you expect the same number of logic updates per display update. 1 or 10, but it should always be same - if it is, no stuttering. Android frame rate is quite steady, on my devices it's just under 60fps for a light NDK/OpenGL app, *but it does fluctuate*. Read on.

There's quite a difference in expectations between setups where you

* have direct control over the core (while) loop, which you can run at the highest rate possible given the ops coded there in C/C++ code, and where if you take too long to process / render, that is entirely your own concern - but typically you have many render frames per logic frame;
* have a (relatively) fixed frame rate dictated to you by the system, which calls your update (`onDrawFrame()` in this case) as a callback e.g. browser JS, Flash, or in this case, Android - here you have one or more logic frames per render frame (see the inversion from the above case?), and you absolutely must complete at least one logic update per frame period (dictated by the system) for things to proceed sanely - this which is fundamentally different.

From early experiences with this, I believe Gaffer's concept (in that article) is geared to the former, i.e. primarily AAA desktop and console games written in C++ where the core loop runs as fast as possible and often without any external timing mechanism (ever seen those Quake demos where they're getting like 400fps?). Let's look at some examples to see what can happen with the latter.

**Example A** \- the display frequency is relatively steady, around 16.7ms period, give or take a millsecond or 2, and for maybe 90% of frames, it is spot on at 16.7. Let's say your logic takes 9ms. Most frames, then, you'll manage just one update. But due to unforeseen delays in the Android operating system, the period on which `onDrawFrame()` fluctuates and sometimes jumps up to 18+ ms every so often, say 5% of the time, and then you are going to end up doing 2 logic updates because you have enough time do so instead of just 1...but the actual display frequency hasn't changed so much that it would have been apparent using a one-logic-update-per-display-update approach anyway, so what do you see? Stuttering, of course.

**Example B** \- Your logic processing takes about 16.3ms on average. If at any stage it jumps up by say 0.5ms, and exceeds the point by which the OS intends to render, you'll also see stuttering, the severity of which depends on the frequency with which you exceed that soft limit of around 16.7ms.

**Crucially,** It's not that the accumulator approach isn't a good one - it's excellent, in fact, and is really the only sane way to handle the fixed timestep required for stable physics without frequent network desync (after all, you cannot just drop the accumulated time, and every client is going to accumulate differently). But if you don't have direct control over the timing loop, you can easily run into problems you didn't expect. And you must appreciate that when the accumulator does build up enough time to run more than one update at a time (the exception rather than the rule), then it may well lead to a jarring visual result. So you will need to do graphical interpolation.

**In conclusion**

You need interpolation if you want to accurately reflect your maximum frame rate as against your slower logic update rate, and with naive interpolation you may still perceive unwanted variances in frame rate due to occasional double-runs of physics and game logic. Admittedly I'm not an expert on interpolation / extrapolation algorithms but it stands to reason that the more frames you use to calculate averages over, the smoother it's going to look, though too many frames has drawbacks.

When there **is** a mechanism in place dictating your timing, it's best to just stick with that and not try to work around it - such loops (as opposed to what Gaffer describes) are intended for one update per frame. If there are good solutions for this type of scenario, I'd love to hear them.

*However*... I've not used Android's Java interface for game dev (only NDK), but what I would suggest (if possible?) is to run a while loop that has nothing to do with `onDrawFrame()` but rather just sits in main doing its game / physics logic things, while `onDrawFrame()` purely handles rendering at the appropriate time. I don't know how that will sync up or even if it will work at all.

For Android NDK as with most native development, you have direct control over the while loop off which everything runs - game logic and render calls - so the problem there is already solved.
> 1 votes

# Answer
The purpose of the fix step time loop is to always update at a fixed time interval. This is important in things like collision which that big delta times could cause objects to phase through another. Updating multiple times between rendering is the desired behaviour. Your loop looks fine but the problem is that the device (or other part of your code) is not fast enough to keep your game running at 60FPS. Perhaps the problem is in the Vsync. See this link.
> 0 votes

# Answer
*\[I'm posting this as an answer because I don't have enough reputation to post comments.\]*

I wanted to add a comment to Arcane Engineer's answer since it is fundamentally wrong because it is based on a misunderstanding on what Gaffer's "Fix your timestep" tries to communicate.

The design suggested by Gaffer disconnects the rendering from the physics (ie updating), so it is not relying on having the highest possible rate of rendering. Nor is it relying on a vsync fixed rate of rendering. The design described by Gaffer allows the rendering to run at any rate (max speed, fixed vsync, or even slower than the physics updates) independently of the updating which in contrast must run at an absolutely fixed rate to achieve the desired determinism of the model progression.

Now to the original question. There is a bit of information missing, namely the value of the delta time (dt). If dt is set to eg. 0.01 as it is in the Gaffer article, then staying in the while loop for two updates is expected behaviour - at least about every other pass through the rendering loop.
> 0 votes

# Answer
I would personally never make my control loop within the render method (here onDraw). However, to prove to Arcane Engineer that he completely misunderstood the functionality of the Fixed Timestep algorithm, and to show the original poster (and any other interested parties) that the algorithm itself works exactly as intended I made this implementation exactly like the original poster intended.

Contrary to the claims of Arcane Engineer the purpose of the algorithm IS to make sure that the updates to the model is running with completely fixed increments even when controlled by a fluctuating timer.

I made a very simple implementation the Gaffer algorithm in Android - as requested - to give you an opportunity to... what was the phrase? *"explain to your children and grandchildren the day when you were knocked to the floor in disbelief"* :-)

This implementation updates the display about 60 times per second. And it updates the model about 100 times per second. But the delta time (dt) can be set to any value - for instance 0.04 to make it run about 25 times per second, but still the animation will be smooth because of the interpolation.

**Activity class**

```
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    private FixedTimestepView view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = new FixedTimestepView(this);
        setContentView(view);
        view.run();
    }

}

```

**The View**

```
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class FixedTimestepView extends View {
// Render frequency
private static final int FPS = 60;
private int worldWidth;
private int worldHeight;

// Gaffer timestep control
private double t = 0.0;
private double dt = 0.01;   // Fixed update speed
private double currentTime;
private double accumulator = 0.0;

// States
private FixedTimestepState mPrevState;
private FixedTimestepState mCurState;
private FixedTimestepState state;

private Paint p = new Paint();

public FixedTimestepView(Context context) {
    super(context);
}

@Override
public void onSizeChanged(int newX, int newY, int oldX, int oldY) {
    super.onSizeChanged(newX, newY, oldX, oldY);
    worldWidth = this.getWidth();
    worldHeight = this.getHeight();
}

public void run() {
    Thread animationThread = new Thread() {
        @Override
        public void run() {
            final long millis = 1000 / FPS;
            final int nanos = (int) ((1000.0f / FPS - millis) * 1000000);
            init();

            while (true) {
                postInvalidate();
                try {
                    Thread.sleep(millis, nanos);
                } catch (InterruptedException ex) {
                }
            }
        }
    };
    animationThread.start();
}

public void init() {
    p.setColor(Color.RED);
    state = new FixedTimestepState();
    mCurState = new FixedTimestepState(50, 50, -100, 65, 20);
    mPrevState = new FixedTimestepState();
    currentTime = System.currentTimeMillis() / 1000.0d;
}

@Override
public void onDraw(Canvas g) {
    // Implementing the Gaffer algorithm directly in the onDraw method

    double newTime = System.currentTimeMillis() / 1000.0d;
    double frameTime = newTime - currentTime;
    if (frameTime > 0.25)
        frameTime = 0.25;
    currentTime = newTime;

    accumulator += frameTime;

    while (accumulator >= dt) {
        mPrevState.set(mCurState);
        integrate(mCurState, t, dt);
        t += dt;
        accumulator -= dt;
    }

    final double alpha = accumulator / dt;

    state.interpolate(mCurState, mPrevState, alpha);

    render(g, state);

}

public void integrate(FixedTimestepState state, double totalTime, double deltaTime) {
    state.update(deltaTime);
    state.handleCollision(worldWidth, worldHeight);
}

public void render(Canvas g, FixedTimestepState interpolatedState) {
    g.drawColor(Color.BLACK);

    final int left = (int)interpolatedState.x;
    final int top = (int)interpolatedState.y;
    final int right = left + (int)interpolatedState.size;
    final int bottom = top + (int)interpolatedState.size;
    g.drawRect(left, top, right, bottom, p);
}

}

```

**The State**

```
public class FixedTimestepState {
public float x;
public float y;
public float vx;
public float vy;
public int size;

public FixedTimestepState() {
    this(0.0f, 0.0f, 0.0f, 0.0f, 0);
}

public FixedTimestepState(float x, float y, float vx, float vy, int size) {
    set(x, y, vx, vy, size);
}

public void set(float x, float y, float vx, float vy, int size) {
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.size = size;
}

public void set(FixedTimestepState state) {
    x = state.x;
    y = state.y;
    vx = state.vx;
    vy = state.vy;
    size = state.size;
}

public void interpolate(FixedTimestepState currentState, FixedTimestepState previousState, double alpha) {
    x = (float)(currentState.x * alpha + previousState.x * (1.0 - alpha));
    y = (float)(currentState.y * alpha + previousState.y * (1.0 - alpha));
    vx = (float)(currentState.vx * alpha + previousState.vx * (1.0 - alpha));
    vy = (float)(currentState.vy * alpha + previousState.vy * (1.0 - alpha));
    size = currentState.size;
}

public void update(double deltaTime) {
    x += vx * deltaTime;
    y += vy * deltaTime;
}

public void handleCollision(int worldWidth, int worldHeight) {
    if (x < 0 && vx < 0) {
        vx *= -1;
        x = -x;
    } else if (x + size > worldWidth && vx > 0) {
        vx *= -1;
        x -= (x + size - worldWidth) * 2;
    }

    if (y < 0 && vy < 0) {
        vy *= -1;
        y = -y;
    } else if (y + size > worldHeight && vy > 0) {
        vy *= -1;
        y -= (y + size - worldHeight) * 2;
    }
}

}

```
> 0 votes

---
Tags: java, android, game-loop, fixed-timestep
---


title: Spriter model not touching ground in?

text:
# Question
Title: Spriter model not touching ground in?
I was attempting to make a game in Construct 2 by using my Spriter Models plugin. However, when I imported the model, rescaled it & changed a few things, I got this:

As seen in the picture, the Spriter model is not touching the platform ground.

Do you know of any ways I could have the model touch the ground?

Thanks in advance,

Jamie

Ps. Here is the link to the files, just in case you guys might wanna have a look at it:

https://drive.google.com/folderview?id=0B11opD9YgSqWbVhaNEVTcGhIRTA&usp=sharing

Pps. You will need the Spriter plugin for Construct 2 to open the project file. The Spriter model files will need Spriter to open it.

# Answer
It looks like your bounding box is **too large** for your sprite, try making sure that the sprite's feet touch the bottom of the bounding box in *Spriter*.

**EDIT:** It turns out can do it Contruct 2 itself, just double click on the part of the sprite that dosent touch the ground to open the sprite editor. Then click on crop and you're good to go!
> 0 votes

---
Tags: sprites, html5, models, platformer, construct-2
---


# Question
Title: How can I separate processing input and update?
I know that game loop is broken up into three distinct phases: processing inputs, update, and render, but I just can't see how I can make processing input and update independent of each other.

Let's say I have a button. If I click on the button, it will increment the number by one on the screen. How can I make this possible? Is it OK to update the logic while processing the input?

For example:

```
 while (!ended)
 {
   while (SDL_PollEvent(&event))
   {
       IF MOUSE EVENT
          IF USER CLICKED ON THE BUTTON
              NUMBER += 1;
   }

   update(); // no job for update as number was incremented above
   draw();
 }

```

Why would I need a distinct update function if we could just update logic/values while processing input like the code above?

Please show me an example using SDL poll event system.

```
 while (!ended)
 {
   while (SDL_PollEvent(&event))
   {

   }

   update();
   draw();
 }

```

# Answer
I think it all depends on how complex your game is. If it is very simple, I don't see why you couldn't updated some game states right at the input query. That is part of the game update, after all.

But you can enforce a cleaner separation in a very simple way if you want. This should also have the advantage of removing the explicit coupling of your portable game code with the SDL library. If you want to change to some other library in the future it's easier that way. Taking mouse input as an example, you could define your own `MouseInput` class, in pseudocode:

```
class MouseInput
{
    int x;
    int y;
    bool leftButtonDown;
    bool rightButtonDown;
    // etc ...
};

```

Then instead of directly updating some game state when you poll inputs from SDL, update your `MouseInput` states:

```
MouseInput mouse;

while (!ended)
{
    while (SDL_PollEvent(&event))
    {
        if (event == LEFT_BTN_DOWN)
        {
            mouse.leftButton = true;
        }
        else if (event == LEFT_BTN_UP)
        {
            mouse.leftButton = false;
        }
        // same for the other buttons and the x,y cursor position.
    }

    // Now whenever something needs to know the current state of
    // the mouse it just queries the local MouseInput instance.
    //
    // It could be a class member, or you can even pass it as a parameter
    // to update() to emphasise that it is a current-frame-only state.
    //
    update(mouse);
    draw();
}

```
> 3 votes

---
Tags: c++, sdl, game-loop
---


title: Keeping high scores on Unity web player

text:
# Question
Title: Keeping high scores on Unity web player
I want the player to be able to save his score when she makes it into top 10 of high scores. Upon success, player will be asked for a name to submit. This does not need to be unique per player. I just want a basic global score board available for everyone who plays the game via web player (from github.io page of the project).

When searched for how to keep high scores, I came across PlayerPrefs.

> On Web players, PlayerPrefs are stored in binary files in the following locations:
>
> * **Mac OS X**: ~/Library/Preferences/Unity/WebPlayerPrefs
> * **Windows:** %APPDATA%\Unity\WebPlayerPrefs

As far as I understood, the results are kept in local machine and won't be same for everyone. So it's good for keeping track of your own score, locally.

As a placeholder in the current version of the game, I keep the scores in a local .txt file in the project directory. Can I succeed with this approach and use the github.io server to maintain a global scoreboard or do I necessarily need a database to achieve this goal?

# Answer
If you want to have a shared leaderboard for all players, then PlayerPrefs is not what you want. It's designed to save a file to the player's local computer, which only they can access. For a global leaderboard, you'll need to implement a server-side component for the game to communicate with.

This page on the Unity wiki might be helpful to get you started.
> 1 votes

# Answer
Look at this tutorial: https://www.youtube.com/watch?v=UvKLmQ6VAtg

You will get the scripts / tutorial-package here: http://mole.bplaced.net/?page\_id=32

It is very easy with this help and completly free...
> 1 votes

---
Tags: unity, databases, leaderboards
---


# Question
Title: NoSQL (CouchDB) database design for MMORPGs
Are there any pratical examples of database implementation for an MMORPG in CouchDB? Even a detailed thesis? I've looked but found very little on practical examples and not even find any good UML examples and plus I see a little bit of an issue with the lack of schema and design by UML. Maybe It's more of a paradigm change but I'm ideally looking for something that has things like:

Users Quests (multipart states) Characters NPC states Items

Just to get started...regards

# Answer
> 2 votes
With a NoSQL database, you are able to more directly map your application data to your datastore. Object-relational impedance mismatch isn't any issue, and as such you can create a more direct relationship between your application's class design and the schema of your NoSQL database.

Example, for a hypothetical Player class, which may contain complex data structures, attempting to store that data into a relational database would require a complex database schema, as well as complex wrapper classes in the game's actual code base. Almost all of this complexity is removed when storing into a NoSQL datastore. You can develop Entity groups that mirror the structure of your game's Player class.

Using NoSQL for MMOGs is still a fairly new concept, because you do lose complex SQL querying which are critical for game designers, and most NoSQL datastores don't offer transaction support, which is another major omission. That said, be sure CouchDB meets the needs of your game, as choosing the wrong database solution could have dire consequences.

I recently wrote a blog post about why we chose to use Google App Engine as our database solution, and I'll be delving deeper into our actual application design and implementation details in later posts, if you want to keep an eye out for them. Even though we are not using CouchDB, I think you may still find it informative, or at least entertaining ;)

Depth-First Design

# Answer
> 1 votes
It is certainly possible but I haven't seen any direct examples. A NoSQL database may be better for MMOs when we consider their scalability across multiple servers. SQL engines can do the same thing but generally require a whole lot more planning and money to do so.

Having messed around with MaNGOS' source (World of Warcraft private server) I can say that the majority of data used is loaded into memory when it is needed and there isn't a high complexity of relational data. Data written to the database is really just a backup for what is in memory. When data is no longer needed in memory it is dropped.

Database type is going to be dependent on how you structure your game engine. If you only load portions of your world at a time then you can just load and store that section of the game world. In that case just about any DB will probably work fine as long as you can quickly query out the objects in that section and quickly write them when you are unloading that section.

# Answer
> 1 votes
Please don't get confused by mixing scalability and SQL vs. NoSQL. There are several frameworks which can seize the power of either database system and they become quite easy to use. Scalability does not come from the database type but the system architecture (trust me, it is a myth that has been proven false several times).

Want scalability? Pick even a MySQL database and use replication (I think PostgreSQL is even better at that). Want fast-access? Use a cache layer (yes, I know these NoSQL databases come with built-in cache).

Please focus on this: **You are not forced to use NoSQL for fast data access**. OTOH if you want to access data maps (i.e. key =\> value pairs for each instance) Hibernate supports this.

Many popular frameworks can be integrated with CouchDB, MongoDB, or Relational Databases and you will likely use them as you use them always.

So my conclusion is: Your approach is wrong. Design the game first. Then use a well-known framework for data mapping. Then add a cache layer (controlled by the application if the database does not support that, but even in some cases you'll want another cache level for the application so be wary there). **When designing your game you should not be focusing on the database internals**. **OTOH if somehow you are forced to use CouchDB**, CouchDB and MongoDB are similar in the way that they store JSON documents with no referential integrity, **but the way you model your game is not essentially different** by using that database (except that, at database level, posession-related objects will literally belong to the parent object).

---
Tags: architecture, mmo, rpg, databases
---


title: Textures quality issues with Libgdx

text:
# Question
Title: Textures quality issues with Libgdx
I have drawn several vector objets and characters ( in Adobe Illustrator ) for my game on Android. They are all scalable at any size without any quality losses ( of course it's vector ^^ ).

I have tried to simulate my gameboard directly on Illustrator just before setting my assests on libdgx to implement them in my game.

I set all the objects at the good size, so that they fit perfectly on my XHDPI device I am running my test on.

As you can see it works great ( for me at least ^^ ), the PNG quality is good for me, as expected !

So I have edited all my PNG at this size, set my assets on libgdx and build my game apk.

And here is a screenshot of my gameboard ( don't pay attention at the differences of placing and objects, but check at the objets presents on both screenshot ).

As you can see, I have a loss of my PNG quality in the game. It can be seen clealry on the hedgehog PNG, but also ( but not as obvious ) on the mushroom ( check at the outline ) and the hole PNG. If you really pay attention, on every objects, you can see pixels that are not visible on my first screenshot.

And I just can't figure out why this is happening Oo If you have any ideas, you are very welcome !

Thanks.

PS : You can check more clearly the 2 gameboard on this two links ( look at them at 100%, display at high resolution ) :

Good quality link, from Illustrator

Poor quality link, from the game

**Second phase of tests :**

We display an object ( the hedgehog ) on our main menu screen to see how it looks like. The things is that it looks like he is suppose to, which means, high quality with no pixels.

The hedgehog PNG is coming from an atlas :

```
layer.addActor(hedgehog);

```

No loss of quality with this method

So we think the problem is comming from the method we are using to display it on our gameboard :

```
blocks[9][3] = new Block(TextureUtils.hedgehog, new Vector2(9, 3));

```

the block is getting the size from the vector we are associating to it, but we have a loss of quality with this method.

# Answer
> 4 votes
I'm assuming that libgdx had to scale the images up for you to fit your xhdpi device. If this is the case, then there are two options that come to mind that you could try in your case:

1. Make the original images at the highest resolution possible. If you can achieve to have one large image, suitable for the largest screen size you're targeting, then you're fine, libgdx will only have to scale it down on smaller screen sizes and no quality would get lost.
2. Apply a `TextureFilter` on your textures. I would start with a Linear-Linear filter like this `texture.setFilter(TextureFilter.Linear, TextureFilter.Linear)`. But I would also suggest you check out this article http://www.badlogicgames.com/wordpress/?p=1403 which explains in detail the aspects (especially performance ones) of applying different combinations of texture filters. Applying the right texture filter on your texture will make it look smooth on an upscale, making sure you don't get into performance troubles.

# Answer
> 0 votes
I just had this same problem and managed to solve it. If your issue was the weird checker-board pattern, it turns out some(all?) android devices cause those artefacts when you take a screenshot.

I was having the same issue and spent some time trying to fix it and ended up looking at my device with a magnifying glass to see the individual pixels and it seems to be fine. I may be misunderstanding your problem though.

---
Tags: android, libgdx, assets, png, vector-art
---


title: Pixelation shader explanation?

text:
# Question
Title: Pixelation shader explanation?
I was looking for a pixelation shader for my postprocessing and came across this shader snippet \- Works pretty well! - Not a whole lot of explanations on how it works except for "Pixelation is process when pixel at \[x, y\] is duplicated into \[x + dx, y + dy\] rectangle"

I re-wrote/formatted the shader a bit:

```
out vec4 FinalColor;
in vec2 FragUV;
uniform sampler2D Texture;

void main()
{
        float Pixels = 512.0;
        float dx = 15.0 * (1.0 / Pixels);
        float dy = 10.0 * (1.0 / Pixels);
        vec2 Coord = vec2(dx * floor(FragUV.x / dx),
                          dy * floor(FragUV.y / dy));
        FinalColor = texture(Texture, Coord);
}

```

My understanding: Messing with the 'Pixels' I found that the higher this number the more pixels there on the screen/the smaller the size pixels get thus a less pixelated effect. Then he's calculating some x and y offset values based on that number and using those offsets to get new texture coordinates to sample from.

My question: I have no idea how that's actually happening. I mean how does all that achieve "duplicating a pixel at \[x, y\] is into \[x + dx, y + dy\] rectangle"? What does 15 and 10 represent? (how much to offset on x and y?) - What happens when we actually multiply dx/dy with the result of the floor function and divide the texture coordinate by them? and why 'floor' in particular?

Any help or explanation is appreciated, thanks!

# Answer
> 6 votes
This is a pixelation shader, it seems. What it does is, it divides the screen into tiny rectangles, the side of each rectangle is determined by the values dx and dy. The smaller the value of `pixels`, the more pixelated the screen is, as that increases the size of `dx` and `dy` and thus the size of the rectangles. The shader, after deciding the dimensions of the rectangle, samples the color from the lower left corner of each rectangle, and fills that whole rectangle with that color. The result is a more pixelated scene.

---
Tags: opengl, glsl, fragment-shader, post-processing
---


# Question
Title: best way to destroy an gameobject in unity
> MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. grid.objGridSize () (at Assets/scripts/grid.cs:119) grid.hit (System.String hitObjString) (at Assets/scripts/grid.cs:109) grid.Update () (at Assets/scripts/grid.cs:80)

I'm getting this error and strange results after finding a gameobject, storing it in a new GameObject variable and then destroying it:

```
void Update () {
    if(Input.GetButtonDown("Fire1")){ // detect left mouse click

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        Debug.Log("clicked");

        if(Physics.Raycast(ray, out hitObj)){
            if(hitObj.collider != null){

                // send a message to the object that got hit
                hit(hitObj.collider.gameObject.name);
            }
        }
    }
}
public void hit(String hitObjString){

    Debug.Log("I got hit: "+name);

    GameObject hitTile = GameObject.Find(hitObjString);

    if( hitTile.tag == "tile"){

        Destroy(hitTile);
    }
}

```

# Answer
> 5 votes
Passing through the gameObject name to a method, then using GameObject.Find to find it again by its name, is bad practice, and inefficient.

GameObject.Find is an expensive operation.

Rather do something like this...

```
    void Update () {
    if(Input.GetButtonDown("Fire1")){ // detect left mouse click

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        Debug.Log("clicked");

        if(Physics.Raycast(ray, out hitObj)){
            if(hitObj.collider != null){
                hit(hitObj);
            }
        }
    }
}
public void hit(GameObject hitObj){

    Debug.Log("I got hit: "+ hitObj.name);

    if( hitObj.tag == "tile"){

        Destroy(hitObj);
    }
}

```

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


# Question
Title: How would I load a new scene when a score that is stored in a string is reached?
This is a code that I am working on for a space shooter. Part of it works and my score does increase by 7 every second while being loaded into a GUI box, but my script does not load my scene when the number reaches 1000. I have made sure that my scene is a part of my build settings and I have tried some fixes but it doesn't load even though I don't get any sort of error. Any Ideas?

```
#pragma strict
function Start(){
InvokeRepeating("EachSecond",1.0,1.0);
}

var score: int = 0;
var addscore = 7;

function EachSecond()
{
score=score+addscore;
}

function OnGUI(){
GUI.Box(Rect(1000,10,100,25), score.ToString());
}
function WinningScore()
{
     if (score >= 1000 )
     {
          Application.LoadLevel("Win");
     }
  }

```

# Answer
You have to call the WinningScore function in the update or in the EachSecond method after you increase your score.
> 2 votes

---
Tags: javascript, gui, unity
---


# Question
Title: Which software to keep track of my project?
I'm about to start the first real phase of my game development which will consist of the acquisition of information, resources and the definition of where I want to go and what I will need for that. I just want to make sure that I'm prepared as best as possible before I actually start development.

I don't like the thought of using Microsoft Word or Excel for my project management... I already worked with MS Project but I don't think it fits my needs.

I need a software where I can easily maintain project steps, milestones, important issues, information about technologies and engines I use, as well as simple notes and thoughts I just want to write down.

I usually prefer a whiteboard for stuff like that but unfortunately it's not a persistent way of storing. ;) Also writing it down the old-school way is something I can think of, but only for quick notes...

Which software do you use for that?
Are there commonly used programs?
Is there any free software at all?

# Answer
> 4 votes
I absolutely LOVE Redmine.

http://www.redmine.org/

So simple, free to install if you have a server to put it on. And the interface is just so clean, a lot of plugins etc. to extend it but just the basic bug tracker, time tracker, calendar, wiki and SVN integration makes it a no brainier for me. Especially great when you start working with multiple people, expanded team or beta testers. Just give them accounts with bug tracker permissions and wait for the feedback =\]

Check it out!

# Answer
> 6 votes
Google Docs are really nice when handling this type of info. You can share them with anyone you wish to include on your project. Google Docs Demo In real time you and your buddies can edit the same document! I do this currently with my design team.

Also you may like the idea of creating your own Wiki for your game to keep track of all the information. Free Wiki Hosting

Have you thought about how you will organize and keep track of your code when you start that? I would suggest using some type of version control such as Git Version Control in combination with possibly GitHub.

# Answer
> 4 votes
I personally use Wiki software. My two favorites are PMWiki (for its simplicity) and Trac. Trac is especially awesome because it is a Bugtracker (where you control Milestones), a Repository Browser and also has a wiki for anything you can imagine. So you have everything in one package, for free!

You'll probably need to install something like XAMPP to use it locally. But it will be much more power if you could host it on your own server.

# Answer
> 4 votes
You really need to look at GitHub it has everything you need: https://github.com/features/projects

They are pretty cheap as well: https://github.com/plans

# Answer
> 2 votes
BaseCamp is nice, if you're willing to pay the money after the 30-day trial (about $12 / mo. -- I do this). It's very flexible, does time-tracking, has revision control on documents and so on. I also really like their to-do approach, and the use of Textile for quick formatting when typing up docs and messages to teammates. More friendly when working in teams, than google docs is. It ties in with various bug tracking solutions and with source control (Subversion, not sure which others but almost certainly Git as well at this stage), and the solution as a whole for project management ties together really well and intuitively. I've used Jira in teams as well, and it sucks by comparison -- way too heavy IMO. I understand it also integrates a sort of chat solution when you pay for the add-on called CampFire(?). But skype does that just as well.

But if not, I definitely agree with KRB that google docs is the cheapest, most effective option for a solo or a 2-4 person team even. You get revision control on docs, and easy sharing.

# Answer
> 1 votes
I've only started developing games myself, and I have to say I'm a big fan of pen and paper to begin with, nothing like writing stuff down to clarify it in your mind. Then I do transfer into something like word/excel and one note (nice for taking snippets of web pages and graphics and the like). Then look at some sort of UML software for proper planning (plenty of free options out there), and www.unfuddle.com for version control with both documentation and code.

But I'm a firm believer that pen and paper is very important in the process, even with music production, I have an A4 notebook for every project I do.

I also would be lost without my whiteboard.

# Answer
> 1 votes
I've used Assembla for a while and it's very powerful, especially if you're going to be working with a team (small or large) at some point. It provides many tools (SVN/Git/CVS, milestones, tickets, wiki, a file archive and many more).

The only downside is that unless you choose one of their community/open source packages (which prevent you from making your "space", as they call it, private) that come with a subset of the available tools, you need to pay a monthly fee depending on the options you want.

It's up to you to decide if the community/open source packages fit your needs or if you can/want to afford one of their monthly plans. I personally use an 8$/month plan for a serious game project I'm working on and it's really great (includes tickets, SVN, milestones, wiki). All tools integrate very well with one another. My friends and I also use assembla for our common open source projects and class assignments as it makes managing a software development team a real breeze.

# Answer
> 1 votes
Bitbucket is a free alternative to the paid private repositories found on Github. It is a bit harder to use, but you won't pay a penny.

# Answer
> 1 votes
Looks like an old thread, but just in case someone is still looking for a project management tool, I recommend WizPro by WizardMeet.

It's totally free to use, but it has also got a decent paid plan for bigger teams. The good thing about it is that it doesn't restrict number of members or the duration of use in the community (free) version. It's just limited by the number of tasks which is reasonably enough to work in a small group.

# Answer
> 0 votes
Recently I started with a team a game project and during the design phase of the game we decide use some tools that may help you on the long run.

For the project management we use Rally: http://www.rallydev.com/ that it's oriented to agile methodologies like Scrum, you can track tasks, milestones, defects of all the members of your project, calendar activities, backlog, etc..., and it's on web so it's very easy to update.

For programming specific task on the personal schedule we use Google Calendar, for project hosting we use Google Code, and for exchange big files and other stuff the best option is Dropbox.

---
Tags: project-management, management
---


# Question
Title: Function call to AndroidJabaObject to an instance of com.prime31.PlayGameServicesPlugin causes the application to stop responding
Using Prime31 PlayGameServices attempting to call 'authenticate' causes the game to stop responding very soon after.

There isn't much I can show as there's literally no logs showing up in logcat.

Is there any way I can debug this?

I did notice 'enableDebugPrints' on the AndroidJavaObject was 'false' and I don't know how to set it to true, which might help with prints?

I've tried catching an exception but that hasn't worked.

# Answer
Turns out I'm an idiot, I was running logcat -s Unity under the mistaken belief all related traces to the crash should be found there - makes sense it wasn't as the Google Play Services loads up its own little window, doesn't make sense why when Google Play fails it takes the host app down with it.

Just a plain logcat revealed the issue was caused by an improper configuration of Google Play Game Services, for some reason that means the application will stop responding, instead of simply failing a sign in attempt with a helpful error which would be much more reasonable.
> 0 votes

---
Tags: android, google-play-services
---


title: Where to put the script?

text:
# Question
Title: Where to put the script?
I watch this video https://www.youtube.com/watch?v=Uhnh8zj\_VPo and my question is where to put the script? I'm a complete noob here but I've at least build a map and moving player character. Yes, Unity please. TQ!

# Answer
> 1 votes
In Unity, scripts are usually attached as script components to game objects to control their behavior.

* Click on the game object in the scene hierarchy tree
* Click on "Add Component" in the inspector
* Select "Script" to add an existing script or "New Script" to create a new one.

Alternatively you can also drag the script file from the project folders directly onto the game object.

By the way, this happens in 5:43 of the video you posted. The author attaches the script to the "Main Camera" of their scene. But I would not recommend this. The only scripts attached to the camera should be those which control the camera. Attaching the script to the player game object might also work, but would also be weird. The "Player" object should only contain scripts which control the player character.

When you have any scripts which control the behavior of the scene as a whole, I would rather recommend to use a new, dedicated game object as a carrier for such scripts. A common convention is to call this game object "Game System".

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


title: AI on a 2d grid in python

text:
# Question
Title: AI on a 2d grid in python
I'm trying to figure out how to do a simple search/chase AI.
I know that I'm going to have to search around the mob entity to figure out if the player is close enough, I could probably get that done on my own, but what comes after is what gets me stuck. Once I have the (x,y) of the player, how do I get my mob entity to move a single cell (up, down, left, or right) until they reach the player entity?
Here's a bit of the code for reference.

Just the first part of the Board class.
Basically the portion where the grid is created once initiated. board = Board(10, 10)

```
class Board(object):
    '''Board class to create empty grid of cells'''
    def __init__(self, x_size, y_size, char='-'):
        self.x_size = x_size
        self.y_size = y_size
        self.char = char
        self.board = [[char for _ in range(x_size)] for _ in range(y_size)]

```

And the Entity class. player = Entity('Player', 5, 5, 10, 'o', 'alive')

```
class Entity(object):
    '''Basic entity object
        Has position and character'''
    def __init__(self, name, x, y, hp, char, state):
        self.name = name
        self.x = x
        self.y = y
        self.hp = hp
        self.char = char
        self.state = state

    def move(self, direction, board):
        '''To update entity position'''
        dx = self.x
        dy = self.y
        valid_moves = board.valid_moves(self)
        if direction == 'left' and (self.x, self.y - 1) in valid_moves:
            self.y = dy - 1
        elif direction == 'right' and (self.x, self.y + 1) in valid_moves:
            self.y = dy + 1
        elif direction == 'up' and (self.x - 1, self.y) in valid_moves:
            self.x = dx - 1
        elif direction == 'down' and (self.x + 1, self.y) in valid_moves:
            self.x = dx + 1
        else:
            if self.name == 'Player':
                print 'You can\'t move there'
                time.sleep(0.3)

```

# Answer
> 2 votes
The problem which you want to solve involves pathfinding. The simplest approach would be to build a graph of the grid and perform a Breadth First Search on that. Each cell is connected to its traversable (i.e. without obstacles) neighbors, so in the graph, each cell (vertex) will have 4 (or less if there are obstacles) connections (edges) to each of its neighbors. Pseudocode for BFS is as follows:

```
def bfs(grid, start, end):
    frontier = Queue()
    frontier.add(start)
    came_from = {}
    came_from[start] = None
    while not frontier.empty():
        current = frontier.remove()
        if current == end:
            break
        for n in current.neighbors:
            if not came_from.has_key(n):
                came_from[n] = current
                frontier.add(n)
    return came_from

```

This returns a dictionary which shows how we arrived at a cell. To obtain a path from this dictionary, just traverse the dictionary till you find the start. Pseudocode:

```
def get_path(grid, start, end):
    came_from = bfs(grid, start, end):
    current = end
    path = [end]
    while not current == start:
        current = came_from[current]
        path.append(current)
    return path.reverse()

```

The path returned by this function starts at "start", i.e. `path[0] = start` and ends at end, i.e. `path[length-1] = end`. This means that the next cell to move will always be `path[1]` provided that the path is recalculated every frame (it should, if the target is/can be moved every frame).

Why to do something so complex for something so trivial, you ask? This makes it all the more easier to compute paths and this method doesn't consume many CPU cycles. Plus, if you add obstacles this will still work, because the cells with obstacles will *not* be returned as neighbors, thus they won't be traversed at all.

Look at this link for interactive examples of how BFS works with pathfinding. I have taken the BFS function pseudocode from that link, but the explanation is based on my implementation for a turn-based game.

---
Tags: python, grid
---


# Question
Title: Collision detection optimization for a top down shooter
I'm relatively new to game development and have been trying to learn how collision detection is coded. I mostly work with Actionscript 3, but I'm learning C++ on the side.

I've been wondering how "bullet hell" and top-down shooters optimize their collision detection with so many objects.

Any information/theories would be great.

# Answer
> 4 votes
They usually handle this through spatial partitioning.

The theory is simple: would a bullet in the top-left corner of the screen need to check against the ship, in the bottom-middle of the screen? Not really; they're too far apart to possibly collide this frame.

How do we solve the problem of "figure out what objects are close enough to collide with other objects?"

Simply, with a grid:

* Divide up the screen into arbitrary cells (eg. 100x100).
* Place/update the position of every object into its cell (note: objects that cross cell boundaries can live in multiple cells)
* On collision check, just get the cells an object belongs to, and check collisions against only other objects in those cells.

This is called "spatial partitioning" in 2D There are a lot of details depending on your target language. In 3D, since we're dealing with a cube, it's sometimes called "octree partitioning" (imagine the space as a 2x2x2 or NxNxN grid of cubes).

For more details, look up 2d spatial partitioning. There should be an available implementation for Flash that you can probably reuse.

# Answer
> 0 votes
I wrote some articles on this awhile back. There are lots of different solutions to this problem, and the best answer depends on what sort of data you are using. A good general purpose solution is to use Zomorodian and Edelsbrunner's collision detection algorithm, which I implemented here:

You can read more about it and related approaches on the following pages:

# Answer
> 0 votes
I'd like to add my two cents here since I'm working on something similar.

I'll admit that spatial partitioning is very important to learn and is quite useful for most 2D games. Especially for ones that are very open world. However if your making your game like space invaders or touhou (which is what i'm doing now) then I'd encourage you to do some math before you start. And just to make sure we are all on the same page *it's very very very much faster to write to ram than it is to read from it* (which is the backbone of spatial hashing/oct trees/bsp's).

**Now take this scenario into account:**
Say you only have one player and the said player has no allies. And on top of that enemy bullets don't collide with anything besides the player(accept maybe the outer window area for cleaning).

I don't think this would be a good place to use anything besides something "close" to brute force collision (basically something not hash related). And here's why: Say you were able to split the window (or world) into 100 total blocks/chunks/hash's. Now lets say that there's about 1k total enemy bullets on the screen and they are fairly evenly spread out. That means we would likely check about 9 blocks around the player so take that 9 and divide it from 1k. That's likely to mean you get around 100 collision checks per frame/game tick.

Now I'll admit that's a huge cutback and the more blocks you use the greater the cutback at the expense of your ram (which if you're binding the game to just the window space like most than this is perfectly acceptable).

However we are only checking all those bullets against a single player (or maybe the other way around but that's not important). So lets take into account the expense of **UPDATING** the spatial table.

Usually this isn't very expensive for static objects but for ones that move around this means that each object will need to grab at least one extra piece of data from the ram to update the hash array. Assuming the above is true than your just basically adding at least 1k extra calls to RAM just to save around 900 calls.

However I think maybe the array/array location is stuffed into a register or kept in the L3 cache for the entire game somehow. Some input would be nice as I'm not an expert at this. But what I'm trying to say is that it's likely a better idea to use a hash table for something like player bullets and enemy positions. Especially if your making it where there can be at least 50 or 100+ enemies at a time and if you are using a LOT of player bullets. Think about it. if you had 100 enemies at a time and there's usually about 20 player bullets on screen at a time than this would mean that doing this brute force style would mean your doing about 2k collision checks at a time. what if you could have it to where each player bullet checks about 1/10 of that using spatial hashing? That would knock that 2k down to about 200 while only updating the hash table about 120 times(100 enemies + 20 player bullets). This would give a savings of about 2k-320 = 1680 calculations:) So the thing to take away is that hash's can be very useful but they shine the most when you are checking more of a variety. As apposed to having just one group of things checking with a single other thing.

Again if anyone has more info on exactly how much cost it is to update the hash table in c++ or any other language/settings please share as it's always nice to have such knowledge under your belt.

---
Tags: collision-detection
---


title: Shaders wont bind to the uniform block

text:
# Question
Title: Shaders wont bind to the uniform block
I'm having an issue with interface block binding.

Example shader:

```
const char* vertexShader =
        "#version 330 core\n"
        "uniform globalMatrices"
        "{"
        "   mat4 vPMatrix;"
        "};"
        "layout(location = 0) in vec2 vPosition;"
        "layout(location = 1) in vec4 vColor;"
        "out vec4 color;"
        "void main()"
        "{"
        "   color = vColor;"
        "   gl_Position = vPMatrix * vec4(vPosition, 1.0, 1.0);"
        "}"

```

After creating the shader program i call functions:

```
    //this is done once per shader
    void BindShaderToMatrixBlock(unsigned int program)
    {
        GLuint globalUniformBlockIndex = glGetUniformBlockIndex(program, "globalMatrices");
        glUniformBlockBinding(program, globalUniformBlockIndex, 0);
    }
    //this is done once
    void BindUniformBlockMatrix()
    {
        glGenBuffers(1, &uniformBlockMatrix);
        glBindBuffer(GL_UNIFORM_BUFFER, uniformBlockMatrix);
        glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), NULL, GL_DYNAMIC_DRAW);
        glBindBuffer(GL_UNIFORM_BUFFER, 0);
        glBindBufferRange(GL_UNIFORM_BUFFER, 0, uniformBlockMatrix, 0, sizeof(glm::mat4));
    }

```

And this is how i update the matrix:

```
inline void SetVPMatrix(const void* data)
{
    glBindBuffer(GL_UNIFORM_BUFFER, uniformBlockMatrix);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), data);
}

```

I tried to debug as much as i could and confirmed that the data gets delivered to the uniform block but for some reason the matrix in the shader stays unchanged.

# Answer
> 1 votes
I did several changes to the code and something of the following fixed my problem:

* changed the order so that all the block binding was done before initializing the uniform buffer
* added "layout (std140)" to the uniform block in the vertex shader
* i made sure that i unbound everything after binding and executing series of commands

thanks wondra for the link, it helped.

---
Tags: opengl, c++, shaders, glm, projection-matrix
---


# Question
Title: How to rotate an object around world aligned axes?
I have a Vector3 which has an euler angle for each axis.

Usually, when I want to create a rotation matrix I will use functions such as D3DXMatrixRotationX passing the respective angle from my rotation vector above and multiply the matrices (ZXY) to create the overall rotation matrix which is used to form the complete object transformation matrix.

However, this method will produce a set of rotations in object space. That is, passing a vector of (90, 0, 90) into my method will create a rotation in world space effectively of (90, 90, 0).

Is there a way to always ensure each component of my rotation vector results in a rotation around the respective world space aligned axes?

EDIT:

This is an animation of what is currently happening - I want a way to rotate around the blue axes, not the red.

EDIT 2:

Just to note I am not looking for a solution involving Euler angles, but simply a way in which I can represent a transformation of multiple rotations around the world axes.

# Answer
Based on you comments, it seems that you're **storing the orientation of the object as a set of Euler angles**, and in/decrementing the angles when the player rotates the object. That is, you have something like this pseudocode:

```
// in player input handling:
if (axis == AXIS_X) object.angleX += dir;
else if (axis == AXIS_Y) object.angleY += dir;
else if (axis == AXIS_Z) object.angleZ += dir;

// in physics update and/or draw code:
matrix = eulerAnglesToMatrix(object.angleX, object.angleY, object.angleZ);

```

As Charles Beattie notes, because rotations don't commute, this won't work as expected unless the player rotates the object in the same order in which the `eulerAnglesToMatrix()` applies the rotations.

In particular, consider the following sequence of rotations:

1. rotate object by *x* degrees around the X axis;
2. rotate object by *y* degrees around the Y axis;
3. rotate object by −*x* degrees around the X axis;
4. rotate object by −*y* degrees around the Y axis.

In the naïve Euler angle representation, as implemented in the pseudocode above, these rotations will cancel out and the object will return to its original orientation. In the real world, this does not happen — if you don't believe me, grab a six-sided die or a Rubik's cube, let *x* = *y* = 90°, and try it out yourself!

The solution, as you note in your own answer, is to **store the orientation of the object as a rotation matrix** (or a quaternion), and update that matrix based on user input. That is, instead of the pseudocode above, you'd do something like this:

```
// in player input handling:
if (axis == AXIS_X) object.orientation *= eulerAnglesToMatrix(dir, 0, 0);
else if (axis == AXIS_Y) object.orientation *= eulerAnglesToMatrix(0, dir, 0);
else if (axis == AXIS_Z) object.orientation *= eulerAnglesToMatrix(0, 0, dir);

// in physics update and/or draw code:
matrix = object.orientation;  // already in matrix form!

```

(Technically, since any rotation matrix or quaternion can be represented as a set of Euler angles, it *is* possible to use them to store the orientation of the object. But the physically correct rule for combining two sequential rotations, each represented as Euler angles, into a single rotation is rather complicated, and essentially amounts to converting the rotations into matrices / quaternions, multiplying them, and then converting the result back into Euler angles.)
> 3 votes

# Answer
The problem with rotations, is that, most people think of it in terms of Euler angles, since they are easy to understand.

Yet most people forget the point that Euler angles **are three sequential angles**. Meaning that rotation around the first axis, will make next rotation be relative to the first original rotation, hence you cannot independently rotate a vector around each of the 3 axis using Euler angles.

This directly translates to matrices when you multiply two matrices, you can think of this multiplication as transforming one matrix to the space of the other matrix.

This is meant to happen with any 3 sequential rotations even when using quaternions.

I want to stress the fact that quaternions are **not a solution** for gimble lock. Actually gimble lock will always happen if you represented Euler angles using quaternions. The problem is not the representation, the problem is *the* 3 sequential steps.

### The Solution?

The solution for rotating a vector around 3 axis independently is to *combine* into a single axis and a single angle, this way you can get rid of the step where you have to do a sequential multiplication. This will effectively translate into:

**My rotation matrix represents the outcome of the rotation around X and Y and Z.**

rather than the Euler interpretation of

**My rotation matrix represents the rotation around X then Y then Z.**

To clarify this I will quote from wikipedia Euler's rotation theorem:

> According to Euler's rotation theorem, any rotation or sequence of rotations of a rigid body or Coordinate system about a fixed point is equivalent to a single rotation by a given angle θ about a fixed axis (called Euler axis) that runs through the fixed point. The Euler axis is typically represented by a unit vector u→. Therefore, any rotation in three dimensions can be represented as a combination of a vector u→ and a scalar θ. Quaternions give a simple way to encode this axis–angle representation in four numbers, and to apply the corresponding rotation to a position vector representing a point relative to the origin in R3.

Notice that multiplying 3 matrices will *always* represent 3 sequential rotations.

Now inorder to combine rotations around 3 axis, you need to get a single axis and single angles that represents the rotation around X,Y,Z. In other words you need to use an Axis/Angle or quaternion representation to get rid of the sequential rotations.

This is usually done, by starting with an initial orientation (orientation can be thought of as a an axis angle), usually represented as a quaternion or an axis angle, and then modifying that orintation to represent your destination orientation. For example you start with the identity quaterion and then rotate by the difference to reach the destination orientation. This way you don't lose any degree of freedom.
> 15 votes

# Answer
You will need to store the order of the the rotations.

```
Rotating around x 90 then rotate around z 90 !=
Rotating around z 90 then rotate around x 90.

```

Store your current rotation matrix and premultiply each rotation as they come.
> 2 votes

# Answer
Switching a combination of rotations from object space to world space is trivial: you just have to reverse the order in which rotations are applied.

In your case, instead of multiplying matrices `Z × X × Y`, you just need to compute `Y × X × Z`.

A rationale for this can be found on Wikipedia: conversion between intrinsic and extrinsic rotations.
> 2 votes

# Answer
In addition to @concept3d answer you can use 3 extrinsic rotation matrices to rotate around axis in world coordinates. Quoting from Wikipedia:

> Extrinsic rotations are elemental rotations that occur about the axes of the fixed coordinate system xyz. The XYZ system rotates, while xyz is fixed. Starting with XYZ overlapping xyz, a composition of three extrinsic rotations can be used to reach any target orientation for XYZ. The Euler or Tait Bryan angles (α, β, γ) are the amplitudes of these elemental rotations. For instance, the target orientation can be reached as follows:
>
> The XYZ-system rotates about the z-axis by α. The X-axis is now at angle α with respect to the x-axis.
>
> The XYZ-system rotates again about the x-axis by β. The Z-axis is now at angle β with respect to the z-axis.
>
> The XYZ-system rotates a third time about the z-axis by γ.
>
> Rotation matrices can be used to represent a sequence of extrinsic rotations. For instance,
>
> R = Z(γ) Y(β) X(α)
>
> represents a composition of extrinsic rotations about axes x-y-z, if used to pre-multiply column vectors, while
>
> R = X(α) Y(β) Z(γ)
>
> represents exactly the same composition when used to post-multiply row vectors.

So what you need is to invert the order of the rotations in relation of what you would do using intrinsic (or local space) rotations. @Syntac asked for a zxy rotation, so we should do a yxz extrinsic rotation to achieve the same result. The code is below:

Matrix values explanation here.

```
// Init things.
D3DXMATRIX *rotationMatrixX = new D3DXMATRIX();
D3DXMATRIX *rotationMatrixY = new D3DXMATRIX();
D3DXMATRIX *rotationMatrixZ = new D3DXMATRIX();
D3DXMATRIX *resultRotationMatrix0 = new D3DXMATRIX();
D3DXMATRIX *resultRotationMatrix1 = new D3DXMATRIX();

D3DXMatrixRotationX(rotationMatrixX, angleX);
D3DXMatrixRotationY(rotationMatrixY, angleY);
D3DXMatrixRotationZ(rotationMatrixZ, angleZ);

// yx extrinsic rotation matrix
D3DXMatrixMultiply(resultRotationMatrix0, rotationMatrixY, rotationMatrixX);
// yxz extrinsic rotation matrix
D3DXMatrixMultiply(resultRotationMatrix1, resultRotationMatrix0, rotationMatrixZ);

D3DXVECTOR4* originalVector = // Original value to be transformed;
D3DXVECTOR4* transformedVector = new D3DXVECTOR4();

// Applying matrix to the vector.
D3DXVec4Transform(transformedVector, originalVector, resultRotationMatrix1);

// Don't forget to clean memory!

```

This code is didactic, not optimal, since You could reuse several D3DXMATRIX matrices.
> 1 votes

# Answer
I'll provide my solution as an answer until someone can explain why this works.

Every render I was rebuilding my quaternion using the angles stored in my rotation vector and then applying the quaternion to my final transform.

However in order to keep it around the world axes I had to retain the quaternion across all frames and only rotate objects using a difference in angle, i.e...

```
// To rotate an angle around X - note this is an additional rotation.
// If currently rotated 90, apply this function with angle of 90, total rotation = 180.
D3DXQUATERNION q;
D3DXQuaternionRotation(&q, D3DXVECTOR3(1.0f, 0.0f, 0.0f), fAngle);
m_qRotation *= q;

//...

// When rendering rebuild world matrix
D3DXMATRIX mTemp;
D3DXMatrixIdentity(&m_mWorld);

// Scale
D3DXMatrixScaling(&mTemp, m_vScale.x, m_vScale.y, m_vScale.z);
m_mWorld *= mTemp;

// Rotate
D3DXMatrixRotationQuaternion(&mTemp, m_qRotation);
m_mWorld *= mTemp;

// Translation
D3DXMatrixTranslation(&mTemp, m_vPosition.x, m_vPosition.y, m_vPosition.z);
m_mWorld *= mTemp;

```

*(Verbose for readiblity)*

I think dsilva.vinicius was trying to get to this point.
> 1 votes

---
Tags: 3d, mathematics, rotation, matrix
---


# Question
Title: Box2d: Is there a way to have collisions but ignore the accompanying forces?
To begin, I know that you can use filtering or isSensor to remove physical collisions. However, I would like to retain the ability to, say for example, stop when trying to move past another player. Essentially, I don't want one player to be able to push another dynamic body with the force that normally accompanies a collision. I've tried static and kinematic bodies, but both obviously have their own problems with trying to have collisions.

An example might be a topdown game such as League of Legends of Starcraft, where units can impede on eachother's movements, but don't apply any force upon collision.

# Answer
I figured it out. Each dynamic body (what you control) must have an accompanying kinetic body "shadow". Their collisions must be set up as follows: each dynamic body only collides with other dynamic bodies' kinematic body shadows but not their own shadow, so dynamic bodies no longer collide with each other. This way, since dynamic bodies can't push kinematic bodies, they won't push each other around. The kinematic bodies can be added to a dynamic body simply by using setTransform to match shadow positions with their parent bodies.
> 3 votes

---
Tags: box2d
---


# Question
Title: opengl z index changing does not zoom in
I am making a simple opengl application where I have a cube and I want to move forward to it with the glTranslate3d function, where I change the z index. One would expect the object to get bigger because of the view but it does not

My code:

```
    glClearColor(0, 0, 0, 1);
    glClearDepth(1.0);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glOrtho(30, width, 0, height, 100, -100);
    glMatrixMode(GL_MODELVIEW);

```

I have tried many things also I have been told that gluPerspective is out dated and should not be used....

EDIT: it works when I rotate the object you can see how 3d it is :p

# Answer
> 1 votes
Orthographic projection is not perspective. This means it won't zoom in if you move the object closer to the camera. If you want to zoom in that way, you need to use perspective projection by using glFrustum.

Other way is to change the relative size of the orthographic projection. Something like this:

```
glOrtho(0, width * zoomlevel, 0, height * zoomlevel, 100, -100);

```

But this messes up your coordinate system if you are trying to achieve pixel-perfect screen-space coordinates. Also the above code will look weird if you expect your objects to be relative to the center of the screen. For that to work better you can use something like this:

```
glOrtho( -width * 0.5f * zoomlevel, width * 0.5f * zoomlevel, -height  * 0.5f * zoomlevel, height  * 0.5f * zoomlevel, 100, -100 );

```

Now you can control the zoom level by setting the `zoomlevel` variable, for example to 0.1f to make it zoom in or 5f to make it zoom out.

# Answer
> 0 votes
You issue is that you use

```
glOrtho(30, width, 0, height, 100, -100);

```

Which makes an orthographic view of the scene. With this, the distance of the objects to the camera is not visible. It is the equivalent of a parallel projection.

You have to make a perspective projection for the objects to be displayed bigger as the get closer, and smaller as they get further away.

You could look into `glFrustum` to make a perspective matrix.

---
Tags: opengl, java, 3d, lwjgl
---


title: Swing GUI for games (performance)

text:
# Question
Title: Swing GUI for games (performance)
I'm developing a game in Slick2D and I'm trying to make GUI.

I've already tried TWL library, but it seems to me a bit complicated and it doesn't cover what I need. In my own implementation of GUI I've encountered a problem with positioning of components. That's why I'm interested in Swing. I would use only its layout system and I would render components on my own (in Slick render loop).

So I'm asking, is it good for performance to do so? May I encounter other problems with Swing?

# Answer
Swing should be fine for your needs.

You should check out this stackexchange for other possible problems with Swing.
> 1 votes

# Answer
For the most part, swing is very easy to learn. Swing itself is not a good developmental language for 2D based games, however, it can be used for minor GUI applications, such as the one you are talking about. I see no performance issues, just the Swing thread and the Slick2D thread may pose difficulty synchronizing, if that's what's needed.
> 0 votes

---
Tags: java, lwjgl, gui, slick, swing
---


# Question
Title: Question about JPanel "transition" for Java Swing
I want to make like a sort of main menu (in GUI).
When the user clicks the start button, the screen transition into another "screen" (JPanel). This image will make it easier to understand.
https://i.stack.imgur.com/gEwkq.png

Currently, I have a MainMenu extends JPanel and that gets added into a driver class with a JFrame. I can't figure how to switch to another class like Game extends JPanel.
So when the user clicks the start button in MainMenu, I want it to somehow hide itself and the Game to show itself.
Thanks.

# Answer
> 1 votes
Something like that?

I made the SlidingLayout library for that purpose. It's a very small and easy-to-use library which aim is to create smooth transitions between two layouts of some components. Thus, making a transition between two screens is very easy to do.

The difference between the two transitions shown in these gifs relies on two lines of code. You can also create more fancy transitions by applying a different delay on each component, so they appear not all at once but with some timing variations between them.

I hope it may be useful to you :)

# Answer
> 0 votes
If you just want a different JPanel to be displayed when the user clicks on the menu then you should give your JFrame's content pane a java.awt.CardLayout. You then add your MainMenu and Game as layout components. Whenever you want to switch between the two, you can just call the `next` method of your CardLayout after you detected a click.

```
MainMenu mainMenu = new MainMenu();
Game game = new Game();

JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
CardLayout cardLayout = new CardLayout();

contentPane.setLayout(cardLayout);
contentPane.add(mainMenu, "MainMenu");
contentPane.add(game, "Game");

frame.setSize(600, 400);
frame.setVisible(true);

while (true) {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }

    cardLayout.next(contentPane);
}

```

However, this will not give you a smooth animated transition, it just flips from one JPanel to another one.

# Answer
> 0 votes
Fancy animations between panels isn't really recommended for Swing layouts, as you'll have to run all the offsets and positions yourself, running an extra thread to update them and send repaint requests.

I'd recommend writing your own UI, as that would provide you with the most flexibility for designing your interface.

If you'd rather use Swing, I highly recommend writing your own layout manager.
(it's not that hard, really, though you'll have to make sure that it interacts with a thread somewhere for the animations to work)

# Answer
> 0 votes
The easiest to do this is to add BOTH JPanels or JComponents to the JFrame and set only ONE of then visible. Then you would have a function that would call the visible component to be invisible and the selected component to be visible.

---
Tags: java, graphics
---


# Question
Title: keyPressed is not working after adding ActionListener to JButton
I have a serious problem while trying to build a menu for my game. I've added two JButton to a main JPanel and added an ActionListener for each of them. The main JPanel also contains the game JPanel which have the keyPressed method inside keyController.

That's how it looks -
Main -\>
JPanel -\>
JButton, JButton,
JPanel which contains the game and keyPressed function inside KeyController class which worked fine before I added the ActionListener for JButton.

For some reason after I added an ActionListener for each of the button, the game JPanel is not getting any keyPreseed events nor KeyRealesed.
Does anyone know the solution for my situation?
Thank you very much!

Main window -

```
  Scanner in = new Scanner(System.in);

    JFrame f = new JFrame("Square V.S Circles");
    f.setUndecorated(true);
    f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    f.add(new JPanelHandler());
    f.pack();

    f.setVisible(true);
    f.setLocationRelativeTo(null);

```

JPanelHandler(main JPanel) -

```
  super.setFocusable(true);

        JButton mybutton = new JButton("Quit");
        JButton sayhi = new JButton("Say hi");

        sayhi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Hi");
        }
        });

         mybutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
           System.exit(0);
        }
        });
        add(mybutton);
        add(sayhi);
        add(new Board(2));

```

Board KeyController(The code inside is working so it's unnecessary to put it here) -

```
private class KeyController extends KeyAdapter {

    public KeyController()
    {
        ..Code
    }

    @Override
    public void keyPressed(KeyEvent e) {

    ...Code

    }

    @Override
    public void keyReleased(KeyEvent e){

     ...Code

    }

}

```

# Answer
> 0 votes
Instead of adding KeyListeners to your panel, try overriding `Component.processKeyEvent` in your window / frame class. You may also need to call `enableEvents(AWTEvent.KEY_EVENT_MASK);` in the initialization. This has generally been the most robust way of handling keyboard in Java that I am aware of.

# Answer
> 0 votes
The problem is that you didn't include this statement:

```
foo.addKeyListener(bar);

```

Where "foo" is the object ( That extends JComponent ) that can add Key Listeners, and "bar" is the class that contains the Key Listener. You can have the class implement KeyListener, or use a private inner class that extends KeyAdapter, which is really up to you.

**However**, event handlers are handled by AWT, not Swing itself, which may lead to some threading issues. Therefore, use Key Bindings and Action Maps, which simply add to the swing thread.

---
Tags: java, swing
---


title: What is a quaternion?

text:
# Question
Title: What is a quaternion?
What is a quaternion, and do how they work? Also, what advantages do you gain using three points on a 2D plane? Finally, when is it considered good practice to use quaternions?

# Answer
> 48 votes
Mathematically, a quaternion is a complex number with 4 dimension. But in game development, Quaternions are often used to describe a rotation in 3d space by encoding:

1. a rotation axis (in form of a 3-dimensional vector)
2. how far to turn around that axis

Note that this information is encoded with sines and cosines inside the quaternion, so in general you shouldn't try to explicitly set or read the quaternion's internal components (x y z w) individually. It's easy to make a mistake that way and get a non-meaningful result. A quaternion math library will usually provide functions to operate on quaternions (eg. converting them to & from Euler angles or axis-angle), which ensures the math is correct and has the side benefit of making your code easier to read and understand.

An alternative way to describe rotations is by describing how far to turn around the 3 fixed axis' x, y, and z (aka Euler angles) which only requires 3 numbers instead of 4 and is usually more intuitive to use. However, euler-angles are subject to a problem called gimbal-lock: When you rotate 90° around one axis, the other two axis become equivalent. With quaternions, this problem does not occur.

Another way to express rotations in 3d space is with a 4x4 transformation matrix. But with a transformation matrix you can not just rotate, but also scale, translate and skew. When you want *only* rotation, a matrix would be overkill and a quaternion a much quicker and simpler solution.

This problem is only relevant in 3d space. In 2d space, you only have one rotation axis. Any rotation can be expressed with a single floating-point number or a single complex number, so you don't have this problem. While you can theoretically express a rotation on a 2d plane with a quaternion where the axis points into (or out of) the plane, it is usually overkill.

# Answer
> 13 votes
This is to add to @Philipp's answer.

> Also, what advantages do you gain using three points on a 2D plane?

You don't really need quaternions if all you're interested is in rotating *on* the plane, i.e. *about* the z axis. In this case, all you need is the yaw angle, and you can exploit the fact that successive rotations about the z axis commute. So you can apply your rotations in any order you wish.

The situation is different if you're rotating on a plane that's not the XY plane. This rotation is equivalent to rotating about an arbitrary 3D axis. Now, you have two choices:

* rotate your plane in 3D so that it coincides with the XY plane and then yaw, and transform back , *or*
* think of your rotation as being in 3D to begin with.

The second choice is easier to code. As @Philipp said, quaternions avoid gimbal lock (if you avoid intermediate RPY or axis/angle conversions).

> Finally, when is it considered good practice to use quaternions?

*Whenever* there are 3D rotations, it's good practice to use quaternions.

E.g.:

* In Qt. Quats make it easy to interpolate between rotations, as in the slerp function.
* ROS uses them for transforming robot poses.
* In the Bullet dynamics engine
* For a very sophisticated application, see here for their use in classical 3D mechanics.

---
Tags: mathematics, terminology
---


# Question
Title: SDL2 not rendering larger texture to smaller texture
With SDL2 I created texture1 of 28800 x 28800 which contains a drawing of a grass background all over the texture.

Then I created texture2 of 2880 x 1620.

Then I set the render target to texture2.

The I set the logical size to 2880 x 1620.

The I renderclear texture2.

Then I rendercopy a rectangle of 2880 x 1620 from texture1 to texture2

Then I renderpresent texture2 but my screen is black.

Is that because I am trying to copy from a larger texture to a smaller texture? What are the limits when it comes to copying from texture to texture with SDL2?

Let me know if you need my code and where to put it. Some websites don't like it when you put your code in a post.

# Answer
> 0 votes
28800 x 28800 may be way too big for a texture. When using textures, SDL is basically a shim over OpenGL/DirectX which talks directly with your graphics card. Texture size limits will depend on your hardware - better graphics cards can use larger textures. For example, OpenGL provides an integer variable `GL_MAX_TEXTURE_SIZE` which represents the maximum width and height supported by the current graphics hardware. According to this crowd-sourced report by Wildfire Games, about 44% of its users' machines support the highest value available, 16384. Those figures may change as new hardware is released.

Keep in mind that if this 28800 x 28800 texture were stored uncompressed, it would be a little over 3 GB, which as of writing requires a mid-level discrete graphics card to even fit in memory. It may be tempting to, for example, use a single mega texture for the entire map, but most games don't do this because this takes up so much memory, which is why techniques like tiling are so common. Whatever your reason for using that giant texture, there's probably a more conventional, memory-efficient alternative.

Finally, for C libraries like SDL2, the convention is to check all return values of functions, since C doesn't have exceptions. Typically, functions return an error code or, in SDL2's case, simply an error indicator like -1, after which you can find out the exact error with a function like `SDL_GetError()`. Failing to do this means you may experience errors that are difficult to diagnose, as this question shows.

---
Tags: textures, sdl2
---


# Question
Title: What is the relationship between Frames-Per-Second and a game loop?
What is the relationship between FPS - Frames Per Second and a game loop? I'm confused how my book is using theses terms.

# Answer
Typically, a frame is drawn every time through the game loop. Thus, the FPS tells you how fast the game is looping.

That said, more sophisticated rendering architectures often decouple the rendering from the main game loop. In that case, the two are only vaguely related.
> 9 votes

# Answer
**FPS** is usually graphics-related in such way, that it is a measure of video rendering time - how many (video) frames per second is game producing, while **Game Loop** (or **Tick**) is related to game-states calculations like: physics, reading and applying of user inputs, udates of game entities, handling network i/o etc.

The reason why it is often mixed is that **many game engines are using the same single loop** calculate its state and then video render.

Note that very often video rendering and/or game loop is synchronised with display **refresh rate** (VSync) to avoid flickering of screen.
> 2 votes

# Answer
First of all, games usually execute 60 FPS on a good computer. To explain the relationship between FPS and the game loop, we have to delve deeper. We have to ask ourselves another question, "How can the FPS and the game loop affect each other?"

The FPS is the frames per second, as you know. The game loop is how the game functions when it executes.

```
while(isRunning){
    updateGameStatus();
    renderScreen();
}

```

In this example I've written using Java, the FPS is not mentioned. Because of this, the FPS has no influence on how fast the game runs. But think about this; **Don't we want the FPS to influence the game?** The answer is of course yes. When the computer updates the game, it's going to **update** as fast as it possibly can, but sometimes it cannot **render** as fast as it can. This can lead to extreme lag issues.

```
 int myFPS = 60;

 while(isRunning){

      if(this.getFPS() < myFPS){
           //We are running behind!
      }

      if(this.getFPS() > myFPS){
           update();
           render();
      }

 }

```

In this example ( in Java ) , I show what a more sophisticated game loop would look like, where the FPS actually DICTATES when the computer will run. Often times, programmers will incorporate a "tick skipping sequence", which will basically ignore all the lost ticks.

So to answer your question, the FPS **can** have influence on your game loop. It just requires some additional knowledge and code.
> 0 votes

---
Tags: game-design, game-loop, terminology
---


title: Aquire disassembly of shader code

text:
# Question
Title: Aquire disassembly of shader code
Is there a way to get the disassembly that your driver generates when compiling a shader? I noticed that you can get an accidental disassembly dump if you go over the maximum thread group size supported by the hardware in compute shaders, so naturally I figured there must be some way to do this for all shader types. Is there a reliable way to get the disassembly (perhaps specific to NVIDIA/AMD/Intel hardware), using tools or even just "hacks" like causing errors during compilation / linking?

# Answer
At least on NVIDIA hardware, the shader assembly representation can be queried using the glGetProgramBinary() OpenGL function (initially part of the gl\_arb\_get\_program\_binary extension), which requires OpenGL 3.0 and upwards.

```
const size_t MAX_SIZE = 1<<24;
char binary[MAX_SIZE];
GLenum format;
GLint length;
glGetProgramBinary(shaderProgramObject,MAX_SIZE,&length,&format,&binary[0]);

```

You can then dump it however you want, for example (for easy copy and paste purposes of this answer) in C++:

```
std::ofstream binaryfile("bin.txt");
binaryfile.write(binary,length);

```

If you open the file with a text editor, it will contain some garbage (presumably the actual compiled binary representation of the assembly code), but at least on the three different sets of hardware and two different sets on driver versions I could test, it will also contain the assembly output of the program. Technically, the output of glGetProgramBinary is implementation (of your driver) dependent, so in the future or in older driver versions it might not contain any assembly, but it seems to work out so far.

I can't test whether AMD hardware drivers output the assembly as well, but it would make sense.
> 6 votes

# Answer
For AMD GPUs, check out Radeon GPU Analyzer \-

Using this you can generate ISA disassembly and performance statistics for DX11, OpenGL and Vulkan shaders, and for OpenCL kernels.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Two dimensional elastic collision of balls
I am trying to create a simple elastic collision simulation in java. (I am using some helper libs like StdRandom)

Here is my Ball class :

```
class Ball
{
    double cx, cy;
    Vector velocity;
    double radius;
    double mass;

    public Ball()
    {
        mass = 1.0;
        radius = 0.025;

        cx = StdRandom.uniform( 0.000+radius, 1.000-radius );
        cy = StdRandom.uniform( 0.000+radius, 1.000-radius );

        // vx = 0.015;
        // vy = 0.025;
        velocity = new Vector();
        velocity.setX( StdRandom.uniform( 0.0010, 0.015 ) );
        velocity.setY( StdRandom.uniform( 0.0010, 0.015 ) );

    }

    public void move()
    {
        cx = cx + velocity.getX();
        cy = cy + velocity.getY();
    }

    // getter methods
    public double getCx(){  return cx;  }
    public double getCy(){  return cy;  }
    public double getVx(){  return velocity.getX(); }
    public double getVy(){  return velocity.getY(); }
    public double getRadius(){  return radius;  }
    public double getMass(){    return mass;    }

    // setter methods
    public void setCx( double val ){    cx = val; }
    public void setCy( double val ){    cy = val; }
    public void setVx( double val ){    velocity.setX( val ); }
    public void setVy( double val ){    velocity.setY( val ); }
    public void setRadius( double val ){    radius = val; }
    public void setMass( double val ){  mass = val; }
}

```

And here is my method for resolving collisions:

```
if ( distSqr == radii_sum*radii_sum )
        {
            double phi, theta1, theta2;         // collision angle, a's movement angle, b's movement angle
            double v1, v2;                      // scalar values of velocity for balls a and b
            double m1, m2;                      // mass for ball's a and b
            double v1xf, v1yf, v2xf, v2yf;      // x and y components of final velocities after collision

            // calculate angles
            phi = Math.atan2( cy1-cy2, cx1-cx2 );
            theta1 = Math.atan2( a.getVy(), a.getVx() );
            theta2 = Math.atan2( b.getVy(), b.getVx() );

            // get mass
            m1 = a.getMass();
            m2 = b.getMass();

            // calculate scalar values of velocities
            v1 = Math.sqrt( a.getVx()*a.getVx() + a.getVy()*a.getVy() );
            v2 = Math.sqrt( b.getVx()*b.getVx() + b.getVy()*b.getVy() );

            v1xf = ((((v1 * Math.cos(Math.toRadians(theta1 - phi)) * (m1 - m2)) + (2 * m2 * v2 * Math.cos(Math.toRadians(theta2 - phi)))) / (m1 + m2)) * Math.cos(Math.toRadians(phi))) + (v1 * Math.sin(Math.toRadians(theta1 - phi)) * Math.cos(Math.toRadians(phi + (Math.PI/2))));
            v2xf = ((((v2 * Math.cos(Math.toRadians(theta2 - phi)) * (m2 - m1)) + (2 * m1 * v1 * Math.cos(Math.toRadians(theta1 - phi)))) / (m1 + m2)) * Math.cos(Math.toRadians(phi))) + (v2 * Math.sin(Math.toRadians(theta2 - phi)) * Math.cos(Math.toRadians(phi + (Math.PI/2))));

            v1yf = ((((v1 * Math.cos(Math.toRadians(theta1 - phi)) * (m1 - m2)) + (2 * m2 * v2 * Math.cos(Math.toRadians(theta2 - phi)))) / (m1 + m2)) * Math.sin(Math.toRadians(phi))) + (v1 * Math.sin(Math.toRadians(theta1 - phi)) * Math.sin(Math.toRadians(phi + (Math.PI/2))));
            v2yf = ((((v2 * Math.cos(Math.toRadians(theta2 - phi)) * (m2 - m1)) + (2 * m1 * v1 * Math.cos(Math.toRadians(theta1 - phi)))) / (m1 + m2)) * Math.sin(Math.toRadians(phi))) + (v2 * Math.sin(Math.toRadians(theta2 - phi)) * Math.sin(Math.toRadians(phi + (Math.PI/2))));

            a.setVx( v1xf );
            a.setVy( v1yf );
            b.setVx( v2xf );
            b.setVy( v2yf );
        }

```

I had some questions -

1. Have I calculated the scalar velocities and angles correctly? The code does not work and balls pass through each other, sometimes even pushing other balls beyond boundary.
2. How do I reflect velocity? As x and y components given above OR single speed var and an angle? If latter then can I use different speeds for x and y components?
3. Should I use a timestep for collision detection? If yes, an example would help!
4. I tried using a randomly generated angle and changed it on collision as:
    1. (vertical wall) newangle = 180-oldangle
    2. (horizontal wall) newangle = (oldangle \> 180) ? 360 -(oldangle - 180) : 180-oldangle

it worked but it becomes a specialized case. How to use a generic case for all lines(since x,y axis are lines indeed)? I know it uses normals but don't know the whole thing.

The collision method has been programmed by following the below link.

Wikipedia Elastic collision in two dimensions, both balls moving

# Answer
I have found the solution, though partially.

Apparently for ball to ball collisions the tangential component remains same because no force acts along it. So normal component can be calculated using one dimension newtonian formula for elastic collisions.

There are two issues though.

1. I had to write specialized case code for wall collisions by hard coding values.
2. The velocity cannot be more than 2\*radius per frame. If its higher than that, the ball skips collision detection and may get stuck into other ball(s).

Since this is not a full fledged application this solution will do fine for now.

I used the procedure in this link
> 1 votes

---
Tags: collision-detection
---


# Question
Title: Do higher-level 'Pure AI' concepts (such as Neural-Nets or Genetic Algos) ever get implemented successfully in commercial games?
Although graphics is my main area of focus, I've been dabbling with Game AI concepts for quite some time now; from simple A\* path-finding to intricate Perceptrons..

My question is this; Does anyone have any examples of successful (or perhaps more interestingly, failed) implementations of some higher-level AI concepts in large-scale commercial titles?

By higher-level, I mean methods of simulating intelligence that are usually found in Pure AI.. For example..

* Neural Networks
* Genetic Algorithms
* Decision Theory

I understand that as well as a financial budget, developers also have a budget of memory usage (with AI often taking a back seat). Many of these methods are costly to implement and provide limited returns.. I am just intrigued to find out if anyone knows where or when any of these (or any other high-level concepts that I've forgot to mention) have been deployed in any well-known games :)

I also know that in this industry, trade-secrets are a fact of life ;) Aside from the AAA titles, if you have any of your own success-stories (or disasters) it would be nice to hear them! :D

# Answer
Generally speaking neural networks and genetic algorithms are not used in games, and apart from recent interest in using neural nets for deep learning, not that often outside of games either.

The main reason these are taught in AI academia is not because of their practical applicability but because they are quite easy to explain as teaching devices - both have mathematical and biological analogues that allow a student to understand how they could work.

In the real world, you typically need reliability and predictability. The problem with learning methods is that if they learn 'in the wild' then they can learn the wrong patterns and be unreliable. An NN or a GA could potentially reach a local maximum which is not guaranteed to be good enough to provide the gameplay experience required, for example. Other times, it might end up being too good, finding a perfect strategy that is unbeatable. Neither is desirable in most entertainment products.

Even if you train offline (ie. before launch, and not during gameplay), an apparently good looking set of data could be hiding anomalies that, once found by a player, are easy to exploit. A neural network in particular typically evolves a set of weights which is quite opaque to study, and the decisions made by it are hard to reason about. It would be difficult for a designer to tweak such an AI routine to perform as desired.

But perhaps the most damning problem is that GAs and NNs are generally not the best tools for any game development task. While good teaching devices, anybody with sufficient knowledge of the subject domain is generally better equipped to use a different method to achieve similar results. This could be anything from other AI techniques such as support vector machines or behaviour trees through to simpler approaches such as state machines or even a long chain of if-then conditionals. These approaches tend to make better use of the developer's domain knowledge and are more reliable and predictable than the learning methods.

I have heard however that some developers have used neural networks during development to train a driver to find a good route around a racetrack, and then this route can then be shipped as part of the game. Note that the final game does not require any neural network code for this to function, not even the trained net.

The 'cost' of the method is not really the problem, incidentally. Both NNs and GAs can be implemented extremely cheaply, with the NN in particular lending itself to pre-calculation and optimisation. The issue is really that of being able to get something useful out of them.
> 19 votes

# Answer
Applications of "academic" AI in games tends to be a lot more subtle than the types of things one normally thinks of as AI in the game sphere. A lot of my Game AI professor's focus back when I was in school was AI for camera control. His other area of interest was AI narrative management which is as far as i know still limited to academia for the most part. A notable example of this later area would be facade.

The main issue for "academic" AI, in games, is that they are solving different problems. You often don't want to satisfy requirements, in game; you just want to satisfy. As it has been worded previously: you don't want to to be easy, but you don't want your AI opponent to be too difficult, either.

That being said, Lionhead's Black and White series of games did use AI similar to what you are talking about with the question above and was at least successful enough for them to make a sequel.

I remember reports of radiant AI from "The Elder Scrolls IV: Oblivion' being an example of this vein of behavior originally as well but it had to be dumbed down because of strange unexpected behavior like NPCs killing each other over food.
> 7 votes

# Answer
They are hard to debug, so a glitch (possibly caused by accidental over optimization) cannot be fixed easily. Because of this, any neural network used it games should learn in real time during gameplay. However, they have been used, for example the game NERO.
> 1 votes

# Answer
Forza uses neural networks for car AI. From what I have heard, they did all the learning ahead of time before they shipped the game, so its a static neural network at runtime.

A buddy of mine on the project told me about it, but this article also talks about it: http://gamingbolt.com/forza-5-developer-best-explains-cloud-technology-create-ai-agents-to-win-for-you
> 1 votes

# Answer
Since you asked for examples in industry, here's one for you: The earliest title I know of that used neural networks was Fantasy Empires, a D&D TBS / action game released 1993. Apparently they used these to drive what the dungeon master figure would say and do in an "intelligent" but "non-predictable" fashion... if you've played the game a lot, you might disagree! The animated dungeon master figure offers guidance on your gameplay style, based on your recent actions, from a collection of static sound bites, using the NN. I assume it is a very simple network indeed.

(see page 57 of the manual for details)
> 1 votes

---
Tags: ai
---