# Question
Title: How to know when a bullet has hit its destination in a game with a fixed timestep?
@James is wording my question better than I am, so I figured I'd put this here:

> I believe what you are asking is that you have a bullet moving in a game with a fixed timestep and that when the bullet collides with something, the time step usually makes the bullet go Past where it would have actually hit making it look like the bullets hit some where beyond where it actually hit.

---

I'm shooting a projectile in a 2D topdown game. The unit can shoot in 360 direction. There's no gravity, there's no arc and it moves at a constant speed (although this last point may change in the future). It's easy to find the point of the unit and the destination of the bullet, but how do I know when the bullet has hit it's destination?

I'll be more specific. The bullet probably won't land directly on the point it was intended to because it moves a certain distance based on the delta of time. The bullet will often be in a state where it will overshoot the destination on the next tick.

How do games usually handle this? I can imagine pros and cons to "always overshoot" and "always undershoot".

# Answer
Correct me if I am wrong, but I believe what you are asking is that you have a bullet moving in a game with a fixed timestep and that when the bullet collides with something, the time step usually makes the bullet go Past where it would have actually hit making it look like the bullets hit some where beyond where it actually hit.

Assuming that is correct, this is quite easy to fix then. All you have to do is move the bullet back to where it actually hit instead of leaving where the timestep would have placed it if the path had been unobstructed. There might be easier ways to accomplish this but basically what you are looking for is where the line the bullet is traveling down intersects the 'face' of whatever it hit.. IE: You want to find out where your ray intersects the line of the object it collided with.

Note that this is a calculation that should only be done after the impact has been confirmed.
> 3 votes

# Answer
There is several ways to choose from when designing Collission detection/response in a game. (The simplest way would be to use a physics-engine which someone else has already developed, there are some free and som which cost but they all should be pretty easy to find on google) Since the question is not specific as to which types of collissions it is about i will provide "The big picture" of a solution.

The problem you are refering to is often referred to as "Bullet through paper" and is probably the most annoying thing when developing games and gets exponentially more difficult to solve relative to the complexity of a physics engine if you are going for precision.

However...

There are some simple solutions which are not precise but still look real since the artifacts are to small or quick to notice.

You can either do so called "Swept-testing" which means that you interpolate between start and destination of all the objects involved in the potential collission but this will get more and more complicated depending on if both objects are dynamic and/or rotating.

A simpler solution is to simply cut the movement into several smaller steps and check each step for collissions.

Lets say you have a circle which is about to collide with a line-segment but as you said the circle moves into and even beyond the line within a single frame. Then you just create find the direction-vector of the movement and multiply with the circles diameter and check for a new collission on each interval until you have reached the final position.

I think this should be enough information for you to get started on finding further information on the subject.
> 1 votes

---
Tags: projectile-physics
---


# Question
Title: no custom background - touchdragged method?
I am beginner in libgdx and trying to experiment .I am using the simple example here .So, I have 2 questions:

1) I want to use my background picture.So, I have a class Assets where I have all the assets.And I use:

```
public static void load () {
        background = loadTexture("background.png");
        backgroundRegion = new TextureRegion(background, 0, 0, 800, 480);

        ...
        dropImage = new Texture(Gdx.files.internal("droplet.png"));
        ...

```

In GameScreen class:

```
public class GameScreen implements Screen {
....
public GameScreen (Game game) {
        this.game = game;

   // create the camera and the SpriteBatch
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 800, 480);
        batch = new SpriteBatch();

     // create a Rectangle to logically represent the bucket
          bucket = new Rectangle();
....
public void draw (float deltaTime) {
         // Gdx.gl.glClearColor(0, 0, 0.2f, 1);
          Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

          // tell the camera to update its matrices.
          camera.update();

          batch.setProjectionMatrix(camera.combined);

          // begin a new batch and draw the bucket and all drops
          batch.begin();
...

```

The problem is that the background doesn't appear (I have it in assets folder as the other files and it is 800x480 pixels).

2) Using

```
if(Gdx.input.isTouched()) {
             Vector3 touchPos = new Vector3();
             touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);

```

the bucket appears where i press the screen. If I want to make bucket movement smooth,to drug it, I realize that I must use event handling and inputprocessor as here.

But I can't find a way to make it work. I mean , I must create a class MyInputProcessor like the above , then at my drop class (main class) do :

```
public class Drop extends Game {
   @Override
   public void create() {

            Settings.load();
        Assets.load();

        MyInputProcessor inputProcessor = new MyInputProcessor();
        Gdx.input.setInputProcessor(inputProcessor);

        setScreen(new GameScreen(this));

```

and then? How should I use it?

Right now I have in GameScreen class:

```
public void draw (float deltaTime) {
         // Gdx.gl.glClearColor(0, 0, 0.2f, 1);
          Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
         ...

          // process user input
          if(Gdx.input.isTouched()) {
             Vector3 touchPos = new Vector3();
             touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
             camera.unproject(touchPos);
             bucket.x = touchPos.x - 64 / 2;
             bucket.y = touchPos.y - 64 / 2;
          }

```

Also , the MyInputProcessor gives

> "The type MyInputProcessor must implement the inherited abstract method InputProcessor.mouseMoved(int, int)"

and at touchMoved

> The method touchMoved(int, int) of type MyInputProcessor must override or implement a supertype method

I want to use

> touchDragged

inside GameScreen class?or in MyInputProcessor?How should I do it?

Thank you!

-----------------------UPDATE----------------------------------------------

```
import com.badlogic.drop.GameScreen;
public class MyInputProcessor implements InputProcessor {

    GameScreen fromgamescreen;

    private Vector3 v = new Vector3(0,0,0);
...
@Override
        public boolean touchDragged(int screenX, int screenY, int pointer) {
           v.x = screenX;
           v.y = screenY;
           fromgamescreen.camera.unproject(v);
           fromgamescreen.bucket.x = v.x - 64 / 2;
           fromgamescreen.bucket.y = v.y - 64 / 2;
           return true;

       }

```

# Answer
> 1 votes
1) In the draw method, you need to call `batch.draw(backgroundRegion,x,y);` to draw the background. Call it after beginning the batch, but before drawing the drops and the bucket.

2) To get rid of the two warnings, change `touchMoved` to `mouseMoved`.

Polling, rather than event-based input handling, is probably adequate for your game. However, if you want to use an InputProcessor, you would get rid of this code:

```
if(Gdx.input.isTouched()) {
             Vector3 touchPos = new Vector3();
             touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
             camera.unproject(touchPos);
             bucket.x = touchPos.x - 64 / 2;
             bucket.y = touchPos.y - 64 / 2;
          }

```

and in the input processor, you would have something like:

```
    private Vector3 v = new Vector3(0,0,0);
    //you don't want to recreate this vector every time an event comes in: that wastes memory
    ...
    public boolean touchDragged(int screenX, int screenY, int pointer) {
            v.x = screenX;
            v.y = screenY;
            camera.unproject(v);
            bucket.x = v.x - 64 / 2;
            bucket.y = v.y - 64 / 2;
            return true;
        }

```

To do it this way, the input processor would need references to the camera and bucket.

---
Tags: android, libgdx
---


title: XNA PC vs Monogame Online Multiplayer

text:
# Question
Title: XNA PC vs Monogame Online Multiplayer
I've got a mostly working PC game in XNA 4, and am looking to make it networked. From the documentation it seems that I can use XNA Networking through GFWL to do LAN sessions, but not online sessions (without each account paying microsoft a bucket of cash...). I started poking around and found MonoGame, but their documentation is kinda scattered. They have a peer to peer sample, but I'd like to know if this translates to the ability to find online sessions before I get started porting my game.

# Answer
> 0 votes
You shouldn't be doing networking through XNA or Monogame.

Use C# / .net's built in System.Net code.

Specifically, sockets... just google "C# .net sockets client-server example" or similar things, and start learning how sockets work. Make an online chat room or something to practice... when you got it down, you can directly move your code over to your XNA or Mono project.

---
Tags: xna, xna-4.0, networking, monogame
---


# Question
Title: Generating a physics body for 2D Worms-like Terrain
I wrote a processing sketch that generates hills for a scorched earth clone, like this:

I'm trying to figure out how to make this a physics object in libgdx, but I'm having problems figuring out how to do that.

