title: Rendering multiline text with SDL_TTF

text:
# Question
Title: Rendering multiline text with SDL_TTF
Can you use any function to render more than a line of text in a surface?

If you can't do this, what whould be the way to go? I am doing the following: Create a surface (not sure if should be a software or a hardware one) and then create as many surfaces as lines my text have, then blitting all the surfaces, and freeing all the surfaces. But this turns to be very slow. This is the code:

```
void Text::updateSurface() {
    if (surface != NULL) {
        SDL_FreeSurface(surface);
    }

    TTF_Font * font = TTF_OpenFont(fontPath.c_str(),size);
    if (font == NULL) {
        ERROR("Null font"<<TTF_GetError());
    }

    int maxWidth = 0;
    int totalHeight = 0;

    std::vector<SDL_Surface *> surfaces;
    for (size_t i=0; i<lines.size(); i++) {
        SDL_Surface * partialSurface = TTF_RenderText_Solid(font, lines[i].c_str(), color);
        if (partialSurface == NULL) {
            ERROR("surface == NULL: "<<TTF_GetError());
        }
        surfaces.push_back(partialSurface);
        totalHeight += partialSurface->h;
        maxWidth = std::max(maxWidth, partialSurface->w);
    }

    TTF_CloseFont(font);

    surface = SDL::allocateSurface(maxWidth,totalHeight);
    if (backgroundColor != NULL) {
        SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format,backgroundColor->r, backgroundColor->g, backgroundColor->b));
    }
    totalHeight = 0;
    for (size_t i = 0; i < surfaces.size(); i++) {
        SDL_Rect dst = {0, totalHeight, 0, 0};
        switch(aligment) {
        case ALIGMENT_RIGHT:
            dst.x = maxWidth - surfaces[i]->w;
            break;
        case ALIGMENT_CENTER:
            dst.x = (maxWidth - surfaces[i]->w) / 2;
            break;
        case ALIGMENT_LEFT:
        default:
            break;
        }
        totalHeight += surfaces[i]->h;
        SDL_BlitSurface(surfaces[i],NULL,surface,&dst);
        SDL_FreeSurface(surfaces[i]);
    }
}

```

This is the code for SDL::allocateSurface(...)

```
static SDL_Surface * allocateSurface(int width, int height, int bpp = -1, Uint32 flags = 0)

SDL_Surface * SDL::allocateSurface(int width, int height, int bpp, Uint32 flags) {
    if (bpp == -1) {
        bpp = SDL::bpp; //SDL_GetVideoInfo()->vfmt->BitsPerPixel;
    }

    if (flags == 0) {
        flags = SDL_HWSURFACE;
    }

    Uint32 rmask, gmask, bmask, amask;

    #if SDL_BYTEORDER == SDL_BIG_ENDIAN
        rmask = 0xff000000;
        gmask = 0x00ff0000;
        bmask = 0x0000ff00;
        amask = 0x000000ff;
    #else
        rmask = 0x000000ff;
        gmask = 0x0000ff00;
        bmask = 0x00ff0000;
        amask = 0xff000000;
    #endif

    return SDL_CreateRGBSurface(flags, width, height, bpp, rmask, gmask, bmask, amask);
}

```

# Answer
Don't render text directly with SDL\_TTF. It's not efficient, at all. Use SDL\_TTF to generate a glyph atlas, or use a tool like AngelCode BMFont. You can get glyph metrics (Width, Height, x advance, etc.) using TTF\_LineSkip to find the vertical distance, and TTF\_GlyphMetrics.

At this point, you can render text yourself. By putting the font glyphs into an atlas, and storing glyph metrics, you can easily render multiple lines, render each glyph in a different style or even font, do various effects, etc. By batching your glyph draws, you can be way more efficient than using SDL\_TTF naively. There's no need to copy whole lines into temporary SDL buffers which are copied to your real output.

It's harder, but worth it. Easy toy render APIs are just that: toys.
> 10 votes

# Answer
There is one more possibility, if performance doesn't matter much, and you are willing to use the newer version SDL2\_TTF(available from the official hg.libsdl.org mercurial repository). SDL2\_TTF has new functions including `TTF_RenderText_Blended_Wrapped`, where you can specify a `wraplength` parameter, which specifies in pixels the maximal width( the surface width also gets padded to this value ). It also supports newline characters, and will break the line at `\n` characters.
> 13 votes

# Answer
Here's the exact code I use for generating a multi-line speech bubble. It's not the best, but it's worked for me so far. I use increments of 5 throughout the function since the sprites for the corners and edges of my speech bubbles are 5x5 pixels.

in-game example:

```
void speechbubble(SDL_Rect origin, int numlines, std::string quote1, std::string quote2, std::string quote3, SDL_Surface* screen)
{
const char* m_quote1 = quote1.c_str();
const char* m_quote2 = quote2.c_str();
const char* m_quote3 = quote3.c_str();
SDL_Surface *spritesheet = load_image("images/spritesheet.bmp");

SDL_Rect smallclip[8];
SDL_Rect m_origin = {origin.x + 5, origin.y + 5, origin.w - 5, origin.h - 5};

smallclip[0].x=0;smallclip[0].y=224;    //top left corner
smallclip[1].x=5;smallclip[1].y=224;    //top right corner
smallclip[2].x=10;smallclip[2].y=224;   //bot left corner
smallclip[3].x=15;smallclip[3].y=224;   //bot right corner
smallclip[4].x=0;smallclip[4].y=229;    //top surface
smallclip[5].x=5;smallclip[5].y=229;    //bot surface
smallclip[6].x=10;smallclip[6].y=229;   //left surface
smallclip[7].x=15;smallclip[7].y=229;   //right surface

for(int i =0;i<8;i++)
{
    smallclip[i].w = 5;
    smallclip[i].h = 5;
}

Uint32 white = SDL_MapRGB(screen->format,255,255,255);

SDL_FillRect(screen,&m_origin,white);

for(int i = 0; i<((origin.w-1)/5);i++)  //top and bottom surfaces
{
    apply_surface(origin.x+5 + (i*5), origin.y, spritesheet, screen, &smallclip[4]);
    apply_surface(origin.x+5 + (i*5), origin.y+origin.h, spritesheet, screen, &smallclip[5]);
}
apply_surface(origin.x+origin.w-5, origin.y, spritesheet, screen, &smallclip[4]);
apply_surface(origin.x+origin.w-5, origin.y+origin.h, spritesheet, screen, &smallclip[5]);

for(int i = 0; i<((origin.h-1)/5);i++)  //left and right surfaces
{
    apply_surface(origin.x, origin.y+5 + (i*5), spritesheet, screen, &smallclip[6]);
    apply_surface(origin.x+origin.w, origin.y+5 + (i*5), spritesheet, screen, &smallclip[7]);
}
apply_surface(origin.x, origin.y+origin.h-5, spritesheet, screen, &smallclip[6]);
apply_surface(origin.x+origin.w, origin.y+origin.h-5, spritesheet, screen, &smallclip[7]);

apply_surface(origin.x, origin.y,spritesheet,screen,&smallclip[0]);                     //apply the corners
apply_surface(origin.x+origin.w, origin.y,spritesheet,screen,&smallclip[1]);
apply_surface(origin.x, origin.y+origin.h,spritesheet,screen,&smallclip[2]);
apply_surface(origin.x+origin.w, origin.y+origin.h,spritesheet,screen,&smallclip[3]);

SDL_Surface* text_quote1 = NULL;
SDL_Surface* text_quote2 = NULL;
SDL_Surface* text_quote3 = NULL;

TTF_Font *font1 = TTF_OpenFont("fonts/CONTRA__.ttf", 14);
SDL_Color color_black = {0,0,0};
SDL_Color color_white = {255,255,255};

if(font1 != NULL)
{
    text_quote1 = TTF_RenderText_Shaded(font1, m_quote1, color_black, color_white);
    if(m_quote2 != NULL) text_quote2 = TTF_RenderText_Shaded(font1, m_quote2, color_black, color_white);
    if(m_quote3 != NULL) text_quote3 = TTF_RenderText_Shaded(font1, m_quote3, color_black, color_white);
}

apply_surface(origin.x+5,origin.y+5,text_quote1,screen);
if(m_quote2 != NULL) apply_surface(origin.x+5,origin.y+19,text_quote2,screen);
if(m_quote3 != NULL) apply_surface(origin.x+5,origin.y+38,text_quote3,screen);
}

```
> 1 votes

# Answer
Try this, instead of `TTF_RenderFont` use `TTF_RenderText_Blended` (just my personal preference) then render the text surface line, then blit onto the main surface and free the text. This way you only have one surface every being rendered on screen.

Heres the method:

```
void printMessageAt(const string& msg, Uint32 x, Uint32 y, TTF_Font *myFont, SDL_Surface *screen) {
    SDL_Rect dest = {x,y,0,0};
    SDL_Color color = {0, 0, 0, 0};

    // This creates the text surface
    SDL_Surface *stext = TTF_RenderText_Blended(myFont, "The line of text to render", color);

    // If it worked, then blit it to the main screen
    // If you wrap this function
    if (stext) {
        SDL_BlitSurface( stext, NULL, screen, &dest );
        // Very important for performance to free the text surface
        SDL_FreeSurface(stext);
    }
    else {
        throw
        string("Couldn't allocate text surface in printMessageAt");
    }
}

```

You can call this multiple times for multiple lines of text. Hope this helps, it essentially relies on the special use of the `SDL_BlitSurface` command.
> 0 votes

---
Tags: rendering, sdl
---


# Question
Title: How can I add custom CSS to a Construct2 game?
I am making a simple game using Construct2. My problem is that Construct2 provides basic HTML buttons, but I want to put a `background-image` on my buttons.

To do that, I want to add custom CSS to my project. But I am not finding any option to add CSS to my project. I have added the CSS in my files directory, but it doesn't automatically work so there must be something else I need to do?

# Answer
I don't believe there is a Construct2-specific way to do this; you just add and refer to the relevant CSS as you would any other HTML project. That is:

* Find the `<head>` element of the HTML page that you'd like to leverage your custom CSS in.
* Add `<link href="PATH-TO-STYLESHEET.css" rel="stylesheet" type="text/css" />`, changing `PATH-TO-STYLESHEET` to refer to the CSS file you want to use (relative to the location of the containing HTML file).

