# Question
Title: Control sprite animation speed using Create JS
How can I control the animation speed of a sprite using create JS?

When you press right and left, the sprite will run through the frames... I'd like to leave the fps at 60, but alter how fast the frames are looped through without altering the main game FPS rate.

See a demo here. Press right and left arrow to see.

I thought changing the bmp animation frequency property would do the trick...

`bmpAnimation.frequency = 2;`

But it did not work...

Or should I be using the jQuery animation?

**Also**, I noticed that each time I hit a random key, the animation plays 1 frame then goes back to first frame. Why is that?

Thanks!

# Answer
Here's your answer:

http://www.htmlgoodies.com/html5/client/html5-gaming-how-to-animate-sprites-in-canvas-with-easeljs.html#fbid=CLhV58xOZNe

This is cut and paste from the above link.

Tutorial 2: Controlling the animation speed and flipping the sprites The simplest way I’ve found to fix the animation’s speed is by using a modulus operator to avoid drawing/updating my sequence during each tick. There’s currently an open issue about this on EaselJS 0.3.2: https://github.com/gskinner/EaselJS/issues/60 To make the character walk normally from left to right, we just need to flip each frame.

EaselJS exposes a SpriteSheetUtils object for that and a flip() method.

// {nameOfFlippedSequence:\["derivativeSequence", flipHorizontally, flipVertically, optionNameOfNextSequence\]} spriteSheet = SpriteSheetUtils.flip( spriteSheet, { walk\_right: \["walk\_left", true, false, null\] });

You’re essentially making a derivative sequence named “walk\_right” based on the “walk\_left” sequence that’s flipped horizontally. Finally, here is the code that slows down the speed animation and handles which sequence to play based on the character position:

function tick() { // To slow down the animation loop of the sprite, we're not redrawing during each tick // With a Modulo 4, we're dividing the speed by 4

```
var speedControl = Ticker.getTicks() % 4;

if (speedControl == 0) {
    // Hit testing the screen width, otherwise our sprite would disappear
    if (bmpSeq.x >= screen_width - 16) {
        // We've reached the right side of our screen
        // We need to walk left now to go back to our initial position
        bmpSeq.direction = -90;
        bmpSeq.gotoAndPlay("walk_left")
    }

    if (bmpSeq.x < 16) {
        // We've reached the left side of our screen
        // We need to walk right now
        bmpSeq.direction = 90;
        bmpSeq.gotoAndPlay("walk_right");
    }

    // Moving the sprite based on the direction & the speed
    if (bmpSeq.direction == 90) {
        bmpSeq.x += bmpSeq.vX;
        bmpSeq.y += bmpSeq.vY;
    }
    else {
        bmpSeq.x -= bmpSeq.vX;
        bmpSeq.y -= bmpSeq.vY;
    }

    // update the stage:
    stage.update();
}

```

}

Sorry the tick function pasted in weird - go to the link for better formatting
> 1 votes

# Answer
I'm not sure this is a solution. Or maybe I dont understand fully.

You want your spritesheet animation to go slower, but i guess you do not want all other elements to go slower, the solution above seems to slow down everything by only calling stage.update each fourth tick.

Or, if you only have one animation on stage, why not just reduce the framerate?
> 0 votes

---
Tags: javascript, animation
---


# Question
Title: Using NDSLib, how to configure video modes to both print text and draw bitmaps on both screens?
In a `NDS` application, i'd like `print text` and `draw bitmaps` on both top and bottom screens. I have been able to setup code to either draw bitmaps or just print text to console.

If I try to enable both at the same time i only get garbage. My guess is there is a memory conflict between `VRAM banks` used by console background (for storing characters sprites) and background buffer used to draw pixels on screen.

My questions is : **how should i configure video modes to be able to draw text and bitmaps on top and bottom screen ?** If not possible, because there is not enough memory, a solution having only text on top screen is also acceptable.

Here is code :

```
#include <nds.h>
#include <stdio.h>

int main() {
    PrintConsole top, bottom;

    //1) bitmap init
    videoSetMode(MODE_5_2D);
    videoSetModeSub(MODE_5_2D);
    bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
    bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);

    //2) console init, incompatible with 1)
    consoleInit(&top, 0, BgType_Text4bpp, BgSize_T_256x256, 0, 0, true, true);
    consoleInit(&bottom, 0, BgType_Text4bpp, BgSize_T_256x256, 0, 0, false, true);

    while (1) {
        swiWaitForVBlank();
        //draw pixels on screens
        for (int y = 0; y < 192; y++) {
            for (int x = 0; x < 256; x++) {
                BG_GFX[x + (y << 8)] = ARGB16(1, x + y, 32, y * x);
                BG_GFX_SUB[x + (y << 8)] = ARGB16(1, 32, y, y * x);
            }
        }
        //print text to console
        consoleSelect(&top);
        printf("top");
        consoleSelect(&bottom);
        printf("bottom");
    }
    return 0;
}

```

# Answer
Let's take a look at the signatures of the functions:

```
PrintConsole* consoleInit  ( PrintConsole *  console,
  int  layer,
  BgType  type,
  BgSize  size,
  int  mapBase,
  int  tileBase,
  bool  mainDisplay,
  bool  loadGraphics
 )

bgInit  ( int  layer,
  BgType  type,
  BgSize  size,
  int  mapBase,
  int  tileBase
 )

```

In both of your calls, you're asking for the two different parts to use the same mapBase and tileBase - in other words, the same area of VRAM.

To make matters worse, you're actually asking the console to overwrite its own memory - it'll use the same VRAM for the map and the tiles.

There's a very handy tool online for checking these VRAM allocation conflicts, and you can fiddle around with it to find some good numbers for you.

However, there is one big problem: your 256x256 background is going to use up a full bank of VRAM.

The NDS has 2 graphics engine, a "main" engine and a "sub" engine. The main engine has access to much more VRAM than the sub engine, which can only use one 128KB bank for backgrounds - and the console also counts as a background.

You will therefore have to exploit the fact that the screen is only 256x192. The simple way would be to just move the console to the end of the bank, but that isn't possible on the sub engine.

Instead, you'll have to move your background deeper into VRAM, say to map base 1 (16K), while the console occupies base 0 for the 4KB of tiles and base 2 (4KB in) for the 2KB map.

Note that you *must* limit your background with this approach.

That means you'll want to do the following initializations:

```
PrintConsole top, bottom;
videoSetMode(MODE_3_2D);
videoSetModeSub(MODE_3_2D);

consoleInit(&top, 0, BgType_Text4bpp, BgSize_T_256x256, 2, 0, true, true);
consoleInit(&bottom, 0, BgType_Text4bpp, BgSize_T_256x256, 2, 0, false, true);
bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 1, 0);
bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 1, 0);

```

(The tool uses BgSize\_B16\_256x192 when used like this, but libnds doesn't define that constant, so I've changed it.)

There is some chance that the actual console or some emulators will still break with this, because you're allocating beyond the 128KB limit, but as long as you don't try to *write* beyond, you should be okay. If it turns out that it still fails, another option would be to use this:

```
PrintConsole top, bottom;
videoSetMode(MODE_3_2D);
videoSetModeSub(MODE_3_2D);

mainBg = bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
subBg = bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);

consoleInit(&top, 0, BgType_Text4bpp, BgSize_T_256x256, 2, 0, true, true);
consoleInit(&bottom, 0, BgType_Text4bpp, BgSize_T_256x256, 2, 0, false, true);

```

but *scroll the background down* by 32 pixels (`bgScroll(mainBg, 0, 32);`) and make sure you either have 32 unused rows of pixels at the top of your 256x256 image, or load your 256x192 image into the appropriate place in VRAM. The console will still clobber parts of the memory allocated for your background, but it will be a part that won't be shown, so it won't be a problem.

EDIT: There is one thing I forgot to point out; this block:

```
    for (int y = 0; y < 192; y++) {
        for (int x = 0; x < 256; x++) {
            BG_GFX[x + (y << 8)] = ARGB16(1, x + y, 32, y * x);
            BG_GFX_SUB[x + (y << 8)] = ARGB16(1, 32, y, y * x);
        }
    }

```

*assumes the background uses base 0*, which obviously is no longer the case.

Instead of using BG\_GFX directly, store the return values from bgInit and bgInitSub and send them to `bgGetGfxPtr` to get the proper starting address:

```
    u16* mainPtr = bgGetGfxPtr(mainId);
    u16* subPtr = bgGetGfxPtr(subId);
    for (int y = 0; y < 192; y++) {
        for (int x = 0; x < 256; x++) {
            mainPtr[x + (y << 8)] = ARGB16(1, x + y, 32, y * x);
            subPtr [x + (y << 8)] = ARGB16(1, 32, y, y * x);
        }
    }

```
> 5 votes

---
Tags: c++, console, nintendo
---


# Question
Title: Should developers make their games easier with new versions?
It seems that the game Angry Birds is becoming gradually easier with new versions. Maybe so people get the illusion of progress and satisfaction of breaking new records?