I thinking about doing this through a `ChainShape` composed of a `vector2` array at each point on the slope. I've tried running this on an android device through a `Box2DDebugRenderer` and `SpriteBatch`, but I can't get anything to show up (although that's another problem).

Does anyone know how to make a physics object like this in box2d?

# Answer
From the documentation on the Box2D site:

> # Worms Clones
>
> Making a worms clone requires arbitrarily destructible terrain. This is beyond the scope of Box2D, so you will have to figure out how to do this on your own.

So you're on your own for building a new terrain when the old one gets a large crater blown into it. I think, following the questions I linked in my comment (How can I generate Worms-style terrain? and How can I convert a 2D bitmap (Used for terrain) to a 2D polygon mesh for collision?), you'll be able to create the terrain and then create a custom polygon shape. The shapes must be convex, so you'll have to break the terrain into smaller convex shapes if the other all shape includes concave portions (like craters, tunnels, etc.).

There's a tutorial here that shows the creation of these shapes. Essentially, you're creating a polygon using a definition object, then passing that definition into `m_world.CreateBody(...)`.
> 3 votes

---
Tags: 2d, box2d, libgdx, terrain-rendering
---


# Question
Title: What is the impact of many AI enemies on state replication networking?
Imagine an online coop style FPS or TDS game where say 2-6 real players fought large amounts (20-60 concurrent) of AI enemies. Could this style of game be reasonably networked over the internet using a Quake or Tribes style partial state replication model? Almost every coop game I know of uses a lockstep style networking in these cases (even games like Halo which use state replication for normal multiplayer, but lockstep for coop/firefight). My concern is that the network download (for clients) and upload (for server) overhead of each AI would end up being about the same as if a real player was in the game. Is this a real concern? Or is the limiting factor on the number of players more about how much data the players upload?

**TLDR;** Can large numbers of AIs be reasonably networked to a few players with a partial state replication model or is lockstep the only real solution.

Any help here would be great!

# Answer
Yes, online games with a large number of artificially intelligent agents is more than plausible.

When using a client-server model, the server runs a master copy of the game simulation, and the clients run their own copy if you are using client-side prediction.

Starsiege: Tribes was able was able to handle 128 human or AI players... in 1998.

> The multiplayer mode supports up to 128 human or AI controlled players in a single game. Performance over the Internet drove the design of the networking model. The model supports low end modem connections and is designed to deal with low bandwidth, high latency and intermittent packet loss.

Source

You can treat AI players just like networked players, with one large benefit - since they live on the server, they don't need to be sent any data which saves the server's bandwidth.

For a game that features many agents running around in an online open world, see Running with Rifles.
> 3 votes

---
Tags: networking, udp
---


# Question
Title: How to handle zooming? (Collision detection and speed are off)
I'm working on a bird's eye view 2D game. I want to zoom in/out based on the entity's speed (similar to GTA 1/2), but I'm struggling with the zooming.

To zoom, I simply scale all the entities by the zoom factor. One problem is that the hit tests are off (still happening with the smaller entities). The other problem is that the object is effectively moving slower (travelling a smaller distance when zoomed in, a larger one when zoomed out).

The only fix I can come up with is to scale all bounding boxes (used in collision detection) as well, and to adjust the speed based on the zoom factor. But that seems wasteful and complex (especially since I'm determining the zoom factor based on the speed).

Is there a better way?

# Answer
> 2 votes
Scaling just the entities won't work. One of the obvious reasons are that you won't scale the distances between them. What you need is a camera concept.

I suppose you are making the game from the scratch, no engine. You will need to implement a position transformation that will happen for every entity just before it gets rendered. E.g. if your rectangular entity is 100x100 pixels big, center of you screen is at \[0, 0\] and the center of the entity is at \[-50,-50\] (top right corner of the entity is in the center of the screen) then before rendering with zoom factor 2, scale it to 200x200, and position it to \[-100, -100\]. Same with every other position and vector in the game.

Note that this is a very naive approach. I believe modern 2D engines use 3D ortogonal projection. The 3D library (OpenGL, Direct X) and the hardware then take care of the scaling.

---
Tags: 2d, collision-detection, graphics, scale
---


title: Formula throwing a ball to destination

text:
# Question
Title: Formula throwing a ball to destination
I am throwing a ball using this:

```
        double v, vx, vy, alpha, t2 = 0;
   if (Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            alpha = MathHelper.ToRadians(60f);
            v = -1230d;
            vy = v * Math.Sin(alpha);
            vx = v * Math.Cos(alpha);

            ball2pos.Y = (float)((vy * t2) + (g * t2 * t2 / 2)) +  graphics.GraphicsDevice.Viewport.Height - ball2.Height;
            ball2pos.X = (float)(-vx * t2);
            t2 = t2 + gameTime.ElapsedGameTime.TotalSeconds; }

```

It works without a problem. It calculates the throw including the gravitation (g). vx is how much it moves per second on the X,vY the Y accelerration (running against gravity), v the strength of the throw and t2 the current time.

But I want to change the formula to throw the ball to a given destination. Say I want to throw my ball from 60 degrees to a target. How much "strength" do I need for it?

What would be the formula? I'm not really good at figuring out that and google doesn't give me what I want. To simplify let's assume that the Y of source and target are the same:

Given: Angle, SourceLocation, TargetLocation, Gravitation

Looking for: Strength

# Answer
> 1 votes
If you have good mathematical abilities, then you can write out the equations for the balls position, substitute the vy and vx with v * cos or sin alpha, and try and solve it on a piece of paper, using simple symbols/letters to represent each variable to remove the clutter and messiness. Then after solving it for v (and subsequently t as well), you can put all the icings back on.

Sorry for this short answer, I might get back on this later.

---
Tags: xna, c#, 2d, physics
---


# Question
Title: How I support different display resolutions?
I'm developing a 2D windows phone game. The game should look the same on every windows phone device. But I have no idea what to do so that my game looks great on every display resolution. How can I do that? What is the best/easiest way?

I don't like letterboxing. So I tried scaling the sprites but that looks blurry(very bad). My sprites are all in PNG format. I created them in Inkscape.

# Answer
> 1 votes
The recommended way seems to be scaling the sprites. You can create alternate images to handle differing resolutions and load them depending on the screen's resolution.

MSDN Article

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: MMORPG Entitiy handling on different maps
**Is this a good approach for a MMORPG entity handling on different maps?**

---

***Map Structure and entity existece:***

A map is basically a parent node in a scene graph. There's one map for each town, room etc. In each of these maps the entities or actors (split up into localplayer/NPC/remoteplayer) exist with their own coordinates in respect to map size. Each map has it's own position in worldmap, it's id and it's own update() method which calls update() on each entity.

---

***Server:***

Server has 2 Hashmaps with key being map\_Id and value being according map reference. One is a pool for every map possible, the other one is currently active (or populated) maps. Also an eventqueue is available containing 2 queues, one for current events and one for new events resulting from current event processing. Events are collected in between ticks by a event fetcher thread accepting incoming events from remote (inbox) and are distributed by a extra event distributor thread (outbox).

Each tick/render server processes the eventqueue and given a actorupdate event calls update() on each affected map (calling update() on every entity). Before/while this processing happens each relevant event in inbox is being distributed to each relevant client. Relevant means the event is of interest to the particular client (e.g. events concerning actors on map1, each client on map1 is then relevant) and the event was not sent by receiver client itself. Each n-ticks sanity check is sent to all clients.

---

***Client***

Client stores current map and possible new map preloaded in reference (if player is in transition zone). Events are processed similar to server but include local only events like AnimationStarted and a event fetcher thread saves all incoming events from server in an inbox.

Each tick the inbox is being put in local current eventqueue, local built server relevant events like ActorMove are being send to the server and all events are being processed just like server does with 2 queues putting new queue into current queue etc. Regardless of own latency client will at some point in time have the sanity check in inbox and must process it.

---

# Answer
**TLDR: To answer your question, if implemented properly, this *does* work to a certain degree.**

I'm using almost exactly the same system for my multiplayer rpg. Entities are part of a hashmap of objects contained within the "World" and each is also in a hashmap within each "Zone." I can call zone.getEntity(ID) or world.getEntity(ID) or zone.sendToAllEntities or world.sendToAllEntities.

This allows for relative locations within the world and zones are relative to each other. Zones could overlap or have large amounts of space between their "locations" but the players would never know this because zones are connected to other zones and not the world.

In each update tick on the server, the world calls foreach zone.update, which calls foreach entity.update, and on the client side, the client will call myzone.update -\> foreach entity.update (for client prediction) and myzone.render -\> foreach entity.render

As "zones" are needed, they are loaded from file and stored in a hashmap if they aren't used within 20-30 minutes, the zone is unloaded (and saved, along with all of the zone's objects).

I'm not so sure this would work in a "massive" situation, as I've only tested with ~50 clients, but I'm sure batches of zones could be run in their own server instance with the proper implementation.

Please excuse my long-drawn out rambling, as I'm sure it seems I've done and feel free to ask any further questions you might have.
> 1 votes

---
Tags: mmo, entities
---


# Question
Title: What is the interval of fragment-shader code execution?
Without any intended delay, is the code of a fragment-shader run once per frame? If not, how often will the code be executed? (I'm new to shaders: I'm talking about glsl if it makes any difference)

# Answer
After you bind your program (2 shaders) with `useProgram` function, shaders are run at every `drawElements` or `drawArrays` call.

You can call those functions at every frame, 1000 times per frame, or once an hour.

You can also examine the "work at the server" during the single `drawElements` call. Vertex (or fragment) shader should be run for every vertex (or fragment). It is usually done on massively parallel hardware systems with many cores. Tens, hundreds or even thousands of instances of the shader program can run at the same time. And those systems are in our pockets! :)
> 4 votes

---
Tags: glsl, performance, fragment-shader
---


# Question
Title: Drawing different per-pixel data on the screen
I want to draw different per-pixel data on the screen, where each pixel has a specific value according to my needs. An example may be a random noise pattern where each pixel is randomly generated.

I'm not sure what is the correct and fastest way to do this. Locking a texture/surface and manipulating the raw pixel data? How is this done in modern graphics programming?

I'm currently trying to do this in Pygame but realized I will face the same problem if I go for C/SDL or OpenGL/DirectX.

# Answer
> 2 votes
> I'm not sure what is the correct and fastest way to do this. Locking a texture/surface and manipulating the raw pixel data? How is this done in modern graphics programming?

If this is something to recompute each frame, if the only input you need is the pixels position, and if you only need to output this directly to the screen, I suppose the modern and fastest way to to this is to simply use a pixel shader on the GPU. Render a full-screen quad with your favorite engine, with a pixel shader that computes a color from the pixel's position. This is similar to doing a full-screen post-process.

If you only need to recompute this one in a while, or if you need to output to something else than the screen, you could render to a texture for later use.

If you need more inputs than simply a pixel's position, you'll have to find a way to pass this info to your pixel shader. You can use uniforms, textures etc. for this purpose.

There are cases where you *could* use the CPU for the sake of simplicity. It will be easier to handle inputs/outputs, and you could save some texture copying time in some cases, but you'll need to workaround the fact that CPUs aren't really made to work on arrays of pixels. To avoid hiccups, you'll have to do it during a loading time, on a different thread, or even offline.

---
Tags: performance, pixel
---


# Question
Title: Painter algorithm on transparant objects
Why do you have to use the painter's algorithm when drawing transparant objects ? Can't you just use a z-buffer, draw all non transparant/opaque objects, then draw all transparant/opaque objects last?