You can find a more in-depth discussion, specific to Construct2, here\], though it essentially just repeats the above advice.

(There are of course other ways, such as leveraging inline CSS within `style` attributes of individual HTML elements, but the above is the more common technique and allows you to avoid a lot of repetition.)
> 2 votes

---
Tags: construct-2, css
---


# Question
Title: Is a Masters degree in computer science beneficial over a Bachelors in the game industry?
Suppose a student (who is seeking to become a video game developer) is studying Computer Science at a state-level university, and is about to complete his or her bachelors degree.

Would the student stand a better chance to get hired as a game developer later if they proceeded to obtain their masters degree in Computer Science, or if they tried to instead obtain an internship or entry-level development position at a local software developer (not game development, but still software development)?

# Answer
The answer is that ***it depends.*** Hiring practices, needs, and wants are different in every studio and even vary over time. Often they vary *wildly*. It may be a benefit, or it may even be disadvantage.

But, that said, generally your resume, which includes your degree, is only going to get you in the door for the part of the interview where you actually talk to a human. Once you get to talk to a human, what you can *actually do* is far more important than what the papers say you can.
> 4 votes

# Answer
The best answer you're going to find is that there is no answer. Right now I am going to persue a Computer Science degree to (hopefully) further my career. On the flip side I have a friend who got an internship and eventually a job working at Nintendo with no official college education. I have a few friends who have obtained some for of degree from a college specializing in game development who work at minimum wage because they're lazy.

tl;dr: **Schooling doesn't guarantee you a job**

So in all, not one solution is really going to be appropriate. It primarily depends on your luck and your skill in your field. The projects that you work on the side, and the portfolio you build is also going to matter.
> 3 votes

# Answer
Between those two choices I don't think either is better. I don't think either is *bad* precisely, but mostly irrelevant to the issue of getting a job as a game developer. Either way what matters is the games you've developed previously, ideally on the job but the next best thing is games you've developed on your own. Getting a master's degree or general software development experience each have different pros and cons so overall I would say they are about equally useful to getting a job as a game developer, but neither is nearly as important as the games you've made.
> 3 votes

# Answer
You will gain more skill and knowledge when you develop games than doing either of those things. Getting a masters might help you gain knowledge useful in resolving certain programming related challenges you may encounter as a game developer. The same can be said about working as an intern in a software firm. I think both paths are somewhat equal because they don't put emphasis on the domain of challenges that naturally occur in the process of game development. While some of these (game development challenges) do overlap with challenges you'll face in the University or at a "generic" software corporation, it will not be sufficient or as effective as developing games today. The differences between a masters and a job in a regular software firm exist but are somewhat perpendicular to the aspects that affect your chances of getting a paying job in the industry. Your chances as others said will increase dramatically if you have something of (great) value to offer and you can actually benefit the team in ways that are more relevant than any of the candidates competing for the position.

In my experience the person who can bring "it" to the table is the one who honed their skills in many (small) projects that were completed successfully.
> 1 votes

# Answer
From my experience (as someone who is finish up his master's degree) it is best to get a masters degree. During your master's degree there will be room for an internship so you get both. Also make sure to choose courses relevant to the game industry (like graphics, geometric algebra, calculus, etc...).

This is because unfortunately game industry related bachelors are 'tainted' these programmes have been creeping up everywhere and usually do not contain the knowledge at all that you need to program games. For example not much of these programmes include advanced calculus and linear algebra courses while most do include some sort of silly gamemake based course. Guess which of these two courses will come more in handy when you're trying to find an efficient algorithm to compute vision metric over a complicated graph structure ;).

Added bonus: people with a master's in CS are very scarce (at least here in the EU) so if you have a hard time finding a game related job you have a very easy time finding something else (that will probably pay a lot better ;) )

**Sources**: me and people I talked to at Nixxes (Tomb Raider) and Abbey Games (Reus) where I did internships) and Crytek where I had an in-house day.

Edit: the opinions here differ a lot. So why not call up a few of your favorite game companies and ask them what they think? Just find their phone number (best) or e-mail address (really only if you cant contact them by phone). Most HR people are actually quite nice and will love to give you some short advice.
> 0 votes

---
Tags: game-industry, education, career, jobs
---


title: Calculating/Predicting a way

text:
# Question
Title: Calculating/Predicting a way
I'm just starting with physics, so I'm not always sure about what I'm doing. It's a 2D project but I'm using 3D physical objects like SphereCollider etc..

**What I have:**

Objects floating in space and affecting each other through gravity:

```
protected virtual IEnumerator OnTriggerStay(Collider other) {
    yield return new WaitForFixedUpdate();

    if(other.attachedRigidbody) {
        Vector3 offsetVector = this.transform.position - other.transform.position;
        float distance = offsetVector.magnitude;
        float gravityForce = (other.rigidbody.mass * mass) / Mathf.Pow(distance, 2);
        // Clamp gravity.
        if(gravityForce > 1.0F) {
            gravityForce = 1.0F;
        }
        other.attachedRigidbody.constantForce.force = offsetVector.normalized * gravityForce;
    }
}

```

There are controllable objects on which the player can click and drag a line away from the object in order to give it a force (shoot) in the opposite direction.

**What I want to achieve:**

The player should see a rough prediction of the way while aiming. That means that the way-prediction needs to take in account the current velocity, the force which would be applied when the player release the mouse button and the gravity of the surrounding objects.

**What I have tried so far:**

For testing purposes I just save the computed/predicted positions in an array and draw those positions in OnDrawGizmos().

I wrote a method which returns the gravity influence for a certain position called computeGravityForPosition(Vector3 position).

And thats how I try to calculate the positions:

```
private void drawWayPrediction() {
    Vector3 pos = this.transform.position;
    // The offsetVector for the shooting action.
    Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    forceVector.z = 0.0F;

    // The predicted momentum scaled up to increase the strength.
    Vector3 force = (forceVector.normalized * forceVector.magnitude);

    // 1. I guess that this is wrong, but don't know how to do it properly.
    momentum = this.rigidbody.velocity + force;

    for(int i = 0; i < predictionPoints.Length; i++) {
        float t = i * Time.fixedDeltaTime;
        momentum += computeGravityForPosition(pos);
        pos += momentum * t * t;
        predictionPoints[i] = pos;
    }
}

```

At the beginning, when the objects just slowly approaching each other it looks okay. After the first shot, the prediction is completely wrong. I guess it is because of 1. in the code. Just adding the force to the velocity is probably horrible wrong.

Thank you very much for your time.

**EDIT:**

I removed seemingly unnessecary parts.

I still think that the main problem lays in 1. in the code. I just don't know how to mix up the current movement of the object (from which I only have the current velocity as far as I know the physics engine of unity) with the new created force:

Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3 force = (forceVector.normalized * forceVector.magnitude);

# Answer
Since you are using an existing framework that handles the physics it should be relatively simple to maintain a clone (or a saved state) of the world and actually run the simulation for a few tics instead of rewriting the code from scratch.

The reason you wish to use a framework or an engine to complete tasks that were resolved fully by other people that have invested thousands of hours or sometimes hundreds of man-years into that project is that you can save a lot of time and do not have to repeat this process cause they made an interface so simple that it's practically effortless to reuse the fruits of their labor in the creation of your project. Learning how it works is against the principles that make programming a productive labor. The whole idea is that it could be used as a black box in the sense that you don't need to know how it works. When you turn on the washing machine, do you need to know how it's engine converts electricity into a force that is agitating the clothes inside warm soapy water in order to get your clothes clean? Probably not. Imagine how many clothes would go dirty if every houseperson would have to fully understand how their washing machine worked to get their clothes clean? All they need to understand is the interface. If you do figure out how it works precisely and can rewrite it more effectively, why use it in the first place? That in essence is how GPUs came to replace CPUs. People learn some in-depth and then reinvent the wheel in a new and improved way. Unless that is what you are set out to do, don't spend your precious time on this.
> 2 votes

---
Tags: c#, unity, physics, projectile-physics
---


title: First encounter with dynamic lighting

