# Question
Title: What data-type should I use for in-game currency?
In a simple business simulation game (built in Java + Slick2D), should a player's current amount of money be stored as a `float` or an `int`, or something else?

In my use-case, most transactions will use cents ($0.50, $1.20, etc.), and simple interest rate calculations will be involved.

I've seen people saying you should never use `float` for currency, as well as people saying you should never use `int` for currency. I feel like I should use `int` and round any necessary percentage calculations. What should I use?

# Answer
> 90 votes
You can use `int`, and consider everything in cents. $1.20 is just 120 cents. At display, you put the decimal in where it belongs.

Interest calculations would just be either truncated or rounded up. So

```
newAmt = round( 120 cents * 1.04 ) = round( 124.8 ) = 125 cents

```

This way you don't have messy decimals always sticking around. You could get rich by adding the unaccounted for money (due to round-downs) into your own bank account

# Answer
> 66 votes
Okay, I'll jump in.

## My advice: it's a game. Take it easy and use `double`.

Here is my rationale:

* `float` does have a precision issue that appears when adding units to millions, so though it might be benign, I would avoid that type. `double` only starts getting problems around the quintillons (a billion billions).
* Since you are going to have interest rates, you will need theoretical infinite precision anyway: with 4% interest rates, $100 will become $104, then $108.16, then $112.4864, etc. This makes `int` and `long` useless because you don't know where to stop with the decimals.
* `BigDecimal` will give you arbitrary precision but will become painfully slow, unless you clamp the precision at some time. What are the rounding rules? How do you choose where to stop? Is it worth having more precision bits than `double`? I believe not.

The reason fixed point arithmetic is used in financial applications is because they are deterministic. The rounding rules are perfectly defined, sometimes by the law, and must be strictly applied, **but rounding still happens** at some point. Any argument in favour of a given type based on precision is likely bogus. All types have precision issues with the kind of computations you are going to do.

## Practical examples

I see quite a few comments claiming things about rounding or precision that I disagree with. Here are a few additional examples to illustrate what I mean.

**Storing**: if your base unit is the cent, you'll probably want to round to the nearest cent when storing values:

```
void SetValue(double v) { m_value = round(v * 100.0) / 100.0; }

```

You will get absolutely no rounding problems when adopting this method that you wouldn't also have with an integer type.

**Retrieving**: all computations can be done directly on the double values, with no conversions:

```
double value = data.GetValue();
value = value / 3.0 * 12.0;
[...]
data.SetValue(value);

```

Note that the above code does not work if you replace `double` with `int64_t`: there will be an implicit conversion to `double`, then *truncation* to `int64_t`, with a possible loss of information.data.GetValue()

**Comparing**: comparisons are the one thing to get right with floating-point types. I suggest using a comparison method such as this one:

```
/* Are values equal to a tenth of a cent? */
bool AreCurrencyValuesEqual(double a, double b) { return abs(a - b) < 0.001; }

```

## Rounding fairness

Suppose you have $9.99 in the account with 4% interest. How much should the player earn?With integer rounding you get $0.03; with floating-point rounding you get $0.04. I believe the latter is more fair.

# Answer
> 21 votes
Floating point types in Java (`float`, `double`) are not good representation for currencies because of one main reason - there is a *machine error* in rounding. Even if a simple calculation returns a whole number - like `12.0/2` (6.0), the floating point might wrongly round it (due tho the specific representation of these types in memory) as `6.0000000000001` or `5.999999999999998` or similar. This is a result of the specific machine rounding that occurs in the processor and it is unique to the computer that calculated it. Usually, it is rarely an issue to operate with these values, since the error is quite negligent, but its a pain to display that to the user.

A possible solution to this would be to use a custom implementations of floating point data type, like `BigDecimal`. It supports better calculation mechanisms which at least isolate the rounding errors not to be machine specific, but are slower in terms of performance.

If you need high productivity, you'd better stick to the simple types. In case you operate with *important financial data*, and **each cent** is important (like a Forex application, or some casino game) then I'd recommend you to use `Long` or `long`. `Long` would allow you to handle large amounts and good precision. Just assume you need, lets say, 4 digits after the decimal point, all you need is to multiply the amount by 10000. Having experience in developing on-line casino games, I've seen `Long` to be often used to represent the money in cents. In Forex applications, the precision is more important, so you'll need a greater multiplier - still, whole numbers are free of machine rounding issues (of course manual rounding like in 3/2 you should handle yourself).

An acceptable option would be to use the standard floating point types - `Float` and `Double`, if performance is more important than accuracy to hundredths of the cent. Then, on your display logic, all you need is to use a **predefined formatting**, so that the ugliness of potential machine rounding does not get to the user.

# Answer
> 17 votes
For **small scale game** and where process speed, memory is important issue (due to precision or work with math co-processor can make painfully slow), there **double** is enough.

But for **large scale games** (for example, social games) and where process speed, memory is not limited, there **BigDecimal** is better. Because here,

* int or long for monetary calculations.
* floats and doubles cannot accurately represent most base 10 real numbers.

**Resources:**

From https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency

> Because floats and doubles cannot accurately represent most base 10 real numbers.
>
> This is how an IEEE-754 floating-point number works: it dedicates a bit for the sign, a few bits to store an exponent, and the rest for the actual fraction. This leads to numbers being represented in a form similar to 1.45 * 10^4; except that instead of the base being 10, it's two.
>
> All real decimal numbers can be seen, in fact, as exact fractions of a power of ten. For instance, 10.45 really is 1045 / 10^2. And just as some fractions can't be represented exactly as a fraction of a power of ten (1 / 3 comes to mind), some of them can't be represented exactly as a fraction of a power of two, either. As a simple example, you simply cannot store 0.1 inside a floating-point variable. You'll get the nearest representable value, which is something like 0.0999999999999999996, and software will round it to 0.1 when displaying it.
>
> However, as you perform more additions, subtractions, multiplications and divisions on inexact numbers, you'll lose more and more precision as the tiny errors add up. This makes floats and doubles inadequate for dealing with money, where perfect accuracy is required.

From Bloch, J., Effective Java, 2nd ed, Item 48:

> ```
> The float and double types are particularly ill-suited for
>
> ```
>
> monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.
>
> ```
> For example, suppose you have $1.03 and you spend 42c. How much money do you have left?
>
> System.out.println(1.03 - .42);
>
> prints out 0.6100000000000001.
>
> The right way to solve this problem is to use BigDecimal,
>
> ```
>
> int or long for monetary calculations.

Also have a look at

# Answer
> 13 votes
You want to *store* your currency in `long` and *calculate* your currency in `double`, at least as a backup. You want all *transactions* to take place as `long`.

The reason you want to store your currency in `long` is that you don't want to lose any currency.

Let's suppose you use a `double`, and you have no money. Someone gives you three dimes, and then takes them back.

```
You:       0.1+0.1+0.1-0.1-0.1-0.1 = 2.7755575615628914E-17

```

Well, that's not so cool. Maybe someone with $10 wants to give their fortune away by first giving you three dimes, and then giving $9.70 to someone else.

```
Them: 10.0-0.1-0.1-0.1-9.7 = 1.7763568394002505E-15

```

And then you give them the dimes back:

```
Them: ...+0.1+0.1+0.1 = 0.3000000000000018

```

This is just broken.

Now, let's use a long, and we'll keep track of tenths of cents (so 1 = $0.001). Let's give everyone on the planet one billion, one hundred and twelve million, seventy five thousand, one hundred and forty three dollars:

```
Us: 7000000000L*1112075143000L = 1 894 569 218 048

```

Um, wait, we can give everyone over a billion dollars, and only spend a little over two? Overflow is a disaster here.

So, whenever you're calculating an amount of money to transfer, use `double` and `Math.round` it to get a `long`. Then fix up balances (add and subtract both accounts) using `long`.

Your economy won't leak, and it will scale up to a quadrillion dollars.

There are more tricky issues--for example, what do you do if you make twenty payments?\*--but this should get you started.

<sup>* You calculate what one payment is, round to `long`; then multiply by `20.0` and check that it's in range; if so, you multiply the payment by `20L` to get the amount deducted from your balance. In general, all transactions must be handled as `long`, so you really need to sum up all the individual transactions; you can multiply as a shortcut, but you need to make sure you don't add rounding errors *and* that you don't overflow, which means you need to check with `double` before doing the real calculation with `long`.</sup>

# Answer
> 8 votes
I'd go as far as to say that any value which may be displayed to the user should almost always be an integer. Money is only the most prominent example of this. Dealing 225 damage four times to a monster with 900 HP and finding that it still has 1 HP left will subtract from the experience just as much as finding that you are an invisible fraction of a penny short of affording something.

On the more technical side I think it's worth noting that one doesn't have to revert to floats to do advanced stuff like interest. As long as you have got enough headroom in your chosen integer type a multiplication and a division will stand in for a multiplication by a decimal number, for instance to add 4%, rounded down:

```
number=(number*104)/100

```

To add 4%, rounded by standard conventions:

```
number=(number*104+50)/100

```

No float point inaccuracy here, the rounding always split exactly on the `.5` mark.

### Edit, the real question:

Seeing how the debate has gone I start to think that outlining what the question is all about may be more useful than a simple `int`/`float` answer. At the core of the question it is not about data types, it's about taking control of the details of a program.

Using an integer to represent a non-integer value forces the programmer to deal with the implementation details. "What precision to use?" and "What way to round?" are questions that must be answered explicitly.

A float on the other hand does not force the programmer to worry, it already does pretty much what one would expect. But since a float is not infinite precision, some rounding will take place, and that rounding is pretty unpredictable.

What happens in one use floats and want to take control of the rounding? It turns out to be almost impossible. The only way to make a float truly predictable is to use only values that can be represented in whole `2^n`s. But that construction makes floats quite hard to use.

Thus the answer to the simple question is: If you want to take control, use integers, if not, use floats.

But the question that is being debated is just another form of the question: Do you want to take control?

# Answer
> 6 votes
Even if it's "only a game", I would use Money Pattern from Martin Fowler, backed up by a long.

Why?

Localization (L10n): Using that pattern you can easily localize your game currency. Think about the old tycoon games like "Transport Tycoon". They easily allow the player to change in-game currency (i.e From British Pound to US Dollar) to meet real world currency.

And

> The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive) (Java Tutorials)

That means you can store 9,000 times current M2 US Money Supply (~10,000 Billion Dollars). Giving you enough room to use any other world currency, probably, even those who had/has hyperinflation (If curious, see post-WWI German inflation, where 1 pound of bread was 3,000,000,000 marks)