Sorry if it is a stupid question, but i guess it's something all beginners run in to.

# Answer
> 3 votes
You can ignore ordering but only with additive blending (common in many particle systems).

With "normal" multiplicative blending, ordering is important. The color buffer accumulates colors. New translucency effects are blended using a source alpha and the inverse of that source alpha. That is, given current color `A` and source color `B` with source alpha `C`, the final color `D` is found using `D=A*(1-C)+B*C`.

If you're looking at a single component, say the color buffer has value 100, trying to blend in value 50 at 10% then value 100 at 30%. You get `100*.9 + 50*.1 = 95`, then you get `95*.7+100*.3 = 96.5`.

Swap the order of the blends. Now you get `100*.7 + 100*.3 = 100`, then `100*.9 + 50*.1 = 95`.

Two different final color values based on the order they're applied in. Hence, order is important if you are aiming for the "standard" blending equation which "looks right."

---
Tags: c++, algorithm, directx11, draw-order
---


# Question
Title: XNA 4.0 - Why does using a RenderTarget2d cause transparency on models?
I have been working through Riemers ShadowMap tutorial and everything was going well until the section on drawing to a separate rendertarget. I am using a different model and quads but I assumed the process would still work.

If I draw the scene directly to the back buffer I get:

When I draw it first to a RenderTarget2D and THEN to the screen, I get this weird transparent effect only on the model, the textured primitives below are still rendered fine:

The RenderTarget is defined:

```
PresentationParameters pp = device.PresentationParameters;
renderTarget = new RenderTarget2D(device, pp.BackBufferWidth,
           pp.BackBufferHeight, true, device.DisplayMode.Format, DepthFormat.Depth24);

```

And it is used in this way:

```
protected override void Draw(GameTime gameTime)
{
    device.SetRenderTarget(renderTarget);

    device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

    DrawScene("Simplest");

    device.SetRenderTarget(null);
    shadowMap = (Texture2D)renderTarget;

    device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
    using (SpriteBatch sb = new SpriteBatch(device))
    {
        sb.Begin();
        sb.Draw(shadowMap, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 1);
        sb.End();

    }
    base.Draw(gameTime);
}

```

What gives?

Edit 1: I resolved the transparency effect by resetting:

```
device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;

```

But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.

Edit 2: Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency. Fixed with:

```
sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

```

# Answer
> 0 votes
Worked it out:

```
device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;

```

But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.

Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency. Fixed with:

```
sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

```

---
Tags: xna, models, alpha
---


title: Generate equal regions in a hex map

text:
# Question
Title: Generate equal regions in a hex map
Taking for example a large (X by Y) hex map, how can I divide it into N regions of connected hexes to simulate countries?

The goal is to generate a hex map that looks like a real life map with countries with different shapes but equal sizes.

# Answer
> 13 votes
Have you tried Lloyd's Algorithm? The procedure is pretty simple, and will generate fairly regular looking regions (depending on how many iterations you run).

1. Tile the map with blank hexes to start.
2. Choose *N* hexes at random. These will represent the "center of mass" for each country.
3. Tag each hex with the center hex it is closest to (Voronoi Diagram). Country *i* is the set of all hexes closest to the *i'th* center hex.
4. Compute the new center of mass for each country.
5. Repeat steps 3 and 4 as many times as you want to smooth out the generated regions.

You don't have to run it very long to produce a nice looking map. This example required only three iterations.

# Answer
> 3 votes
One simple way you could try.

1. Randomly select `n` hexes. Each one will start a group.
2. For each group try to expand the initial hex in a random direction.
3. If all hexes around the chosen hex are occupied, mark as tapped, change hex.
4. Repeat until each group is 20 hex long or have no more space to expand (all hexes tapped).

I didn't test but this should generate Islands and somewhat avoid long thin braces. Also, Most likely there will be neighbors borders but not necessarily each one will be in touch of other, that density will depend on the value of `n`.
Some groups also might be cornered by others and reach less than 20 size, you can assure grown space by spawning the starter hexes at a minimum distance of each other.
Test and tweak as needed.
Also, not related with this problem but very, very useful to working with hexes, visit this page: http://www.redblobgames.com/grids/hexagons/#basics
It aggregates a whole bunch of hex info in a single place with a nice visual.

# Answer
> 2 votes
I definitely think some type of graph structure would make this possible. Basically create an edge between two Hex nodes if they are next to each other to simulate the whole map. However, I am not sure the exact algorithm for generating a "country" within that map. The thing is, depending on how you want the country to "look" you would need different algorithms.

Off the top of my head, I would recommend picking a point and moving outwards from there, picking a random tile within your "growing country" which has an adjacent tile that is not part of the country.

A strategy pattern could be used to switch out algorithms depending on what type of country look you want. http://en.wikipedia.org/wiki/Strategy\_pattern i.e. do you want a slim coastline country like chile? Or do you want something that is more round and contained?

Graph properties may also allow you to tweak what you want the end "country" to look like: http://en.wikipedia.org/wiki/Eccentricity\_(graph\_theory)

Want a large country? Tweak the graph properties and force the generated country (which is just a graph) to have the properties that give it a "look" you will want.

Last but not least, Graphs will also be very useful for defining borders between countries. You could build a graph that has a connection between two nodes if countries border each other. This might be useful for some type of partitioning in your game and will allow you to possibly optimize certain things further along in development.

# Answer
> 2 votes
One small note: you say 'looks like a real life map with countries of different shapes but equal sizes), but 'real' countries are vastly different in size even within certain regions — even the 'large' countries of Europe can vary hugely, with e.g. France being more than twice as large as Italy. With that said, there are obviously gameplay regions to try and keep sizes roughly the same - just be aware that a little variation here is probably a *good* thing!

My initial approach to the problem would be to 'evolve' (rather than 'grow') your regions:

* Start with some concrete division of the map into roughly equal-sized chunks by straight lines (for instance, if you wanted 6 countries, then you might divide the map into three horizontal slices, and then split each of those slices 'on the diagonal' into two pieces). This is obviously easy to do programmatically, especially since it doesn't have to be very exact (in fact, probably shouldn't be very exact).
* Do an initial pass on the division, building a 'boundary' data structure: a set of hexes which have some neighbor currently belonging to a different country. This would also be a good time to tally a count of how many hexes are in each country.

Now, for as long as you want, run the following pseudocode:

```
Pick a random hex A from the boundary list;
Pick a random neighbor B of this hex from a different country;
if (A's country has more hexes than B's country has) {
  change hex A to belong to B's country;
} else if (B's country has more hexes than A's country has) {
  change hex B to belong to A's country;
} else {
  flip a coin to decide which to change;
}
if ( the changed hex's old country has become disconnected ) {
  undo and reject this move;
} else {
  update the boundary list around the changed hex and its neighbors;
}

```

This will maintain a rough balance between the size of any two neighboring countries, and the 'disconnected' check (which can be done with a simple flood-fill algorithm) makes sure that no country ever breaks apart into pieces. Updating the boundary list is a constant-time operation - the changed hex will obviously always still be on the boundary, and you can just check its six neighbors to see if any of them has either become a boundary cell (because its neighbor is now in a different country) or stopped being a boundary cell (because its neighbor's in the same country now), modifying the boundary set as needed.

For a refinement of this approach, you can even make the condition of which hex to change a bit randomized - rather than always 'balancing' the two countries, you can always make the swap with a certain probability, and even gradually diminish that probability over time (similar to the cooling process in a Simulated Annealing algorithm) to start to force them to be roughly the same size.

Note that this won't guarantee that all areas are exactly the same size (which is impossible unless N perfectly divides your grid size anyway), and it won't even guarantee that all countries are within one hex of each other in area; it *should* guarantee (run for enough iterations) that each country is no more than one hex larger or smaller than each of its immediate neighbors, though.

---
Tags: mathematics, maps, hexagonal-grid
---


# Question
Title: Seamless tiling with TexturePacker and Marmalade/IwGX
I'm looking for a way to get seamless tiling working, where the tiles are sprites off a TexturePacker sprite sheet, and the rendering is done with Marmalade's IwGX's streams. I also need to render the tiles in multiple scales at the same time.

Even with TP settings "reduce border artifacts: off" and "inner padding: 0", there are very noticeable, pixel-wide gaps between the tiles. If I move the tiles close together, they look fine at a scale of 1, but anything smaller or larger yields gaps.

If I use one tile per texture, I get no gaps, but it means that I either can't have a variety, or each tile will take one draw call + material switching, which is not only slow, but brings the gaps back.

Any tips?

# Answer
Setting "extrude: 1" in TexturePacker, then `CIwMaterial::ALPHA_NONE`/`DEFAULT` for the alpha mode of the material that the sprites are rendered off, solves the problem.
> 2 votes

---
Tags: rendering, tiles, marmalade, texture-atlas
---


# Question
Title: What are the benefits of using a game engine to build a voxel game?
I'm learning and developing a game like *"Minecraft"*. I've seen many games being made without a game engine, so I'm worried that using a game engine will lead to performance issues.

If I was developing a game with many static objects, the game engine would be helping me a lot. However, in a game where all meshes are generated by code, how would a game engine help me? Regardless of whether I use it or not, I'll have to build a voxel engine, because no game engines come with that functionality.

I know it does some optimizations, like Frustum culling, but I don't know if I should continue using it, or build my own voxel engine. This questions is not about any specific game engine or programming language; just how a general game engine would be useful, when creating a voxel game.

# Answer
There are many more things to the game that will be taken care of by a game engine than just the management of meshes. Control input, sounds, lighting, GUI, meshes other than the terrain, camera, etc.

So the benefit of using an engine comes from all the other features it provides. If you're going to be writing a voxel engine anyway, might as well have everything else taken care of as well.
> 6 votes

# Answer
Using a game engine will simplify your task significantly. If you want a tutorial go here: https://sites.google.com/site/letsmakeavoxelengine/

If you're worried about performance the dont use java.

Dont worry about performance at first. Just get something to work then you can worry about optimizing it.
> -2 votes

---
Tags: voxels
---


# Question
Title: How can I use triangle picking to determine location of a triangle in world space coordinates?
I am trying to implement point and click movement in my game, but at the moment I am stumped about how I can select parts of a mesh for the player to walk to.

So what I have done is I have got a navigational mesh in my game. I can select points from it but what I want to do is be able to select the navigational mesh in real time and be able to tell the player where to go on the navigational Mesh, how can I achieve this?

I thought triangle-picking might be one way to determine which mesh I am selecting with mouse-unproject but I think I need a bit more accuracy than that, no?

How can I achieve point and click on a navigational mesh in real time?

# Answer
> 1 votes
If you use triangle picking, you only need to solve for a line/plane intersection test to find the point on the triangle that you clicked on.

Use the raycast as your line and treat the triangle as a plane.

# Answer
> 0 votes
In theory your navigation mesh should be fairly sparse with a few big triangles. Ray/triangle intersection is also fairly fast if you don't have many triangles. The best approach is likely to simply fire a ray from the camera through the cursor and see if it intersects any of the triangles from your nav-mesh, and if so, tell the player to move there.

---
Tags: xna, c#, movement, path-finding, navmesh
---


# Question
Title: Rotating each quad in a batch separately?
**Background**

In my app I use the following code to rotate my quad:

**Code**

```
    //Rotate the quad

Matrix.setIdentityM(mRotationMatrix, 0);
Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

```

And then apply the matrices:

```
// Combine the rotation matrix with the projection and camera view
Matrix.multiplyMM(mvpMatrix2, 0, mvpMatrix, 0,  mRotationMatrix, 0);
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(iProgId, "uMVPMatrix");
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix2, 0);

```

The above code works great when I'm drawing single quads.

**Problem**

However, if I have a few quads with the same texture to draw, I batch them up and draw them with one call to `glDrawArrays`.

I can't work out if it is possible to rotate each individual quad *before* drawing them (or how to do it if it is possible) - I realise, they will all be rotated the same amount at the same time but this isn't an issue).