text:
# Question
Title: First encounter with dynamic lighting
I have a game idea with lots of pretty lights (literally) in mind that I would really love to implement, but I have essentially zero experience with shadow mapping, deferred rendering, the lot of it. I've done some research into 2D shadow-casting, and I think I might try a method similar to this, but I haven't a fathom how to create a virtual rectangular manipulation of a polar image (from the point-light's perspective on the map).

My question: How can I create a virtual rectangular manipulation of a polar image whose process is quick enough that it can be run twice per frame every time a light moves in-game?

I'd like to be able to handle at least 4 dynamic lights on-screen at any time, but I'll take what I can get. I've started to learn OpenGL, so hopefully this isn't too high above my skill level.

# Answer
## 2D Shadows Via Shader

Here is a link to a very good article on implementing a 2D shadow mapping system. Also see here for a slightly different version.

These techniques have the advantage of working on all 2D objects, even those with complex shapes as a result of transparency in their textures. These versions are reliant on fragment shaders but if you are working with opengl or directx this should not be a problem.

These techniques also have the advantage of being very efficient and only scaling with the screen resolution. In other words; increased image complexity will not result in a change in performance.

## 2D Ray Casting

Some other techniques are more akin to ray casting. The link posted by Roy T. is an excellent example.

Often these techniques involve casting rays towards vertices of scene geometry to test visibility, but sadly they require that all shadow casting objects have a geometric definition. Luckily this is often a requirement anyway since many games feature a physics engine which has a similar requirement and so there are plenty tools to help create these definitions for your art assets, such as this.

A further drawback to this form of 2D shadows is that its complexity scales with the scene geometry complexity. Adding more objects to the scene means, not only more vertices to test the visibility of, but also more objects to detect ray collisions with. So unlike the technique above, you may find that this technique limits your scene budget.

However, the advantage to this technique is that it's fairly straight forward to understand/implement. Also, it can generally be applied in any system, whether your using C++ and opengl or HTML5 and javascript. That being said, shaders are becoming more ubiquitous.

There are, of course, some very good reasons to use this method. Firstly, you may have actually already have most of the main functionality required or are planning to implement it for other reasons; efficient ray/edge intersection testing and 2d object geometry as an edge/vertex list. Secondly, you may find that for your typical scene or the rendering system you happen to be using that this method is more efficient than the shader based shadow mapping. As always, picking the technique is entirely based on why you want to use it.

## Something Hacky

As a little extra that doesn't really address the question - if you fancy a simpler, hackier method and you are lighting an appropriate tile map based scene (or just one with a really low resolution) you can always try light propagation. Use Bresenham's Line Algorythm to cast rays out along the tile map from the light source until you reach a non-empty cell, reducing the light contribution at each step.
> 1 votes

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


# Question
Title: Using Lua for configuration and localization data
Since my game is already going to be scripted with Lua, I've decided to make all my configuration and localization data defined using Lua tables. For example, this could be a basic locale file:

```
-- en-us.lua
text = {
    error = {
        sdl = "Error initializing SDL",
        opengl = "Error initializing OpenGL",
        resource = "Error loading resource $",
        -- ...
    },
    menu = {
        offline = "Play solo",
        online = "Play co-op",
        quit = "Quit",
        -- ...
    },
    -- ...
}

```

Different locales and profiles can be loaded simply by choosing the right file, for example between `en-us.lua` and `fr.lua`.

Because the table is in global scope, it's easy for other Lua code to reference. If a script needed to access a configuration variable or throw an error, it would just have to look up the value using something like `text.error.opengl` or `config.graphics.fullscreen`.

The difficulties come when native code (C) has to work with these values. There are basically two options that I can think of:

1. The tables are loaded into client code as a tree. It's easy to get and set values on the client side, but changes on either side need to be synchronized.
2. The native code does no caching and instead directly reads from/writes to the Lua state each time. Possible performance issues?

What's the best way to handle this from the native side?

# Answer
> 1 votes
I highly recommend you implement it using the gettext system. It is widely ported and very well supported, for example having lots of tools that support its workflow.

One workflow is to add gettext calls in your code like this:

```
printf(_("My name is %s.\n"), my_name);

```

Which you can use `xgettext` to generate a `.pot` file. Using this file, translators generate a language-specific `.po` file, which they can fill like this (everything except the `msgstr` is generated):

```
#: src/name.c:36
msgid "My name is %s.\n"
msgstr "Je m'appelle %s.\n"

```

As I've said, this system is very well supported. I haven't used it in Lua, but Wikipedia states that there is a Lua implementation.

# Answer
> 0 votes
I wrote an open-source library that does that. It provides an easy access to Lua data from C++ code, while providing a set of interesting features like data hot reloading and late binding. It is not limited to strings, too.

Here it is: https://github.com/tynril/luadata/

I've used it for a few personal projects, but I'm not aware of other people using it, which means there might be some bugs here and there, but as far as I've used it, it is pretty stable.

Sorry for the blatant advertising, but it seems to answer your question, and I don't profit from it anyway.

---
Tags: c, lua
---


title: Passing Input to Compute Shader

text:
# Question
Title: Passing Input to Compute Shader
I am using D3D11 on D3D10 hardware, trying to get a very simple compute shader to run (my hardware supports cs\_4\_0).

What is the best way to pass data to the compute shader?

I've seen some samples use a constant buffer (cbuffer), but it seems very restrictive to me (in the hlsl cbuffer declaration I'd have to specify the amount of input (e.g. if a want to process an array of floats, I'd have to declare in my hlsl cbuffer an array of floats with a specific number of elements).

Other examples pass the input in the structured input the comp. shader will store the results in. Besides the fact that this might not suit my particular algorithm (maybe a thread needs access to more that just one element) I can't declare my structured input as dynamic, so to update it from the cpu (i.e. to add new values for the GPU to process) I'd have to use UpdateSubresource, which is not as efficient as Map, Unmap.

So, there must be a better way to send input to the Compute Shader. Any suggestions?

# Answer
I would use:

* One structured buffer (read-only) for the input
* Another structured buffer (read-write) for the output
* A constant buffer to store a few global parameters, if necessary, such as the size of the arrays.

For example:

```
struct Input { /* blah blah */ };
StructuredBuffer<Input> inputArray : register(t0);      // Shader resource binding

struct Output { /* blah blah */ };
RWStructuredBuffer<Output> outputArray : register(u0);  // UAV binding

cbuffer globals : register(b0)
{
    float someParameter;
    float anotherParameter;
    uint numInputs;
};

```

Constant buffers are not designed for large amounts of data (more than a few kilobytes at a time). However, they are designed to be efficient to access, especially when all the threads in the dispatch are going to be looking at the same constants.

Structured buffers are better suited for larger amounts of data, where individual threads are going to be reading/writing individual records. (Although keeping data in SOA instead of AOS layout benefits the GPU memory system just as it does in CPU SIMD code. I would consider using SOA if your structs are going to be bigger than 16 bytes.)

You can have multiple structured buffers. Some can be read-only, and some can be read-write. There's no requirement that you use the same buffer for both input and output.

Also note that another possibility is typed buffers, like `Buffer<float4>`, in cases where the buffer format matches one of the DXGI formats.

Last, I don't know why you said you "can't declare my structured input as dynamic". There should be no problem with creating a structured buffer with dynamic usage, allowing you to use Map/Unmap. This is certainly allowed by the API. The only restriction is that you can't use the `NO_OVERWRITE` map flag (prior to D3D11.1); you have to use `DISCARD` instead.
> 0 votes

---
Tags: directx11, input, gpgpu
---


# Question
Title: How to compute tile offset for different isometric angles?
I am working on an isometric game and the designers want to use a different isometric angle than the default one, where I simply had to do a 2/1 offset based on tile size.

I know what the new isometric angle is, how can I work out the w/h ratio to offset my tiles ?

# Answer
> 1 votes
As @Sam points out, this is essentially all about trig.

`tan(angle) = opp/adj` implies that if you know the `angle` and either the width or the height, you can find the other dimension. For example, by rearranging: `opp = adj * arctan(angle)`.

---
Tags: tiles, isometric
---


# Question
Title: Fog Of War - Is looping over every tile inefficient?
I'm trying to optimize my static FOW code for my 2D tile-based game and the bottleneck seems to be in the rendering of the fog (rather than the circle drawing algorithm or other aspect of the code).

It's a fairly simple implementation - there are two steps.

First, the game renders everything normally as if there is no fog. Then after the fact, the FOW code loops over every row and every column of tiles and if the tile is "hidden" behind fog, it draws black over the tile.

Everywhere on the web I see that this is the method most used - but to me it seems like it'd be much more efficient to set all of the tiles black, and only show through the tiles which are visible.

Although this sounds logical, in my case it turned out to be not very efficient either.

The Fog grid's tile size is different than the actual game's tile size, which provides some special challenges.

Are there any better methods for generating the Fog of War?

(The game's implementation is in Java, I can provide pseudocode if you'd like.)

Any help is appreciated.

EDIT: I've tried 2 circle-drawing algorithms, and there was little difference in performance (the original proved a little faster).

When I moved the fog code into the level drawing loop, I saw a notable performance increase, but it isn't a lasting solution because my fog grid size is larger than my map grid size.

EDIT 2: Here's the pseudocode - I don't feel comfortable posting the real code, as it isn't mine to post.

Level.render

```
for all x
    for all y
        if {x,y} is in view of camera
            render tile

for all visible entities
    if entity is in view of camera
        render entity

call FOW.render()

```

FOW.render

```
for all x
    for all y
        if {x,y} is in view of camera
            if tile is hidden by fog
                 render fog

```

# Answer
> 1 votes
Depending on how your fog of war works, either permanent or dynamic, you could:

Dynamic: Define the distance from your entity for fog to start being generated. Determine whether a tile has fog or not on the first render loop, effectively eliminating the second.

or

Permanent: Store whether a tile has fog or not on the actual tile itself and check to see if the fog has been lifted during an update loop.

---
Tags: java, fog-of-war
---


# Question
Title: Is it feasible to use a DHT to span an MMO over many servers for improving reliability?
At the moment I have an idea for how to handle distributing MMO servers. At the core is a bunch of worker nodes that all share the same set of distributed hash tables. Each DHT stores a specific game component. Each frame a coordinator server (which there can also be many of) pushes work out to all of the connected worker nodes and wait for them to complete all of the assigned tasks.

The system is also divided up into four parts: the client, which obviously the player uses. The proxy server that sits behind load balancers and users connect to. All they do is process incoming user packets, verify them and passes the request to the work cluster. The work cluster receives packets from proxies and append them to a process queue and wait for the frame event from the controller node to process them.

I just want to know if adding a DHT to the worker nodes like this would be feasible? This should allow redundency and high availability out of the box as DHT's are quite good at that.

# Answer
I think the overhead of using DHT is too big. Normally a component is looked up in a local hash table. If you're lucky that is a single hash operation and a memory look-up. These operations are in the order of nanoseconds

Using distributed hash tables means that two servers would need to talk together. Using a normal local networking connection this is in the order of milliseconds, or a million times slower.

Even if you would use something as outlandish as Infiniband to connect the two servers the latency would still be in the order of microseconds, or a thousand times slower.

And this is just the connection latency we are talking about. There is also the cost of finding the data on the server and then sending it. All of which takes a lot more time than computing that single pointer to memory on a single machine.
> 2 votes

# Answer
I would say, as somebody who has worked on MMOs, that this approach seems a little half-baked (perhaps that's just because you're omitting portions of it?), but more importantly takes far, far too granular approach to the distribution of tasks across a network of machines.

The overhead of the intercommunication protocol would impact your performance significantly, and debugging the thing would be quite a nightmare.

A far better approach would be to distribute work at a higher level, choosing a level of granularity that maintains as much local coherency as possible so all your processing for "nearby" actions, players, events, et cetera occurs on one server (on Guild Wars 2, we distributed work at the map / region level, for example -- although note that this is *not* how the "sharding" in GW2 worked, that was a done differently and for a different reason).
> 2 votes

---
Tags: networking, mmo, entity-system, distribution
---


# Question
Title: Why are my geometry-shader-generated billboards not showing up given the following code?
My program is a rain particle system. After processing a list of positions of rain particles, I passed them to the geometry shader for generating a billboard for each position.

If I use a simple method to generate the billboard, (it is a rectangle, not really a billboard), it work well and I can see them in the render target. This simple method proves that the input positions for the geometry shader are right. The below HLSL source implement this simple billboard.

```
[maxvertexcount(4)]
void GSMAIN( point GS_INPUT input[1], inout TriangleStream<PS_INPUT> SpriteStream )
{
    //Transform to view space
    float4 viewposition = mul(float4(input[0].position, 1.0f), WorldViewMatrix);

    // Emit two new triangles
    for (int i = 0; i < 4; i++)
    {
        // Transform to clip space
        //g_positions is an array of four deltal vectors in the form: (-scale, +scale, 0, 0)..
        output.position = mul(viewposition + g_positions[i], ProjMatrix);
        output.texcoords = g_texcoords[i];
        output.color = color;

        SpriteStream.Append(output);
    }
    SpriteStream.RestartStrip();
}

```

But if I changed to create a real billboard, it shows nothing. My method is based the velocity vector of rain drop. The implementation is in below:

```
[maxvertexcount(4)]
void GSMAIN( point GS_INPUT input[1], inout TriangleStream<PS_INPUT> SpriteStream )
{
    PS_INPUT output;

    //Velocity of raindrop = Rate + original velocity
    //The billboard will stays along this vector
    float3 velocityVector =  input[0].speed.xyz/FrameRate + TotalVelocity;

    //ViewPosition: the position of camera
    GenRainSpriteVertices(input[0].position, velocityVector, ViewPosition, pos);

    for(int i = 0; i < 4; i++)
    {
        output.position = mul(float4(pos[i], 1.0f), WorldViewProjMatrix);
        output.texcoords = g_texcoords[0];
        output.color = color;
        SpriteStream.Append(output);
    }
}

///////////////////////////////////////////////////
//The function generating billboard from
//1. Point Position
//2. Eye Position
//3. Velocity vector
///////////////////////////////////////////////////
void GenRainSpriteVertices(float3 worldPos, float3 velVec, float3 eyePos, out float3           outPos[4])
{
    float height = g_SpriteSize / 2.0;
    float width = height / 10.0;

    velVec = normalize(velVec);
    float3 eyeVec = eyePos - worldPos;
    float3 eyeOnVelVecPlane = eyePos - ((dot(eyeVec, velVec)) * velVec);
    float3 projectedEyeVec = eyeOnVelVecPlane - worldPos;
    float3 sideVec = normalize(cross(projectedEyeVec, velVec));

    outPos[0] = worldPos - (sideVec * 0.5*width);
    outPos[1] = outPos[0] + (sideVec * width);
    outPos[2] = outPos[0] + (velVec * height);
    outPos[3] = outPos[2] + (sideVec * width);
}

```

I tried to use Nsight and Graphics Diagnostics in VS2012 to debug, and all of them show that the geometry shader generated the right vertices. The following pictures are from Visual Studio and Nsight, which present the result after the geometry shader finished its job.

And the next result is from Nsight:

For some reason, the generated vertices in the geometry shader are discarded in the pixel shader. Why might this be?

# Answer
> 4 votes
The fact that something is rendered when you use your "simple method" and the geometry can be seen in Nsight led me to guess that the triangles were being back-faced culled. This is because the winding order of the vertices you create disagrees with the culling mode you are using (to put it another way, all your triangles are now facing away from the camera).

You could either disable back-face culling for this effect or (probably better) reverse the winding order of your created geometry.

---
Tags: sprites, directx11, particles, geometry-shader, billboarding
---


# Question
Title: How can make an object orbit a sphere in a random direction?
How can I move an object on a random orbital path around a sphere?

I've created some objects at an initial position that is essentially a random point on the sphere offset by some distance (say, 10.0).

Now I want to choose a random direction and have the object orbit the sphere in that direction. How can I accomplish that?

# Answer
First generate a random 3D rotation matrix. Then for each frame compute a simple, boring rotation vector around the center (e.g `x = r*cos(k*t), y = r*sin(k*t), z = 0`), multiply it by the rotation matrix, add it to the center of the sphere, and you have a random orbit.
> 2 votes

---
Tags: mathematics, orbit
---


# Question
Title: Why do I get this file loading exception when trying to draw sprites with libgdx?
I'm having trouble with the "Drawing Images" section on the libgdx tutorial. I set up the documents completely and I typed the code as follows:

```
public class Game implements ApplicationListener {
        public static final String LOG = Game.class.getSimpleName();
        private FPSLogger fpsLogger;
        private SpriteBatch batch;
        private Texture texture;
        private Sprite sprite;
        private TextureRegion region;

        //removed irrelevant code for this question...

        @Override
        public void render() {
                texture = new Texture(Gdx.files.internal("android.png"));
                region = new TextureRegion(texture, 20, 20, 50, 50);
                sprite = new Sprite(texture, 20, 20, 50, 50);
                sprite.setPosition(10, 10);
                sprite.setRotation(45);

                Gdx.gl.glClearColor(0f, 1f, 0f, 1f);
                Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
                batch.begin();
                batch.draw(texture,10,10);
                batch.draw(region,10,10);
                sprite.draw(batch);
                batch.end();

                // output the current FPS
                fpsLogger.log();
        }
}

```

I went through the tutorial on the website but when I run the code I get errors:

> ```
> Exception in thread "LWJGL Application"
> com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: android.png at
> com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:137)  at
> com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:55) at
> com.badlogic.gdx.graphics.Texture.load(Texture.java:175)  at
> com.badlogic.gdx.graphics.Texture.create(Texture.java:159)    at
> com.badlogic.gdx.graphics.Texture.<init>(Texture.java:133)    at
> com.badlogic.gdx.graphics.Texture.<init>(Texture.java:122)    at
> com.game.Game.render(Game.java:46)    at
> com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop (LwjglApplication.java:163) at
> com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113)
> Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: android.png (Internal)     at
> com.badlogic.gdx.files.FileHandle.read(FileHandle.java:108)   at
> com.badlogic.gdx.files.FileHandle.length(FileHandle.java:364)     at
> com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:156)  at
> com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:134)  ... 8 more
>
> ```

I set the android.png in my assests folder in my android project linking it to the desktop one, I don't understand what I'm doing wrong. What is making these errors?

# Answer
The relevant part of that stack trace appears to be the message about not being able to find the `android.png` file. Since you assert the file does exist on-disk, the problem is likely an issue with the working directory of your application at the time you attempt to load the file and the file's location relative to that working directory.

I'm not entirely sure if this is true of Java applications, but the working directory is generally going to default to that of the application itself or the working directory of the shell that invoked the application (if launching it from a console). So, if your image is in an "assets" subfolder relative to the application, you'd have to attempt to load "assets/android.png" and not just "android.png".

Also note that because the image appears in an assets subfolder in your project structure, that does not necessarily mean it will be deployed with the final built application unless you've configured your IDE/toolchain (which you don't specify) to do so.

In a pinch, you may be able to use the `getAbsoluteFile` method of the `File` object to print the absolute path of the image at runtime to the console or in your debugger. That may help you diagnose where your program *expects* the image to be versus where it actually is.
> 6 votes

# Answer
The real problem to the code you posted above is these three lines:

```
texture = new Texture(Gdx.files.internal("android.png"));
region = new TextureRegion(texture, 20, 20, 50, 50);
sprite = new Sprite(texture, 20, 20, 50, 50);

```

You are instantiating these things in the render loop which is a really bad idea. @Override the create method and create them in there.

Here is a good reference: http://code.google.com/p/libgdx/wiki/ApplicationLifecycle
> 4 votes

# Answer
I encountered the same problem. (I am using eclipse indigo on ubuntu 10.04). The libgdx project setup tool creates android and desktop projects The asset folder in desktop project is a link to android project assets folder When you add a new file to the assets folder ,it takes some time for eclipse to register that a new file is added,as such FileNotFoundError is thrown. Manualy refreshing the linked folder from eclipse resolved the problem for me.

Hope this helps others.
> 3 votes

# Answer
I had a similar problem and I decided to try taking assets/filename.png and shortening it to just filename.png and that fixed my loading issue. I had to manually refresh as well. Thanks for the tip David Dimalanta. :)