I would like to know if gradual small modifications of games to enhance the sense of improvement and learning by users is known/common/standard practice in game developing. (I don't mean to say that there is anything wrong with such a practice.)

# Answer
> 23 votes
I think there are a few reasons why games may get easier (or appear to do so)

* **A side effect of maturing code**. Fixing bugs, adding new features and polishing existing features can all have the effect of reducing difficulty. So these games may actually be getting closer to the developers intended level of difficulty, where as they started too hard. For instance, in your example of Angry Birds, subtle changes in the constants of the physics simulation can have a dramatic effect on game play. These could have easily changed the difficulty of the game.
* **Marketing purposes**. Developers may also change the difficulty of the game for marketing purposes. Making a game easier can expand your casual user base.
* **Direct user feedback**. Users may complain about a specific level or feature of the game that's difficult to use.
* **Game statistics**. Many developers are building in reporting into their games. Particularly with level based progress games (like Angry Birds). These reports can tell developers how much progress users make, number of retries on a particular level and when the user quits the game. All of these statistics can be valuable in detecting trends in player behavior. If a developer were to see that a significant portion of players retried a certain level multiple times, then quit the game, they might take a look at that level and see if it's too difficult.

So should developers take any of the above action? Like most things related to humans, it's a balancing act. The number of variables involved in the decision is enormous and ever changing. Since no one knows the exact recipe for perfection, it's impossible to know if the changes you make will make the game better or worse. Even then, most any change will be received as bad by some and good by others. The best course will depend on the game and the developers and their obligations.

# Answer
> 4 votes
While I have never heard of it being done through patches explicitly, a common way of getting the same effect is to have dynamic difficulty in a game. The game is made easier/harder based on the players performance or some other heuristic. This can often be a bit controversial, much like auto-aim in first person shooters, but the answer to your question is; yes it is common and is appropriate where it makes the game more fun for the target audience.

Through patches I have only heard of the game being made easier/harder in cases where a mistake was made in the design.

# Answer
> 4 votes
Some games are difficult to play because the *controls* are difficult. If you look at the early Angry Birds, you never really know where the birds will fly.

Later revisions make the *controls* easier, by showing preview of the curve the bird will fly. At the same time they can make the levels themselves more difficult.

The effect is that the player feels more in control, and this is a *good* thing.

Compare parkour in assassins creed to parkour in mirror's edge - in creed the player feels much more in control. Granted, the scope and focus of the games is different, but in general, player feels much more *bad ass* when parkouring in assassins creed than in mirror's edge.

Other examples of great controls include super meat boy and the knytt games - make it as easy and as natural as possible for player to control the character - in other words, make the game easy to play - and then build a challenge to the player. The result feels *fair* \- the challenge isn't to learn controls, but what the actual challenge should be.

To answer the question, whether games should be "easier" in new versions.. I don't feel that is the case; should they improve in new versions? Yes.

# Answer
> 2 votes
I noticed this happens frequently in MMOs so I thought this would be worth answering for this particular genre. In particular for each update the old content becomes easier while the new content takes a considerable amount of time to complete. So.

Why would developers make their games easier with each new update **in MMOs**?

* It gives lower level characters a chance to catch up to some of the high level characters. This is desirable because many players aim for the high-level 'just-released' content.
* More players in a level range leads to more competition and more fun (easier to find groups/guilds/clans/parties/PVP).
* It also motivates the higher level players to keep playing - if they give up, they'll be passed by newer players (and lose control of their server depending on the mechanics of the particular game).

Examples of this happening:

* Blessed Spirit Shots and Herbs in Lineage II. Initially it took years to obtain level 75, it can now be achieved in a few weeks.
* Rest XP in World of Warcraft

# Answer
> 2 votes
Yes, game developers should make their games easier. Moreover, they should not wait for new versions to do so: they should try to make the first version easier. Nearly all games are too hard for many players.

There are a couple of reasons why this happens, both forms of the typical mind fallacy (the belief that everyone else is pretty much the same as you).

First, game developers typically work in a cycle where they write code (or design levels) and then test their work by playing it. This means that their sense of how the game plays is biased towards their own experience of it. As a game progresses, the developers get better and better at playing it, and lose all insight into how the game plays for a beginner.

The only way to correct for this bias is to bring in fresh testers—people who have never played the game before—and observe them (so-called *kleenex testing*). But even with this kind of testing you risk testing only on people who, while they may not have played *your* game before, are skilled game players in general.

Second, there's a common belief among game developers that making a game easy in some way "cheapens" the experience: that rewards won't be appreciated by players who didn't put in the work. But people differ: not everyone appreciates games in this way. The players who most appreciate overcoming difficulties are exactly the players who will *seek out* difficulties even if the game makes them optional.

Harmonix is an example of a game developer taking a long time to get the difficulty level right. Their first game, *Frequency*, was very hard, and each successive rhythm-action game has been slightly easier. For example, the first *Rock Band* game is easy enough for most adult beginners to play a few of the easier songs, but still too hard for some beginners and for young children. Why did Harmonix not make it possible for beginners to play *all* of the songs? Why did they not make it easy enough for young children (who love the game) to join in? Finally *Rock Band 3* got it right with a "no failure" setting.

I can only guess that the *Rock Band* developers did not initially consider the possibility that families would enjoy the experience of playing the game together even if not all family members have the hand-eye coordination to hit a drum in time. They had to see people trying it (and the consequent frustration when most of the game proved to be out of reach) before they were motivated to make it easy enough.

# Answer
> 0 votes
this might actually be a combination of things that are going on with the game, and the player simultaneously, but for different reasons.

1: the player may be learning the game to the extent of being able to master the tools they are given in a First Person Shooter becoming more and more accurate with a gun that is designed to have issues, or learning a different strategy to complete a given situation. these are all bases for player improvement (which some of the other answers have stated, or alluded to.

2: it may be to do with the difficulty curve of the game (there are multiple, but I will only talk about specifics here). as a game progresses it is expected to present more, and more challenges to the player, and by nature the player is needed to gain more, and more skill to proceed (see 1), and by virtue the game can continue to increase the difficulty of the game itself. the most common of these curves are linear increasing, increasing step function, and (one that I dislike, but is still used) logarithmic.

3: it may also be that the tools that are given to the player directly modify the difficulty curve by bringing it more toward a linear constant, or a fractionally increasing linear. though it should be said that with these new tools can also greatly increase the difficulty because the player is expected to have more of an advantage otherwise (this is where we get the step function difficulty curve where the steps are increased every time the player earns a new tool)

when all of these parts are used in tandem if one, or a couple are under-, or even over-expected then the game can easily become too easy or too difficult, or just seem that way.

like in your example of Angry Birds. as the game progresses the player is presented with different bird types that have different abilities that should conform to the given puzzle. so it is expected that the game still has a difficulty curve, but because each puzzle is in isolation of the others they must be evaluated individually instead of on a curve, and by nature the difficulty of a given puzzle is independent, but the game overall should still conform to a curve.

as a note that this answer only considers player skill, and never takes into account luck.

---
Tags: game-design, marketing
---


# Question
Title: Asking the user to place the joystick in the center while calibrating
I would like to know why exactly calibration programs (usually?) ask the user to place the joystick in middle, that is: Why isn't moving the handle in a complete circle (usually?) enough to calibrate a joystick?

# Answer
> 9 votes
Moving the joystick in a complete circle gives you the upper bounds of the joystick range, but the at rest (i.e. no input) position of the joystick can't be accurately determined from those values.

You could assume that that rest position is the exact center of the available range but that is only true in ideal circumstances. Over time controllers wear in non-uniform ways. You want the actual rest position for the device, which can only be accurately determined by asking for it during calibration.

# Answer
> 2 votes
It is possible they are trying to remove the user from the calibration. Usually joysticks are spring loaded to return to the centered (neutral) position so really what they are asking users to do is to just let go and stay hands off during calibration.

The less human interaction, the more consistent the results.

---
Tags: input, joystick
---


# Question
Title: How do I draw a full resolution texture to a window of the same resolution?
My image is 1280x800, and my screen size is 1280x800. It should draw perfectly. I'm creating a quad the size of the screen, and setting the texture to fit the quad. But right now it draws a square texture on my upper left corner of my screen that's out of scale and not large enough.

I don't know why it doesn't work, I've tried writing the size of the texture larger when drawing and it seems to work sort-of, but I don't know why it didn't work when drawing on a 1280x800 quad.

How do I create a fullscreen quad?

Here's how I'm currently doing it:

This is my OPENGL and display setup code:

```
    DisplayMode displayMode = null;
    DisplayMode[] modes = Display.getAvailableDisplayModes();

    for (int i = 0; i < modes.length; i++) {
        if (modes[i].getWidth() == World.SCREEN_WIDTH && modes[i].getHeight() == World.SCREEN_HEIGHT && modes[i].isFullscreenCapable()) {
            displayMode = modes[i];
        }
    }

    Display.setDisplayMode(displayMode);
    Display.setFullscreen(false);
    Display.create();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, World.SCREEN_WIDTH, World.SCREEN_HEIGHT, 0, 1, -1);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_TEXTURE_2D);

```

This is my code for drawing the textured quad:

```
    background = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/menu/background.png")));

    glBindTexture(GL_TEXTURE_2D, background.getTextureID());
    glPushMatrix();
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex2f(0, 0); // Upper left

    glTexCoord2f(1, 0);
    glVertex2f(World.SCREEN_WIDTH, 0); // Upper right

    glTexCoord2f(1, 1);
    glVertex2f(World.SCREEN_WIDTH, World.SCREEN_HEIGHT); // Lower right

    glTexCoord2f(0, 1);
    glVertex2f(0, World.SCREEN_HEIGHT); // Lower left
    glEnd();
    glPopMatrix();

```

# Answer
> 5 votes
A probable cause is that you may not have identity in your modelview matrix when you come to draw the fullscreen quad. This could happen if you're drawing anything else before the quad.

I note from your setup code that you correctly switch the matrix mode to GL\_MODELVIEW, but then you *don't make a glLoadIdentity call* after doing so (this is OK as it should be initially identity, but it's a good habit to get into).

When drawing your quad, you have it surrounded by a glPushMatrix/glPopMatrix call. This on it's own isn't sufficient to make a matrix identity; from the specification:

> glPushMatrix pushes the current matrix stack down by one, *duplicating the current matrix*. That is, after a glPushMatrix call, *the matrix on top of the stack is identical to the one below it*.

(My emphasis.)

In other words, if your previous modelview matrix was not identity, then following the glPushMatrix call the new modelview matrix will also not be identity.

The simplest fix is to add a glLoadIdentity after your glPushMatrix call.

---
Tags: opengl, java, lwjgl, slick
---


title: Unused constant buffers in shaders

text:
# Question
Title: Unused constant buffers in shaders
If you define a constant buffer in a shader, for example

```
cbuffer test : register(c2)
{
    float4x4 data;
}

```

But never actually use the data in the shader, does that incur any runtime cost at all? It's convenient for me to do this but not at the cost of slowing runtime performance at all. When I time it I don't see any difference...

# Answer
> 2 votes
It should not incur any runtime cost on the GPU. A constant buffer is just a chunk of data in memory somewhere; if it's never accessed, there shouldn't be any cost to having it there. It's possible that it adds slightly to the CPU cost due to the graphics driver needing to validate things when the constant buffer is updated or bound to the pipeline. But if you're measuring no change in timings then I wouldn't worry about it.

# Answer
> 2 votes
For a completely unused constant buffer the shader compiler will see what's happening and D3D won't even allocate a slot for it to be bound in. You can easily verify this by using the reflection API on the compiled shader.

This means you can declare every constant buffer in every shader, and still not go over the limit as long as you don't actually use too many of them.

This means you can create a single header file for them, and use preprocessor macros to make it compile both as C/C++ structure definitions and as shader constant buffers. That way the two sides can't get out of sync with each other.

---
Tags: directx11
---


# Question
Title: Simple 3D collision detection for general polyhedra
I have correctly set up a SAT system. I now need to determine a simple, fast, and general purpose collision detection mechanism to identify the collision points. These points will then be used to determine the constraints for Catto's algorithm.

Unfortunately there seems to be a huge set of candidate algorithms, hence my confusion.

My first take would be, given that SAT tells me the candidate triangle-vertex or triangle-triangle for the collision, to perform the following: \- if SAT results in a T-V collision, we are done; collision is at V \- if SAT results in a T-T collision, then the collision points are found by intersecting the vertices of triangle1 with triangle2 and the edges of triangle1 with triangle2

Am I missing something big?

# Answer
> 7 votes
Are you sure you set up your SAT correctly? You have cross product edge checks to cover, not only face axes. Assuming you have it setup correctly, move on:

Lucky for you manifold generation (finding points of contact + penetration depth + collision normal) is really simple with the SAT. There are two major cases of collisions for general convex polyhedra when dealing with the SAT: something-face and edge-edge. Lets start with something face:

Something has hit a face. This can be multiple edges, or just one vertex. It really doesn't matter which of these two cases you are dealing with, as both use the same exact code to generate contact information, hence calling it the "something hit a face" case. First, the face that contributed the axis of least separation will be called the reference face. The most anti-normal face on the opposing object will be called the incident face. Clip the incident face against the reference face side planes.

*Image from Dirk Gregorius's GDC 2013 lecture*

Above is a picture of the side planes of one of the faces in contact. These side planes are what you must clip the incident face against.

Here is a 2D representation of the side planes of a face:

After clipping, all resulting contact points need to be tested against the reference face. Discard all contacts in front of the reference plane. You are now left with contact points below the reference face. The deepest point will represent the penetration depth for the collision, though with Sequential Impulses you will want each contact to be aware of its own penetration depth, in order to solve each point of contact iteratively, thus allowing convergence to a global solution.

For the edge-edge case life is a little simpler. Just compute the closest points on the two offending edges, average the points together, and use this single point as the only point of contact.

For clipping I recommend Sutherland-Hodgman. See Real-Time Collision Detection by Ericson for a wonderful and robust implementation of this clipping routine.

Each point of contact's collision normal should just be the reference face's normal for the something-face case. For edge-edge the cross product between the two faces defines the collision normal. There is a small gotcha with cross products: there is no guaranteed orientation. By convention the normal should point in a defined direction from the reference object to the incident object. You'll need to come up with a way to ensure your normal direction is consistent (hint: see Dirk's GDC 2013 slides).