**Rotation method**

```
public void rotateBatchQuads(int[] coordinates, int angle){

    for (x=0;x<coordinates.length;x+=2){

        //Center of quad (Along the x)
        float centreX = coordinates[x]+quadWidth/2;  //Pseudo code
        float centreY = coordinates[x+1]+quadHeight/2 //Pseudo code
        //Center of quad (Along the y)

        //Rotate the quad
        Matrix.setIdentityM(mRotationMatrix, 0);
        Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
        Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
        Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);
    }
}

```

# Answer
You can rotate the vertices before copying them into a vertex buffer. Something like:

```
batch = vertex[SIZE]
vbo = gl.CreateBuffer(SIZE * sizeof(vertex))
default_quad = { (-1,-1), (-1,1), (1,1), (1,-1) }
transformed_vertices = vertex[4]

draw(sprites)
{
  for each sprite in sprites
  {
    matrix = sprite.CalculateModelWorldMatrix()
    matrix.ApplyTo(default_quad_vertices, transformed_vertices)
    batch.Append(transformed_vertices)

    if batch.IsFull
    {
      gl.BufferData(vbo, batch)
      gl.Draw(vbo)
      batch.Clear()
    }
  }

  if not batch.IsEmpty
  {
    gl.BufferData(vbo, batch)
    gl.Draw(vbo)
    batch.Clear()
  }
}

```

Multiply the standard quad vertices by the sprite's model-world matrix in your CPU code then append them to an array. Copy the array to your VBO. Draw. Give the shader just the world-view (camera) and view-projection matrices (as your vertices will have already been transformed to world space so the GPU has no use for a model-world matrix).

Applying the transform simply means to multiply each vertex of a quad with the sprite's model-view matrix on the CPU. Each sprite can have a completely different transform, there's no need for all rendered sprites to have the same rotation (or scale or position).

Note that in this approach, you should NOT create a new array of vertices for your batch or a new VBO each frame. Create these once and cache them. Creating them again wastes processing time and produces excess garbage for the GC. Create them once at a reasonable size and reuse them. Never ever allocate (create new objects) inside your rendering loop unless you literally can't avoid it. If you end up with too many quads to fit into the sizes you chose, you can process the quads in chunks. e.g. if your buffer can only hold 100 quads and you have 120 of them, draw 100 quads in one batch and the remaining 20 in a second batch.

Once GLES 3.0 is available on all your target platforms and hardware you should look into *instancing* which is a more efficient way of doing the above on the hardware. With instancing you can create a buffer filled with the transformation matrices of `X` quads into a buffer (or even the raw position/rotation/scale data used to compute the matrix) and then ask the GPU to draw a generic quad `X` number of times using that buffer as input data for each individual instance.
> 2 votes

# Answer
You can also use an array of uniform matrices and draw in groups based on the number of uniform matrices you are able to store in the GLSL shader.

You will hit uniform limits fairly quickly with this approach.
> 0 votes

# Answer
In this case you'd consider multiplying each quad's base position by your mRotationMatrix on the CPU, then loading the result into a dynamic VBO for drawing. That's a clear tradeoff - the overhead of CPU-side matrix multiplications, together with the overhead of having to transfer the quad data each frame, and that together with the fact that dynamic VBOs just aren't going to be as fast as static would mean that you may or may not come out on the right side of it being faster versus a single draw call per quad.

Another option for you is to rebuild the rotation matrix in your vertex shader from 3 extra input attributes (centerX, centerY, angle); if you can simplify this well enough it may turn out to be the fastest option of all.
> 0 votes

---
Tags: android, rotation, opengl-es2
---


# Question
Title: small independent game development on a virtual machine
I've been learning about OpenGL and SFML with c++ now for about 6-8 months, and would like to work on a small little personal game to put some of my skills to the test.

Now I want to kill two birds with one stone, and also increase my knowledge of Ubuntu and linux development in general by developing this project in Ubuntu. Currently my main computer runs Windows 7 while I have an older computer than runs Fedora 18, so I set up an ubuntu 12.04 LTS virtual machine on my main computer. The problem is, what effects does this have graphics wise? I know windows virtual machines running games can often have some graphical and input bugs, should I not use a virtual machine? Or this fine and I'm simply over thinking the subject? Thanks!

Note\**

I am using VM VirtualBox on my windows 7 desktop.

# Answer
> 4 votes
So long as you are fine sticking to the version of GL provided by VirtualBox Guest Additions you should be okay. Performance will be a worse than native but even professional-grade GL apps and games can work quite well inside a VirtualBox VM. I'm been led to believe that VMWare Player has better GL support for guests but I have not personally compared them. I would try both, see which one works better for you (of if they work at all).

Short version: just try it and see.

---
Tags: opengl, c++, sfml, linux
---


# Question
Title: Full-screen post-processing and texture size
I am newbie writing a post-processing code for mobile devices, and asking some trivial, conventional solution for a specific problem.

AFAIK, post-processing in OpenGL is trivially done with FBO bound to a texture. Anyway, target screen size is usually not square and non-POT(power-of-two) numbers, while texture size needs to be the POT numbers. For example, iPhone 4 screen size is 640x960 pixels. Because all textures need to be POT sized, texture size for post-processing should be 1024x1024 to cover all the pixels. But in this case, over half of the pixels are just *wasted*. It really feels bad to me. Because simply wasted amount is huge.

Of course I can use smaller 512x512 texture if the post-processing doesn't need to be pixel-perfect. But still, I waste large portions of memory if I keep aspect-ratio. I can fill the texture by adjusting aspect-ratio, but in this case, we need to adjust fragment shader algorithms to get correct result.

Here're my questions.

1. If I need pixel-perfect post-processing, should I use larger texture which wasting large portion of it? Is this trivial? Or is there better solution? (For example, binding multiple small texture patches to a FBO.)
2. If I use smaller texture, what is trivial method to handle the aspect-ratio issue? Just use only small portion of the texture keeping aspect-ratio? Or adjust the fragment shader algorithm?

# Answer
> 4 votes
After doing some googling around, it appears that OpenGL ES 2 actually does support non-pow2 textures, but not (necessarily) with mipmaps or repeat wrap mode (source). Fortunately, for postprocessing you don't need mipmaps or repeat wrap mode, so you can size the textures to match the framebuffer exactly.

---
Tags: opengl-es2, post-processing
---


# Question
Title: how can we define dynamic Path of ViewObject(Bitmap) On Canvas
I am Currently working on One **2D Android Game,**

In this game One **ViewObject(Bitmap)** is moving Across Screen On **Parabola Path** Like in this Image, But this Path is Static, the Static path is getting throught the Drawing with Fingure on canvas,

As Same as signature Drawing.

The Bitmap Move code On this Static Path is

```
//animation step
private static int iMaxAnimationStep = 900;
private int iCurStep = 0;
private Path ptCurve = new Path(); //curve
private PathMeasure pm;            //curve measure
private float fSegmentLen;         //curve segment length

 //init smooth curve
    PointF point = aPoints.get(0);
    ptCurve.moveTo(point.x, point.y);

    for(int i = 0; i < aPoints.size() - 1; i++){
        point = aPoints.get(i);
        PointF next = aPoints.get(i+1);
  ptCurve.quadTo(point.x, point.y, (next.x + point.x) / 2, (point.y + next.y) / 2);
    }

    pm = new PathMeasure(ptCurve, false);
    fSegmentLen = pm.getLength() / iMaxAnimationStep;//20 animation steps

    //animate the Bitmap
    Matrix  mxTransform = new Matrix();
    if (iCurStep <= iMaxAnimationStep)
    {

        pm.getMatrix(fSegmentLen * iCurStep, mxTransform,
                PathMeasure.POSITION_MATRIX_FLAG);
        mxTransform.preTranslate(-Bitmap.getWidth(), -Bitmap.getHeight());

       canvas.drawBitmap(Bitmap, mxTransform, null);

        iCurStep++; //advance to the next step
        mPauseViewHandler.post(mPauseViewRunnable);
    } else {
        iCurStep = 0;

    }

```