"Sometimes, you don't need to write "assets/android.png". "android.png" is fine but make sure that the name of the file and the file extention type (i.e. PNG, JPEG, TXT) are matched and correct." - That's the line that did it for me right there.
> 1 votes

# Answer
Sometimes, you don't need to write "*assets/android.png*". "*android.png*" is fine but make sure that the name of the file and the file extention type (i.e. *PNG, JPEG, TXT*) are matched and correct. Also, it is better to put it only at the *create()* method (*show()* method if you're implementing *Screen*) even the **sprite** and **region** if you're initializing it to prevent from getting a *Nullpointer Exception* error message.
> 0 votes

---
Tags: android, libgdx, spritebatch
---


# Question
Title: Best way to organize models with multiple meshes and textures?
I have character models which have different parts, ex: upper body, head, lower body; each part is a separate mesh in the same model. Each part has several textures associated with it (diffuse, normal, etc).

I'm wondering if there is a best practice for associating the textures with the meshes, given a .obj file as the model, for example, and .tga files for the textures.

So for instance, making sure the head textures get mapped on to the head object.

One way would be having a separate file for each mesh, and using the file names to associate them with their textures, but that seems impractical.

Is there a nice, clean way to do this, which is both easy to program (importing and rendering) and easy for the artist?

# Answer
> 2 votes
Many typical source formats already do what you're asking for in data. The format will contain a list of N materials and a list of M meshes with a mapping for each particular mesh to the material it uses. Your converter can convert these directly to your in-engine format.

Other formats make use of external references, which is handy if you have multiple meshes that share materials. The format is again usually the same: the format has a list of N material references and M meshes and maps each mesh to its material.

In engine, you would either use a reference/pointer/handle to each material for each mesh or use an ID system. You load your optimized format which would likely use a reference system as in the previous paragraph. When you load `foo.model` you'd get a hierarchy of M meshes each with an identiier of the material resource to load. You load the material if not already loaded and attach the handle/id to the mesh.

For example, you might have the files:

```
/asset/material/stone.mat
/asset/material/steel.mat
/asset/model/gargoyle.model
/asset/model/gargoyle/face.mat
/asset/model/rock.model
/asset/model/sword.model

```

In such a setup, your `gargoyle.mod` might have 4 sub meshes using 3 materials, something like:

```
body => /asset/material/stone.mat
sword => /asset/material/steel.mat
armor => /asset/material/steel.mat
head => /asset/model/gargoyle/face.mat

```

This maps to a structure like:

```
materials: [0:stone, 1:steel, 2:face]
meshes: [0:(body, 0), 1:(sword, 1), 2:(armor, 1), 3:(head, 2)]

```