---
Tags: collision-detection, physics, separating-axis-theorem
---


# Question
Title: Propel entities at some angle (depending on explosion's position)
I have a 2D platformer. There are multiple particles that are just 1x1 colored pixels. Let's assume there are 256 particles laid out as a 16x16 cube. Say I popped an explosion right in the middle. All of these particles should fly out all over the place.

My question is how would I calculate the angle at which they have to be propelled toward and find what the initial velocity vector right after the blast has to be set to. I already have gravity and friction so that they would be naturally attracted to the ground and slow down after they have traveled a good distance along the X axis.

# Answer
> 5 votes
You don't need to use any trigonometry for this. If you want the objects to be propelled straight away from the explosion, just give them a velocity proportional to the vector between the explosion point and the object's position.

Additionally, you'd probably want to make objects near the center fly faster, so one approach would be to find the vector from the explosion point to the object, calculate its length, normalize it, then scale it by some falloff function applied to the previous length.

# Answer
> 3 votes
Luckily this is really easy. Just take the case of one particle and one explosion.

Say the particle is at (5, 5) and the explosion is at (0, 0). Just by drawing this and looking at the picture, you can tell that the particle should move along the imaginary line between the origin and its location.

So what you need is a vector that points from the explosion to your particle. Here is how you calculate this vector:

```
Vector direction = particle.position - explosion.position

```

Then you should take your direction vector and normalize it (divide the components of the vector by the vector's length. After normalization the length of the vector is 1, and you can scale this vector however you like.

Once you have your scaled direction, just use it to directly move the particles position, thus treating the scaled vector as a velocity.

# Answer
> 0 votes
You should look into 'impulse force' since you are using physics...Impulse is calculated as force * time...or mass * change in velocity...if your particles are motionless before the explosion, an impulse from the explosion will give your particles dynamic motion( less linear )...

impulse link

---
Tags: mathematics, physics, trigonometry
---


title: Hemispherical Projection

text:
# Question
Title: Hemispherical Projection
I'm trying to implement a radiosity processor. I'm aware of many places online to find information about radiosity. I found a great source on NVidia's website is GPU Gems - Chapter 39. On this page they talk about Hemispherical projection. I've implemented a projector that will place mesh 'vertices' on a unit hemisphere...the problem is that the rasterizer only linearly interpolates between vertices along an edge...

...is there a way to adjust the method of interpolation?

Here is shader code for hemispherical projection...it does place the objects correctly, however, the edges between the vertices are straight...when true hemispherical projection would create rounded edges...

```
float4x4 mW;
float4x4 mV;
float4x4 mP;
float4x4 mOrtho;
float2 vNearFar;
static const float PI = 3.14159265f;

texture g_TextureDiffuse;
sampler g_SamplerDiffuse = sampler_state
{
    Texture = <g_TextureDiffuse>;
    MinFilter = Point;
    MagFilter = Linear;
    MipFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VS_IN
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 UV : TEXCOORD0;
};

struct PS_IN
{
        float4 Position : POSITION0;
    float3 Normal : TEXCOORD0;
    float2 UV : TEXCOORD1;
    float4 Pos2 : TEXCOORD2;
};

PS_IN VS( VS_IN input )
{
    PS_IN output = ( PS_IN )0;

    float4x4 mWV = mul( mW, mV );
    float4x4 mWVP = mul( mWV, mP );
        half4 vPos = mul( input.Position, mWV );

    half3 vHemi = normalize( vPos.xyz );

    half3 fNearFar = vNearFar.y - vNearFar.x;

    output.Position.xy = vHemi.xy * fNearFar;
    output.Position.z = ( vPos.z / ( vNearFar.y - vNearFar.x ) );
    output.Position.w = fNearFar;
    output.Pos2 = output.Position;
    output.Normal = mul( input.Normal, mWV );
    output.UV = input.UV;
    return output;
}

float4 PS( PS_IN input ) : COLOR0
{
    //float2 uv = input.UV - 0.5;
    //float z = sqrt( 1.0 - input.Pos2.x * input.Pos2.x - input.Pos2.y * input.Pos2.y );
        //float a = ( z * tan( ( PI / 2 ) * 0.5 ) );
        //return tex2D( g_SamplerDiffuse, ( uv * a ) + 0.5 );

    float4 diffuse = tex2D( g_SamplerDiffuse, input.UV );
    return diffuse;
}

technique Render
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VS();
            PixelShader = compile ps_2_0 PS();
    }
}

```

Here is screenshot:

It may be difficult to tell, but the cube has two faces( triangles ) per side( 6 sides, 12 faces ). From the picture you may be able to see the problem with flat edges...this problem is well documented...I'm trying to avaoid having to render 5 different images( hemicube ) to approximate a hemisphere...I'm mostly interested in hearing about methods of implementing a hemisphere...I also tried( to no avail ) to write a pixel shader that would warp the final( post scene render ) image. I didn't get great results...

...it also just came to me that I don't necessarily need a render result for computing the form factor...just the area that the projected object consumes within the area of the hemisphere base...

...any thoughts are appreciated!

... here is a screenshot of the cube subdivided...much better...still not accurate

# Answer
Hardware rasterizers are only designed to support perspective projection, and they assume that positions and other attributes can be interpolated "linearly" (actually, they use perspective-correct interpolation, where quantities vary along a linear path but not necessarily at a linear rate). They cannot rasterize hemispherical/fisheye/parabolic projections natively.

You can of course calculate these projections in the vertex shader, but unless all your geometry is quite highly tessellated, you'll run into problems that way: geometry too close to the camera will be rasterized inaccurately (so the radiosity result will be inaccurate as well), and it's possible for objects behind a wall to penetrate the wall and become visible when they shouldn't be.

Ignacio Castaño tried various nonlinear projections when working on the lighting capture system for The Witness, and didn't get anywhere with them. He eventually went with hemicubes. (Ignacio's other articles on that blog are also worth reading if you're building a radiosity solver.)
> 3 votes

---
Tags: c++, shaders, hlsl, radiosity
---


title: One to one aiming in 2D platformer

text:
# Question
Title: One to one aiming in 2D platformer
Hello all I have been having an issue with a 2D platformer I'm working on in Unity. It has an aiming style similar to Shadow Complex where the aiming will rotate around the character in direction to wherever the right joystick (360 controller) will be facing. Here's some expert drawings to visualize the issue.

What I have currently working involves raycasts and getting it to rotate which works and is fun but I would really prefer to have the cursor "snap" to the correct position. I'm not sure if I'm on to the correct way to do this or if my "snapping" method is the best possible way to do this.

# Answer
> 1 votes
I think you're overcomplicating this quite a bit. If I understood you right, you want to allow the player to aim to any degree, but this will snap to specific presets (like 8 directions).

To "snap" a value to one of `number_of_steps` equidistant values between a `minimum` and `maximum` value (talking about angles most likely `0` and `360`, or `0` and `2 * Math.PI` or whatever) you can use a rather easy expression:

```
snapped = (Math.Round(((value - minimum) / (maximum - minimum)) * number_of_steps, 0) / number_of_steps) * (maximum - minimum) + minimum;

```

This is a bit complicated, so here's the simplified variation assuming your value's range is always from 0 to 1:

```
snapped = Math.Round(value * number_of_steps, 0) / number_of_steps;

```

It's rather easy to understand once you know the general idea: By multiplicating a value between 0 and 1 with ne number of steps and then rounding the result you essentially force the result to be a multiple of `1 / number_of_steps`. With the final division you're scaling the value back to the range between 0 and 1.

---

Here's an example:

* You've got the value 0.67 and you'd like to snap it to one of 4 possible positions (i.e. 0, 0.25, 0.5, or 0.75; 1 would be the same as 0).
* Multiplying your value by 4 you'll end up with 2.68.
* Rounded this will be 3.
* After dividing it by 4, you'll get 0.75, which is indeed the closest point.

---

Now, to apply this to your problem, all you have to do is determine the angle the player is aiming to (hint: `Math.Atan2()`). Scale this to the range between 0 and 1, apply the formula above, scale it back and use it to rotate your turret, bullet, whatever.

---
Tags: 2d, unity, platformer, joystick, aiming
---


title: Can't get indices with VBO working

text:
# Question
Title: Can't get indices with VBO working
I'm learning opengl for a few days only. Now I'm trying to use indices for my cube, but can't get it working, I don't see anything on screen.

```
struct Vertex
{
    GLfloat position[3];
    GLfloat color[4];
};
vector<Vertex> meshData = {
    {{-1.0f, -1.0f, -1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{1.0f, -1.0f, -1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{1.0f,  1.0f, -1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{-1.0f, 1.0f, -1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{-1.0f, -1.0f,  1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{1.0f, -1.0f,  1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{1.0f,  1.0f,  1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{-1.0f,  1.0f,  1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    {{-1.0f,  1.0f,  1.0f}, {0.0f, 0.5f, 0.3f, 1.0f}},
    };
vector<GLubyte> indices = {
    0, 4, 5, 0, 5, 1,
    1, 5, 6, 1, 6, 2,
    2, 6, 7, 2, 7, 3,
    3, 7, 4, 3, 4, 0,
    4, 7, 6, 4, 6, 5,
    3, 0, 1, 3, 1, 2
};

```

loading:

```
// mesh
GLuint buffer[1];
glGenBuffers(1, buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer[0]);
glBufferData(GL_ARRAY_BUFFER, meshData.size() * sizeof(Vertex), &meshData[0], GL_STATIC_DRAW);
vboBufferId = buffer[0];

// indices
GLuint indicesBuffer;
glGenBuffers(1, &indicesBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLubyte), &indices[0], GL_STATIC_DRAW);
vboBufferId = indicesBuffer;

```

rendering:

```
glUseProgram(getShaderProgram());

glBindBuffer(GL_ARRAY_BUFFER, getBufferId());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, getIndicesBufferId());

glEnableVertexAttribArray(positionHandle);
glVertexAttribPointer(positionHandle, 3, GL_FLOAT, false, sizeof(Vertex), (void*)offsetof(Vertex, position));

glEnableVertexAttribArray(colorHandle);
glVertexAttribPointer(colorHandle, 4, GL_FLOAT, false, sizeof(Vertex), (void*)offsetof(Vertex, color));

mvpMatrix = projectionMatrix * modelViewMatrix * getModelMatrix();
glUniformMatrix4fv(MVPMatrixHandle, 1, false, value_ptr(mvpMatrix));
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, 0);

```

P.S. I just noticed, that I'm getting warning `<qgl2DrvAPI_glDrawElementsInstancedXXX:893>: GL_INVALID_VALUE` in the logcat. What's wrong?

# Answer
You are storing the buffer object name for your elements in `vboBufferId`, when I expect you are meaning to store it in some other variable like `indiciesBufferId`. Otherwise, you're just overwriting the name for the vertex buffer object that you previously stored there and losing it.
> 1 votes

---
Tags: c++, android, opengl-es2, vbo
---


# Question
Title: Should response be tied to request in a multiplayer game?
I wonder if server responses on client operation requests should be tied by some operation id?

**Tied would be when:**

1.Client app sends request to server to e.g. buy item X, and sets operation id as ID.

2.Server responds with operation id and true or false. This would mean that operation with that id was successful or not.

**Untied example:**

1.Client app sends request to server to e.g. buy item X

2.Server responds with just an updated data of item X, where new item owner would be mentioned. This way client can check if owner name is equal to it's own name and if true, assume that item was bought successfully. Same response data could be sent to other clients, to let them know that item X was bought by someone.

**Which approach is better?**

IMHO untied is better and simpler in implementation, but it feels like there can be so many edge cases which I don't see right now.

# Answer
Consider how you can remove ambiguity in your design. A combination of the two choices or the second choice would do that well. For example, you can also send back an enum letting the client know bit more information, something like `ErrorItemPurchasedByOtherPlayer` or `SuccessItemPurchased`. Of course enums would be converted into a byte or two to simplify the data transfer. Simply returning `true` or `false` is ambiguous because it doesn't really give you much information.

Returning an enum, along with the updated item information would give you all the information you need. I don't think it's necessary to inform other players *who* purchased the item, but you could push an update on item availability to other players also viewing the store when an item is purchased.

Your untied example is the same as your tied example, it just contains more information (it's trivial to extract true/false from the supplied information). So there aren't edge cases added.
> 0 votes

---
Tags: networking, multiplayer
---


# Question
Title: Libgdx explain steps for beginner to create and use image as a box2d body
I am basically from corona background and new to LibGdx , familiar with stage and actor from scene2D. Now wants to use physics body from box2d in the game besides using actor from scene2D.

But I need to use images in the game as body... not shapes..

anyone please explain me the steps to use images as a body.

Thanks..

# Answer
> 7 votes
> But I need to use images in the game as body... not shapes..

In Box2D, you will need to create shapes anyway, you can't really go without them. A *body* is composed of *fixtures* and a fixture is a *shape*, that's it.

Here is the official Box2D manual if you want to read more about those concepts.

> anyone please explain me the steps to use images as a body

As i already said, you can't. But a thing you may not know is that you can use convex polygons as shapes (see the related part of the manual).

Assume you have your player entity having this sprite:

You may want to create a body for your player entity which will contain a main fixture having the following polygon as shape:

There is a great tool you may find useful, it's called Physics Body Editor. From the official page:

> Physics Body Editor is all about making your life easier with physics engines. Specifically, it targets the creation of collision shapes for your game objects: we call them rigid bodies. It can also let you combine these objects together and link them with joints to create complex objects: we call them dynamic objects.

*Note: the above image show the `auto-trace` feature of this software*

Physics Body Editor will create a JSON file that you will need to use in your game to create your fixtures, fortunately, libGDX comes with a native loader and here is a code i took from the demo that shows how to do it:

```
BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("data/test.json"));

// 1. Create a BodyDef, as usual.
BodyDef bd = new BodyDef();
bd.type = BodyType.DynamicBody;

// 2. Create a FixtureDef, as usual.
FixtureDef fd = new FixtureDef();
fd.density = 1;
fd.friction = 0.5f;
fd.restitution = 0.3f;

// 3. Create a Body, as usual.
bottleModel = world.createBody(bd);

// 4. Create the body fixture automatically by using the loader.
loader.attachFixture(bottleModel, "test01", fd, BOTTLE_WIDTH);
bottleModelOrigin = loader.getOrigin("test01", BOTTLE_WIDTH).cpy();

```

Your question is not really clear and i assumed that what you wanted to achieve was to have physics simulation based on your sprites. This can't be done directly in Box2D by supplying sprites to body or whatever but here is how to do it using shapes and a pretty useful tool :)

---
Tags: box2d, libgdx, body
---


# Question
Title: Multiplayer platformer - Are server corrections normally required with a single client on the server?
I am currently working on a rather simple multiplayer platformer. I read quite a bit of articles on the techniques used to hide latency, but I still fail to get my head around certain of the concepts. I find the topic very interesting and like to try ideas by myself, but I think asking gamedev stackexchange will be more efficient for my question. I will try my best to describe my current situation and what question arose along the way.

Right now, I only want to have a single player synced with the server. Theoretically, I assumed a player by himself with client-side prediction would not require server corrections, since there are no external factors that influence his movement. Therefore, my prototype currently only has one player synced with a server without server corrections being sent.

If you are familiar with game networking, I think you may skip the context sections, though I may have done something wrong along the way as well.

## The client loop (once per frame, once every ~16.67ms)

The simplified client loop looks like:

1. Check for local input (WASD) and package them as actions (e.g. `Type=MoveLeft, Time=132.0902, ID=15`). We keep the packaged actions to eventually send them later. Also, we directly apply the desired action to the local physics simulation of the game. For example, if we have a `MoveLeft` action, we apply a force towards the left on the player's velocity.
2. Check to send actions. To prevent from abusing the bandwidth of the client, only send the packaged actions at certain intervals (e.g. 30ms).
3. Apply server modifications. At a certain point this will handle deltas and corrections received by the server and apply them to the local simulation of the game. For this particular question, this is not used.
4. Update local physics. Run the physics loop on the main player. Basically, this does the client-side prediction of the player's movement. This adds gravity to the player's velocity, applies the player's velocity to his position, fixes collisions along the way, etc. I should specify that the physics simulation is always executed with a fixed delta seconds (called multiple times depending on the real delta seconds).

I'm skipping a few specific details about the physics and other sections because I feel they are not required for the question, but feel free to let me know if they would be relevant to the question.

## The server loop (every 15ms)

The simplified server loop looks like:

1. Handle actions. Check for received action packages from clients and apply them to the server physics simulation. For example, we could receive 5 `MoveLeft` actions, and *we would apply the force to the velocity 5 times*. **It is important to note, a whole action package is executed on one "frame"**, contrarily to the client where it is applied as soon as the action happens.
2. Update the game logic. We update the game physics, moving players and fixing collisions, etc. We also package any important events that happened to be sent to players (e.g. a player's health dropped, a player died, etc.) later on.
3. Send corrections. We regularly (e.g. once every 35ms) send deltas to other players (e.g. player positions, health, etc.) if they recently changed. This part is not currently implemented, as I want the simulation of a single player to give the same results on the client and server without corrections, to make sure that the client-side prediction works fine.

## The problem

The current system works fine under simple circumstances, and I was happily surprised to see that it gave very similar results with simple horizontal movements(the inaccuracies are due to floating point precision errors, I believe):

*Please ignore the prototype graphics. White rectangle = player, Red rectangles = obstacles, Blue = background*

However, I'm getting sync errors after doing time sensitive movements, such as jumping and moving close to an isolated obstacle:

In theory, I would expect both to always end up with the same results, as there are no external factors to the client influencing his position. In practice, though, I think I understand the problem.

Since jumping around an obstacle like that is very dependant on the timing of the player, small variations of *when* the velocity is applied to the position will have repercutions on the outcome (e.g. the client could move away just in time to avoid a collision with the obstacle, while the server would do it as it receives the whole action package later on and stay stuck on the obstacle for a small amount of time, changing the final result). The difference between how the client and server handle it is mainly that the client does all of its actions as they happen, while the server does them all in bulks as it receives them.

## The question

This long context finally leads to my question (thank you for reading this far): **Is it normal to require server corrections even when there is only one player synced with the server, or should I use certain techniques to avoid desynchronization on time-sensitive situations?**

I have thought of certain possible solutions, some of which I am less comfortable with:

1. Implement server correction. Simply assume that this is normal behavior and correct errors as they happen. I wanted to implement it anyway, but I just wanted to make sure that what I have done so far is acceptable.
2. Use the provided client time to apply the desired actions. I guess this would be similar to lag compensation, requiring to "go back in time" and check for movement. Kind of like applying server corrections, go back in time and reapply the next actions after that. I really dislike the idea. It looks complex, expensive in resources and requires trusting the client's given time (although I do plan to really check that the time looks relatively legit).
3. Ask GameDevelopment StackExchange for a great new idea that will fix all of my problems.

I am just starting out in the world of game networking, so please feel free to correct/criticize/insult any of the concepts above or give ideas/resources that could help me along my journey in the Wonderful World of Networking. Pardon me if I could have found my answer elsewhere, I have failed at that.

Thank you very much for your precious time.

# Answer
> 11 votes
In such cases, you may be better off letting the client be slightly authoritative. For such precise controls you're extremely unlikely to get good behavior even with really advanced correction and prediction.

The client needs to extend from just sending "I jumped" messages to sending "I jumped from X,Y at time T" messages. The server then checks that the location is within close proximity to what it thinks the player was at at time T (which you can limit to a reasonably small time in the past) to protect against cheating, then simulate the jump from the position the client sent. The server only corrects the client when it is far out of whack (usually due to lag or the like).

This sort of technique is used in conjunction with correction and interpolation in order to make the game feel responsive on the local client and look smooth for remote clients.

---
Tags: physics, networking, multiplayer, platformer
---


title: UK Indie studio registration

text:
# Question
Title: UK Indie studio registration
I'm from the UK and I've just about completed making an indie game and had some interest from several online retailers that sell games. This requires me filling in a basic contract.

I'm just one guy who works from home as a hobby, I go by a studio name for my game solely because that's the norm.

Do I need to register my 'company' name before I can go any further?

EDIT: I'm already registered as self employed from prior work in a different field

# Answer
To have a legal agreement with anyone using business name you need legal ground to use that name. Short answer is yes you need to register your business.

There are of course the thing that if you will get paid you need a business to pay taxes for that profit but you can become self-employed which will be easier at the start than starting a LLC (Limited Liability Company).

On the other hand starting a LLC will give you more financial independence in cases when things don't go as planned as you can only lose money invested in that business while all your personal items (house, car, money and other belongings) are safe.
> 7 votes

# Answer
Forming a limited company is recommended when you want to do business, because it separates your private financial destiny from that of your company. Should your company go bankrupt and have lots of unpaid bills and loans, you won't have to pay them with your private money. Only the money you invested in the company will be touched.

Unless, of course, you perform illegal misconduct. Depending on what exactly you did (or did not), you can be made liable. So inform yourself about your local laws in this regard, especially (but not only) tax laws. Corporate tax fraud, even unintentional, is something the authorities in most countries have absolutely zero tolerance for.
> 3 votes

# Answer
In the UK you can do this as a sole trader. Get some further advice about using a Trading name e.g. "Your Name trading as Studio Name" or "Studio Name is the trading name of Your Name". The relevant law is the Business Names Act 1985. This is the simplest one to use but you should still get some advice about what you need to do comply.
> 0 votes

---
Tags: business
---


# Question
Title: Should I use a visual tool or code myself?
I've been writing a small game in Python that generates random dungeon rooms with creatures for the player to fight. It's all text based, choose your own adventure style. A couple months of working on it later, I'm wondering if it would be better to seek some development software instead of manually coding it all? When is it better to code manually and when is it better to use a tool (Unity, Gamemaker, etc.)

# Answer
There is no guidelines for this, as it's based on your own opinions, priorities, needs and such matters, that none else can really answer.

However, i'll give it a shot.

**Code your own stuff if:**

* You really just wanna learn to program and become better in it.
* There is no tools made for this job.
* You are kind of person ( like me ), who can't seem to finish anything, but likes to code.

**Use existing tools if:**

* You are trying to make money with game and time is your worst enemy.\*
* Your skills are not even remotely there, what others has done and you really need to have it working as nicely. ( Physics libraries, particle engines etc )
* You don't really like coding, but still are interested in game making

So, these "guidelines" came from my head and might not make any sense to you, but it's something to think about.

* If you are creating games as day job, ie, you need to make money out of time invested in the game. Then, you just can't develop everything by your self. This means that instead of coding your 3D engine, you have to adapt and use something others has done. UDK, Source and Unity3D offer great variety and great power for 3D games. It's hard to compete against those with your own engine, while making money out of game.

And its not just engines, its network libraries, physics and all that. Libraries that might have been tested and used for many years already. If you are limited with time, then you can't start everything from scratch
> 4 votes

---
Tags: software-engineering, tools
---


# Question
Title: Move a player in the opposite direction they are looking
I'm looking to move the player in the opposite direction they are facing with a specified force. Rather than try to explain that better I created an image showing what I mean,

I've tried reversing the cameras values but I couldn't get that to work, any ideas? Or was revering the values the correct way to go about it? If so how would I properly do that in Unity using C# (Assuming the Main camera is my player)?

**EDIT**: For replacing the camera values I can't find the old code, but I remember multiplying the camera rotation values by -1 and using that with a speed vector.

# Answer
> 0 votes
You are doing some odd things.

A quaternion's role is not to specify a direction directly, but to encapsulate a rotation transformation. The math you've shown is tantamount to "apply the same rotations about the opposite axis". Though correct, it causes extra complexity and obfuscation. Vectors are simple and easy to intuit; quaternions are an application of 4-dimensional math in order to simplify rotation transformations, but they're indecipherable as values.

You multiply that quaternion by a `speed` variable, which means it must be type `Vector3` (using this overloaded operator). In physics, speed is generally a directionless quantity rather than a vector. Velocity is the property that combines speed and direction as a vector.

If you stored directions rather than quaternions, you could inspect the values of your directions anywhere and immediately recognize the Euler components. You could add multiple directions together, as a whole or as individual axis components. You could (sometimes) rotate any of them by simple axis-angle transformations. You would only need to pull out the quaternions to accomplish a 3-axis rotation. And if your `speed` was directionless, you could apply it in any direction simply by multiplying it by a unit vector, like @sftrabbit described.

In case you decide to try to implement any of these suggestions, this is the unit direction opposite to the camera's direction (`forward` property):

```
Vector3 backward = Camera.main.transform.forward * -1;

```

# Answer
> 0 votes
Okay fixed the problem - I was incorrectly getting the reverse before. This is the new code using the advice from @sftrabbit.

```
    Quaternion test = new Quaternion(-transform.rotation.x, -transform.rotation.y, -transform.rotation.z, transform.rotation.w);
    speed = test * speed;

```

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


# Question
Title: Will lots of haptic feedback kill motors?
My game centers around joystick oddities, sort of, to make it more interesting.

I've got a cheap $6 joystick that is like a usb PS3 controller. Surprisingly, I find it of great quality, with excellent feedback.

I don't care about it so much, because of the price but I don't want to kill motors in a users expensive joystick.

Basically, it will be running for minutes at a time every once in a while.(Well, not constantly, but almost constantly)

Are these motors really good, and hard to wear down or will I quickly kill them?

Thanks for your time.

# Answer
> 8 votes
**Yes.** Eventually. But it's not something you likely need to worry about.

If the motors are brushless motors, they'll last as long as the ball bearings. A very long time (usually). However, if they're the more common brush type motors, they'll be shorter lived (but still a long time!) and get less powerful the more they're used. The quality of the motors is likely to vary greatly. They can work from hundreds of hours of continuous use, to thousands. The motors will most likely last longer than the game will be played (nothing against your game).

You should use the feedback motors as much as you need them to make the game play the way you want it to. Make sure you're not over using them! You can always give the player the option of disabling the feedback, or reducing it. The responsibility of maintaining the hardware is always the user's, give them some choices. If they don't have the choice to disable the feedback, their only option to "save" their controller is to not play your game.

# Answer
> 1 votes
I would say no. That's because they are MEANT to be used. For example, what's the point of flying a combat flight sim with a haptic controller if it's not basically constantly doing things to give you feedback? It would be rather pointless if it just twitched every few minutes.

---
Tags: joystick, force-feedback
---


# Question
Title: Tiled based pathfinding in a 1- or 2-dimensional array
As far as I know all tile based map editors export a JSON object containing one dimensional arrays. While most pathfinding libraries/tutorials are only provided for two dimensional arrays.

Also if for example I would like to do pathfinding in this one dimensional array and this array is huge i'm geussing this would cause performance issues.

So why is it that most tile based map editors output a one dimensional and how should I handle those regarding pathfinding?

example tile editor:

http://elias-schuett.de/git/Online-Tile-Map-Editor/#

Just google pathfinding to find all the two dimensional patfhfinding tutorials

# Answer
Well, that's a mildly silly way to represent a map.

In order to use path-finding and such on those maps - or to use them for most anything, really - you need a method for addressing the contents using your 2D coordinates. Assuming you know the dimensions of the map (25x19 in the example you linked) you can translate between the \[x,y\] coordinates and 1D array index fairly simply:

```
index = y * 25 + x;

```

Or in reverse:

```
int x = index % 25;
int y = index / 25;

```

And once you can do that, you're off and running. Scan the foreground layer's array for blocking (or non-blocking, depending on your path-finding algorithm) items, converting the resulting list of indices to a list of \[x,y\] nodes

Depending on your path-finding algorithm you can either generate a list of unblocked or block nodes by scanning the 1D array, then converting indices to \[x,y\] coordinates.
> 2 votes

---
Tags: path-finding, tilemap
---


title: iOS with cocos2d to MVC or not to MVC?

text:
# Question
Title: iOS with cocos2d to MVC or not to MVC?
I am working with cocos2d.

All my objects are declared on the `CCLayer` that I'm using, I have the logic of the game there and all the `CCSprites`.

Should I put the `CCSprite` for the player and all it's related properties (HP, Velocity, etc) in a Player object and then have that player object in my `CCLayer`?

But then how to add the `CCSprite` of the player to the `CCLayer`? Should I put in the `CCLayer` this?:

```
[self addChild:[PlayerObject playerSprite]];

```

Or should I create a controller?

# Answer
I think it's a matter of preference. Depending on the type of game, the MVC architecture might be a good fit, sometimes/mostly it will feel out of place though. I have used it for puzzle games before (eg. your board is the model, the controller handles user input and makes the changes on the board and a view that renders these changes).

Another architecture that works well for game development is the component pattern. Your approach even goes into that direction, because you have a `Player` object and add a `Sprite` component added to it. Depending on the scale of your game and flexibility you need, you might even want to go further and have a basic `Entity` class and components that define the entities look/behavior etc. And when you make this data-driven, then the real fun starts :)

Generally, I'd try to separate your game-logic as much as possible from your drawing API (in this case cocos2d). If you wanted to port your game to another platform/engine, then you'll have to separate all your code from the engine API anyway.

So instead of having a `CCLayer` that instantiates your player, rather have some sort of `Controller` that creates the `CCLayer` and your entities and adds them to the layer.
> 1 votes

---
Tags: ios, cocos2d-iphone, design-patterns
---


# Question
Title: storing procedurally generated roguelike world into zones
I am currently developing a 3D roguelike game which will take place in a very large world. The world is generated by procedural algorithm supplied by external script in run time. To speed up rendering and minimalize memory requirenments I am dividing world into zones. A zone is a 2D rectangle of maximum size 1024 x 1024 (doesn't need to be a square), that holds dynamically allocated (via single `new`) array of `Tile`'s. `Tile` is defined to be as small as possible, to minimalize use of memory. Only the zones visible to screen or in immediately neighbor are in memory, rest are loaded from harddisc file on the need to basis.

The problem I have is that map generator does not need to know about logical zone layout, so it can generate this kind of map (especially for higher Z-levels, like lofts in city):

This would be waaaay too much memory waste to enclose it in 1024 x 1024 so, it's better to put it into smaller chuncks like this:

So, finally the question: how can I convert data supplied by world generator script into actual world structure in memory?

What I've thought about so far:

1. Script has a method `SetTile(x, y, tileType)`, and the world is automatically recalculated every let's say 100 cells, so the zones are put as efficiency as possible. This will require LOTS of zone copying, moving, resizing, etc. - that's a really slow operation, but it will keep world layout in logical order, so for example it would be easier to implement methods like `GetTile(x, y)` in the script
2. Script has a method `SetTile(x, y, tileType)` which temporary just store a Tile into std::vector and after everything is done, the world runs a second pass that's calculates zones. This is way faster, but has a drawback - since Tile are set in no particular order, it's really hard to have `GetTile(x, y)` method in the script. Perhaps there is a solution for that drawback, I am just not having any idea of - `std::map` is way too slow to be used here.
3. If it cannot be done off screen, maybe the solution would be to expose zones into script and being created explicitly (I mean put into script API `CreateZone()` function and similar) - I don't want this, because scripts will be exposed to end users and I want to make them as robust as possible.
4. Perhaps there is other solution? Maybe I can organize world generation in some other way (I still need scripts, but it may be a script that generates only part of the world and then connect)?

Additional things I just came up: the entire world can be too large to be put in the memory at once. So it twist the problem even further - I have to break world generation part (in script) into stages. Any suggestions?

As for technology: I am using C++ 03' without Boost and AngelScript as scripting language

# Answer
The way that Dwarf Fortress and many other similar 3D roguelikes handle huge world maps is to break the map into chunks. Typically these are vertical slices of world map that are easy to stream in-out on the fly. Which is how Minecraft and Dwarf Fortress in Adventure Mode work.

In Fortress Mode, Dwarf Fortress allows you to select a block of chunks to play in. More chunks means slower play.

This generally solves the overall performance issues and trouble with loading an entire map at once, even for smaller maps. I would hold off on complex solutions until you actually have a problem. However, here are some options. It seems from your examples that you are going for an urban game. If that means skyscrapers that soar to hundreds of floors or more, that certainly could begin to cause performance issues, especially if those floors spread across multiple Z levels with maintenance spaces between floors like many tall buildings have.

In this case, there is no reason at all not to break the map into chunks horizontally as well. You can discard totally empty ones from the map. Or if your game will allow construction, just leave them empty (or filled with air, or whatever your game needs.)

*Digression:* Actually, a roguelike set in massively tall buildings that models air pressure could be really awesome...
> 4 votes

# Answer
If I understand your question correctly, your main concern is storing / accessing the generated tiles. Good news: you don't have to reserve the empty space for all the tiles that are not generated yet. There are many ways of storing 'irregularly shaped' data structures.

For example, a possible solution is to build a list of pointers to the tiles you've already generated.

The list (grey box) has a dynamic size, starting at 0, and growing with each pointer (red circle) you put in it. So if you've only generated 3 tiles so far, you're going to have a list of 3 pointers. This way, you won't have to reserve the memory for millions of tiles in advance.

When searching for a specific tile, you iterate on the pointer list, and check the properties of the tile that the current pointer is pointing to. In C#, with a List representation for example, a search would look like this:

```
Tile GetTile(int x, int y)
{
   foreach (var tile in tileList)
   {
      if (tile.X == x && tile.Y == y) return tile;
   }
   return null;
}

```

There shouldn't be a scenario, where all the tiles are generated and loaded into the memory at the same time. As the player moves, just remove the pointers that you no longer need from the list (and their corresponding tiles from the memory). Make sure you have a small delay though, otherwise the memory operations could cause lags when the player's moving quickly in and out of a zone or tile.
> 3 votes

---
Tags: procedural-generation, tilemap, roguelikes, angelscript
---


# Question
Title: How can I clean up and smooth out procedurally generated terrain?
I am experimenting with procedural content generation, and starting with generating terrain from fractional brownian noise. The terrain produced looks fairly realistic, but has many artifacts and splotches of random terrain everywhere. Here are some examples:

How can I clean up the terrain so that it has smooth transitions from terrain type to terrain type without the scattered spots?

# Answer
is it the size that makes those splotches undesirable?

if so, you can process your data again and if the patch doesn't cover a certain area, replace it with something more desirable
> 2 votes

---
Tags: 2d, procedural-generation, terrain, terrain-rendering, perlin-noise
---


# Question
Title: Texture2D can't find my sprite - how to setup the content directory in XNA
So I keep getting told that `spr_lives` can't be found. I'm working out of a book and using the samples given to me (have not changed the code or folder structure, so it /should/ work) but nothing's working unfortunately. I know it's a directory issue but I'm unclear on how to remedy it.

Picture of both code and folder structure:

# Answer
You have to ensure that the images in your content project has this properties:

You have to check if your Xna game project have a reference to your content project:

You can check your /bin/debug/Content folder, to see if the xnb files are there:
> 2 votes

---
Tags: c#, xna-4.0
---


# Question
Title: 3D BSP rendering for maps made in 2d platform style
I wish to render a 3D map which is always seen from top, camera is in sky and always looking at earth. Sample of a floor layout:

I don't think I need complex structures like BSP trees to render them. I mean I can divide the map in grids and render them like done in 2D platform games. I just want to know if this is a good idea and what may go wrong if I don't choose a BSP tree rendering here. Please also mention is any better known rendering techniques are available for such situations.

# Answer
From your sample image, it looks like the projection you're using is orthographic. If that's the case you can pre-render the whole map to an image/set of images( depending on your resolution) . Then in your game you can just crop to the portion of the image that would be visible from the camera and paint the image in the background.

Of course, this will only work if the characters in the scene are always painted on top of your floor plan.
> 1 votes

---
Tags: rendering, maps, platformer, binary-space-partitioning
---


# Question
Title: Can I use p/invoke in libraries loaded as assets in Unity Free?
I am interested in using utilising third-party libraries in Unity Free.

I know Unity can use managed libraries as assets, but only the Pro version supports using native libraries (`DllImport` within scripts). This thread, however suggests that it is possible to import DLLs in the free version.

I would like to utilise native libraries (as a hobbyist I cannot afford the Pro version), but want to do it the supported way so I don't have to worry about Unity 'fixing' this hole if that is what it is.

Is there any supported way to use native libraries with Unity free (in other words, is the method described in that thread using `DllImport` safe and reliable, or is it a workaround that might be patched away)?

# Answer
> 2 votes
You can use `DllImport` in compiled managed DLLs which are referenced in your C# code.

However you will not be able to use your resulting product on any system other than windows.

For additional information see this thread.

---
Tags: unity
---


# Question
Title: Can I use Playstation controller button icons in my game?
I'm currently working on a game that will be released on PC with controller support, and I'm trying to find a way on how to best represent controller icons within the game.

I'm assuming I can't simply use Playstation or Xbox controller icons in my game without having some form of license first (right?).

So how would it be best to convey something like 'Press X to interact' in a PC game for controllers?

# Answer
While the letter X is not copy protected, the specific cross used on the controller, along with the other shapes: , are trademarked. Using your own art to represent the buttons (as in your example image), should be OK under fair use, specifically nominative fair use. Where the qualifications for nominative fair use are one of the following situations:

> * The product or service cannot be readily identified without using the trademark (e.g. trademark is descriptive of a person, place, or product attribute).
> * The user only uses as much of the mark as is necessary for the identification (e.g. the words but not the font or symbol).
> * The user does nothing to suggest sponsorship or endorsement by the trademark holder. This applies even if the nominative use is commercial, and the same test applies for metatags.

In this case, you're not trying to use the symbols as your own, but instead are directly referring to Sony's trademarked buttons, which likely falls under the first category.

If you're unsure, talk to a lawyer. If you're taking advice from someone on the internet, talk to a lawyer.
> 11 votes

---
Tags: legal, licensing, controllers
---


title: Can I change vertex buffer's size?

text:
# Question
Title: Can I change vertex buffer's size?
Maybe it's a stupid question but I actually don't know - is it possible to change vertex buffer's size after it's been already created (with `CreateBuffer()`)? If so, how do I update its data (with both `Map()` and `UpdateSubresource()`) when the new data contains more/less vertices?

I'm interested in vertex buffers and dx11 but the question probably applies also to index buffers and opengl.

# Answer
No, at least in D3D11 it is not possible to change the size of a buffer or texture after it's been allocated. You would have to release the old buffer and create a new one (which is inadvisable to do often, as it can hurt performance).

It's okay to only use part of a vertex buffer, so if you know the maximum size your data will be, I'd allocate the buffer to that size; then you can just write to and draw from as much of it as you need in a given frame.
> 9 votes

---
Tags: c++, directx11, vertex-buffer
---


# Question
Title: How can I implement a simple "jump" action with three.js and/or Physijs?
Assume I have a simple Physijs object like this car. How can I adapt something like this to "jump" (hydraulics ftw!) when pressing spacebar for instance?

I'm currently thinking `applyCentralImpulse` should come into play.

# Answer
Well, the documentation is apparently non-existent at this point, but searching the source yields the following:

```
applyCentralImpulse = function ( force )

```

So, create a vector pointing up, `upVector.set( 0, jumpFactor, 0 );`, then use `applyCentralImpulse` to the vehicle to make it jump.

Alternatively, you can use `applyImpulse ( force, offset )` and supply an offset to position the force under the front wheels, thereby giving your hydraulics "the win".
> 3 votes

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


# Question
Title: What are some ideal algorithms for Rogue-like 2D dungeon generation?
What are some good resources regarding procedural content generation in the context of dungeon generation?

Closest article I could find was Algorithm for generating a 2d maze, which isn't quite what I'm looking for. Features, such as rooms and connected hallways, are ideal.

Thanks!

# Answer
> 30 votes
This has been more or less answered before. Your first stop place should be http://pcg.wikidot.com/
Since I was informed of this not being a helpful answer at all, this page on the wiki deals with Dungeon generators specifically and links to various articles on the subject.
http://pcg.wikidot.com/pcg-algorithm:dungeon-generation
I'd still recommend browsing the whole wiki though, as procedural content generation is just a very creative approach and any and all ideas are valid. It's a lateral thinking challenge - and a fun one at that.

# Answer
> 23 votes
I managed to get reasonably good looking levels by using the following algorithm, based on a square grid:

First, create a set of rooms. Random parameters will define the size of rooms and their numbers. An adaptive algorithm could even define some zones that are made of large hallways, and others of very small rooms.

Then, you need to make sure that all rooms are connected to each other. For this, run a pathfinder to dig corridors (let's say, A\*) in between each pair of rooms, giving a random chosen weight to existing spaces (rooms or other corridors) compared to space not yet carved (the walls). If the difference in weight is small, then digging new corridors will be reasonably cheap, and the algorithm will make many corridors in between rooms, with many possibilities to go from a place to another. If the difference in weight is high, then the algorithm will prefer going through existing rooms and corridors, making the paths more tortuous, and with fewer choices to reach a certain destination.

This allows you, from a small number of parameters, to create very different looking levels, from sparse massive halls with small corridors linking them to a hive looking maze of closely interconnected chambers.

Here is an example of a generated level.

Based on this algorithm, you could add wall decoration that depends on the zone, make corridors smaller or larger, make special rooms, and so on.

# Answer
> 12 votes
If you like reading code and can parse C#, may I suggest the dungeon generator my roguelike Amaranth uses? It's here. It handles connected rooms, extensible features, and some other nice stuff.

If you pull down and build the whole project, there's a standalone tool that will generate and draw the dungeons so you can tweak it and see how it works.

# Answer
> 4 votes
All these are great ideas. I have taken a little bit from RogueBasin and pcg.wikidot.com, and have written my own implementation in C#.

I really liked the 'natural' look of cave-like levels that can be generated by using the cellular automata method. To understand what I mean by cellular automata method, imagine Conway's Game of Life. My code uses whats called the 4-5 method, which means a tile will become a wall if it is a wall and 4 or more of its nine neighbors are walls, or if it is not a wall and 5 or more neighbors are walls. I start by filling the map randomly with walls or space, then visit each x/y position iteratively and apply the 4-5 rule. In order to help alleviate the problem of forming isolated caves, after filling the map randomly, I blank a horizontal line across the map, setting each tile to a space instead of a wall, before applying the 4-5 rule to each tile.

You can view the code for my map handler class, and any improvements I make here

or an archived version here.

# Answer
> 2 votes
I'd think the most direct place to find this is to actually look at the source code. Two major players in the field, Angband and Nethack, are both open-source.

---
Tags: procedural-generation
---


title: Drawing 2D Images "3D-Like"

text:
# Question
Title: Drawing 2D Images "3D-Like"
So, I want to use textures for weapons in my FPS game instead of actual models. However, if I just draw the texture onto a square in the game, it has the rotation and stuff, but it looks "2D". How can I make it look like it has width?

The best example I can think of is probably Minecraft. If you hold a tool in Minecraft (such as a pickaxe), the texture is drawn and it has an "edge" that shares a color with the color of the actual pixel next to it.

That was probably really confusing, so here's a picture of what I mean: Original:

Edge highlighted:

How can I do this with XNA?

My code basically makes a square right now (four vertexpositiontexture vertices), and I use BasicEffect to attach an image to it.

# Answer
This is how I do it in my Minecraft clone: http://pastebin.com/10JH8HHF

I apologize for the lack of comments in the source, however I will try to explain here:

I will skip explanation of the Direct3D specific code - all it is doing is getting access to the texture data in memory.

1. The function is called with one of the arguments a pointer to an array of vertices. The array must be the maximum possible size to ensure no buffer overruns.
2. I loop through each texel in the texture (the 2 nested loops) and check the alpha value of each texel. If the alpha value is zero, I simply `continue;` to the next texel.
3. When a non-zero-alpha texel is found, I create the front and back faces for the "3D texel" or cube representing the texel. I set the color of the cube vertices to the color value from the texture.
4. Then I check the alpha values of the texels on each of the four sides of the texel, and if there is a zero-alpha texel, it means the texel is an edge, and therefore I create the corresponding face (i.e. left face).
5. Mesh is created, I return the number of vertices used in the 3d mesh so the caller can then create a vertex buffer of the correct size.

And we are finished! The result: (my MC clone)
> 3 votes

# Answer
Two approaches come to my mind:

1. Render bounding box of the object. The box would be an extrusion of the quad that you are currently rendering. Then implement a shader that does raymarching inside the box to look for texels. This is like volume rendering a 3D texture, but the depth of the texture is 1. This might not be efficient enough though. The positive side about this solution is that after implementing the shader you can easily use any texture.
2. As a preprocessing step calculate all edges of the texture (including interior edges). Create a mesh based on the edges. There are probably many ways to find the edges, but the following algorithm should be quite simple to implement.
    1. Start by creating two vertices in the corners between and around all texels. For `w * h` texture you would have `2*(w+1)*(h+1)` vertices.
    2. Create faces for all horizontal edges around each texel if the left side is empty and the right side is not, or vice versa. If left and right are both empty or filled, no edge is created. The normal for the face is either (-1,0,0) or (1,0,0) depending which side was empty. Do the same thing in vertical direction.
    3. To reduce the number of faces go through the faces and combine adjacent edges together where vertices are shared and the normals are pointing to same direction. If you have the faces stored in a 2D-array the adjacent faces should be fast to locate. Alternatively you can just compare all faces against each other.
    4. Remove vertices that are not referenced by any of the remaining faces.

I would choose the second approach if the textures are static. Both of the approaches can produce the same visual style you have in the screenshots. If you want less pixelated look, smooth edges, support for semi-transparency or something like that, you might need different algorithms or improve those listed above.
> 4 votes

# Answer
Well, minecraft uses no models it draws each pixel in the image as a cube. It uses the alpha channel to get rid of the pixels, which I don't know if XNA supports it. So pretty much I recommend going through all the pixels and render ones that aren't the color that means it's not a part of the texture.
> 0 votes

# Answer
Well this involves 3D projection drawing which is generally handled by the graphics card. It's possible to do obviously in software, but it will be a lot slower and XNA isnt really designed for that. However, what I believe minecraft does is all of the models are actually converted polygons (or they begin like that) and are drawn with textures applied. That said, if you want to draw a 3D image, just map it to a quad, which sounds like what you're doing, however maybe you could post some of your images so we can see what you are having trouble with.
> -1 votes

---
Tags: xna, c#, game-design, minecraft-modding, .net
---


# Question
Title: Need opinions on my component based design
I have an Entity class and a Component class. The Entity class has a list of attached components, and each component also has a member variable that is a reference to the entity that it is attached to (cyclical design).

Then, there is the EntityManager class, which has a list of (you guessed it!) entities, and each entity also has a reference to its encapsulating entity manager.

The reason for this cyclical design is due to data reliance. To explain further, my Entity class is essentially just a giant bucket of data: any data any type of entity needs already exists on this class when it is instantiated. However, in order to make use of this data, the Entity needs the relevant components attached. For example, my Rendering component takes the Entity's spriteData member and draws it to the backbuffer. Without a rendering component, spriteData is not utilized. Since my components need to access the Entity's member variables, each component needs a reference to the Entity it is attached to.

For an example of why my entity needs a reference to the entity manager, it is because some components (such as collision) need to access other entities' data buckets in order to function (for collision, this would be checking nearby entities' position vector and comparing it to the component's referenced entity).

There is more to it than this, but I just wanted to highlight the central idea of what I was doing, and wanted opinions on whether a cyclical approach like this (with little data encapsulation as well..) is a good idea or not. Maybe I'm just overthinking it /shrug. Opinions on how to steer the design would be hugely appreciated, as well.

# Answer
> 2 votes
Entity systems do exist since years, your design decision is not new. For example take a look at the Artemis framework, or my own implementation.

To provide some feedback on your system, I wrap it the other way around. Your current approach is to have an entity class and attach properties to it.

```
class Property
{

};

class Entity
{
    std::vector<Property*> properties;
};

std::vector<Entity*> entities;

```

Instead, you could drop the entity base class, represent entities by integer ids, and group the properties of the same type together in maps.

```
std::unordered_map<int, SpriteProperty> sprites;
std::unordered_map<int, PositionProperty> positions;

```

Which sprite corresponds to which position is given by the id thus the integer key. The advantage of this design is that it leads to more data oriented code. It is much faster, to loop over all `PositionProperties` and update them (which could even be done in parallel), than to loop over all entities and each update all their different properties.

Using ids to represent entities also has the advantage that you could easily store them to disk and load them back into the system without loosing their identity.

---
Tags: architecture, component-based, entity-system, entity-component
---


# Question
Title: Why can a certain DirectX mode produce display lag?
I have written two small test games using DirectX 9. One uses

`presentParams.Windowed = false;`

`presentParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;`

and the other one uses

`presentParams.Windowed = false; // same results with true`

`presentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;`

Both use exactly the same window position, size and style. Both are written to cover the screen completely, even when using "Windowed = true".

In the latter game, to vsync and avoid tearing, my code waits until a certain scan line is passed. My tests showed: On different PCs it has to wait for different scan lines to avoid tearing completely. This is a drawback, since it has to be tweaked individually by the user. Is this technique used in any games?

And, compared to this technique, why does DirectX produce a display lag when "Windowed = false" is used with D3DPRESENT\_INTERVAL\_ONE?

---

To clarify where the lag occurs:

`Windowed = false + INTERVAL_ONE => LAG`

`Windowed = false + ...IMMEDIATE => no lag`

---

Not mentioned in the question but tested:

`Windowed = true; + INTERVAL_ONE => no lag, tearing`

`Windowed = true; + ...IMMEDIATE => no lag`

# Answer
> 0 votes
With vsync on, and the CPU running faster than the GPU D3D will buffer up to three frames worth of GPU commands.

You can prevent it from doing that by forcing a CPU\<-\>GPU sync which you can do with by issuing and waiting for queries or by adjusting video card settings ("Maximum pre-rendered frames" on Nvidia cards).

Having one frame buffered up allows the GPU to work on a different frame to the CPU, without that they can't run in parallel so performance will suffer.

Having multiple frames buffered up is what allows SLI systems to improve performance by giving one frame to each card, so you need to be careful when limiting how many can be buffered.

---
Tags: directx9, lag
---


title: Shared Texture2D in XNA

text:
# Question
Title: Shared Texture2D in XNA
I am trying to define texture2d objects as shared. The reason of why I am trying to do is, I made an xna user control and my project loads unlimited (as much as the user wants) my XNA User Control. And all of the textures are same. I don't want to load textures for everyone of them (think how much ram size it will use if I do it)

The real problem is:

```
cmMaps = New ContentManager(Services, "Maps")

```

As you see, ContentManager news ServiceProvider for initialization. When I look at the codes where Services variant modified, I see this lines:

```
GraphicsDeviceService = GraphicsDeviceService.AddRef(Handle, ClientSize.Width, ClientSize.Height)
m_services.AddService(Of IGraphicsDeviceService)(GraphicsDeviceService)

```

Why I can't define global Texture2D objects. Why is it specific for the window or control that the XNA tries to draw on?

Is it possible to define em as shared variant and able to use it in every XNA UserControl?

Note: I took UserControl source codes from this page: http://xbox.create.msdn.com/en-US/education/catalog/sample/winforms\_series\_1

# Answer
The `ContentManager` class has built in functionality to only load one instant of the texture2d to the GPU memory. After the first

```
Texture2d myTexture = myContentManager.Load<Texture2d>(myFileName);

```

any other loading of `myFileName` through `myContentManager` will be a reference to the first, not a separate instance of the texture data.

so as long as all the different userControls are passed a reference to the same Services container... and that Services container is storing a ContentManager reference... and you use that ContentManager to load all your textures in any or all your userControls, then they will all share the same GPU instance of your texture.
> 0 votes

---
Tags: xna, xna-4.0
---


# Question
Title: How to use C++11 chrono header for a clock
In first, sorry for my bad english. :) I'm making a game using SFML and C++11 new features, but I've got a problem with my custom Clock class (made to replace the SFML one). When I get the elapsed time since the clock instanciation, it returns it in microseconds. But I'd want it to return nanoseconds, I don't understand what happens. My question is, why do I get microseconds instead of nanoseconds ? Here is my main :

```
#include "clock.h"
#include <SFML/Window.hpp>
#include <iostream>

int main() {
    sf::Window window(sf::VideoMode(800,600), "title");
    sf::Event event;
    window.setFramerateLimit(60);
    Clock<std::chrono::nanoseconds> clock;

    while(window.isOpen()) {
        while(window.pollEvent(event)) {
            if(event.type == sf::Event::Closed) window.close();
        }

        std::cout << clock.Restart().count() << std::endl;
        /* I would like it to print about 16666666 (ns), but it prints about 16666 (μs) */

        window.display();
    }

    return 0;
}

```

And there is my Clock.h file :

```
#ifndef CLOCK_H
#define CLOCK_H

#include <chrono>

template < typename Period >
class Clock {
public:
                                                                    Clock();
    Period                                                          GetElapsedTime() const;
    Period                                                          Restart();

private:
    std::chrono::time_point< std::chrono::high_resolution_clock >   mTimePoint;
};

template < typename Period >
Clock< Period >::Clock()
    : mTimePoint( std::chrono::high_resolution_clock::now() ) {
}

template < typename Period >
Period Clock< Period >::GetElapsedTime() const {
    const Period elapsedTime( std::chrono::high_resolution_clock::now() - mTimePoint );
    // Here, elapsedTime.count() equals ~16666 too, but I want nanoseconds, so why ?!
    return elapsedTime;
}

template < typename Period >
Period Clock< Period >::Restart() {
    const Period period( GetElapsedTime() );
    mTimePoint = std::chrono::high_resolution_clock::now();
    return period;
}

#endif // CLOCK_H

```

# Answer
First, your code should display time in nanoseconds as you asked. If you want more help on what is displayed, show us the output.

Second:

> My question is, why do I get microseconds instead of nanoseconds ?

If you are on Windows, using Visual Studio 2012 or 2013, there is a bug in the chrono standard library implementation that makes the high resolution clock having around 8 milliseconds resolution instead of something closer to micro or nanoseconds.

> Thanks for reporting this bug. I wanted to let you know what's happening with it. I'm still keeping track of it, but it's been resolved as "Deferred" because we may not have time to fix it in VC12. (Note: VC8 = VS 2005, VC9 = VS 2008, VC10 = VS 2010, VC11 = VS 2012.)

Source: https://connect.microsoft.com/VisualStudio/feedback/details/719443/#

At the moment, if you want to keep using a cross-platform stl-like library usage, do like me, use Boost.Chrono instead. It works as expected and have a good granularity on Windows and other platforms. Using it, maybe with typedefs or 'using' instructions, makes you use the same interface as chrono but you can still switch to the standard library once you get the fixed implementation. (or use a different C++ implementation)

One important thing to note though: standard library threading facilities for waiting (std::sleep\_for/until, std::condition\_variable and std::mutex members) are dependant on std::chrono. This means that if you want to use them you will have the same time precision problem using Visual Studio 2012/13 when using these synchronization tools. It might not be a problem for a lot of application, except most games, because slow downs dues to longer waits can easily be perceptible by the player.

So if you decide to use standard threading facilities, and want high precision, use Boost.Thread and Boost.Chrono together. Boost.Chrono can't be used with the standard thread library, so you either have to live with the precision bug or use Boost.Chrono and Boost.Thread together.

I'm sure it will be fixed in coming patches but don't expect such a fix before the beginning of 2014 (or the very end of 2013 but I don't count no it).
> 3 votes

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


# Question
Title: How to render models using a personalized projection matrix?
I'm creating a game with a great sprite demand. Out team is considering automatizing the sprite generation using 3D models. The problem is we have a very particular ortographic projection:

We have already set up a good projection matrix. The problem is none of the 3D renderer of nowadays have an option for using custom matrixes.

How is this kind of problem dealt with?

# Answer
You can use Blender for that. But it has nothing to do with matrixes, the only thing you need to set up is the ortographic camera.

See this blog post for a generic approach in making graphics from 3d models. You will need the same approach except for a custom camera with orthographic view.
> 1 votes

---
Tags: opengl, 2d, 3d, graphics, animation
---