But My Problem is I want to Move This **ViewObject(Bitmap)** On **Dynamic Path(in parabola curve)** & that Dynamic curved path will work in Any Device.

I have searched Lot but i can't Find Solution How to get **Dynamic Path (in parabola curve)**.

help! If you have Any Solution,Suggestion, idea ,tutorial regarding this post is Mostly Appreciated.

# Answer
If I understand your question correctly, you're looking for a damped harmonic function which would be something along the lines of . In this function x would be time and it would give you the vertical acceleration of the bounce.

An example of an optimized version of the function to your situation might be (replaced x with t for time) which would result in the graph of:

At f(0), the function will return 1 or the full "force" of the bounce. You cannot have a -delta\_time the function has a limited domain of t \>= 0 so the function always returns a number between -1 and 1 so you can use it as a scalar for a velocity.

If you just want the height of a bounce just get the absolute value so it becomes which will look like:

This is a scalar from 0-1 so just multiply it by the height:

*Images courtesy of Wolfram Alpha*
> 3 votes

# Answer
I would recommend looking at Box2D. It is a physical engine that will take care of all the physics your game needs. However, if you think this engine is an overkill, just write the simple bouncing mechanism yourself.

Create a `vector acceleration`, a `vector velocity` and a `vector position`. Then on each frame you use the formula's found by integration. Assume `step` is your timestep in seconds (which is probably something like `1/60`).

`position += integral(velocity, 0, step)`, where
`velocity += integral(acceleration, 0, step)`, where
`acceleration = (0, -9.81)`.

So substitute these things in each other gives:

```
velocity += integral(acceleration, 0, step);
vector velocity0 = velocity;
velocity = velocity0 + vector(acceleration.x * step, acceleration.y * step);

```

The same for position:

```
position += integral(velocity, step)
position += integral(velocity0 + vector(acceleration.x * step, acceleration.y * step), 0, step)
position += vector(velocity0.x * step + 0.5 * acceleration.x * step * step, velocity0.y * step + 0.5 * acceleration.x * step * step);

```

So the code you have to apply each frame is:

```
vector velocity0 = velocity;
velocity += vector(acceleration.x * step, acceleration.y * step);
position += vector(velocity0.x * step + 0.5 * acceleration.x * step * step, velocity0.y * step + 0.5 * acceleration.y * step * step);

```

Now, to bounce, just check when `position.y < 0`. If that happens, do this:

```
velocity = vector(velocity.x, -velocity.y * restitution)
position.y = 0

```

Where `restitution` is a factor between `0` and `1`. A normal value would be like `0.6`.
> 0 votes

# Answer
Go with simple kinematics. after every bounce the velocity that the entity collided with becomes the initial velocity for the next move. The entity moves in a parabola because of acceleration due to gravity, repeat until many times as necessary. For different curve shapes(more narrow or wider) experiment with direction and velocity at which the object moves.
> -1 votes

---
Tags: 2d, android, physics, html-canvas
---


# Question
Title: Parallax background positions when jumping
I am currently building my first Mobile game. The concept is pretty simple, it's a sideways scroller.

I have implemented 5 layers to act as parallax scrolling, these are working quite well for general movement. However they look a bit weak when jumping, I would like to apply some sort of ratio which gives a 3d effect to the jump. I made a basic attempt, however it just looks a bit naff.

I have struggled to find any tutorials on this , could anyone provide any help?

As requested, here is some example code

```
    backgroundJumpEnd = function(){
    transition.to(hills,{time=600,y=153})
    transition.to(hills2,{time=600,y=153})
    transition.to(hills3,{time=600,y=153})
    transition.to(tree,{time=600,y=153})
    transition.to(trees,{time=600,y=180})
    transition.to(cloudsBig,{time=500,y=cloudsBig.y-6})
    transition.to(cloudsBig2,{time=500,y=cloudsBig2.y-6})
    transition.to(cloudsSmall,{time=500,y=cloudsSmall.y-2})
    transition.to(cloudsSmall2,{time=500,y=cloudsSmall2.y-2})
    transition.to(sky,{time=500,y=sky.y-3})
    transition.to(sky2,{time=500,y=sky2.y-3})
    transition.to(sky3,{time=500,y=sky3.y-3 })
    transition.to(floor,{time=500,y=floor.y-15})
`}`

`backgroundJumpStart = function (){
    transition.to(hills , {time=500, y=180,onComplete=backgroundJumpEnd })
    transition.to(hills2,{time=500,y=180})
    transition.to(hills3,{time=500,y=180})
    transition.to(tree,{time=500,y=185})
    transition.to(trees,{time=500,y=220})
    transition.to(cloudsBig,{time=500,y=cloudsBig.y+6})
    transition.to(cloudsBig2,{time=500,y=cloudsBig2.y+6})
    transition.to(cloudsSmall,{time=500,y=cloudsSmall.y+2})
    transition.to(cloudsSmall2,{time=500,y=cloudsSmall2.y+2})
    transition.to(sky,{time=500,y=sky.y+3})
    transition.to(sky2,{time=500,y=sky2.y+3})
    transition.to(sky3,{time=500,y=sky3.y+3})
    transition.to(floor,{time=500,y=floor.y+15})
}`

```

# Answer
> 1 votes
I have used Parallax background in my game and I don't understand, why should the vertical and horizontal ratio should be any different. I have only 3 layers. Static background, parallax layer that moves half the speed as the front (game) layer. In my game, there's a lot of vertical and horizontal movement and it simply looks the best when the vertical and horizontal movement is the same.

Now adding one more layer that moves 1/4 of the speed horizontally (so it is further), why shouldn't it be the same ratio vertically?

If I just consider mathematical point of view, parallax layers are like slices of the real world. We make a lot of simplifications when making games, so let's do some:

Draw a hypothetical line from your eye all the way the infinity, so the line is perpendicular to your body. The point in infinity never moves.