Your engine basically loads that data, loading any materials referenced that's it's missing. Assuming you've already loaded a number of materials, the in-memory format would be similar to the above but with different IDs (mapping to in-memory structures and not the on-file structure):

```
materials: [..., 25:stone, ..., 57:steel, ..., 93:face, ...]
models: [..., gargoyle: [0:(body, 25), 1:(sword, 57), 2:(armor, 57), 3:(face, 93)], ...]

```

A library like Open Asset Importer makes writing your converters much easier given all the formats it supports. You may need to modify it or branch out if your source format extensions (3d authoring plugins) get too advanced, though it does have a degree of flexibility.

---
Tags: textures, software-engineering, models, assets
---


# Question
Title: OpenGL Fragment Shader Interpolation Vs Inverse Calculation
I have found openGL fragment shader tutorials on the web, some that use use inverse calculations to revert the fragment coordinate back to the world space and others that interpolate the position. With that said...

1. Is there a difference between interpolated world-space position and the actual world space position calculated using inverse matrices and the fragment window space coordinates?
2. Does anyone know of any resources that would help me understand the mathematical differences between these two things, if they are different?
3. If they aren't different, then why would anyone use inverse matrices instead of interpolating, which seems less expensive?

I wrote a shader to test 1, but I cannot tell if rounding errors are to blame for the differences or not.

Thanks!

# Answer
> 2 votes
The idea in both cases is to calculate the world-space position of the fragment, so hopefully, if implemented correctly, there should be no difference. :) (Aside from errors due to floating-point math, anyway.)

There are two methods because they're used in different contexts. When rendering a mesh, whose vertices live in 3D space, you would use interpolation because the vertex shader has the world-space position of each vertex, so it's simple and cheap to interpolate it to generate a position for each fragment.

The method based on transforming the fragment coordinate from screen space back to world space would typically be used when doing screen-space postprocessing, such as in deferred shading. In this case you aren't rendering the mesh whose coordinates you're tracking; you're rendering a full-screen quad or something, and the data about where each pixel is in space is coming from the previously rendered depth buffer.

By combining the per-pixel depth value and the fragment's screen-space coordinates you can then reconstruct its position. Matt Pettineo of Ready At Dawn has a good series of articles on this process.

---
Tags: opengl
---


# Question
Title: How do I create smoke-like beam or aura effects?
I mean things like the *Team Fortress 2* medic gun:

...or the *Killzone: Shadow Fall* anti-gravity effect:

How do these work?

# Answer
Typically the trick to this sort of effect is use of scrolling textures. Particles will often be involved but they are usually only an embellishment.

It is the case that effects like this are bespoke and although they share a similar starting point the final effect is always a result of tweaks and tinkering until the art director is happy.

To take the effect to its most basic however you have two elements: the geometry and the texture coordinates. The geometry defines the basic outline shape of the effect while the movement of the texture coordinates defines movement within the geometry (and of course the texture itself defines the shape of whatever is moving along the geometry).

So for example, if you wanted some sort of arcing energy gun, you could construct a camera facing triangle strip along a path from gun to target, and change the shape of the arc over time to give a sense of dynamism. You could then animate the texture coordinates so that the texture scrolls down the length of the beam to give the impression of movement from gun to target. Use alpha in the texture to soften the edges and give the illusion of pulses. This would obviously be a very basic effect but add another set of texture coords and you can start to build something that looks far more complicated than the sum of its parts.
> 2 votes

# Answer
As Mr. Beast say, these effects (like fire, auras, etc.) are usually made with particle systems.

A particle system simulate a lot (10-10000?) small elements emitted by a source, an that flow through a path. The path may be as complex as required.

Each particle is shown in the scene with a sprite. And may be improved with an animated texture, blending effects, or shaders.

For very simple auras, some games just use 3 axis-oriented quads with a amazing animated texture.

Following a youtube example of particle system. https://www.youtube.com/watch?v=a8uZUqIEsoI
> 1 votes

---
Tags: graphic-effects
---


# Question
Title: Exporting distinct images from a sprite sheet using GIMP
I have recently found that in Photoshop there is a script that enables you to export individual images on different layers into distinct png images on disk.

Is it GIMP capable of doing the same thing and how?

I have a sprite sheet (png image) and there are 36 perfectly aligned images in 4 rows (64x64 pixels each). I have to cut and export 36 times.

Can be GIMP of some help here? I don't have Photoshop.

# Answer
> 2 votes
You can use Guillotine to slice the image along the guides or take a look at this plugin, which is used to make tiles out of an image - which is what you probably want.

# Answer
> 1 votes
I would recommend looking into Python and the Python Imaging Library.

I am developing my first cocos2d game and following guidance from a book, I am using the technique of slicing an image to use as the scrolling background of the game. The author recommends having each slice on a different layer in a image-editing program and exporting them to TexturePacker.

Having spent 10 minutes, with Pixelmator, trying to figure out *how* to slice and copy each slice, and getting no where, I thought "%?@$ that!" and turned to scripting.

1. It took 30 seconds to install `py27-pil` using macports.
2. It took me 30 minutes to develop a python script and allows an input image to be sliced into n-pieces (and I am no Python expert).
3. It takes 3 seconds to run the script (the input is 2048x1534).

Here's a link to the script, if anyone's interested.

---
Tags: animation, spritesheet, png, gimp, export
---


# Question
Title: How can I create delays for sprite animations that work correctly when the application is killed and restored?
Please see my original question here:

Using System Time to compute delay times that correctly deal with app pauses?

In summary, I am attempting to to introduce a delay (say of 5 seconds or so) before a sprite takes a particular action (say a jump) - but this needs to be preserved when the user pauses the game or the system kills the app and it is re-launched. I tried to carry out the suggestion in the answer to my previous question (to save the time on app pause and then compare it to current time when resumed to see how long the app was inactive for, then to add this to the time that I check against, but this comes with it's own problems and I'm still not sure of the best approach).

* When the app is re-started following the system trashing it to reclaim resources, the time (now correctly adjusted to include time the app was sitting in the background). I reset & compare the time when restoring the bundle. However, it then takes 4 or 5 seconds to re-load everything (this is an OpenGL app, so resources are loaded in onSurfaceCreated which comes after the Bundle is restored) so by the time the game starts, vital seconds have already passed (so, lets say when resuming there should be 4 seconds remaining before a sprite appears, it will still appear instantly).
* As mentioned, when the app goes into the background, I'm storing the time and then comparing it to the time when the bundle is restored to get the 'app not active' time - however, what happens in cases when the user (or system) sends the app into the background but the app stays active, and is then re-launched? the Bundle is then never restored, so I can't grab the restore time to do the comparisons.

So how best to deal with sprite delays which won't break when the app is in the background and not running? Basically I seem to need a way to have a timer that can be stopped when the app is paused or not active. (The countdown method I described in the original question seems to be the closest thing, ie, just keep a value of say 100 and decrease it each time a game-tic occurs, this would be a lot easier and tidier, however, it would also mean if the game were to ever run slower than 60 ticks per seconds, the delays would be longer), but is there someway I could use 'real' time rather than something anchored to my tics per second that *wont'* carry on merrily when the game isn't running?

---

**Code for delay based on System time (this is in my game logic update)**

```
//Timer is initially set to 0, so grab time to start timer
if (timer == 0)
timer = System.currentTimeMillis();

//Delay completed? (5 Seconds)
if (System.currentTimeMillis()>Timer+5000){
//Reset for next delay
levelTimer = System.currentTimeMillis();
//Carry out required action here (example, jump or more sprite)
}

```

**Code to reset and re-adjust the timer (currently in onRestoreInstanceState)**

```
timer+=(System.currentTimeMillis()-pauseDuration);

```

# Answer
You can always implement a clock by yourself which is updated together with the real time clock. If you implement your own clock, you can even scale it for a slow-motion effect, or speed it up, as seen in many tower defense games.

**Update:** Okay, you may want to consider using a set of 3 variables to keep track of time:

* current time (now)
* previous time (prev)
* elapsed time (delta)

Updating those variables looks like this:

```
prev = now;
now = System.currentTimeMillis();
delta = now - prev;

```

You manage those values for the real time clock. For your game clock, you also need a `scale` factor to speed up or slow down animations (real time scale = 1). The game clock update depends on the real time clock. You can then define various operations on your game clock, such as start(), stop(), setScale(double), etc. However, there are a few things to be aware of:

* Your updates should depend on the game clocks elapsed time (dynamic time step).
* You need an accumulator for your game clock to keep track of real elapsed time which is below 1 unit of elapsed game time.

Additionally, you should use a timer abstraction to schedule events such as your delay. All timers are updated using the game clock, therefore pausing/deactivating the game will pause the timers.
> 1 votes

# Answer
I find it easiest to keep a delta time per frame updated in the `onDrawFrame()` of my surface view's renderer. This way it always reflects only the time that has elapsed since my last draw call, and I can accumulate this value as needed for delays and timing.

The following is a quick example of how I usually implement this:

```
public class GameRenderer implements GLSurfaceView.Renderer {
    public final static float NANO_SCALE = 1000000000.0f;
    public final static float DELTA_LIMIT = 0.1f;

    protected long startTime = System.nanoTime();
    protected float deltaTime = DELTA_LIMIT;

    public void onSurfaceCreated(GL10 gl, EGLConfig config)  {
       // do surface creation / re-creation here
       startTime = System.nanoTime();
    }

    public void onDrawFrame(GL10 gl)  {
       // do the following before drawing your frame
       deltaTime = ( System.nanoTime() - startTime ) / NANO_SCALE;
       if ( deltaTime > DELTA_TIME_LIMIT )
          deltaTime = DELTA_TIME_LIMIT;
       startTime = System.nanoTime();

       // draw your frame here and use deltaTime as needed :)
    }
}

```

This is a very basic idea of what I mean, but the important part is that you update the `startTime` **last** in `onSurfaceCreated` so that it is called after initialization or reloading is completed. Another thing is to ensure that you never get "very large values" so we check the delta time and limit it to some maximum value (1/10th of a second in the example). This prevents slowdowns from causing large time values which could cause chaos for things like physics, collision detection, etc.

Once you have this in place you can use the delta time to calculate active run times, for example:

```
public class GameRenderer implements GLSurfaceView.Renderer {

   float timeBeforeNextSprite = 0.0f;

   public void onDrawFrame(GL10 gl)  {
      // assuming deltaTime is calculated as in above example

      timeBeforeNextSprite += deltaTime;
      if ( timeBeforeNextSprite >= 5.0f )  {
         // draw your sprite here
         timeBeforeNextSprite = 0.0f;
      }
   }
}

```

Now of course you may want to make the `deltaTime` "global" so it can be accessed from anywhere you may need it, but I'll leave the actual implementation details to you.

This is only one way to do it, and you can implement it in a different place than the surface view, but the idea remains the same: restart your timing when the game starts/restarts and calculate delta time each game tick - also, make sure you limit the delta time to a reasonable value to prevent problems.
> 0 votes

---
Tags: java, android, sprites, timer, timing
---


# Question
Title: Where is the error in my perspective projection implementation?
My question is not really a game development question, but since it's based on 3D programming, I thought it would fit best here.

I've got a line made out of Point3D objects where the value of `x`, `y`, and `z` are somewhere in those regions:

```
x: 0 - 640
y: 0 - 480
z: 0 - 4000

```

I'd like to project those lines into a plane with the size of 640 * 480 (the same size as the base `x * y` values were) using a oerspective projection. I found some information about the matrix I should use in an old computer graphics script (there are a lot of different matrixes around the net too), but could not get it to work.

Based on this tutorial, I'm using the following parameters:

```
float n = 1000; // near plane
float f = 4000; // far plane
float l = 0;    // left side
float r = 640;  // right side
float b = 480;  // bottom
float t = 0;    // top

float m11 = (2 * n) / (r - l);
float m22 = (2 * n) / (t - b);
float m31 = (r + l) / (r - l);
float m32 = (t + b) / (t - b);
float m33 = (-1 * (f + n)) / (f - n);
float m43 = (-2 * f * n) / (f - n);
float m34 = (-2 * f * n) / (f - n);

m = new Matrix3D(m11,   0,   0,   0,
                   0, m22,   0,   0,
                 m31, m32, m33,  -1,
                   0,   0, m43,   0);

```

Now all the result-points I receive from doing a `m.Transform(myPoint3D)` are in ranges like:

```
x = -1,015 to -1,694
y = 1,568 to 1,572

```

In my understanding those values should be in ranges from -1 to 1, and I would scale them to fit into my plane, but those results look totally chaotic... Also, the resulting z-values aren't "flat" but ranging from 2.903 to 2.996.

Any ideas where my error is?

# Answer
> 2 votes
Take a look at this MSDN LINK, they tell you all you need to know to create a projection matrix that you can use. And that one is really good.

For your results, the x&y seems correct. indeed the values are supposed to be inside -1 to 1, but the fact is that you also have scaling in place as well as they can endup outside of the screen. To get them into screen cordinates wich im assuming you are after, there is a simple forumla to transform them from clip space to screen space.

```
xy = xy * 0.5 + 0.5;
xy *= wh

```

Where x&y are the x and y of the point, and w is width of the screen and h is the height.
This will give you the screen coordinates of your points.

---
Tags: c#, 3d, projection, perspective
---


title: Animating a sprite with mecanim

text:
# Question
Title: Animating a sprite with mecanim
I want to try animating sprites with the Unity's mecanim. All the tutorials I found used bipedal humanoids, which already have the avatar for the animator component and imported animations.

What I want, is to create animations inside Unity(like in legacy) and use the animation state machine. **So the question is:** How do you animate a single sprite using a mecanim's animation state machine?

# Answer
> 1 votes
Got the animation working with the new mecanim system. Something to note is that Unity **does not allow** physics and animations on a `GameObject` at the same time.

You can create legacy type animations for an object following these steps:

1. Create a new animation controller
2. Create a new animation
3. Add Animator component to the object
4. Open the object in the animation window with the object selected
5. Click *Add Curve* and select Transform/Rotation
6. Set the second keyframe y-axis rotation to 180
7. Press play to see the animation

These animations can then be added to the animation state tree.

---
Tags: unity, animation, sprites, mecanim
---


# Question
Title: Circular dependency when creating entities
I have the following problem:

I have a a class called Stage, that keeps an list of *entities*, which it iterates over every update loop, and updates them. One of these entities might be a weapon (PEW PEW!) that when updating spawns new entities (projectiles, KA-ZOOM, KER BANG!). How do I add these new entities to the list in of entities in Stage? Currently, I have Stage as an singleton with global access, so that the entities which in turn spawns entities just calls the instance of Stage's addEntity method, but that feels silly.

Stage -\> Entity (weapon) -\> Stage again?

I have a similar problem when creating enemies:

Stage -\> Entity (enemy wave) -\> Stage again

I've been thinking about passing the List into all entities that can create other entities, but then I'd have to change the update method for the base Entity class so that it takes this list, a list which most entities have no need of. Also, when adding an entity to Stage, Stage must be made aware of a number of graphics components for that entity, in order for Stage to be able to tell the renderer (which has an OpenGL context) to load the appropriate resources for those graphic components.

Any ideas what I should do? Am I doing it the wrong way now?

Also, while we're at it, why is Singletons so frowned upon?

# Answer
Add event handling.

There's a ton of different ways you can implement event handling, but the main idea is that different components of your game interact via events, eliminating most cross/circular dependencies. Just as an example, you might have an `eventHandler` class (can be singleton, if you so wish), which receives and forwards events. All classes would have access to the `eventHandler`, and would communicate through it.

As for the singleton pattern (or anti-pattern), it's been answered before.
> 1 votes

# Answer
It looks like your entities should be able to trigger the creation any other type entity.

Option 1: (the case you explained)

```
public class WolfSpawner extends Entity
{
    public void Update()
    {
        Wolf wolf = new Wolf();
        Stage.Instance.AddEntity(wolf);
    }
}

```

Option 2: (in this case the Spawner is not aware about the Stage)

```
public class Spawner extends Entity
{
    protected Vector<ISpawnListener> spawnListeners;

    public void AddSpawnListener(ISpawnListener spawnListener)
    {
        if (spawnListeners == null)
            spawnListeners = new Vector();

        spawnListeners.Add(spawnListener);
    }

    public void RemoveSpawnListener(ISpawnListener spawnListener)
    {
        // ...
    }

    public void Spawn(Entity entity)
    {
        if (spawnListeners != null && !spawnListeners.isEmpty())
        {
            foreach(var spawnListener in spawnListeners)
            {
                spawnListener.Spawned(entity)
            }
        }
    }
}

public class WolfSpawner extends Spawner
{
    public void Update()
    {
        Wolf wolf = new Wolf();
        Spawn(wolf);
    }

}

// Listener interface
public interface ISpawnListener {
    void Spawned(Entity entity);
}

public class Stage implements ISpawnListener
{
    private Vector<Entity> entities;

    public void Spawned(Entity entity)
    {
        AddEntity(entity)
    }

    public void AddEntity(Entity entity)
    {
        entities.Add(entity);

        if(entity instanceof Spawner)
        {
            var spawner = (Spawner)entity;
            spawner.AddSpawnListener(this);
        }
    }

    public void RemoveEntity(Entity entity)
    {
        entities.Remove(entity);

        if(entity instanceof Spawner)
        {
            var spawner = (Spawner)entity;
            spawner.RemoveSpawnListener(this);
        }
    }
}

```

There are a other options available to tackle this problem.

Singleton is not a bad pattern, the implementation of it *is* or how you get that single instance *is*. There are scenarios when you only need a single instance of an object in your application.
> 0 votes

---
Tags: java, android, architecture, opengl-es2
---


# Question
Title: Is it possible to be a game artist and not work on character/creature animation?
If I don't want to develop and animate living characters (animals, humans, robots, et cetera) for games, but I *do* want to develop/animate objects (TVs, phones, cars, et cetera) or levels... is it possible to have a career as an artist in the industry?

# Answer
If you work in a big company, there will probably be few 3D artists for specific tasks. One of them might be soft body modeller that will do characters and animals, etc. You can be level designer, make some fences, houses, rocks, perhaps lightining artist which is really crazy if you are good one. You can type in your portfolio that you are level designer and show some beatifull landscapes for example. I think level designer is what you search for.

On the other hand, I think you must spend some time trying to build characters, at every try you will get better. Traditional paining and 3D modelling are kinda different. If you model a TV, you can also model a human, you just need some time to get the feeling of the creation of soft body models.

Also if you model long enough, your brain will get boored and you will start wanting to model something completely different, so in time you might get get interested.

PS: I had no idea coding games requires math knowledge, I'm not good at all in math, but I keep forward becouse I want to create a game :D
> 7 votes

# Answer
It's *possible*. Perhaps less feasible. Many artists focus purely on modelling machines or architecture, for instance. Or characters. But for game designers, it's a bit different. You tend to need to be less of a brilliant artist and more of a generalist in order to cover different design topics.

It does depend though on the types of games you want to be involved in making. Remember that when potential clients / employers review your portfolio, they are going to be looking specifically for those things they expect to see in their game. For example, awesome medieval arms and armour, contemporary cars, or sci-fi vehicles.

Modelling these specifics are viable skillsets all on their own, because those in the industry know that modelling / animating any one class of thing very well means you will tend not to be quite as practiced in other areas. Artists' specialisations are typically respected if they show good ability in said realm.

This is no different for game programmers. Specialisation is a common aspect of tech industry teams, and especially in a field as complex and multifacted as game development, where teams are often large and every member has a very specific role to play in shipping product.

I'd suggest you maybe spend a couple of months at some point on characters in Max, just so you can say you have a basic grasp, if needed. Your other work will form the centrepiece of your resume.
> 5 votes

# Answer
It sounds like the job title you should be shooting for is environment artist. Those are artist who specialize in scenery and props. There is generally a bigger demand for environment artists than character artists; if you think about all the open-world games coming out these days it's pretty obvious why.
> 2 votes

# Answer
Sure, game artists are either: character artists, environment artists, effects artists

it sounds like you want to be an environment artist.

animating objects often falls under effects (fire, smoke) or level design (doors opening, drawbridge moving) or tech art (all of the above).
> 1 votes

---
Tags: art, career
---


# Question
Title: Black Box Functionality Testing Methods that apply to an MMO
I've been interesed in a career in Video Game QA for a long time now. I've participated in roughly a dozen+ public/closed betas for different games, everything from FPS, MMO, MOBA and RTS, as well as a lot of early access Indie Games recently.