Long is easy to persist, very fast and *should* give you enough room to do all interest calculations using only integer arithmetics, eBusiness answer gives an explanation on how to do that.

# Answer
> 2 votes
How much work do you want to put in to this? How important is accuracy? Do you care about tracking the fractional errors that occur with rounding and the imprecision of representing decimal numbers in a binary system?

Ultimately I tend toward spending a bit more time coding and implementing unit tests for "corner cases" and known problematic cases - so I would be thinking in terms of a modified BigInteger which encompasses arbitrarily large amounts and maintains the fractional bits with either a BigDecimal or a BigRational part (two BigIntegers, one for the denominator and another for the numerator) - and include code to keep the fractional part an actual fraction by (perhaps only periodically) adding any non-fractional part to the main BigInteger. Then I would internally keep track of everything in cents just to keep the fractional parts out of the GUI calculations.

Probably way to complex for a (simple) game - but good for a library published as open source! Just would need to figure out ways to keep the performance good when dealing with the fractional bits...

# Answer
> 2 votes
Certainly not float. With only 7 digits, you only have accuracy like:

12,345.67 123,456.7x

So you see, already with 10^5 dollars, you are losing track of pennies. double is usable for game purposes, not in real life because of accuracy concerns.

But long (and by this I mean 64 bit, or long long in C++) is not enough if you are going to be tracking transactions and summing them up. It's enough to maintain the net holdings of any company, but all the transactions for a year could overflow. That depends on how big your financial "world" is in the game.

# Answer
> 0 votes
Another solution I'll add here is to make a money class. The class would be something like (could even simply be a struct).

```
class Money
{
     string currencyType; //the type of currency example USD could be an enum as well
     bool isNegativeValue;
     unsigned long int wholeUnits;
     unsigned short int partialUnits;
}

```

This would allow you to represent the cents in this case as an integer and the whole dollars as an integer. Since you have a seperate flag for being negative, you can use unsigned integers for your values which doubles the possible amount (you could also write a number class that applies this idea to numbers to get REALLY big numbers). All you would need to do is overload math operators and you could use this like any old datatype. It takes up more memory, but it really expands the value limits.

This could further be expanded to include things like number of partial units per whole units so you could have currencies that subdivide on something other than 100 sub units, cents in this case, per dollar. You could have a 125 floopies make up one flooper for example.

Edit:

I'll expand the idea in that you could also have a look up table of sorts, that the money class can access that would provide an exchange rate for it's currency versus all other currencies. You could build this into your operator overloading functions. Therefore, if you automatically try to add 4 USD to 4 British pounds, it would automatically give you 6.6 pounds (as of writing).

# Answer
> 0 votes
As mentioned in one of the comments on your original question, this issue has been covered on StackExchange: https://stackoverflow.com/questions/8148684/what-is-the-best-data-type-to-use-for-money-in-java-app

Basically, floating point types should never be used to represent currencies, and like most languages Java has a more appropriate type. Oracle's own documentation on primitives suggests using BigDecimal.

# Answer
> -1 votes
**Use class** it's the best way. You can hide implementation of your money you can switch double/long what ever you want at any time.

Example

```
class Money
{
    private long count;//Store here what ever you want in what type you want i suggest long or int
    //methods constructors etc.
    public String print()
    {
        return count/100.F; //convert this to string
    }
}

```

In your code use simply getter it is better way i think and you can store more useful methods.

---
Tags: java, data, economy
---


# Question
Title: Gamma Space and Linear Space with Shader
I am using Unity and I can choose between two color space mode in the settings: Gamma or Linear Space.

I am trying to build a Custom Lighting Surface shader but I am facing some problems with those Color Space. Because the render is not the same depending of the Color Space.

If I render the lightDir, Normal or viewDir I can see that they are different depending of the Color Space I use.

I made some test and the result I have in Linear Space is great but how can I obtain the same result in Gamma Space ? Are there some transformations ? On what component should I apply those transformations ?

Thank you very much !

# Answer
> 4 votes
First of all, you don't do your render in gamma space to get the same results as in linear, but to have "gamma correct" final image. The topic is a bit complicated, so see the link in the end of the answer if you want to learn about it in-depth. The process of applying gamma correction to your scene follows: (I've seen this in a presentation from a graphics programmer at Naugty Dog, the creators of Uncharted.)
You have to sample your diffuse color in shader (be it texture or material color), then take the `float4 color = pow(diffuse,2.2f); //2.2f is the default gamma value` of it then apply your lighting calculations. After all your lighting is calculated and applied to the color, you have to take the power of the inverse of your gamma eg. 1.0f/2.2f for your final color.
So in the end you have the following process (taken from the presentation):

* Account for gamma when reading textures: `color = pow( tex2D( Sampler, Uv ), 2.2 )`
* Do your lighting calculations
* Account for gamma on color output: `finalcolor = pow( color, 1/2.2 )`

For full explanations, please see this presentation

---
Tags: opengl, shaders, directx, glsl, hlsl
---


title: Game Database-Server Specifications

text:
# Question
Title: Game Database-Server Specifications
Our team is going to publish game in social networks. Expected DAU is about 100k, which is about 500 concurrent connections and 100-400 transactions\sec. Our main risk is the game-database server(Windows Server 2008 using MySQL) because it would handle most of the load. As player enters game server SELECTs his gamestate and caches it in memory. After it most queries will be simple UPDATEs. No complex queries are planned.

So we've stumbled upon game-database configuration questions:

1) Is CPU much important for game-database server? Would 1 Intel Xeon E3-1230(or 1270) be enough for us?

2) Is RAM much important for game-database server? Would 24-32gb DDR3 RAM be enough for us?

3) Is SSD much better than HD in terms of game-database server?

# Answer
> 1 votes
It depends on how you use your database. When you have a lot of complex queries, you will need a lot of CPU power. More simpler queries are usually IO-bound, which means faster hard drives would be a better investment. More RAM usually means better caching, which means that consecutive identical queries can be answered faster. But there are also some types of queries which benefit from more RAM.

The only way to reliably find your bottleneck is through benchmarking. Create a bunch of scripts which simulate normal game operation and let a few dozen instances of them run on your test database. While you do this, monitor CPU, RAM and IO usage of your database. That should tell you where your bottleneck is and allow you to extrapolate your requirements for the production-server.

---
Tags: server, configuration
---


title: Scaling/Rotating triangle

text:
# Question
Title: Scaling/Rotating triangle
I have a Triangle class and a list of triangles representing my 3D model shape.

When I update the position, the rotation or the scale of my model, I also want my triangles list to be updated.

I already made the function to update triangle position, but I can't make it for rotation/scale...

```
private void UpdateModelTrianglesPos(Vector3 oldPos, Vector3 newPos)
{
    Vector3 diff = newPos - oldPos;
    for (int i = 0; i < _trianglesPositions.Count; i++)
        _trianglesPositions[i].UpdatePosition(diff);
}

```

Thank you for your help!

# Answer
> 0 votes
This is a bad way to go about it. Every time you want to move your model AT ALL you have to change every triangle.

You should have one transform per mesh. I assume you have a model class, so what you'll want to do is give each model class either 3 vectors for scale, rotation, and translation or a single matrix. When you want to move the model you simply have to change the vectors or matrix accordingly.

Now, right before you draw you should upload your transform to your vertex shader. Now you can use it as needed uniformly across all your vertices.

This is a pretty standard way of dealing with this. A vertex should only describe it's local coordinates. That is, its position relative to other vertices in the model. You then construct your model matrix per model object, and your view matrix per viewport.

Your scene should follow this structure:

```
Per Vertex               Per Model               Per Viewport    Everything is now pixels
local coordindates -> model coordinates -> model view coordinates -> screen coordinates.

```

Hope this helps. Just read up on your 3D theory and you'll get it in no time!

---
Tags: xna, c#, matrix
---


# Question
Title: How to change transform.position.x after a state is changed?
When I press attack button, player will change to Normal Attack state to perform Normal Attack animation and you will notice the player seem like step back a little bit as the width of sprite for Normal Attack animation is longer than Idle animation.

http://youtu.be/hnPXt-kprqQ

To solve this issue. I need to change the `transform.position.x =+ 0.5` to move a bit further to match the position of Idle animation stands and `transform.position.x =- 0.5` when Normal Attack state done its animation and back to Idle state.

How can I perform `transform.position.x =- 0.5` when when Normal Attack state done its animation and back to Idle state?

# Answer
> 1 votes
Unity won't allow you change a transforms components individually. You can create a new transform and initialize it accordingly, then assign it to game object.

```
Vector3 pos = transform.position;
Vector3 tmp(pos.x+0.5, pos.y, pos.z);
transform.position = tmp;

```

# Answer
> 1 votes
Simpler yet is to use the built in `Translate` method. It allows for more complex movement, like moving relative to the camera or local space and is pretty simple to use:

```
transform.Translate(0.5, 0, 0, Space.World);

```

or

```
transform.Translate(-0.5, 0, 0, Space.World);

```

---
Tags: unity, unityscript
---


# Question
Title: How can I capture key events on the Mac when using OpenGL?
I have code that renders a triangle using OpenGL. I would like to control it using the arrow keys on the keyboard.

Anyone know how I would do this on OS X? I think I can create an Objective-C file and import NSEvent, however, I was looking to try this without the need for Objective-C. I would also like to avoid SDL.