When you move left one meter, the start point of the line moves one meter to the left. The point that we will consider placement of parallax layer with horizontal ratio 0.5 (let's call it X, it moves half the distance) will move half a meter left. Now go back and duck. The line will move 1 meter down (depends on your height, really...) and the point X moves half a meter down, doesn't it?

So doesn't it look "weak" simply because your run left and right for a long distance, but you jump only a little?

---

**TLDR: Same ratio.**

# Answer
> 0 votes
It's hard to answer without seeing what you have and how it compares to what you want.

First thing's first, change all those values to variables. That'll make it much easier to update.

Second, your JumpStart and JumpEnd have different time values for your hills, which from what little I know of your code, should make things look weird. Also, their y values are different, which should slowly pull them out of sync.

Third, a picture would help. Most parallax games use foreground, midground, and background. Occasionally, games throw in more layers, but they're not necessary. This naturally groups your elements into the segments that move together (the further you get from the screen, the less they should move). With the code you have here, it's hard to tell which elements should move more than others.

---
Tags: 2d, parallax-scrolling
---


# Question
Title: UnityScript generating UnityEngine error
I have the following code set out for a simple animation in Unity:

```
#pragma strict
function Start () {

}

function Update () {
    if (Input.GetButtonDown("KeyCode.W")){
        animation.Play("dogWalk", WrapMode.Loop);
    }
};

```

Unfortunately, I have no idea what to do with namespaces (since they occasionally pop up as warnings but don't seem to have any purpose), and line 12 (animation.Play("dogWalk", WrapMode.Loop);) keeps generating an error regarding UnityEngine. What does it mean, and how do I fix it?

TL;DR:

* What do namespaces do?
* What does the error mean and how do I get rid of it?

# Answer
Namespaces are like "virtual folders" where you put your classes in. Just in code. Like how Packages work in Java or AS3. Eventhough in those two languages they are explicitly structured in actual folders too. It prevents Class names to conflict with each other and it allows for vendors to be denoted.

For example:

```
com.paulsoft.game.MyObject;

```

Like @Tetrad said, you're passing an argument to the function that is invalid.
> 0 votes

# Answer
You're calling animation.Play with the wrong argument types.

http://docs.unity3d.com/Documentation/ScriptReference/Animation.Play.html

The second parameter is a `PlayMode`, not a `WrapMode`.
> 1 votes

---
Tags: unity, animation, events, unityscript
---


# Question
Title: Tools for assembling textures into DDS files
There are plenty of tools for making images. I'm not looking for one of those; I have many tools for creating an image. I've got tools for compressing images, generating mipmaps, and even for poking at their basic data format.

My issue is with texture assembly. DDS files support cubemaps, array textures, and even cubemap arrays. But I don't know of a tool that can pack a series of images into a cubemap or the like. What tools are available for doing this kind of thing?

# Answer
> 2 votes
There is a tool called DxTex. It comes with the DirecX SDK (Utilities folder). It can create Mipmaps, Cubemaps, Volumemaps and several other things you might want to do with your textures.

# Answer
> 1 votes
According to the documentation, the nvassemble tool shipped with nVidia's Texture Tools 2 suite should be able to assemble image files into volume textures, cube maps and texture arrays.

http://code.google.com/p/nvidia-texture-tools/wiki/CommandLineTools

Unfortunately, the parts necessary for volume texture and texure array assembly are commented out in the accompanying source code and I could not find a reason for that.

EDIT: Some time ago I contacted the author of the nVidia Texture Tools (Ignacio Castano) to find out why some parts of the nvassemble code are commented out. Here's what he had to say:

> The assemble tool is very limited, I never had the need to extend it further or add the features that you propose \[...\]

# Answer
> 0 votes
PVRTexTool supports DDS export of texture arrays and cubemaps. Not sure if it supports cubemap arrays.

---
Tags: textures, tools
---


title: Loop through arrays to create a map

text:
# Question
Title: Loop through arrays to create a map
I have a 2D array called `map` which holds the coordinates to my level like this:

```
float[,] map =
{
    {1, 0, 1, 0, 1},
    {0, 1, 0, 1, 0},
    {1, 0, 1, 0, 1},
    {0, 1, 0, 1, 0},
    {1, 0, 1, 0, 1}
};

```

I'm trying to use this to create a cube at each value. In this map, each value in the area holds the height of my cube. So value {0, 0} is equal to 1 and value {2, 3} is equal to 0.

The line that creates my cube is simple enough I think. It creates it based on a `Vector3` value.

My question is, how can I create a for loop to set each value in the `Vector3` related to the map array?

For example, for value {0, 0}, the `Vector3` would be (0, 1, 0).

Feel free to ask questions if you're confused.

Edit: this is what I'm doint at the moment

```
for (int x = 0; x < 5; x++)
{
    mapX[x] = x;
}

for (int z = 0; z < 5; z++)
{
    mapZ[z] = z;
}

for (int x = 0; x < 5; x++)
{
    for (int z = 0; z < 5; z++)
    {
        cubes.Add(new Vector3(mapX[x], 0, mapZ[z]), Matrix.Identity, grass);
    }
}

```

The y value is staying a zero because I can't figure this stupid problem out...

# Answer
> 0 votes
First off, if you plan on using larger sized maps, I would recommend using jagged arrays instead of multidimensional arrays. Jagged arrays have faster element access time. Although the use of jagged or multidimensional can be easily debated.

Second, you don't appear to be using your `map` variable anywhere in your posted code. You instead appear to be using two separate arrays, why?

Third, you want to perform the outer loop on the rows, and the inner loop on the columns of the array. And then you pull the height value from the array.

So, assuming height is represented in the Z dimension in your application:

```
int[][] map;

// You'd initialize the map here with data
map = new int[5][];
for(int i = 0; i < map.Length; i++){ map[i] = new int[5]; }

// Also, assuming a cube width/height/depth of 1
for(int y = 0; y < map.Length; y++){
    for(int x = 0; x < map[y].Length; x++){
        cubes.Add(new Vector3(x, y, map[y][x]), Matrix.Identity, grass);
    }
}

```

Or with multidimensional arrays:

```
int[,] map;
int height = 5;
int width = 5;

// You'd initialize the map here with data
map = new int[height, width];

// Also, assuming a cube width/height/depth of 1
for(int y = 0; y < height; y++){
    for(int x = 0; x < width; x++){
        cubes.Add(new Vector3(x, y, map[y,x]), Matrix.Identity, grass);
    }
}

```

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


# Question
Title: How can I properly access the components in my C++ Entity-Component-Systems?
*(What I'm describing is based on this design: What is an entity system framework?, scroll down and you'll find it)*

I'm having some problems creating an entity-component system in C++. I have my Component class:

```
class Component { /* ... */ };

```

Which is actually an interface, for other components to be created. So, to create a custom component, I just implement the interface and add the data that will be used in-game:

```
class SampleComponent : public Component { int foo, float bar ... };

```

These components are stored inside an Entity class, which gives each instance of Entity a unique ID:

```
class Entity {
     int ID;
     std::unordered_map<string, Component*> components;
     string getName();
     /* ... */
};

```

Components are added to the entity by hashing the component's name (this probably isn't such a great idea). When I add a custom component, it is stored as a Component type (base class).

Now, on the other hand, I have a System interface, which uses a Node interface inside. The Node class is used to store some of a single entity's components (as the System isn't interested in using all of the entity's components). When the System has to `update()`, it only need to iterate through the Nodes it stored created from different entities. So:

```
/* System and Node implementations: (not the interfaces!) */

class SampleSystem : public System {
        std::list<SampleNode> nodes; //uses SampleNode, not Node
        void update();
        /* ... */
};

class SampleNode : public Node {
        /* Here I define which components SampleNode (and SampleSystem) "needs" */
        SampleComponent* sc;
        PhysicsComponent* pc;
        /* ... more components could go here */
};

```

Now the problem: let's say I build the SampleNodes by passing an entity to the SampleSystem. The SampleNode then "checks" if the entity has the required components to be used by the SampleSystem. The problem appears when I need access the desired component inside the Entity: the component is stored in a `Component` (base class) collection, so I can't access the component and copy it over to the new node. I've temporarily solved the problem by casting the `Component` down to a derived type, but I wanted to know if there is a better way of doing this. I understand if this would mean re-designing what I already have. Thanks.

# Answer
If you are going to be storing the `Component`s in a collection all together then you must use a common base class as the type stored in the collection, and thus you must cast to the correct type when you try to access the `Component`s in the collection. The problems of trying to cast to the wrong derived class can be eliminated by clever use of templates and the `typeid` function, however:

With a map declared like so:

```
std::unordered_map<const std::type_info* , Component *> components;

```

an addComponent function like:

```
components[&typeid(*component)] = component;

```

and a getComponent:

```
template <typename T>
T* getComponent()
{
    if(components.count(&typeid(T)) != 0)
    {
        return static_cast<T*>(components[&typeid(T)]);
    }
    else
    {
        return NullComponent;
    }
}

```

You will not get a miscast. This is because `typeid` will return a pointer to the type info of the runtime type (the most derived type) of the component. Since the component is stored with that type info as it's key, the cast can not possibly cause issues because of mismatched types. You also get compile time type checking on the template type as it has to be a type derived from Component or the `static_cast<T*>` will have mismatched types with the `unordered_map`.

You do not need to store the components of different types in common collection, though. If you abandon the idea of an `Entity` containing `Component`s, and instead have each `Component` store an `Entity` (in reality, it will probably be just an integer ID), then you can store each derived component type in its own collection of the derived type instead of as the common base type, and find the `Component`s "belonging to" an `Entity` through that ID.

This second implementation is a bit more unintuitive to think about than the first, but it could probably be hidden as implementation details behind an interface so the users of the system don't need to care. I won't comment on which is better as I have not really used the second, but I don't see using static\_cast as a problem with as strong a guarantee on types as the first implementation provides. Note that it requires RTTI which may or may not be an issue depending on platform and/or philosophical convictions.
> 23 votes

# Answer
Chewy has it right, but if you're using C++11 you have some new types you can use.

Instead of using `const std::type_info*` as the key in your map, you could use `std::type_index` (see cppreference.com), which is a wrapper around the `std::type_info`. Why would you use it? The `std::type_index` actually stores the relationship with the `std::type_info` as a pointer, but that's one pointer less for you to worry about.

If you are indeed using C++11, I would recommend storing the `Component` references inside smart pointers. So the map could be something like:

```
std::map<std::type_index, std::shared_ptr<Component> > components

```

Adding a new entry could be done so:

```
components[std::type_index(typeid(*component))] = component

```

where `component` is of type `std::shared_ptr<Component>`. Retrieving a reference to a given type of `Component` could look like:

```
template <typename T>
std::shared_ptr<T> getComponent()
{
    std::type_index index(typeid(T));
    if(components.count(std::type_index(typeid(T)) != 0)
    {
        return static_pointer_cast<T>(components[index]);
    }
    else
    {
        return NullComponent
    }
}

```

Note also the use of `static_pointer_cast` instead of `static_cast`.
> 17 votes

---
Tags: c++, entity-system, entity-component
---


title: Data driven tool for gamedesigner

text:
# Question
Title: Data driven tool for gamedesigner
I'm looking for a software my gamedesigner can use setting monster characteristics.

Like one row of all monster types (and ability to add new ones) One column of all 'templates' (normal, small, big, healer... and new ones) and in each cell between them (like in excel), say for the Zombie-Rat, there would be data to store, say HP, speed, images to use, etc.

I have tried to do this in an excel spread sheet and export in .csv / .xml **but I can only have one information per cell in excel** (actually .ods).

Would be nice if it is free too.

Tl;dr I need a tool that my non-programming gamedesigner can use to save data with and that I can get the data out from.

Thanks!

# Answer
You could build a simple tool that allows a game designer to create entities and allow them to configure all of the values you mentioned here and when they are done, have it save the Entity out to a custom file. This custom file can be laid out in whatever fashion you want and could be read in by the engine.

I am personally working on a game engine project where I have embedded the Squirrel scripting language and I have provided a simple C++-side API that can be accessed by the scripting language to create the UI. I also wrote a tool for designing levels. I was thinking about integrating this type of Entity configuration directly into my level editor so the designer can populate the level with entities.

As I said, these data files can be read in at run-time and if you design the API / tool well enough it should be easy for your designer to grasp.
> 1 votes

---
Tags: game-design, xml, data-driven
---


# Question
Title: Serious gameplay issue by spawning enemies according to elapsed time
EDIT: I have changed the title as I think that this is a general gamedevelopment question but, on a technical note, I am using Cocos2d v2.0

Some time ago I had asked a question on which was the most efficient way/method to spawn enemies.

I have choosen to spawn my enemies on the "update" cycle of the main GameScene. In short: at each update call every single enemy in the enemy array is checked and if the enemy has not spawn and the total elapsed time is greater than the current time then the enemy will spawn.

I have realized **only now** that basing the spawn time on the total **elapsed time** has the following drawback.

For example, in a vertical scrolling shooter game, ff the frame rate is very low (e.g. 20 fps) then the spawn position will be much different from each other.

I have "planned" and "engineered" my **gameplay around 60fps**, so if for any chance there is a framedrop then the user will have a different user experience also in terms of enemy spawn position (normally, in those "bad" cases the user should be affected only by the lower frame rate but here is actually getting a **different game** \- in certain cases easier in other cases more difficult).

On the bright side I have been using Cocos2d 2.0 that limits the game to only more powerful devices plus I have optimized my game quiet a lot (use of spritebatch nodes and pvr.ccz compressed images) which means that on avarage the game is running relatively fast.

Remains the drawback that we are talking about **"avarage fps" and hence different users with different iPhones will have different spawning positions of enemies**.

Any suggestion to limit this drawback? Am I the only one experiencing/noticing this?

# Answer
> 4 votes
Frames Per Second (FPS) should be just that. The number of frames drawn every second. What FPS is not is something that you should be basing your gameplay timings around. You are running into issues when spawning enemies according to elapsed time because the rest of your game is not based around time, I bet.

In your current setup I imagine you are updating fixed values every frame. The trick is to make sure the change in time has been taken into account here as well. A simple example of this is when it comes to moving your character.

The simple way that we all start out with when making games is we think "I want the player to move 1 pixels forward on the X axis every frame." This usually results in code that looks like the following:

`Player.Position.X += 1;` \- this is not correct.

The correct way of thinking would be "I want the player to move 60 pixels forward on the X axis every second (equating to 1 pixel per frame at 60fps). The reason you want to think this way is because you can now very easily incorporate time into the equation.

`Player.Position.X += time * speed;`

With this approach, if you for some reason get a 4 second stutter in your gameplay, this has been handled for because your movement is based around time instead of frames.

While I don't feel this question / answer is really a duplicate considering the circumstances around your question, am rather confident they are relevant to the issue you are seeing and I would highly recommend you read through the information there to further your understanding on what I explained above.

# Answer
> -1 votes
Create your own thread that will be checking the array of enemies and adding them to the game. Also sort the enemies by time they are supposed to arrive and stop on the first enemy that in not supposed to arrive yet - then you don't need to check all of them. You can implement this by using stack. Push the enemies to the stack in the opposite order and pop() them when needed.

How to do this in cocos2d, I don't know, but this should be the general idea.

---
Tags: game-design, cocos2d, game-loop, user-experience, fixed-timestep
---


title: How do I use TextureRegion?

text:
# Question
Title: How do I use TextureRegion?
I can't understand how to use texture region.

I have a png file which has images (sprite sheet) and I must "extract" every image I want.

From here it just says `TextureRegion(texture, 20, 20, 50, 50);`

Where `20, 20, 50, 50` describes the portion of the texture,

How can I find which portion has the image I want to extract?

Should I open the png file with Gimp for example? And then I am search for some coordinates? And if yes, how?

# Answer
The params describes the upper left location of the region and the width/height. So 20,20,50,50 describes a region starting at 20,20 and then has a width and height of 50. However, extracting regions manually can be a pain. Texture packer allows you to put multiple images together into a single texture. Then using texture atlas you can retrieve those regions by name.

Packer and Atlas Info: https://code.google.com/p/libgdx/wiki/TexturePacker#Running\_TexturePacker2

A GUI Packer: https://code.google.com/p/libgdx-texturepacker-gui/
> 2 votes

# Answer
As you said, you need to know the position and size of every image inside the sheet, in pixels, this is usually easy if you have all images the same size, it is just multiplication matter.

If you are using several images with different sizes, you will need an archive that maps each image position and size. This file is usually generated by the program you used to pack the images into a single one. There is actually a program available with Libgdx called TexturePacker.
The TexturePacker will take a full folder of images and generate one or more sheets and a `.pack` file mapping each image and position with its name.

Having that it is just matter of instancing a `TextureAtlas` and using `findRegion("imageName")` to recover the `TextureRegion`.
> 1 votes

---
Tags: android, textures, libgdx, texture-atlas
---


# Question
Title: Using a switch command in one shader vs multiple shaders
If you have multiple shaders, could you instead of switching between shaders all the time just have one shader with a switch and each case will send you along to another shader function which you require for that specific object? ( And you would send an enumerated value through your constant buffer for that specific object)

I guess the real question is. What would take up the most performance, the `switch` or the switching between shaders?

Example:

```
BigShader(){
   switch(a){
      case 0 :
        { return transPSShader();}
      case 1:
        { return nonTransPSShader();}
ect.
}

```

# Answer
Typically, branching of any kind (switches, if-statements, loops with non-constant iterations) are best avoided. This is mildly true on the PC (not enough to be worth worrying about at all outside of very tight inner loops), especially true on some general-purpose CPUs like the 360's Xenon (common hardware that makes indirect references on branches tolerable on modern super-scalar out-of-order deep-pipeline CPUs was left off the Xenon to save on cost), and especially true on GPUs.

GPUs are very special beasts. They do not work like a general-purpose CPU. They run potentially thousands of copies of a shader at a time, and there are limitations imposed on the hardware to make this possible. One of these limitations is that a number of execution cores share resources. For sake of example, let's say 4 cores are tied together like this on our hypothetical GPU.

So at any time, four "core" are running a shader in lock-step. They share an instruction pointer. They sort-of share a register file. The SIMD behavior of your shaders is not like SIMD behavior on the CPU which is typically used in games; each shader isn't doing four-way vector operations at once, but rather, all four cores work on a single component from the four different data streams at once. These four cores are tightly tied together.

The shared instruction pointer is key. If two of your shaders in this group execute switch case 1 and the other two run switch case 2, all four cores must run both switch cases! Predicated instructions are used to ensure that the results of the instructions in the "off" case are ignored for a particular core, but it still takes the time to execute the instruction and do any memory/register/texture accesses (which is why you should only do texture lookups in uniform code paths), etc.

Hence, branches are "slow" in the fact that your hardware ends up really under-utilized. A potentially very large portion of it ends up spending time evaluating instructions that have no effect. This is different than the CPU case where branches hurt because of pipeline stalls and mispredictions; the GPU often has very restricted branching capabilities anyway.

Is this "slower" than swapping out shaders? That depends. If you batch up your draw commands such that you do all draw operations using a particular shader in a row (so you don't switch from shader A to shader B and then back to shader A, but rather do all drawing with shader A and only then do drawing needing shader B)... it still depends, but it will *probably* be faster with this batching. As will all things performance-related, you need to test and find out specifically for your application and target hardware. If your switch statements are simple enough you might find that it is indeed quicker to use them.

It is often better *anyway* to batch up object with identical material properties (same shaders, textures, material constant buffers, etc.) just to avoid changing active resources even when using an uber shader. Breaking up your shaders to play well with this is often not hard at the low-end of the graphics scale. It can get to be a bit more difficult with multiple material types in a deferred shading context, and here a semi-uber shader approach is typically taken (often just for BRDF calculations and the like).

Note that engines like CryTek have taken the uber shader approach (unsure if the most recent incarnations still do), so it's certainly usable for very high-end games in the real world.
> 9 votes

---
Tags: shaders, performance, directx11
---


# Question
Title: Why do most video game guns reload without losing unused ammo in the magazine?
If I have picked up 500 spare ammo and I 73/100 bullets in my current gun, why will I end up with 473 spare ammo instead of 400 (losing the 73 unused rounds in the previous magazine)?

Is this just to make it easier on the player?

I want to make a challenge shooting game and it seems like timing your reloads would be interesting.

Is there any reason I should stick to the norm?

# Answer
> 80 votes
It's not true that "every game ever made" uses the reloading mechanic you've described. I can think of least one (Red Orchestra) that didn't, and others which I believe didn't as well (Day of Defeat, Rainbow Six).

But that's not the point.

This is simply a game mechanics decision, often made because the designers felt that the complexity introduced by a more complex or realistic reloading mechanic would not add any additional fun to the game (and in fact might actively annoy players). It's not all that dissimilar from the choice not to require characters to feed themselves, or stop for bathroom breaks, in most games.

Thus, the decision was made to opt for a simply mechanic that eschews realism in favor of a system that treats every gun as having a giant continuous "hopper" of bullets you just dump your spares into when you reload.

If you think you can build an interesting, fun mechanic by forcing players to be more careful with their reloads (and I think it's totally doable), then by all means go for it.

# Answer
> 21 votes
I was involved in the development of the halflife2 mod hidden-source, which enforces the 'full reload' strategy.

The reason for this is that we wanted the game to be very tense and give the marine players much more to worry about. We wanted to discourage spray-and-pray tactics by giving firing your weapon a large cost.

Each marine spawns with limited ammunition. Allowing them to reload partial magazines gave them too much freedom and changing damage/lowering ammo count made the weapons and the marine loadouts look unprofessional and unrealistic.

# Answer
> 8 votes
Actually in real life you use a dump pouch where you can quickly drop a non-empty magazine so you can refill it when there's a break in combat. Refilling or redistributing cartridges would probably not be well received by most modern gamers but if you are going for a more realistic take then I'm sure military personnel and gun-nuts would appreciate your focus on detail.

# Answer
> 3 votes
Instead of throwing your magazine away, couldn't developers choose to make reloading a half-emptied magazine longer. Since the player would need to remove bullets from a full magazine and place them in a half empty magazine. Except maybe for a revolver, it would reload faster with less bullets to fill the "magazine"

A lot of games encourage reloading before the clip is empty because this would be faster then let the system autoreload on empty magazine (Some more engagement of the player, because he has to monitor his clip and press the reload button instead of just holding down a button).

One could argue that during a fight, no soldier would do this. But no soldier would throw away a half emptied magazine either, there are no benefits for him doing that, except maybe that he is more capable of performing a longer burst/support.

I think you have to make a difference between a simulator or survival, versus a more arcade game. People want to think that when they shoot 6 bullets, after reloading it should be -6, and not -whatever magazine size is. While in a survival or sim, you want the real experience, and make a conscience disission if you want to have the benefit of a full clip during a burst/support or you rather preserve ammo

# Answer
> 3 votes
In short, there are two main stylistic camps; tactical and adrenaline.

Adrenalin design is much like it sounds, almost the candy of video games. Lone wolf, run-and-gun styles that make very little sense outside of that game world, or even in it, but are a cheap hook to get lots of players. **Call of Duty**, in recent years, has been a great example of this philosophy. This sort of design is often pursued by large, established studios where executive meddling is more rampant. However, some games, such as Halo, use the magazine limit as a sort of damper on weapon effectiveness for balance. Because they consider magazines very similarly to cool-down or spin-up, they don't use them as units of ammo like in the real world. There's some merit to that discussion. (For example, in **Halo Combat Evolved**, most human guns were good for 4 kills per magazine if every shot hit. This let them focus each weapon on role rather than a hierarchy.)

In tactical design, teamwork, tradeoffs, and thinking as you play are vaunted, but you lose some of the addictive adrenaline. This allows clever players who aren't necessarily as "twitchy" to stand on a level field with their hair-trigger foes. This sort of design is often more popular with smaller studios who can make non-mainstream calls like that. A great example is **Frontlines: Fuel of War**, where the assault rifle loadout got about a dozen magazines and half dozen launcher grenades. The result was that you could always be prepared for a shootout and and that some waste was acceptable, but 1-round mags were totally averted.

The conclusion is that you should use whatever fits your overarching vision for the game. Will it be more tactical? Give them lots of ammo, tie ammo to mags, and let them sort it out! Will it be more adrenalin-y? Don't make them think too hard!

# Answer
> 2 votes
Why can I suddenly heal catastrophic wounds by running over medical kits? It's called POETIC LICENCE. These are **games, not simulations**. As previously mentioned, things like Red Orchestra or the SWAT games are more realistic in this regards. Call Of Dudebro and the like possibly aren't.

# Answer
> 2 votes
The reason is that games usually have an audience they wish to target. There are people who enjoy playing realistic military simulators, and there are others, who enjoy more arcade-style shooters. If the game is planned for the second demographic in the above example, then a realistic reload system would just frustrate the players. There are plenty of video games using realistic reloading, but they usually have a different playing style as they target a different audience (these usually have other realistic settings, like bullet ballistics, reduced carrying capacity, more lethal wounds, no easy healing, horrible accuracy while moving, etc.).

# Answer
> 2 votes
To expand on what Josh Petrie and Alan B said, the broad, or general answer is that games employ various abstractions that *remove* parts of the real-world that the game developer decided are not contributing to the game-play they want, or is not worth the investment (or didn't make the cut, or they run out of time/money, or it collided with other(s) aspect(s) of the game that they decided to prefer one over the other, etc-etc). Whether it is HP instead of --for example-- blood lose, or critical hits instead of a major artery rupture, etc-etc.

On top of that, in many cases game developer sometimes just stick with what they saw in other games. Or in other words, "the norm" is sometime just lack of desire/resources to explore different ways of doing things or "don't fix it if it ain't broke" attitude, which can something leads to what can be regarded as unofficial tradition. Also, this may be a marketing decision (assuming it *is* easier to sell a game that the potential player base is already familiar with, i.e. more of the same).

Taking inspiration from other games is completely OK, but if there is some kind of aspect about a games (whether in this genre or another) that you personally think would be interesting to change, than don't get hung up about the current "state of the arts" too much.

The traditional way of doing things was not *necessarily* been establish by a vigorous process of trail and error.

---
Tags: game-design, shooter
---


# Question
Title: What techniques make next gen look so realistic
I have watch several gameplays from upcoming titles for ps4 and xbox one and I must admit that they are breath taking.

Of course with new hardware, models will have more polygons and higher texture resolution but that is obvious tip of iceberg. So my question is :Are there any complete new techniques, algorithms, shaders broadly used in next gen, already known on paper but not used in current gen because of limitation of hardware or this is all same but more complex,less generic or made for in-house use(unknown for public) to provide better visual result for specified engine.

From my observation:

* Realistic particles,fluids (papers?)
* Geometry shaders (examples?)

What I expected to see but was not shown:

* Fracturing
* Generic destruction of buildings and cars!

Is this still to compute heavy for large scale scenes?

# Answer
> Are there any complete new techniques, algorithms, shaders broadly used in next gen, already known on paper but not used in current gen because of limitation of hardware or this is all same but more complex,less generic or made for in-house use(unknown for public) to provide better visual result for specified engine.

Mostly all about lighting models which required more capable shader engines and more GPU memory/bandwidth.

There are various other useful techniques like computer shader, tessellation, etc., but most of the "realistic wow" is all about lighting.

Improved texture fidelity also helps a lot. The 256/512M available on older console hardware was nowhere near enough compared to the PC.

> What I expected to see but was not shown:
>
> Fracturing Generic destruction of buildings and cars! Is this still to compute heavy for large scale scenes?

Yes. These require complicated physics models and data-definitions. Some last-gen games like Force Unleashed did some "real" deformable physics but only in limited/specific circumstances, e.g. the doors you could "force bend" open.

Modeling the destruction of a building even semi-realistically using just physics for example would require physically modeling the structure and interior of the building as well as its outside "veneer." We're talking a *huge* increase in content creation time and cost. Destruction can be faked a bit more easily by creating pre-broken versions of assets and then using physics to just move about the pieces, but this both looks wrong for most non-simple objects (it's done for rocks and trees and the like in many games, but not buildings or cars or complex objects) and is still a huge time/money sink compared to just not having destructible terrain.

Games are all smoke and mirrors. The world simulation you see is faked to every extent possible. There's a limit to how "realistic" games are going to get any time soon.
> 4 votes

# Answer
From what I've seen so far, I'd add:

* Cloth simulation
* Sub-surface scattering
* Volumetric lighting and particles
* Procedural character animation alá Euphoria ?
> 0 votes

# Answer
Well there are multiple techniques that increase realism:

* Better Lighting (dynamic and pre rendered in light maps etc.)
* More polygons usually through tessellation
* Modern Post-process effects (take a look here http://www.youtube.com/watch?v=seWKj2c9-qk)
* Detail - more polygons - high res. textures etc
* Animations

These are the most effective effects IMHO.

Next-Gen games try everything in order to gain better performance, so instead of calculating lighting per pixel they make lighting effects in post processes like YEBIS 2. pre-rendering is another way to gain performance

P.S: Don't forget that most trailers said at the beginning "in-engine footage" and that's clearly not the same as "in-game footage".

**EDIT:**

> Generic destruction of buildings and cars!

http://www.youtube.com/watch?v=wqQiZUvLTAk
> 0 votes

---
Tags: algorithm, shaders
---


title: How to optimize SpriteBatch usage?

text:
# Question
Title: How to optimize SpriteBatch usage?
From what I understand, SpriteBatch's purpose is to batch as many draw operations to send to the GPU. Each batch can handle one texture at a time, and changing SpriteBatch context/texture is expensive, so when you need to draw many different textures in one frame you use a texture atlas, putting sprites that are most likely to be drawn by the same component in the same page.

So my questions are:

* Assuming there are numerous components using the same texture page, how am I supposed to group them together and issue their drawing method?
* What is an efficient way to deal with a component that uses sprites from two different texture pages? Should I handle two different drawing methods for each texture page? or perhaps take the context texture page as parameter and draw only what's relevant for it?
* What about dynamically generated textures?
* What if you don't know which texture pages a component needs? (For example, a custom visual equipment where you can't possible put all the equips in the same texture page since there might be thousands of em, and it's determined only at runtime)

I've seen many articles on how SpriteBatches work *technically* but nothing meaningfull on how to actually make the best use out of them. Would a good solution be to somehow queue my draw operations sorted by texture? If so, what would be a good *generic* way to implement it?

# Answer
> 1 votes
Im assuming you are using spritebatch from xna/monogame, unless you are using a differnt API that does a similar function.

Spritebatch can handle multipe textures and draw calls within Begin() and End() functions, with little performance hinderance depending on how many draw calls you are performing per frame. The only time Spritebatch becomes expensive is if you are calling Begin() multiple times per frame in order to change Modes and Renderstates. Typically you want to try and keep it to one Begin() call per frame unless trying to create a specific effect without hlsl.

As for multiple components using the same texture, simply have an assest manager that holds a dictionary/map with a with all the assets you need loaded in, then pass a string to your component that will get the reference to the texture and store that reference to be called during the draw function. Alternatively, pass in the asset manager to your component and do a get function using the string key during your draw function.

The latter part of my last paragraph can help with your multiple textures issue as you can create more than a draw call during your component Render() function for each texture you need to access.

As for your last question, again the same thing. You can store the string keys and the location on texture in an xml/text file and access your asset manager at runtime and pass in the string and texture coordinates during your draw call.

---
Tags: graphics, textures, graphics-programming, spritebatch, texture-atlas
---


# Question
Title: How is good is Java as a language for browser based mmo games?
Somewhat related to Is Java viable for serious game development?

I have decided to make a browser based mmo game. But the only programming language I know is Java.

So I would like to know how good is java as language for browser based game development especially in terms of performance and speed compared to popular languages like PHP ? Is there any studies on this subject based on performance and speed of programming languages on browser based games ?

# Answer
There is one thing that bothered me about your question:

> "..But the only programming language I know is Java."

So learn another one!

Anyway, Java as a *client* in the browser fails on many, many fronts.

For one, Java 7 (and most likely Java 8) doesn't even *work* in Chrome on Mac OS X because the Java people decided to stop supporting 32-bit, and Chrome is a 32-bit browser. To me this speaks volumes about Sun/Oracle's *attitude* towards supporting "every system" like they have claimed in the past. So right off the bat you have these compatibility problems with Macs and older systems, requiring workaround. So much for "write once, run anywhere".

I really think you're better off either building a native client, or using HTML 5 (if it will be a simple browser-based game) or using Flash instead. Flash is *much* more proven as a multiplatform, in-browser tech that works. Realm of the Mad God was programmed using Flash, as well as oodles of newgrounds entries.

Here's to not seeing that godforsaken java cup on any new games
> 4 votes

# Answer
There are no good or bad programming languages. You can program the same thing in any turing-complete language. It is more about your personal feelings. If you like the syntax, if you like existing compilers / interpreters / SDKs etc.

For me: I don't like Java syntax, I don't like Eclipse, I don't like Java VM from Oracle, I don't like Oracle's attitude to Java, so the answer is NO! :)
> 0 votes

---
Tags: java, game-industry, browser-based-games, php
---