I'm not some 12 year old kid who thinks playing video games every day will be fun. I know it's tedius work with strict deadlines and a lot of pressure. I enjoy the analytical side of the process and I would like to make this passion a career.

I currently have a few upcoming closed beta weekends scheduled that I'm going to be participating in.

What are some ways I can use these to really improve as a tester?

Anyone in this line of work that would be willing to share some pointers for what type of experience people hiring for a QA job would be looking for, besides the obvious; analytical, attention to detail, communication, etc

Additional information: Feel like I should also mention that I have a lot of programming experience as well. I'm currently a Software Engineering major in my final year, but what I'm really interesting in is QA.

Thank you

EDIT:: I'd like to get this back opened so let me see if I can word this more appropriately.

What are some professional Game Functionality/UX Testing methodologies that I could apply to an upcoming Closed Beta Weekend event for WildStars or Elder Scrolls Online.

I'm looking for information that I could use to provide a thourough evaluation of game aspects that I could then include in a Resume or Testing Profile/Portfolio to show a potential employer "This is how I planned my session out, this is how I executed it and this is what I found."

I hope this is less open ended then my original post.

# Answer
> 2 votes
1) Learn to log quality bugs. Finding a bug is one thing, presenting it in a way that a developer understands why the behavior is a bug and having enough detail to actually fix it without wasting time is a HUGE asset.

* Clear concise title (should not be vague or unclear "Bug!!" is not a helpful title, "Character clips through can clip through wall in World 1 Act 2 while carry an ammo crate" is better)
* Steps to reproduce (always try to reproduce the issue and then list the steps to do so clearly)
* Severity of the issue (helps in triage, the game crashing will most likely trump the color of a characters cape not being correct)
* Screen shots if possible
* Environmental data (what hardware is in use? Operating system? Version / Build of the software)
* What the expected behavior was (this is your reasoning for thinking what you're logging is a bug)
* What the actual behavior is (clearly define the actual behavior)

2) There are always bugs, always. Know that there will always be bugs, you can never find them all especially in complex software. There is a trade off between time and risk. Always try to prioritize testing the functionality that would impact the most users first and provides the most return on time spent testing.

3) Mentally prepare yourself by asking how you would test something that is open ended. In some companies there are really strict requirements to test against, a lot of times this isn't the case. If a developer told you they implemented the "save" functionality and send you a build but no requirements, stop and think if you can't come up with a list of 30+ questions / things to test over the next 10-15 minutes think again.

4) If you can code (which you say you can) pick up a scripting language, Python or Ruby for example. Use them. Make side projects. Make small utilities. Become so comfortable that you don't have to look up syntax and can write a script that does something useful quickly. Automating menial tasks that you have to do in your daily testing is a huge asset, even if it isn't directly automating testing of the software.

I do not work in the Gaming Industry, but do QA for a living and most of this should carry over.

---
Tags: testing, career, beta
---


# Question
Title: How to import or "using" a custom class in Unity script?
I have downloaded the JSONObject plugin for parsing JSON in Unity but when I use it in a script I get an error indicating JSONObject cannot be found. My question is how do I use a custom object class defined inside another class. I know I need a using directive to solve this but I am not sure of the path to these custom objects I have imported. They are in the root project folder inside JSONObject folder and class is called JSONObject.

Thanks

# Answer
> 1 votes
Assuming that you're using C#, there are two steps to include a third party DLL in your Unity project (these steps may be different for Unityscript or Boo).

First, you'll need to include the DLL in the root directory of your project. Next, you'll need to include the "using" directive (ie: the "using" keyword, followed by the namespace in which JSONObject is defined) at the top of any source code files which use the JSONObject library.

I'm not sure which JSON library you're using, but I've had a great experience with LitJSON. It's very easy to use, and very lightweight. I've experimented with a number of other C# JSON libraries, but many of them have dependencies on unsupported .NET libraries, or are very complex or bloated.

# Answer
> 0 votes
This is just a clarification on John's answer - the way we got it to work and a slight extension for maintenance.

First of all, right-click in Project view in Unity, pick "Import new asset". Navigate to your DLL and add it. You can organise it as necessary (e.g. putting it in a "Libraries" folder).

Then exactly as John said, use the using directive.

Now if/when you get an updated library (in our case it's one of our own libraries so it's constantly updating), you can copy it over the top of the existing one. This also means if you're building the library yourself, you can set the output location in Visual Studio for that project to be /yourunityproject/assets/libs.

# Answer
> 0 votes
You have to put the JSONObject files in the folder "assets/plugins". Then you can access it from your UnityScript code without using a directive.

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


# Question
Title: How do some games save without creating data files?
I downloaded a game called *Brain Exercise with Dr.Kawashima*. It contains only one executable and *no data files*. However, it's still possible to save the game!

Where does the save data go?

# Answer
> 19 votes
It may be making saves in the Registry or somewhere under your %APPDATA% folder, or in your homedir's "My Documents" or "My Games" subfolders. Or anywhere else on your hard drive, for that matter. It is unlikely to be modifying its own exe to save, although I suppose that is possible (if a very bad idea: see AttackingHobo's comment below for a sample of the reasons why).

---

When looking into this kind of thing on Windows, I tend to use tools like Sysinternals Process Monitor (aka `procmon.exe`), which will display filesystem and registry activity (among other things, it is verbose -- spend some time filtering down to what you want to see).

# Answer
> 3 votes
While it's perfectly possible to modify the executable (it's what viruses do all the time, and you can append whatever you want to an exe and read from the end of the file - not sure how windows user levels interfere with it, haven't done it since the golden days of MS-DOS) I'd indeed suspect the registry is used.
Copy the executable over an install on another system and see if it has your savegame, if it does you know it's the exe being modified.

# Answer
> 1 votes
While it might not have been that common when this question was originally created, some games today store their savegames on a server connected to the internet in The Cloud™. This usually requires that the user authenticates itself with a username and password. When the game itself has no account management, a digital distribution system can provide this. Steam, for example, offers an API for storing game data on their servers.

---
Tags: savegame, file
---


# Question
Title: Is having a master builder object a bad idea?
I have wondered about using the following approach to creating Entity objects in a personal project. What I want is to be able to keep track of all Entity objects that get created, so whenever an instance is created, it should automatically get added to a bookkeeping list.

The approach I thought of using is to create a class that can hand out new Entity objects, rather than allowing them to be created directly. This class is called EntityFactory. It's not the factory pattern though. Basically, I define my Entity base class with a private constructor and made EntityFactory a friend class so that it could instantiate Entity objects and hand them out.

The only downside I can see is that I would have to pass around the EntityFactory object.

Will there be other problems? Is this a bad idea? If so, what alternatives are there to have automatic tracking of all Entity objects that get instantiated.

# Answer
> 6 votes
This is still, essentially, a factory, just not one that creates things via runtime keys. It uses compile-time keys (effectively) instead.

You have touched on the major downside: you'll need to make this factory accessible everywhere you want to be able to create entities. This, however, is also an *upside* because it means you can control what interfaces are *allowed* to create objects on a very granular level: if you don't give an interface access to the factory, it can't create new things.

Whether or not you actually need all entities to automatically be tracked somewhere aside, this is a more reasonable pattern for doing so than putting that code in, for example, the entity constructor, since it does not overly pessimize your code against the future need to create entities that *aren't* tracked (perhaps for testing scenarios, or lazy evaluation, et cetera).

# Answer
> -2 votes
A method which I used for one of my projects is to create a parent class which precedes over all entities and then I used polymorphism to make all the entities the type of the Parent.

Essentially you'll make a list of type Entity and then when you want to modify a specific type then you cast it to its original class type to access any variables that the parent class wouldn't have access to.

You add the specific Entity to the list by casting it to what the parent would class would be. In this case Entity.

Essentially it would look something like this:

```
Dog d;
Cat c;
Bird b;

Animal AnimalList;

AnimalList.add(static_cast<Animal> d);
AnimalList.add(static_cast<Animal> c);
AnimalList.add(static_cast<Animal> b);

```

The benefits of this method are you will have a permanent list of objects of the same type and thus will make things easier for, for example, collision detection or updating all of their positions. As you will have a neat list to compare against rather than several lists.

```
for(int i = 0; i < AnimalList.size(); i++)
{
AnimalList.at(i).update();
AnimalList.at(i).collisionCheck();

if(AnimalList.at(i) == type(Dog))
{
Dog d = static_cast<Dog>AnimalList.at(i);
d.bark(); //Poor example as you'd probably have multiple creatures having a Cry() //method so they could all have the same function like update();
}
}

```

However it becomes a problem when you want to do checks against specific types. In that case you will have to scour through the list checking against all of the the types to find the right ones. A bypass to this maybe making a indices list for items you want to specifically keep track of. Though I doubt you'll be seeing any performance issues unless you're dealing with a huge list of Entities.

---
Tags: design-patterns, architecture
---


# Question
Title: How can I calculate spotlight lighting in Vertex/Fragment shader in Unity?
I've written a vertex/fragment shader for my game. It uses 3 textures and represents a floating water on the wall (so I have 1 texture for water, 1 for geometry and the last one is mask) so it looks like this:

But I also need a spot light attached to the camera to lit my geometry, and this is the single dynamic light source on the stage.

Well, I can use a surface shader to take dynamic lighting into attention, but I want to avoid using them because: it will be much larger and its execution will be much slower. Besides, I need only one dynamic light source, so I can (can I?) just calculate its lighting in the shader, and pass a position/direction to the shader using material.SetVector(). It is something like:

```
float4 frag(FragmentInput i) : COLOR0
{
    float4 col = i.col * tex2D(_Texture, i.uv);
    col.a = tex2D(_AlphaMask, i.uv).r / 2;

    if(col.a > 0.25f) // it's water, just return the scrolled texture color
    {
        float4 l1 = tex2D(_WaterTexture, float2(i.uv.x, i.uv.y - _Time.y / 16));
        float4 l2 = tex2D(_WaterTexture, float2(i.uv.x, i.uv.y - _Time.y / 8));
        return float4((l1 * l2).rgb, 0.5f);
    }
    else // it's geometry calculate spot light lighting
    {
        float lit = // ... calculations here ...
        return col * lit;
    }
}

```

Is it possible to do this? Will it work faster than the surface shader?