# Answer
> 1 votes
Unless you use a third-party library (like SDL, which you've stated a desire to avoid...), the sane way to do this is via Objective-C, through your `NSOpenGLView` or some custom subclass of `NSView` (if you want to do more advanced management of your OpenGL context manually).

Both of those classes subclass `NSResponder`, which allows you to respond to mouse and key events by implementing the appropriate selector (such as `keyDown:` or `keyUp:`) in your view subclass. Make sure you also implement `acceptsFirstResponder` to allow your view to become a responder and get the key events in the first place:

```
- (BOOL)acceptsFirstResponder {
  return YES;
}

- (void)keyDown:(NSEvent *)event{
  unichar character = [[event charactersIgnoringModifiers]:characterAtIndex:0];
  // ...process 'character' here...
}

```

If you *are* using a third-party library to do you window management and view creation, that library should provide you a mechanism to deal with key events. If it doesn't, look and see if it offers a way to provide a custom `NSView`, and if it doesn't do *either* of those things, you should find a better library. SFML is a popular alternative.

---
Tags: c
---


# Question
Title: Why do I see this "ghosting" effect with my sprite in SDL?
I'm using SDL to create a 2D side-scrolling platformer, but I'm getting ghosting from the sprite. I'm not used to programming with graphics or SDL so excuse any stupid remarks I make.

Here's the issue:

The tutorial I'm following: http://gamedevgeek.com/tutorials/moving-sprites-with-sdl/

```
int main(int argc, char* argv[])
{
    SDL_Surface *screen, *temp, *sprite;
    int colorkey;

    SDL_Init(SDL_INIT_VIDEO); //Initialize SDL

    SDL_WM_SetCaption(WINDOW_TITLE, 0); //Window title

    screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0); //Create window frame

    SDL_EnableKeyRepeat(70, 70); //Keyboard Repeat

    temp   = SDL_LoadBMP("sprite.bmp"); //Load the actual sprite
    sprite = SDL_DisplayFormat(temp);
    SDL_FreeSurface(temp);

    /* setup sprite colorkey and turn on RLE */
    colorkey = SDL_MapRGB(screen->format, 160, 136, 128); //Make this RGB color transparent, so sprite isn't surrounded by a colored box
    SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey);

    spriteRect.x = 150; //Initial X Position
    spriteRect.y = 150; //Initial Y Position

    /* set animation frame */
    srcRect.x = 0;
    srcRect.y = 0;
    srcRect.w = SPRITE_SIZE;
    srcRect.h = SPRITE_SIZE;

    gameover = 0;

    /* message pump */
    while (!gameover)
    {
        SDL_Event event;

        /* look for an event */
        if (SDL_PollEvent(&event)) {
            HandleEvent(event);
        }

        /* collide with edges of screen */
        if (spriteRect.x <= 0)
            spriteRect.x = 0;
        if (spriteRect.x >= WINDOW_WIDTH - SPRITE_SIZE)
            spriteRect.x = WINDOW_WIDTH - SPRITE_SIZE;

        if (spriteRect.y <= 0)
            spriteRect.y = 0;
        if (spriteRect.y >= WINDOW_HEIGHT - SPRITE_SIZE)
            spriteRect.y = WINDOW_HEIGHT - SPRITE_SIZE;

        SDL_BlitSurface(sprite, &srcRect, screen, &spriteRect);
        SDL_UpdateRect(screen, 0, 0, 0, 0);
    }

    /* clean up */
    SDL_FreeSurface(sprite);
    SDL_Quit();

    return 0;
}

```

# Answer
> 2 votes
This sort of "smearing" effect is generally the result of not re-painting the entire screen between frames, so every subsequent frame contains the previous frame plus what you just drew on top of it. In your case you're only repeatedly blitting your sprite to the render surface, so you get multiple copies of the sprite.

You could clear the entire background with a function like `SDL_FillRect` or, as your game progresses in complexity, add a background image (perhaps via `SDL_BlitSurface`) fills the whole screen and paint that first at the top of the frame. In the Old Days we would use dirty rectangles to optimize this process and only redraw what has changed, but these days the power of modern GPUs makes that largely unnecessary for most computers, and we can just repaint everything from a blank slate every frame.

---
Tags: 2d, sdl, platformer, side-scroller
---


# Question
Title: How can I animate the stretching of a sprite over time?
My goal is to find the function to stretch a sprite like my example below, and then get it to animate during a certain time. It is like an interpolation, where the starting point is the original image, and the final point is the stretched image. Any idea?

Here is an example, hope it is clear.

# Answer
The `SpriteBatch` class's `Draw` method has an overload that allows you to specify a scale factor. Thus, to render a sprite in a stretched frame, do something like:

```
// Scale the sprite 50% along X (like in your example).
var scale = new Vector2(0.5f, 1.0f);

// Draw the sprite with that scale.
spriteBatch.Draw(
  texture,
  position,
  null,
  Color.White,
  0.0f,
  Vector2.Zero,
  scale,
  SpriteEffects.None,
  0
);

```

To achieve an animation of this effect, store your scale factor somewhere (a member in your `Game` class would be simple to start with), and update it over time in your game's `Update` method. The `Update` method gives you a `GameTime` object containing the elapsed time since the last update. Every update, adjust your scaling factor by the amount you want to scale per second using the `TotalSeconds` member of the elapsed time span object.
> 1 votes

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


# Question
Title: Can I use a list sorted by Morton Code for broad phase collision detection?
Until now I used a list of objects sorted by a single axis for limiting the amount of objects that collisions are checked against.

The idea is simple: if the x coordinate of two objects differs by more than their width it is plain impossible that they collide. So if I want to know all possible objects inside a specific rectangle I just need to check those that are inside the indices of the smallest possible and the biggest possible x value.

Now recently I have learned about Morton Code as a way of reducing multiple axes into a single value that preserves locality. However the implications for it aren't 100% clear to me.

**Can I determine something like "all objects with a morton code smaller than *varA* or bigger than *varB* can't possibly be inside rectangle A"? If so how do I determine these values?**

# Answer
> 2 votes
## Overview

The morton encoding technique, or z-order curve, essentially generates a grid index for a given coordinate if the grid is stored in a 1 dimensional array in z-order. This can therefore be used as a spatial hashing technique that can generate something similar to an octree/quadtree within a single dimensional array.

So, for a given arbitrary collision shape, if you can determine the set of morton codes that shape encompasses, then you can index the grid with these codes to see if there is any other geometry stored there, just like with an oct/quad tree.

As with other spatial partitioning, finding a hit at one of these indexes may directly imply that a collision has occurred, but it may simply act as a culling method to reduce tests as further collision checks are needed to prove a collision occurred.

## Answer

Sadly, due to the nature of the storage you can't simply state "an object spans the indices i to j". The morton codes that an arbitrary shape spans will likely group into ranges, but there is likely to be more than 1 range;

See this image (I can't link it as it's an unsupported format).

A box; top left (2.5, 2.5) top right (3.5, 2.5) bottom left (2.5, 4.5) bottom right (3.5, 4.5) - would contain the Morton codes; 001111 and 100101 which aren't consecutive.

Typically objects are indexed by translating double/single precision positions into an int (sometimes scaling is applied to the values depending on the scene) which is then used to create the morton code. So if you want to find the codes an object encompasses you should calculate the set of integer points within that shape and generate the codes for those positions.

Given an axially aligned bounding box of an arbitrary size and position you can see how this might be fairly straight forward. In 2d translate the corners to the nearest int position, then starting from the top left increment x by 1 till you hit the right hand side x, then increment y and repeat. Keep looping till y = bottom y (assuming the y value is positive down the screen);

```
  for (int y = ceiling(top); u <= floor(bottom); ++y
  {
    for (int x = ceiling(left); x <= floor(right); ++x
    {
      Geometry* geometry;
      int mortonCode = generateMortonCode(x, y);
      if ((geometry = geometryArray[mortonCode]) != NULL)
      {
        collisionCheck(rectangle, geometry);
      }
    }
  }

```

Note: For C/C++ users, rounding using a cast to int will sometimes give a number outside of the box, so use ceiling and floor; for top and left use ceiling, for bottom and right use floor. Again, this assumes y is positive down, so bottom \> top.

Note: For collision detection you may want to allow the generation of codes surrounding the shape (swap ceiling and floor in the code above) to provide a slightly larger set of points which definitely will cover an area bigger than the shape you're checking.

---
Tags: collision-detection, algorithm, performance
---


# Question
Title: How can I unify the collision handling of melee/spell attacks in a networked environment?
I am trying to figure a good way to create the battle system of a game. The game is fast paced and the gameplay needs to be precise (think hack n slash)

What I would like to achieve is a simple and unified system that could manage any type of attacks, that could be tweaked.

My first idea is to use physics shape: For example an arrow will just be a little capsule moving forward, an explosion would be a growing sphere collider, and melee combat could be done by spawning a box in front of the player.

One problem I have with this is that I'd like to have an authoritative server for multiplayer, which means I shouldn't use too much actual physics.

So, is there any standard way people program these sort of systems, do you know any good starting point better than just using physics?

# Answer
> 2 votes
Fundamentally, you're going to be doing collision detection with what are essentially physics volumes (simple primitive shapes like spheres and cylinders) to achieve what you want, unless you want to start sacrificing accuracy and doing even simpler ray checks. Consequently, it makes some sense to use a physics API for this. These sort of computations are exactly the kind of things physics APIs tend to do well.

Guild Wars 2 used basic physics volumes like you are describing for server-side collision detection between attacks and characters and the like. It is a viable plan; just try to keep your collision volumes as simple as possible for the effect in question and profile when you discover bottlenecks.

You may also want to do client-side prediction of the collisions, using physics or simpler checks, to avoid latency and keep your game feeling responsive.

---
Tags: unity, physics, multiplayer, combat
---


# Question
Title: Why am I getting a return value of zero from my position computation function?
Ok I have a Function int x(), which is used in

```
new Rectangle(x(),a,a,a);

```

in DrawMethod in XNA but when I use it I get x() = 0 as as the answer.Here is my CODE:

```
int x()
        {
            int px = (128 * 5);
            int xx = 0;
            for (int i = 0; i < 6; i++)
            {

                if (Mouse.GetState().X > px)
                {
                    //xx = Mouse.GetState().X;
                    xx = px;
                    break;
                }
                else
                { px -= 128; }
            }

            return xx;
        }

```

Here is the DrawMethod Code:

```
if (set)
        {
            spriteBatch.Draw(texture, new Rectangle(x(), y(), texture.Width, texture.Height), Color.White);
            textpositionX = x();
            textpositionY = y();
            set = false;
            select = false;
            place = true;

        }
        else if(select)
        {
            spriteBatch.Draw(texture, new Rectangle(Mouse.GetState().X - texture.Width / 2, Mouse.GetState().Y-texture.Height / 2, texture.Width, texture.Height), Color.White);

        }
        else if (place)
        { spriteBatch.Draw(texture, new Rectangle(textpositionX, textpositionY, texture.Width, texture.Height), Color.White);
        select = false;
        set = false;
        }

```

# Answer
> 1 votes
One useful debugging technique to determine why some particular behavior is happening is to work backwards from that behavior's observable effect. In this case, the effect is that `x()` returns 0. So let's examine `x`:

* `x` only has one return statement, so that's the only place you can be returning zero. The value returned is the variable `xx`.
* `xx` is a local, and receives a value in two places in the code. First, it receives a value of zero upon initialization. Second, it receives the value of `px` upon taking the positive branch of your `if` statement. If you never take that positive branch, you'll never modify `xx` and thus will return 0.
* So, is it possible that you never take that positive branch? The condition is that the mouse's X position is greater than `px`, which starts at 640 and decreases by 128 five times (so the final value of `px` is 0). So you'll never take that branch if the mouse's X position is negative, which as was pointed out in the comments, is totally possible.

Consequently, we can conclude that your function is returning zero because the mouse is off the left edge of the client area when you run it.

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


# Question
Title: How can I implement real-time mutual object reflection?
So, given a scene like this (cubemap skybox with "real" spheres)

Everything looks great, except for the fact that the spheres don't reflect each other.

What's a good way to go about this? The first thing that came to mind was to render an environment map for each cube, and apply that to each cube along with the skybox. However, that will be insanely slow when updated per frame, given that the spheres are moving relative to each other and a static map won't work.

I realize this may fall under the category of ray tracing and be difficult to achieve real-time, but perhaps someone has addressed this problem in the past?

# Answer
> 6 votes
You can use recursive Enivornment mapping (using cube maps) as follows. It is slow if you try to do it fully every frame however, the approximation is to use the previous frames output so it builds up the reflections over time (which will be unnoticeable given good frame rates). So you only need to process one extra frame's worth of data on each render.

> Recursive reﬂections of curved objects in a scene can be performed using environment mapping \[253, 849, 933\]. For example, imagine a red and a blue mirrored ball some distance from each other. Generate an EM for the red sphere, then generate an EM for the blue while using the red sphere’s EM during its creation. The blue sphere now includes a reﬂection of the red sphere, which in turn reﬂects the world. This recursion should in theory go on for several steps (until we cannot make out any diﬀerences), but this is expensive. A cheaper version of this computes only one environment map per frame using the environment maps from the previous frame \[360\]. This gives approximate recursive reﬂections. Figure 9.46 shows some examples using this technique.
>
> Akenine-Mo¨ller, Tomas (2012-02-22). Real-Time Rendering, Third Edition (Page 391). A. K. Peters. Kindle Edition.

---
Tags: opengl, glsl, reflection-rendering
---


# Question
Title: Can Simple Direct Media Layer be used with WebGL?
I have read that on desktop OpenGL + SDL is a great way to learn. In looking at WebGL I couldn't find a Web version of SDL. On their site I see bindings for all sorts of languages, but no JavaScript. It seems obvious that this gives an answer of 'no' to my question, but I also came upon code snips while googling around that seemed to be doing it. Whatever the missing piece is I'm not getting it...

# Answer
> 5 votes
When used with OpenGL SDL is responsible for opening a window, creating an opengl context, handling events, etc. The drawing part is OpenGL responsibility.

In a browser, you already have a window, ways to handle events and a way to get a context, SDL would not be very helpful in this scenario.

Although, mimicking the SDL API in javascript might be helpful for those familiar with it, I couldn't find anything for a webgl game. If you are interested in using javascript for developing SDL apllications, there is node-sdl, though.

# Answer
> 5 votes
The literal answer is actually yes because the Emscripten project, for compiling C++ applications to Javascript for running in browsers, provides an implementation: "libc and stdlibc++ support is very good. SDL support is sufficient to run quite a lot of code. OpenGL support is in very good shape for OpenGL ES 2.0-type code, and even some other types," in https://github.com/kripken/emscripten/wiki/FAQ

However that is only useful for compiling C / C++ written SDL using apps to browsers -- not at all for developing in Javascript for browsers to begin with, for all the reasons given in previous answers. Just a note for the record :) And this is what allows Quake and Unreal and such to be compiled to run with webgl in browsers..

# Answer
> 2 votes
I think it's highly unlikely that SDL + WebGL is a useful combination.

SDL is a C library, and WebGL can only be used with Javascript. While it is possible to compile C code into Javascript, none of the underlying libraries used by SDL are available from inside a web browser.

Also the level of abstraction is fundamentally different: SDL was originally conceived as a small layer to allow native C programs to gain access to Framebuffers in an OS independent and convenient way. This allows games which use software rendering to be written more easily.

On the other hand, WebGL is for Javascript in a browser rendering into a canvas. This is already implementation-agnostic.

You're probably better off using something like Three.js if you are targetting a web browser (NB: do not consider this a recommendation)

---
Tags: sdl, webgl
---


# Question
Title: Why is the player not resting in the center of the camera?
Is it possible to create a combination of the following two cameras described in Andrew Russell's answer? XNA Platformer Sample: Supporting multiple resolutions?

I want to implement a scrolling camera that is focused on the player. In addition, I want to scale the viewport, so that the game looks on every resolution the same.

I already tried to combine the two cameras, but the player is not resting in the center of the screen. Currently scaling the viewport to any resolution higher than 800×480 de-centers the character. The character moves out of the viewport after a while.

My code:

```
Vector2 vp, gameWorldSize = new Vector2(800, 480);
Matrix camera;
float ScaleX, ScaleY, Scale;
float TranslateX, TranslateY;

ScaleX = vp.X / gameWorldSize.X;
ScaleY = vp.Y / gameWorldSize.Y;
Scale = Math.Min(ScaleX, ScaleY);

TranslateX = (vp.X - (gameWorldSize.X * Scale)) / 2f - player.Playerposition.X + gameWorldSize.X / 2;
TranslateY = (vp.Y - (gameWorldSize.Y * Scale)) / 2f - player.Playerposition.Y + gameWorldSize.Y / 2;

camera = Matrix.CreateScale(Scale, Scale, 1) * Matrix.CreateTranslation(TranslateX, TranslateY, 0);

```

What is wrong? Is it not possible to combine the two cameras?

# Answer
> 1 votes
I think should do the trick:

```
ScaleX = vp.X / gameWorldSize.X;
ScaleY = vp.Y / gameWorldSize.Y;
Scale = Math.Min(ScaleX, ScaleY);

camera = Matrix.CreateTranslation(-Player.Position)
       * Matrix.CreateScale(Scale, Scale, 1)
       * Matrix.CreateTranslation( ViewPort.Width/2, Viewport.Height/2, 0);

```

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


# Question
Title: Dynamic 2d terrain loading / stitching in Unity
I'm currently working on a top down 2d game (in Unity 2d) where I'd like to build a huge terrain for the player to explore. My question is - do you have any good practices or ideas on how to chunk the terrain, work on it in Unity (should I work on terrain chunks in different scenes etc.) and finally load it dynamically and efficiently in runtime ?

# Answer
> 2 votes
One way is to make it with a grid where you place new terrain tiles as necessary. See here for an explanation and a simple TerrainManager: http://upshift.org/2012/02/building-endless-terrain-in-unity3d/

---
Tags: 2d, unity, terrain
---


# Question
Title: Spritebuilder and CCScrollView, page indicators not showing up?
I'm using Spritebuilder to make my game, and CCScrollView usually saves me quite a bit of time. I'm trying to implement the scroll view much in the same way as the home screen on an iphone uses the UIScrollView. I want the page indicators to be visible and change as you scroll through the pages (the little white dots for iOS 7).

In Spritebuilder I set up the CCScrollView as a child of a CCNode. Then I set the content node to another one of my ccbi files, `EasyPackpage1`. When I run my project, everything works pretty well. **I currently have a content node that is large enough so that it has three different pages, so if I scroll to the right it locks onto the next page, scroll to the right again, it locks onto the next page. The only problem is that the page indicators are non-existent**. How can I get these page indicators?

If someone knows the solution for doing this using purely code, that would also be greatly appreciated. Cocos2d v3 still has very little documentation and I haven't been able to find much on how to use CCScrollView, since it looks like CCScrollLayer is deprecated in v3.

Thanks for the help!

# Answer
> 1 votes
The trick is to use the `CCScrollViewDelegate` methods to detect scroll events.

Add a `CCLabelTTF` and call it `_pageLabel`.

In Xcode, make the scene containing your scroll view adhere to the `CCScrollViewDelegate` :

```
@interface myScene : CCNode <CCScrollViewDelegate>

```

Then, in `didLoadFromCCB`, set the scroll view delegate to `self` :

```
_scrollView.delegate = self;

```

and finally,

```
- (void)scrollViewDidScroll:(CCScrollView *)scrollView
{
    // change your page indicator label or sprite to show new page
        // use _scrollView.horizontalPage to get the page
}

```

---
Tags: ios, cocos2d-iphone, objective-c, xcode
---


# Question
Title: How do I check why is no output on screen?
I'm using OpenGL 3.3+, and I'm trying to create an orthographic projection to draw on screen. I have the model data in a buffer:

```
X    Y
0,   0
50,  100
100, 0

```

And I create my Model-View-Projection matrix as follows:

```
glm::mat4 projection = glm::ortho(0.f, 100.f, 0.f, 100.f);
    glm::mat4 view = glm::lookAt(
        glm::vec3(0, 0, 5),
        glm::vec3(0, 0, 0),
        glm::vec3(0, 1, 0)
    );
    glm::mat4 model = glm::mat4(1);

    glm::mat4 mvp = projection * view * model;

```

In my debugging efforts, I used the values from the model buffer and did the same operations the shader was doing, but on the CPU using GLM:

```
glm::vec4 pos(x, y, 1.0, 1.0);
posicao = mvp * posicao;

```

And got these results:

```
X    Y
-1, -1
0,   1
1,  -1

```

Which were as expected, as the Vertex Shader's code is plain simply multiplying the matrix by the incoming vec4(vec2(x, y), 1, 1). In my understanding, this should've outputted a triangle on my screen, but it's blank. What are some ways I can debug this?

# Answer
Some of the things I typically try when nothing appears to be drawing on the screen:

* Disable backface culling (in case your geometry winding is wrong)
* Change the glClearColor() to something other than black (texturing problems can cause your geometry to be drawn solid black, in which case you won't see it)
* Change your fragment shader to output a specific solid color
* If you use framebuffers anywhere, try explicitly calling glBindFramebuffer(GL\_FRAMEBUFFER, 0) before drawing your triangle, to rule out binding leaks
* Continuously rotate your camera angle in a loop (in case the geometry is accidentally behind you)
* Make sure your geometry is not within your near clip distance (try setting the near clip distance as small as possible, and moving the geometry further away)
> 9 votes

---
Tags: opengl, mathematics, rendering, matrix, projection
---


# Question
Title: AS3 Starling in Fullscreen Mode cuts off most of the screen
I have a mixed mode (classic Flash Renderer + Starling) AIR AS3 project that I'm switching to fullscreen with

```
 stage.align=StageAlign.TOP_LEFT;
 stage.scaleMode=StageScaleMode.SHOW_ALL;
 // Swtich to Fullscreen with
 stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;

```

When I do this, I have a callback on the Event.RESIZE event to resize my Starling instance to fullscreen:

```
private function resizeStarling(e:Event):void
{
            var size:Point = new Point();
            if(this.stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE)
            {
                size.x = Capabilities.screenResolutionX;
                size.y = Capabilities.screenResolutionY;

            }
            else
            {
                size.x = WIDTH;
                size.y = HEIGHT;
            }

            RectangleUtil.fit(
                new Rectangle(0, 0, stage.stageWidth, stage.stageHeight),
                new Rectangle(0, 0, size.x, size.y),
                ScaleMode.SHOW_ALL, false,
                Starling.current.viewPort);
}

```

The set to FULL\_SCREEN\_INTERACTIVE turns all my normal flash Stage object based UI and visuals to full-screen mode. However, while the Starling graphics are correctly upscaled, they only occupy the upper left corner of the screen, and the remaining three quadrants are cut off. I haven't validated yet, but I suspect that the segment being displayed is the same dimensions as the original windowed stage size. Any ideas on what I'm forgetting to do to achieve fullscreen Starling displays that are actually fullscreen? This is on OSX.

# Answer
> 1 votes
Okay, finally figured this out, so putting the bits here for anyone else who is trying to solve this problem.

In straight Flash (no Starling invoked), you can simply switch between windowed and fullscreen by using `stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;` or `stage.displayState = StageDisplayState.NORMAL;` If you've previously set the following:

```
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.SHOW_ALL;

```

Then Flash AIR will just autoscale your app for you.

However, once you invoke Starling, this no longer works. Here's how I got around it.

First, in the app.xml, I made sure I had the following settings:

```
<maximizable>false</maximizable>
<resizable>false</resizable>
<width>1280</width>
<height>720</height>
<minSize>1280 720</minSize>

```

Obviously, you'll set your size to whatever is appropriate for you. Then in the startup class for the app itself, I only define the framerate and background color for the SWF, not the app size:

```
[SWF(frameRate= 30, backgroundColor="#000000")]

```

Set the **stage.align** and **stage.scaleMode**, as above, then you need to do a few calculations. Somewhere in code, capture your default windowed screen dimensions in some static variables (I use **WIDTH** and **HEIGHT** set to 1280 and 720 respectively), and then in your main class **onAddedToStage** handler (you'll need to have an event listener for **Event.ADDED\_TO\_STAGE** in your constructor), create and then call this method to cache away the upscale ratio to a private member variable:

```
private function calculateScreenRatio():void
{
     var ratioX:Number = Capabilities.screenResolutionX / WIDTH;
     var ratioY:Number = Capabilities.screenResolutionY / HEIGHT;
     m_fsRatio = Math.min(ratioX,ratioY);
}

```

Great, now you have the proper scaling ratio for your fullscreen mode. Now you need to do three more things: 1) Setup Starling with the proper default stage size, 2) Handle Resize Events in Starling, and 3) Handle Resize Events for your classic stage.

First, setting up Starling:

```
// create our Starling instance
var viewRect:Rectangle = new Rectangle(0,0, WIDTH, HEIGHT);
mStarling = new Starling( StarlingRootSprite, stage, viewRect);
// set anti-aliasing (higher the better quality but slower performance)
mStarling.antiAliasing = 0;  // Pixel Game, no AA!
mStarling.start();

```

Now in your StarlingRootSprite class, have a handler for the Starling resize event (not the classic Flash event):

```
this.stage.addEventListener(ResizeEvent.RESIZE,onResize);

```

and your onResize method should look like:

```
private function onResize(resizeEvent:ResizeEvent, size:Point):void
{
    RectangleUtil.fit(
        new Rectangle(0, 0, stage.stageWidth, stage.stageHeight),
        new Rectangle(0, 0, size.x, size.y),
        ScaleMode.SHOW_ALL, false,
        Starling.current.viewPort);
}

```

That will properly resize Starling to fullscreen or windowed on a resize. Now we just need to handle the classic Flash stage, which won't resize automatically for us. Create another event listener for the classic Flash resize event, probably also in your **onAddedToStage** method for the base app class:

```
this.stage.addEventListener(Event.RESIZE, onResize);

```

And then make an onResize method like this:

```
private function onResize(e:Event):void
{
    if(stage.displayState == StageDisplayState.NORMAL)
    {
        this.scaleY = this.scaleX = 1;
    }
    else
    {
        this.scaleY = this.scaleX = m_fsRatio;
    }
}

```

You're done. Now both Flash and Starling will resize properly when you set stage.displayState to swap between windowed and fullscreen. The advantage here is that if the user pressed ESC in fullscreen mode, both event handlers will capture the event and properly resize down to Windowed mode. Also, your Starling and Flash displays will be properly sized and not missing any segments in fullscreen mode.

---
Tags: flash, actionscript-3, starling
---


# Question
Title: How should a hive AI distribute tasks between worker drones?
I've been studying AI design—things like behavior trees and FSMs. They make sense from the perspective of deciding a specific entity's goal and action.

However, the AI in my game is very *hive-like*; multiple drones share the same knowledge and desires. What a particular drone can do is unimportant, as each can do any task. Instead, it's a question of which drone would be the best choice for a particular task, given the list of tasks to be done.

For example: The AI decides it wants a particular resource type gathered. Different resource types are available at various locations across the map. Which drone should it send to gather the resource? All are capable, but some might be further away from the resource. Some might already be gathering a different resource. Some might be performing tasks that the player is actively waiting on, or that strongly affect the player's success.

To decide, the AI would need to evaluate various factors and continually re-evaluate as the game progresses, without stepping on it's own toes and continually reassigning jobs to the same drones.

Is there a field of AI suited to this sort of task distribution that I can look into?

# Answer
Real-time strategy game AI is a closely related and well-studied field:

> Early research in AI for RTS games \[1\] identified the following six challenges:
>
> * Resource management
> * Decision making under uncertainty
> * Spatial and temporal reasoning
> * Collaboration (between multiple AIs)
> * Opponent modeling and learning
> * Adversarial real-time planning

a survey of *Starcraft*.

That "\[1\]" refers to M. Buro, *Real-time strategy games: A new AI research challenge,* in IJCAI 2003. International Joint Conferences on Artificial Intelligence, 2003, pp. 1534–1535. It refers to various other recent (2012–) research too.

Additionally to academic papers, you might want to study open source RTS games such as Spring.
> 1 votes

---
Tags: ai
---


# Question
Title: Sprite detached from the screen but contact is still made
Well, i'm facing a strange problem with my code. I'm trying to remove a sprite named ice when either of player, enemy or the ground comes in contact with the ice. The contact is made successfully and the ice is hidden after the contact but due to some reasons the player,enemy and the ground still comes in contact with the ice. I want the ice object to be completely removed from the scene when contact is made. I'm using the below code:

public void beginContact(Contact contact) { // TODO Auto-generated method stub Fixture x1 = contact.getFixtureA(); Fixture x2 = contact.getFixtureB();

```
if (x1.getBody().getUserData().equals("player")
        && x2.getBody().getUserData().equals("ice") && gb.isVisible()==true) {
    Log.i("Contact Made", "CN");
    detachChild(gb);
    gb.setVisible(false);
    score = score + 1;
    scoreText.setText("Score: " + score);
}
if (x1.getBody().getUserData().equals("ground")
        && x2.getBody().getUserData().equals("ice") && gb.isVisible()==true) {
    detachChild(gb);
    gb.setVisible(false);

}
if (x1.getBody().getUserData().equals("enemy")
        && x2.getBody().getUserData().equals("ice") && gb.isVisible()==true) {
    detachChild(gb);
    gb.setVisible(false);

}

```

}

# Answer
> 0 votes
You are detaching the sprite, but not the physics body. The physics body and sprite are connected by the physics connector which basically just moves and rotates the sprite based on the body's position and rotation. You have to either destroy the body or set it as not active.

```
mPhysicsWorld.destroyBody(body);

```

or

```
body.setActive(false);

```

Both will do. Destorying a body in AndEndengine must be done at a specific time (at the beginning of the next loop cycle is the best) otherwise you might get some errors.

Here's a link to another stackoverflow question that deals with it.

---
Tags: andengine
---


# Question
Title: What does a "video system not initialised" error in pygame mean?
I'm trying to play music when a key is pressed in pygame, then print a message.

When I run this script:

```
import pygame
import time

pressedkeys = pygame.key.get_pressed()

pygame.init()                      #initialize pygame
pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag

try:
    firstMusic = pygame.mixer.Sound("C:\(pathForMyMusicFile).wav")  #load sound
    secondMusic = pygame.mixer.Sound("C:\(pathForMy2ndMusicFile).wav")  #load sound

except:
    raise UserWarning, "could not load or play soundfiles"

if pressedkeys[pygame.K_SPACE]:
    firstMusic.play(-1)
    time.sleep(2)

```

I get this error:

> ```
> pressedkeys = pygame.key.get_pressed()
> pygame.error: video system not initialised
> Script terminated.
>
> ```

What am I doing wrong?

I'm using Stani's Python Editor.

# Answer
> 1 votes
Random assumption since I've never used Pygame:

You can't receive/check keyboard events before initializing Pygame first. So move down your `pressedkeys = ...` line to be after `pygame.init()`?

---
Tags: pygame, keyboard
---


# Question
Title: How to edit key-value pairs (like a Dictionary) in Unity's inspector?
I have a spell system I am creating, the principle is as follows:

* Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector.
* I have a Spell enum listing all possible spells in the code, which is used in the game logic
* When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations
* Each actor (be it players or enemies) needs to have a list of possible animations for the spells

The problems with how I am trying to implement are:

* For listing each actor's animations I could use a `Dictionary<Spell, Animation>`, but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type.
* I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary

I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations

# Answer
One quick way to get key-value pairs in Unity's inspector is to define a serializable entry class, and then use an array or List\<\> of them. eg...

```
public class SpellAnimationMap : ScriptableObject
{
   [System.Serializable]
   public class SpellAnimationEntry
   {
       public Spell spell;
       public AnimationClip animation;
   }

   public SpellAnimationEntry[] spellAnimations;
}

```

Automatically, this will give you a resizeable list in the inspector where you can enter the key and value, without needing to write a custom inspector.

The result looks like this:

(One trick: if the serialized entry class contains a "Name" field, that string will be displayed instead of the bland "Element 0" headings. Useful if you have more complex data you want to be able to navigate efficiently.)

Making this a ScriptableObject allows you to treat it as an Asset shared between entity types/instances that need the same animation set, avoiding overhead of duplicating the list for each. (Other classes tend to be serialized per-instance in Unity). To go this route, you'll need to add a small editor script to let you create instances of these in your Assets folder.

---

**Edit:** now it's even easier - you can just add this attribute above your ScriptableObject:

```
[CreateAssetMenu(fileName = "fileName.asset", menuName = "Some Folder/Menu Label")]

```