# Answer
What you want to do is definitely possible, since Unity does it in the built-in shaders, and there's nothing in those that you can't duplicate. I can't say whether doing it yourself result in a faster shader than what Unity would generate from a surface shader.

Have a look at Unity's shader utility code, which includes macros to help you access the lighting information from your shaders. You'll should find these in the Unity install tree (`C:\Program Files (x86)\Unity\Editor\Data\CGIncludes` on my Windows machine, `/Applications/Unity/Unity.app/Contents/CGIncludes` on my Mac). The file that's relevant to your goal is `AutoLight.cginc`.

You'd need to include `AutoLight.cginc` in your shader and then use the macros in there to do the work. Looks like you'll want to:

* Add `LIGHTING_COORDS(idx1, idx2)` to your fragment input
* Call `TRANSFER_VERTEX_TO_FRAGMENT(a)` in your vertex shader
* Call `LIGHT_ATTENUATION(a)` in your fragment shader to get the light level
* Use `_LightColor0` to get the light's color

(Note 0: The `idx1` and `idx2` parameters are indexes of two `TEXCOORD` semantics.)

(Note 1: In the macro calls above, the parameter is the fragment input structure.)

(Note 2: I haven't used spotlights in Unity, so it's fairly likely that you'll have to debug my approach a little.)

Hope this helps!
> 2 votes

# Answer
As Netherwire implied in reply to my previous answer, the real question seems to be "How can I make an object respond to only one of several light sources in my scene?"

That's answered here, in Unity's own community answer system:

http://answers.unity3d.com/questions/8646/light-affecting-only-specific-objects.html

In this case, you would need to assign the wall object to its own layer, then edit each non-spot light source so that the light's Culling Mask does not include the wall object's layer.
> 0 votes

---
Tags: unity, shaders, lighting
---


# Question
Title: 2D AABBs and resolving multiple collisions
Okay, so this is a problem I've been trying to figure out for quite some time. Mine is a 2D platformer game with a world made up of (usually) immobile tiles and mobile sprites, both of which use AABBs to represent their hitboxes. This game is NOT grid-based due to some complications with moving layers of tiles.

I can detect collisions and easily figure out the depth of the collision. I use the "shallowest axis method" to determine which way to resolve a collision between the sprite and the tile. If the sprite is deeper horizontally than vertically, the direction to resolve is either up or down. If the sprite is deeper vertically than horizontally, the direction to resolve is either left or right.

This is simple enough, and it works pretty well. That is, until you have a sprite colliding with more than one tile. As, by their nature, each collision has to be checked separately, different collisions may have different direction to resolve in. For example, if a sprite is trying to walk across a row of tiles, for one frame they will intersect the next tile such that the horizontal depth is shorter than the vertical depth. As the collision says "resolve left", it will be pushed back and will be stuck on the corner.

I've been mulling this problem over, on and off, for quite some time, and several solutions have come to me, but all have flaws. I could mark certain sides as unreachable, but without a grid-based engine, determining "unreachability" is remarkably complex, especially with moving layers of tiles always a possibility.

Another possible method would be to predict collisions before they happen and "work back" the movement to the point of the collision, I suppose, but I'm not sure how the math on that works.

I feel that I'm missing something incredibly obvious, especially since games from the 80s have already solved this problem.

# Answer
> 7 votes
## The problem

The problem lies in your method of collision resolution. Your method goes as follows:

1. Move the player.
2. Check for collision.
3. Determine the shortest collision depth.
4. Resolve collision.

The problem with this, is that it can easily move the player in the wrong direction. You can see how this might happen in the image below:

Because the player is moving down to the right, and is above the ground, you would expect the player to land on top of the ground (by the green box). But instead, it gets pushed out of the ground to the left (represented by the red box). This can be a problem if the player is trying to jump from one platform to another, because the player may end up falling to his death due to bad collision code.

## The solution

The solution to this problem is actually pretty simple. Instead of using the above method, you resolve collision like so:

1. Move the player along the X axis.
2. Check for colliding tiles.
3. Resolve X collision.
4. Move the player along the Y axis.
5. Check for colliding tiles.
6. Resolve Y collision.

Now I hope that you didn't throw your depth check code away, because you are still going to need it for steps 3 and 6.

To resolve collision between tiles on either of the two axes (after moving the player), you first get the depth of the collision. You then take the depth of the collision, and subtract that from the axes that you are currently checking for collision. Note that the depth should be negative if you are moving to the left, so that the player moves in the right direction.

Using this method, you will not only not have to worry about collision bugs like the one in the scenario in the above image, but this method also can handle collision with multiple tiles.

**Example code:**

```
void move(velocity)
{
    top = player.y / TILE_HEIGHT;
    bottom = top + (player.height / TILE_HEIGHT);
    left = player.x / TILE_WIDTH;
    right = left + (player.width / TILE_WIDTH);

    // Check X

    player.x += velocity.x;
    player.updateAABB();
    for(int tx = left - 1; tx <= right + 1; tx++)
    {
        for(int ty = top - 1; ty <= bottom + 1; ty++)
        {
            aabb = world.getTileAABB(tx, ty);
            if(aabb.collidesWith(player.aabb))
            {
                depth = player.aabb.getXDepth(aabb);
                player.x -= depth;
            }
        }
    }

    // Now check Y

    player.y += velocity.y;
    player.updateAABB();
    for(int tx = left - 1; tx <= right + 1; tx++)
    {
        for(int ty = top - 1; ty <= bottom + 1; ty++)
        {
            aabb = world.getTileAABB(tx, ty);
            if(aabb.collidesWith(player.aabb))
            {
                depth = player.aabb.getYDepth(aabb);
                player.y -= depth;
            }
        }
    }

    player.updateAABB();
}

```

# Answer
> 0 votes
You're overthinking the problem and conflating a couple of issues. But that's okay because, as you said, this is a very solved problem with lots of great answers out there.

Let's break it down:

1. **Tilemaps**. Your first example is of a sprite walking across a bunch of tiles laid out horizontally (or sliding down a wall of tiles laid out vertically, they're isomorphic). One very elegant solution to this is to simply not check the edges of tiles where we know a sprite can't get to, such as edges that are "underground" or edges that border another completely solid tile.

You're right that the sprite would descend due to to gravity, then move laterally, then get stuck... but the answer is to *not care about the left or right edges of the tiles that are underground*. That way, your collision resolution routine only moves the sprite vertically — and your sprite can go on its merry way.

Check out the Metanet tile tutorials for a step-by-step explanation of this. You say in your question that you're not using a traditional tilemap, but that's okay too: static tiles are in the tilemap and update as above, while moving platforms and such update as #2 below.
2. **Other AABBs**. You'll only run into a problem if, in a single frame, your sprite can move a distance larger than the width/height of most AABBs in your game. If it can't, you're golden: resolve the collisions one-by-one and it'll work just fine.

If the AABBs *can* move very fast in a single frame then you should "sweep" the movement when checking for collisions: chunk up the movement into tinier fractions and check for collisions at each step.

---
Tags: c#, collision-detection, monogame, collision-resolution, aabb
---


# Question
Title: Stop diagonal selection in my Match-3 game
I have a matching game where the user drags their finger over items to select them.

The problem is, i only want the user to be able to select items by dragging vertically or horizontally, not diagonally.

Here is my method that detects if the user is dragging over a item and then adds it to an array to be removed:

```
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {

    camera.unproject(vecTemp.set(screenX, screenY, 0));

    int x = (int) vecTemp.x;
    int y = (int) vecTemp.y;

//checking to see if any objects match with the selected type and match with the position currently being dragged over
    for (GameObject object : gameObjects) {
        int ox = Math.round(object.getX());
        int oy = Math.round(object.getY());

            if (object.getType() == selectedType
                    && x == ox
                    && y == oy
                    && !selectedObjects.contains(object,true)) {
                // You probably also want to add a condition here, to check, if the previously added object is next to the new object (x >= dx-1 && x <= dx+1 && y >= dy-1 && y <=dy+1)

 //add item to array here

                break;
            }

        }

    return true;

}

```

Anyone have any ideas of how i can change my code to not use diagonal drags?

# Answer
> 0 votes
It looks like you already know what you need to do based on your comment. As the user slides over items and you add them to a list you need to check to make sure that the second item shares either an x or y with the first one (making it horizontal or vertical to it). Then you need to make sure the third item has the same x or y as the first two.

---
Tags: java, libgdx
---


title: Unity, Cannot See Items on the Scene

text:
# Question
Title: Unity, Cannot See Items on the Scene
I am new to unity. I have created an asset by using Blender and managed to put it in the scene. But somehow now I can only see one item at a scene. For example I can only see camera when I clicked "Main camera" at the Hierarchy toolbar. When I clicked the asset, the camera is hidden from the scene along with lighting etc. This is difficult for me since I need to put my asset in front of the camera. Where can I toggle back the views for everything in the scene?

# Answer
You should have the "Gizmos" menu in the scene view, check if everything is checked there, you should also know that importing from blender will naturally downscale your objects to 0.1 of their scale, you can change that by setting scale back to 1 in the import settings.

When your objects are downscaled to the point you cannot see them if you focus on one of them you'll loose the visibility over the gizmos and vice versa.

If after checking this it is still occuring could you post the specifics of your scene setup?
> 3 votes

# Answer
Do you mean you don't have a scene view? A screenshot would help determine what is the issue. But if you don't have a scene view you can right click any of the tabs e.g "Hierarchy" and select Add Tab-\> Scene.
> 2 votes

# Answer
I think your camera is not focusing your asset. Make your camera look at your asset. Set camera's position to 0,0,0 and your asset's position to 0,0,10. You can find your asset now. Hope this helps.
> 1 votes

---
Tags: unity
---


# Question
Title: Does installing the DirectX SDK add project templates to Visual Studio?
I have Visual Studio 2013 installed on my machine, and I have installed the latest DirectX SDK, but it doesn't seem to have added any DirectX project templates to VS. Should it have? Or do I need to get them separately?

# Answer
> 2 votes
No, it is not supposed to add any templates for you. You have to manual link to wards the include and library folder.

# Answer
> 1 votes
It doesnt include it for you, it's your job to point where it is located. Also note if you are using Windows 8 SDK or Windows 8.1 SDK, it includes already DirectX SDK as you can see here.

---
Tags: directx, visual-studio
---