This puts the ScriptableObject into your Create menu, like so:

---

You can optionally make the array private and serialized so that it still shows up in the inspector, but add a public Dictionary (or private dictionary with a public GetAnimation(Spell spell) method) for clients to consume for more efficient lookups. In its OnEnable() method, the SpellAnimationMap can iterate through its inspector-populated array to build this dictionary once, again sharing the benefit between all client instances. (Note that OnEnable() is also called in the editor when the asset is first created, so be sure to check that your array is non-null before you try to read it)

Finally, you can add as much into this entry datatype as you need. It could include the prefab too, for instance, or any number of other bits of data you want to link to the spell key.

It's also possible to write custom inspectors to populate Dictionary\<,\> fields directly, but the impression that I get is that it's fussy to get working smoothly.
> 33 votes

---
Tags: unity, architecture, rpg, data-structure, editors
---


# Question
Title: Level progression starting from target total XP
I'm sort of a newbie here, so pardon me if I don't get any of the lingo right.

But I'm trying to create a level progression that charts with the "10,000 hr" rule such that, basically, each hour worked will equal 1 XP and level 99 (xx, if you will) charts with having accumulated 10,000 XP.

I understand how I can make a straight progression of levels, but what I really want to do is create a sloped progression, where you level up more often early and then it requires more and more effort to level up as the progress goes on. (The only targets, I guess, are level 1 being 0 and level 99 being 10,000.)

Any ideas? Can anyone help? (I'm sure this is simple, but if you can show me the way toward the answer, I'll gift you by first-born sword.)

# Answer
A simple method is to use a Geometric Series:

TotalXP(level) = a + ar + ar^2 +...+ ar^(level-1)

Where a is the XP required to reach level 1, and r is the common ratio by which the level gaps increase.

Then the total XP is:

a(1 - r^maxLevel)/(1 - r)

You can plug in numbers for r until you get the steepness of acceleration that you want (say using a spreadsheet or graphing app), then divide your magic number 10 000 by (1-r^n)/(1-r) to get the required a.

As an aside, please don't make me work for a full hour to get one measly XP. ;)
> 0 votes

# Answer
What you want to generate is a table of values that can be hand-tweaked to adjust the gameplay experience as necessary.

To make the maths simple, generate a curve that goes from 0-1 on both axes and then scale the result as appropriate.

One possible curve that will give you fast progression at the start and slow at the end is simply:

xp\_required = level * level

To get control of the steepness of the curve try a function of this form, where bigger values for k will give you steeper curves.

xp\_required = (k^level - 1) / (k-1)
> 0 votes

---
Tags: levels
---


# Question
Title: RGBA values not coming as intended | LibGDX
As it states, my RGBA values aren't coming out the way I want it to be. My RBGBA values are As it states, I am trying to create a orange tinted color on my game.

```
221, 189, 98, 0.7

```

I am using a ShapRenderer called tint, and here is the code:

```
ShapRenderer tint = new ShapRenderer();
tint.begin(ShapeType.Fill);
tint.setColor(221, 189, 98, 0.4f);
tint.rect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
tint.end();

```

I had tried this out in CSS, and it came out with the correct color. But with LibGDX, the game screen is plain white. The opacity (rgb 'A' value) does not have any affect on the tint color.

# Answer
> 2 votes
You must use floats between 1 and 0 in the setColor method, so you can just divide the numbers you're already using by 255f. To make the color transparent you need to enable blending like this: `Gdx.gl.glEnable(GL20.GL_BLEND);` And set the glClearColor to `Gdx.gl.glClearColor(0, 0, 0, 0);`

---
Tags: java, libgdx
---


# Question
Title: Creating Platform game with Inclined Levels
Till now I have developed platform games in which a player can only move and detect tiles linearly. I wonder on how to implement games in which a player can move on an inclined or irregular surface.

I use libgdx to develop games and Tiled Map Editor to create level maps.

On research, I found RUBE is something I need for what I want to do.

Is this true? I will have to use Box 2D if I want to make such games.

Can't we do it using Tiled? If so... how to detect collision in that case?

If there is some other way through which I can do so? Thanks in advance for any suggestion.

# Answer
After a lot of research, I finally found out a way... I can use Tiled Map Editor to design my level...and create an object layer to draw shape/boundaries for collision and then to convert those boundaries/shapes as Box2D objects in my game using a Box2DParser. The results are awesome.
> 1 votes

# Answer
No, you don't have to use any specific toolset and you don't have to use any specific (physics) library either.

It's just a question of convenience, since things like Box2D will provide you other benefits as well, e.g. being able to do collision, physics simulation etc.

If you're not using tiles, you'll most likely want to write your own custom editor.

As an alternative, you could as well use tiled to draw rough outlines that are then interpolated by the game engine to create smooth surfaces (this could get tricky to edit!).

Creating smooth landscapes is actually pretty easy, but there are many things where you can optimize your algorithm.

Here's a short example of some basic "smooth landscape":

* Your landscape or map is defined by several height points, in essence it's a 2D height map:
* To fill the gaps, you can use any algorithm you want, e.g. splines or just linear interpolation:

If you worry about performance/complexity, you can use different algorithms for game logic (like collision detection) and rendering.
* Now, once you've got your player character (or any other entity), you determine the closest height map point to the left and right of that entity. Based on that it's quite trivial to compute the actual ground height at that specific position:

For linear interpolation, it's possible to draw/calculate the triangle the character is standing on. Once you've determined the slope (`deltay / deltax`) it's easy to determine the ground height where the character stands.
* Now, to prevent your character from falling through the ground, all you have to do is move him up as long as he's under the ground. This will also allow your character to walk over the terrain if you move him left/right.
* There's just one issue left: Don't allow the character to climb too steep ground. There are multiple possible approaches, e.g. just check the slope. If it's too steep, don't allow the character to walk towards it anymore.

Of course, this is simplified a lot and this won't allow you to create caves, floating platforms, etc. However, those can be done as easy, you'll just need a more complex algorithm. Rather than checking a chain of points, you'll have to determine whether specific parts of your character overlap with map objects (= polygons).

**Edit:** Since I've had a few minutes, I've created a quick example utilizing jsFiddle (Source). Just make sure to click in the results window and you'll be able to run around using the left/right arrow keys.
> 9 votes

# Answer
A spline function is used which produces curves based on discrete control points which you place; examples of curve generation functions that use control points are Catmull-Rom or Bezier. x is known, y is unknown; so use the spline function to get the y position of the curve for that x, then place your character at that x,y position.
> 0 votes

---
Tags: libgdx, platformer
---


# Question
Title: How do I create a score based on two or more weighted parameters?
In my game I have two variables `x` and `y` which should be "included" in the final score, but with different "weights" (unknown and possibly different), so I need some function `f(x, y)` with an output in the `0<=f(x, y)<=inf` interval.

There are some constraints on x and y:

```
1<=x<=60
1<=y<=9999

```

What is the best way to combine these two values to actually look nice?

Generally, what is the best way to combine different number of variables with different constraints without them "overlapping"?

# Answer
> 1 votes
I'm going to assume that your inputs are integers. Then since we have only a finite set of outputs, we can map them to an integer ranking in order of least to greatest, as I'll do here. You can remap them to an arbitrary curve from there if you prefer.

Geometrically, you're looking for a curve in a 2D grid that goes from the point (1, 1) to (60, 9999), visiting every integer point within the rectangle with those corners exactly once.

You can then use this to associate every such (x,y) with a unique integer score in the range \[1, 599940\]. (ie. a bijection, as is necessary for your "no overlap" criterion)

You also want to ensure that if (x2, y2) has a greater score than (x1, y1), then either x2 \> x1 or y2 \> y1. (ie. a higher score must strictly dominate a lower score on at least one axis)

The most straightforward way to do this (given your desire to make x more important than y) is to scan up each column to the top (y = 9999), then zig-zag back down to the start of the next column (y = 1). That yields the function:

score = 9999 * x + y - 9999

Testing out a few values: (1, 1) =\> 1, (1, 2) =\> 2, (1, 9999) =\> 9999, (2, 1) =\> 10000, (60, 9999) =\> 599940.

If you want a pattern that keeps x & y more balanced in their importance, you could try using a Z-order curve like Morton Ordering, but the way this jumps around will be very difficult for players to understand, and it may appear to them that their score is being assigned randomly. Increasing x or y will always yield a greater score from such a curve, but which one gives a bigger increase will vary. Increasing your y by 1 may increase your score by 5 in one place, and by 100 in another.

**A different approach:**

If we don't care about densely filling our score space (ie. there can be gaps between two valid scores, where no combination of inputs will give an intermediate score), we can think about this as a linear combination with specially-chosen weights:

score = xWeight * x + yWeight * y + zWeight * z - (xWeight * xMin + yWeight * yMin + zWeight * zMin)

The weights have to be in particular ratios to avoid collisions though. The only way I know how to find them is by exhaustive search. There's probably better ways, but here's a clumsy example:

```
for(xWeight = 1; xWeight < maxWeight; xWeight++)
{
   for(yWeight = 1; yWeight < xWeight; yWeight++)
   {
       if(CheckWeights(xWeight, yWeight))
          validWeights.Add(xWeight, yWeight);
   }
}

bool CheckWeights(int xWeight, int yWeight)
{
   for(x = 1; x < xMax; x++)
   {
       // Is there any collision between this multiple of x and a multiple of y?
       if(x * xWeight % yWeight == 0 && x*xWeight/yWeight < yMax)
         return false;
   }
   return true;
}

```

This gives you lots of choices of weights, but getting close to particular ratios usually requires making the weights (and search space) fairly large. For instance, with weights under 100 we can get an xWeight:yWeight ratio as low as 1.010204 (99, 98), or as high as 1.622951 (99, 61) (assuming the xWeight is to be strictly larger than yWeight)

To extend this beyond two variables, find weights you like for the first two. Then generate all scores that can be formed using those variables and those weights. Next, repeat, finding a weight for the next variable and a weight for the score-so-far (in this search, the for loop over the domain of x would instead loop over the domain of valid scores from the previous step). You can repeat until you run out of variables or your search space becomes too impractical.

In terms of the geometric analogy, this method corresponds most closely to the second drawing, with the diagonal zig-zag. Choosing different weights is analogous to tilting the zig-zag to be steeper or shallower.

---
Tags: leaderboards, ranking
---


# Question
Title: Artemis Framework - delete all entities with a given type of component
In artemis framework how can I list all entities wtih a given type of component and delete them from the world? I couldn't find any examples in the documentation and it seems there's no straightforward way of doing this

# Answer
> 2 votes
Here's an example system that deletes all entities with the "Expires" component:

```
public class DeleteEntitiesSystem extends EntitySystem {

    public DeleteEntitiesSystem() {
        super(Aspect.getAspectForAll(Expires.class));
    }

    @Override
    protected void processEntities(Array<Entity> entities) {
        for (Entity e : entities) {
            e.deleteFromWorld();
        }
    }
}

```

---
Tags: artemis
---


# Question
Title: How can I avoid repeatedly setting up SDL in VS 2013?
Do I *have to* set up SDL 2.0.3 every time I make a new project?

I tried putting `sdl.dll` in `system32` so that I don't have to include it in my project folders, but that didn't work.

# Answer
> 3 votes
I'm not quite sure what you mean by *"setting up SDL"*. You have to `#include` headers and link to binaries of libraries for each project.

In Visual Studio, there are so called property sheets that let to share properties between projects. You could create one that contains SDL as linker input but I highly doubt that applying the property sheet is faster than just linking to the library.

# Answer
> 3 votes
To use SDL (or any other similarly-packaged dependency), you have to:

* Add the path to the SDL headers to the additional include directories, so the compiler can find them when you `#include "SDL.h"` or whatnot.
* Add the path to the import library (the `.lib`) to the linker search paths.
* Actually link against the import library.
* Distribute the actual DLL next to your shipping executable (or elsewhere in the DLL search path).

The first three steps can be set in the project properties of your project, in the C++ and linker tabs respectively. You can set these ones and use property sheets to save the settings, importing them into a new project. Alternatively you can just set up a basic skeleton project, install it as a Visual Studio template or just create a clone every time you want to start a new project.

Don't try to put your dependencies in system directories like `system32` or Visual Studio's standard headers directory. Not only is that bad for you, because you are contaminating what should be an off-limits directory, but it will make it harder to deal with projects that use different versions of a dependency and it doesn't solve the problems of ultimately packaging the dependency for distribution.

If you don't want to keep the copies of your dependencies directly in the folder structure of your project (which is what I'd recommend, since it makes each project an isolated silo that can be configured to build immediately upon checking out from version control with no additional setup), you can create a "ThirdParty" directory to store all your dependencies.

Somewhere in a userspace portion of your hard drive (like in your "My Documents" folder), create a "ThirdParty" directory that has one directory for each dependency (like "SDL" or "GLEW" or "Bullet" and so on). In each of those directories, make a subdirectory for each major version (1.0, 2.0, et cetera) and drop the appropriate dependency, directly as distributed from the vendor, in there.

# Answer
> 0 votes
There are 2 things you can do:

* VS Express: Take the header folder of SDL and put it into the standart header folder. This allows you to use the files like this:

> #include "SDL/main.h"

Then you've to put the sdl-lib files into the standart folder for Libs. then you can link the using

> #pragma comment (lib,"theLibYouNeedToLink.lib").

For the Dll I'd create a directory called Libs and add this Directory to the path variable. That's the dirty way.

-In other, commercial version of VS you can create Projects and save them as templates. The only thing you've to do after is to place the dll as state above.

---
Tags: c++, sdl, visual-studio
---


# Question
Title: XNA 4.0 - Strange edges with multilight shader
I am generating a light, a depth and a normalmap to calculate the lightning at each pixel with multiple lights.

On both rendertargets, i set the preferredMultiSampleCount parameter to 16 samples because I want smooth edges. It seems to work well on the first picture (normalmap). In the second picture (lightmap), multisampling works great, too. But somehow there are flickering edges at the end of each model.

I think it may have to do something with the depthmap because due to using Surfaceformat.Single I have to use

```
minfilter = point;
magfilter = point;
mipfilter = point;

```

for the Texture filter and I think AA doesnt work with filter type point.

Is this a known newbie problem or should I upload the source of my shader files for a better understanding of my problem?

EDIT: If I turn multisampling off, I dont get these edges: (Take a look at the bottom of the square in the middle.. )

# Answer
If you're using any form of deferred lighting/shading, you'll have problems with multisample antialiasing because pixel shaders normally only run once per pixel. When you do your lighting passes, the depth and normal values within each pixel will get averaged out before being seen by the shader. This will cause problems at edges, where you have very different depth and normals at different samples, so the lighting result will be totally wrong.

Ideally, at edges the lighting would be calculated once for each surface present in the pixel. Unfortunately, in DX9 (which XNA is built on) it is not possible to access the individual samples in a multisample buffer, so as far as I'm aware there is no way to do deferred shading correctly with multisampling. (In DX11, it is possible.)

As János mentioned in the comments, an alternative approach is postprocess antialiasing, where you render the scene normally (without MSAA) and apply a postprocess filter such as FXAA, MLAA, or SMAA, which attempt to detect jaggies and blur them out. This can work quite well, though it's ultimately limited by the resolution of the input image.

Supersample antialasing is another alternative, though quite expensive. This would involve rendering the scene at 2x (or more) of the final resolution), doing all lighting and shading at this high resolution, then scaling down to the final resolution at the end.
> 4 votes

---
Tags: xna, 3d, shaders, hlsl
---


# Question
Title: How can I create a resizeable 2D camera with parallax scrolling?
I want to create a Windows Phone jump-and-run game with parallax scrolling. The character should always be in centered in the viewport.

I use the following camera so that the viewport looks on every resolution the same:

```
Vector2 vp, gameWorldSize = new Vector2(800, 480);
vp = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
ScaleX = vp.X / gameWorldSize.X;
ScaleY = vp.Y / gameWorldSize.Y;
Scale = Math.Min(ScaleX, ScaleY);
Vector2 PlayerPosition;
Vector2 Viewport;
float Scale;

public Matrix GetMatrix(float scrollingspeed)
{
  return Matrix.CreateTranslation(new Vector3(-PlayerPosition.X, -PlayerPosition.Y, 0) * scrollingspeed)
   * Matrix.CreateScale(Scale, Scale, 1)
   * Matrix.CreateTranslation(Viewport.X / 2, Viewport.Y / 2, 0);
}

```

I draw the sprites like this:

```
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.GetMatrix(0.8f));
  BackgroundLayer1.Render(spriteBatch);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.GetMatrix(1.0f));
  Player.Render(spriteBatch);
spriteBatch.End();

//in the Player class:
batch.Draw(Playertex, new Rectangle(400, 240, Playertex.Width, Playertex.Height), null, Color.White, 0, new Vector2(Playertex.Width / 2, Playertex.Height / 2), SpriteEffects.None, 0f);
//in the BackgroundLayer1 class:
batch.Draw(Background1tex, new Rectangle(400, 240, Background1tex.Width, Background1tex.Height), null, Color.White, 0, new Vector2(Background1tex.Width / 2, Background1tex.Height / 2), SpriteEffects.None, 1.0f);

```

The camera is working fine and the player is always in the center of the viewport, but I don't know how to implement Parallax Scrolling. What is the best way to implement Parallax Scrolling?

How can I create a resizeable 2D viewport that follows the player and supports parallax scrolling?

**UPDATE1:** In addition, the background sprites shouldn't repeat in a loop, because I have ten 800x480 pixel sprites that are drawn one after another. For example, the first sprite is drawn at (0,0), the second at (800,0), the third at (1600,0), … The last sprite(number 10) is the end of the level. The player can move back but not further. I will create more than one layer of sprites, but every layer with a different speed factor to create the Parallax Scrolling.

How can I add the speed factor so that the background sprites move slower than the player sprite?

**UPDATE2:** If I draw "BackgroundLayer1" with a scrolling speed of 1.0f, the sprite is drawn on the correct position, but if I change the scrolling speed to another value(for example 0.8f), then the sprites of "BackgroundLayer1" aren't drawn on the correct position.

Why are the sprites of "BackgroundLayer1" not drawn on the same position if I change the scrolling speed? What is wrong? The sprites should be drawn on the same positions, even if I change the scrolling speed.

In these two pictures, you see the differences if I change the scrolling speed of BackgroundLayer1:

scrollingspeed = 1.0f

http://s1.directupload.net/images/140505/qdi6cqwz.jpg

scrollingspeed = 0.8f

http://s1.directupload.net/images/140505/56ferzuv.jpg

# Answer
> 4 votes
The X position of the background have to be calculated with the X position of the player and a speed factor.

```
 Texture2D ParallaxTex;
 Rectangle ParallaxBounds = graphics.Viewport.Bounds;

 spriteBatch.Begin();  //With no camera view transform

 ParallaxBounds.X = (Player.X * Factor) % ParallaxBounds.Width;

 spriteBatch.Draw(ParallaxTex, ParallaxBounds, null, Color.White);

 ParallaxBounds.X -= ParallaxBounds.Width;

 spriteBatch.Draw(ParallaxTex, ParallaxBounds, null, Color.White, ..., SpriteFlips.Horizontally);

 spriteBatch.End();

```

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


# Question
Title: App using LWJGL can't find display mode extension on Linux
I'm running LWJGL app on Ubuntu virtual machine with no phisical graphic card. I set up Xvfb and Mesa3D but it fails with exception

```
java.lang.ExceptionInInitializerError: null
        at org.lwjgl.opengl.Pbuffer.createPbuffer(Pbuffer.java:234) ~[lwjgl.jar:na]
        at org.lwjgl.opengl.Pbuffer.<init>(Pbuffer.java:219) ~[lwjgl.jar:na]
        at org.lwjgl.opengl.Pbuffer.<init>(Pbuffer.java:190) ~[lwjgl.jar:na]
...
Caused by: java.lang.RuntimeException: org.lwjgl.LWJGLException: No display mode extension is available
        at org.lwjgl.opengl.Display.<clinit>(Display.java:141) ~[lwjgl.jar:na]
        ... 7 common frames omitted
Caused by: org.lwjgl.LWJGLException: No display mode extension is available
        at org.lwjgl.opengl.LinuxDisplay.init(LinuxDisplay.java:724) ~[lwjgl.jar:na]
        at org.lwjgl.opengl.Display.<clinit>(Display.java:138) ~[lwjgl.jar:na]

```

App is running from cron using script

```
export DISPLAY=localhost:1.0
export XAUTHORITY=/home/ubuntu/.Xauthority
xauth add localhost:1 . 11111111111111111111111111111111
Xvfb :1 -screen 0 1024x768x16 -nolisten tcp
/home/username/start.sh

```

Most of steps above were adopted from here but I'm not sure I did it correctly. Any help would be appreciated!

# Answer
> -1 votes
I had a similar error when trying to run a LWJGL program remotely using VirtualGL. It can be reproduced with the GLGears demo from http://lwjgl.org/demos.php. For the test, I grabbed the files as follows:

```
wget http://lwjgl.org/webstart/{lwjgl_test,media}.jar
wget http://lwjgl.org/webstart/2.9.1/{lwjgl,lwjgl_util,jinput,native_linux}.jar
unzip native_linux.jar libjinput-linux64.so liblwjgl64.so

```

The command to run it over VGL:

```
vglrun java -Dorg.lwjgl.util.Debug=true \
    -Djava.library.path=$PWD \
    -cp $(echo *.jar | tr ' ' :) \
    org.lwjgl.test.opengl.Gears

```

This gives exactly the error you have:

```
Could not locate symbol glXEnumerateVideoDevicesNV
Could not locate symbol glXBindVideoCaptureDeviceNV
[LWJGL] Xrandr extension not available
[LWJGL] XF86VidMode extension not available
[LWJGL] No display mode extensions available
Exception in thread "main" java.lang.ExceptionInInitializerError
        at org.lwjgl.test.opengl.Gears.init(Gears.java:159)
        at org.lwjgl.test.opengl.Gears.execute(Gears.java:85)
        at org.lwjgl.test.opengl.Gears.main(Gears.java:76)
Caused by: java.lang.RuntimeException: org.lwjgl.LWJGLException: No display mode extension is available
        at org.lwjgl.opengl.Display.<clinit>(Display.java:141)
        ... 3 more
Caused by: org.lwjgl.LWJGLException: No display mode extension is available
        at org.lwjgl.opengl.LinuxDisplay.init(LinuxDisplay.java:724)
        at org.lwjgl.opengl.Display.<clinit>(Display.java:138)
        ... 3 more

```

The error comes from src/java/org/lwjgl/opengl/LinuxDisplay.java:199, it looks like it has something to do with mode extensions not being advertised by the X server:

```
private static int getBestDisplayModeExtension() {
    int result;
    if (isXrandrSupported()) {
        LWJGLUtil.log("Using Xrandr for display mode switching");
        result = XRANDR;
    } else if (isXF86VidModeSupported()) {
        LWJGLUtil.log("Using XF86VidMode for display mode switching");
        result = XF86VIDMODE;
    } else {
        LWJGLUtil.log("No display mode extensions available");
        result = NONE;
    }
    return result;
}

```

In my case, `ssh -Y user@host` instead of `ssh -X user@host` was enough to forward the RandR extension. Do this only if you trust the other host! According to this post, you can enable RandR for Xvfb with:

```
Xvfb +extension RANDR [further options]

```

---
Tags: opengl, lwjgl
---


# Question
Title: How can I scale a subset of my game view during rendering?
I am developing a 2d game which has a lateral panel and a main panel with the scenario. I want to scale the main scenario to apply a zoom (only the main panel portion of the screen).

I think if I use `SDL_SetRenderTarget` I will be able to change textures and then zoom it, in runtime. I have to use only SDL2 library or some extension. I can't use openGL.

How can I accomplish this?

# Answer
> 1 votes
What you should do is render to a texture (via render targets) and then draw the texture to the screen. Then take a portion of the texture and render it with in a rectangle somewhere on screen. (SDL\_RenderCopy lets you only draw a portion of the texture)

---
Tags: textures, sdl, scale
---


# Question
Title: How do I set which side of a mesh is visible?
I know little about 3D game development, but I'm trying to understand how to set what side of a mesh has the visible face. I am using *Wild Magic 5* and my object looks like this:

```
VertexFormat* ssVFormat = VertexFormat::Create(2,
    VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
    VertexFormat::AU_COLOR, VertexFormat::AT_FLOAT4, 0);
int ssVStride = ssVFormat->GetStride();

VertexBuffer* ssVBuffer = new0 VertexBuffer(8, ssVStride);
VertexBufferAccessor ssVba(ssVFormat, ssVBuffer);
Float4 ssColor(0.0f, 0.0f, 1.0f, 0.25f);
ssVba.Position<Float3>(0) = Float3(0.0f, 0.0f, 1.0f);
ssVba.Position<Float3>(1) = Float3(1.0f, 0.0f, 1.0f);
ssVba.Position<Float3>(2) = Float3(1.0f, 1.0f, 1.0f);
ssVba.Position<Float3>(3) = Float3(0.0f, 1.0f, 1.0f);
ssVba.Position<Float3>(4) = Float3(0.0f, 0.0f, 0.0f);
ssVba.Position<Float3>(5) = Float3(1.0f, 0.0f, 0.0f);
ssVba.Position<Float3>(6) = Float3(1.0f, 1.0f, 0.0f);
ssVba.Position<Float3>(7) = Float3(0.0f, 1.0f, 0.0f);
ssVba.Color<Float4>(0, 0) = ssColor;
ssVba.Color<Float4>(0, 1) = ssColor;
ssVba.Color<Float4>(0, 2) = ssColor;
ssVba.Color<Float4>(0, 3) = ssColor;

IndexBuffer* ssIBuffer = new0 IndexBuffer(12, sizeof(int));
int* indices = (int*)ssIBuffer->GetData();
indices[0] = 0; indices[1] = 1; indices[2] = 2;
indices[3] = 0; indices[4] = 2; indices[5] = 3;
indices[6] = 7; indices[7] = 4; indices[8] = 3;
indices[9] = 0; indices[10] = 4; indices[11] = 3;

TriMeshPtr mRectangle = new0 TriMesh(ssVFormat, ssVBuffer, ssIBuffer);
mRectangle->Update();

// Create a vertex color effect for the screen rectangle.
VertexColor4Effect* ssEffect = new0 VertexColor4Effect();
mRectangle->SetEffectInstance(ssEffect->CreateInstance());

return mRectangle;

```

How do I set what side is the visible face? Am I using the right terminology? I'm sure this engine can set it—I just don't know how.

# Answer
### Side determination is done using the direction the vertices are wound in "window-space."

Basically, that means after you project your geometry onto the image plane (window), you either shade the front or the back of a triangle. Which side is being shaded is determined by following the path the vertices that make up each triangle takes. Technically, it is much simpler than that... you can determine winding direction using something called the signed area test.

### Consider the equation for the area of a right triangle:

1/2 **Base** x **Height**

Ordinarily, **Base** and **Height** are assumed to be positive because in every day life negative lengths are meaningless. But if you include direction in either, suddenly and quite meaningfully, the area of a triangle can be either positive or negative.

### Visualization of Signed Area Test:

As you can see, triangles are always either arranged in a clockwise or counter-clockwise winding, and graphics APIs let you establish which one is supposed to represent the front. You must arrange your vertices according to this convention.

Likewise, APIs allow you to ***cull*** either the front or back (*or both, as silly as that sounds*) of polygons. So you need to define both the front-face orientation and the side(s) to cull before you can say which side of a polygon is going to be visible.
> 2 votes

---
Tags: 3d, rendering
---


title: vertex is bending inwards

text:
# Question
Title: vertex is bending inwards
I am trying to draw a picket fence, but the center of the picket vertex looks bent in the middle,

why is the picket bending inwards to the left?

```
// draw fence pickets
float a;
for (a=-25; a<=25; a+=0.256) {

    glBegin(GL_POLYGON);
    glColor3f(  1,  1,  1 );
    glVertex3f( a,       25, 0 );
    glVertex3f( a+0.128, 25, 0 );
    glVertex3f( a,       25, 1 );
    glVertex3f( a+0.128, 25, 1 );
    glEnd();

}

```

# Answer
Your vertices are in the wrong order. Try this:

```
glVertex3f( a,       25, 0 );
glVertex3f( a+0.128, 25, 0 );
glVertex3f( a+0.128, 25, 1 );
glVertex3f( a,       25, 1 );

```

Remember that the vertices have to be in the order you would find by tracing around the outline of the polygon counterclockwise. Your original order was cutting through the middle of the polygon.
> 2 votes

---
Tags: opengl, vertex
---


title: pixel art game looks like it is lagging

text:
# Question
Title: pixel art game looks like it is lagging
As you can see from the title, I'm working on a game using pixel art. To archive that, I create a 160x90 texture, draw everything onto that and scale it up. But the player in this game only moves about 10 pixels per second in some places. Luckily, the position isn't stored in pixels, but as a float, so the player can also be at (10.234, 3.76543). Because the map is big, the player is always centered on the screen and the world moves, instead. But as of my current implementation, I round the player's position to whole pixels in each update call. Otherwise, the engine would place all the world's sprites between the pyhsical pixels and they would be interpolated and look very unsharp and not very pixel-artish.

And there comes the problem: because the player moves just 10px/sec, the world only moves on the screen every 1/10 second. And that, of course looks like the game was running at 10 fps (it actually runs at 60fps).

So what is the recommended approach for that? Should I stick to what I current have got or should I let the graphic card do what it wants to do and let it interpolate the pixels and simply ignore the blurry effect.

PS: I know this question is *similar* but the difference is that in his case, he wants to avoid this staircase effect, while in my case, I want to avoid the lag

# Answer
> 3 votes
**Update**

The player does not see the games' framerates. The players see the amount of changes that happen on the screen per second (i.e. the amount of frames that are different from the frames before them per second).

There are some ways to increase this value from 10 to 30, 60 or 120.

1. Make the world a grid of rectangles (blocks of pixels) and make the motion itself in pixels which are fractions of blocks. The player will always stop in integral positions so the world aligns with the gui when the player stops but we'll slide when the player moves around.
2. Make the player's character animation more detailed, adding more frames so the player character itself will be changing when the player is moving (does not make sense to me but could work while keeping the world always aligned).
3. Add some animated things in the background and foreground that constantly move or flicker (stars, clouds and etc.) to keep the feel of animation.

If you are not adding something that moves with higher frequency or a different frequency at least then the game is not actually refreshing at a frequency greater than 0.1 seconds.

---

From what you are saying the game is in 160 X 90 but I'm sure the actual view could be in 800 x 450 for instance? Then you could maintain the "blocky" look and keep the image sharpness by simply drawing each pixel as a 5 x 5 rectangle and moving the world in steps of 0.2 instead of integral steps. This way you would get a feel of 50fps and will not get the blurriness you described.

You could also do something like deepnight often does in Ludum Dare where the pixels are actually replaced by large blocks to give a look reminiscent of 8-bit games on a CRT.

http://dl.dropboxusercontent.com/u/4952054/ludumdare20/postRelease/index.html

# Answer
> 1 votes
Move the player faster? If it already looks the way you want but the problem is that the movement is too slow, as you seem to say.

Also I think it is possible to disable interpolation in the drawing, we do that in our pixel art game. (using cocos2d-iphone which is OpenGL)

---
Tags: pixel-art
---