# Question
Title: What has stopped MMORTS games from being successful?
We all know that there have been attempts to create commercially successful MMORTS games, but all have failed. By failed, I mean that they didn't get really popular in the gaming community. Why is that?

**What is an MMORTS?**

It's like an RTS (a real-time strategy; Rome: Total war, Stronghold, StarCraft, WarCraft) but has an MMO component, meaning that you not only build your economy and industry, but you get to compete with other players doing just that in real time.

This interests me because I'm trying to make a game that is similar to an MMORTS as well.

**Summary:** what are the reasons that are stopping the MMORTS genre from evolving?

# Answer
## Update

For those interested, I did a write up about these problems and a few others, as well as possible solution. You can find it at my blog.

---

@JoshPetrie hit a lot of it on the nose, but I'll add a little to it as well.

Some friends and I a while back wanted to make a real MMORTS and went through the process of building a general game design outline that included features and a story and a few other things, and I can say from experience, transporting an RTS to a persistent state MMO presents a lot of difficult challenges for the genre.

For example, what would it mean to be offline? How does an entire civilization go offline? And what is to stop players from logging off when they are about to be rushed by another player? What happens to the land you own when you are offline? Are your buildings still there? Can people trade with you? Attack you?

What are the persistent goals? What is the point of the game in the long term? Build a big army? Build a civilization? For what purpose are you doing this? To fight other people? Where? How?

What happens if all of your civilization is destroyed? What does that mean? Do you revive? Do you have to start over? That would probably be frustrating.

What stops veterans with huge civilizations from destroying new players? What is a new player? Does the world just constantly expand? How much land do you get? When you conquer other players, do you get their land?

And there are a lot more questions just like these listed that crop up in taking an RTS to a persistent state. And that doesn't even touch on the MMO aspects and issues that crop up there. RTS, as the genre is now, is not made for a persistent state MMO environment.

Now, I will tell you, we came up with solutions for most of the above, so it isn't impossible. In fact, I would still be interested in some day seeing if I could get this to work. If anyone is interested in the solutions to some of these, I can do a write-up outside of this answer if you leave a comment. This answer, however, is long enough as it is...
> 26 votes

# Answer
MMOs have significantly higher infrastructure and ongoing maintenance costs than non-MMO games, primarily because most MMOs also include a heavy element of persistence, and in the interest of ensuring integrity it's the developers or publishers who typically shoulder that burden.

Because of that, it's important to ask *how the player will benefit* from making the game in question an MMO. The business benefits are fairly obvious: extra income from subscriptions or microtransactions, et cetera. But those benefits only apply if you have players, and players will want to have fun, so it's important that your players can have *more fun because your game is an MMO*. Otherwise, it's likely not worth the overhead to add the MMO aspect to the game.

Thus, I would content that the reason you don't see a lot of high-profile commercial MMORTS attempts (at all, let alone successful ones) are because the RTS genre doesn't necessarily get that much more fun when you scale the gameplay scope up to include hundreds and hundreds of other players.

Many RTS games revolve around building mechanics, which perforce roots a player to a specific region of the world. RPGs can be more fun as MMOs because a player can explore the world more freely, and thus encounter and interact with other live players in a more emergent fashion. The fact that players remain relatively fixed in the world in most RTS limits the number of other players any given player may interact with.

The other major aspect of RTS games is unit control and coordination. Through this mechanism a player might be given more freedom to wander the world and encounter others, but unless the player is going to move all their units in one big swarm you have a serious problem with their attention being split (which implies some interesting technical challenges in terms of the amount of data that must be reported as well) between various groups of units that are scouting, attacking, et cetera over huge areas.

Probably you don't see may successful MMO RTS games because nobody has found a great way to make the critical parts of the RTS game type work within a massively-multiplayer scope in a way that actually *adds* to the fun of the game.
> 19 votes

# Answer
There has been a commercial MMO RTS released in Korea nearly 8 years ago, but it was essentially MMORPG + RTS.

MMORPG part of the game was you controlling a "General", fully customizable and you can go to town, talk to people in a massive world.

RTS part of the game was when you engaged other player Generals. The game screen changes to a full RTS.

Other player generals, not in the fight, can spectate but with a new game screen.

I am not sure if this game was a huge success but at the time it had several thousand players, and had in game items.

With regards to a MMORTS, I'd imagine it would consume insane amount of bandwith. And like KTash mentioned, there's so many design questions in regards to persistence, however I am more concerned with how you would possibly be able to control entire army in the real world with thousands of other player's army.
> 3 votes

# Answer
4-6 player RTS's in games like War 3 or Starcraft can have a 20-30 minute play time.

RTS play typically has a couple ways it can go, because of the tiering of units:

1. 0 min~10 min: Initial building and rush opportunity (usually lowest tier units). If game ends here, it was a "rush" victory
2. 10 min~20 min: Sustained attack and expansion thwarting, if game ends here it'll be with mid-tier units
3. 20 min~30 min or later: Epic battle with top tier units.

RTS games have *short* games, and the victor is **decided early on** due to key strategic mistakes or loss of a group of units, or just huge disparity in skill level.

So, how can an RTS work as an MMO? Slow time down? Then it'd be more boring, and probably difficult to sustain your audience (if your partner leaves or is afk for 5 min in an RTS you could lose the game. What if your partner were afk for 3 weeks in an MMO rts?).
> 0 votes

---
Tags: mmo, mmorts
---


title: Defining an OpenGL unit

text:
# Question
Title: Defining an OpenGL unit
I have read that you can define your OpenGL unit by using `glViewport`. As far as I understood if you use something like `glViewport(0,0,600,600)` then 1 OpenGL unit = 600 pixels. Now my problem is what happens if the 2 sizes aren't equal? How do you calculate your OpenGL unit?

# Answer
glViewport actually defines the size of your window, so `glViewport(0,0,600,600)` defines a window of `600 x 600`.

By default opengl's coordinate system sees `0,0` as the center of your window and `1,1` as the upper right hand. If you want to change that you use either glOrtho or gluPerspective. Using `glOrtho` to figure the unit/pixel ratio is easy:

given:

```
glViewport(screen_left,screen_top,width,height);
glOrtho(negative_x,positive_x,negative_y,positive_y,positive_z,negative_z);

```

where:

**Screen coordinates**

```
screen_left // the x coordinate that your window is created at
// relative to your screen
screen_top // the y coordinate that your window is created at
// relative to your screen

```

**Opengl Coordinates**

```
negative_x // the left x coordinate that opengl sees
positive_x // the right x coordinate that opengl sees

negative_x // the bottom y coordinate that opengl sees
positive_x // the top y coordinate that opengl sees

```

Be sure to note that screen coordinates are **not** opengl coordinates

then:

```
x_ratio = (positive_x - negative_x)/width;
y_ratio = (positive_y - negative_y)/height;

```

Try this tutorial's lesson 2 & 3 on setting up the viewport correctly.
> 8 votes

# Answer
glViewport is just a transformation; see here for an explanation of where it fits into the pipeline and how it's applied. It may be helpful to think of it as defining an area of the window to draw to, but you should also understand that in reality it's something else.

Regarding "units", OpenGL does not define any "units" at all at any stage in it's pipeline, nor does it provide any means by which you may do so. It's up to you to decide how co-ordinates map to "units" in your own program (C/C++/etc) code; so for example if you see a call to glTranslate you get both the choice of and the responsibility for what the values passed to it mean in terms of your own code.
> 0 votes

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


title: Dynamic Textures

text:
# Question
Title: Dynamic Textures
I am pretty new to this 3D designing and animating, and as an indie developer I need to do everything on my own

I have created this simple box character And I want to texture it, have looked around for solution and all seem to require UV-Mapping. Is it normal if I create a texture for each part of the character (legs have texture,head another texture file and it goes..) Or I should learn it the hard way and simply create one texture for the entire character.

What are the pros and cons of this approach, noting that I am targeting mobiles. and may I get resources about texturing for mobile games ?

EDIT : knowing that I am targeting mobiles (low resources compared to PC), Is it possible to dynamically render textures via the engine without needing files ? I guess it would be easier to update textures later compared to using a file, knowing the characters are simple cubes and shapes and simple colours would be rendered on them (with few details of course)

# Answer
> 1 votes
Separate textures is very bad performance-wise. Modern content pipelines usually subdivide a mesh in individual parts separated by material, so this adds additional GPU instructions when drawing the model. Here is how drawing a model that has three separate textures five times would be in code:

```
for (int i = 0; i < 5; i++)
{
    SetTexture(headTexture);
    SetModel(headModel);
    Draw();

    SetTexture(torsoTexture);
    SetModel(torsoModel);
    Draw();

    SetTexture(legsTexture);
    SetModel(legsModel);
    Draw();
}

```

That would be 15 `SetTexture`, `SetModel` and `Draw` calls each. Knowing that each one has some kind of overhead when calling (mainly due to CPU \<-\> GPU communication), you end wasting some precious resources and making the frame drawing slower.

Now, this would be the code if you had to draw a model with only one texture:

```
for (int i = 0; i < 5; i++)
{
    SetTexture(bodyTexture);
    SetModel(bodyModel);
    Draw();
}

```

That would equal to 5 `SetTexture`, `SetModel` and `Draw` calls each. But wait, modern engines cache values before performing operations, so when `SetTexture` or `SetModel` are called with the same value as the last time, no operation is performed because the GPU already has that state set! So in the end, you would have one `SetTexture` and `SetModel` calls, and 5 `Draw`. 7 function calls instead of the 45 you would have the other way.

# Answer
> 0 votes
To use one single texture on a character:

Pro:

* Less textures to store, load, and render. Generally speaking, it's more efficient in time and space.

Con:

* You might have less details on smaller parts.
* If you want to change partial outlook on a character in the game (for example, a paper doll system, or player customized character), you will need a lot more big textures. In this case it's actually taking more spaces in storage, and maybe memory.

So it really depends on your game design.

---
Tags: unity, textures, javascript
---


# Question
Title: Making Procedurally Generated Top-Down Landscapes Interesting
I'm working on a game with a procedurally generated world. Ideally, I'd like to generate landscapes as beautiful as Minecraft's worlds are. Minecraft has chasms, and waterfalls, and mountains, and rolling hills, and oceans, etc. But as this is going to be a top-down (actually 3/4 perspective) game, I don't believe most of that is possible. The main reason being how hard it is to try and represent height in this perspective. Zelda: A Link to the Past created the illusion of height well, but this would be very hard to recreate procedurally, and also introduces some problems such as the fact that the tallest structures have to be at the top of the map.

So, I'd like to know some techniques to make landscapes interesting in a top-down format without having to fake a 3rd dimension. (You cannot create or destroy terrain in this game, so that gives us a little more flexibility.)

EDIT: To make things a little more clear, I'm trying to avoid worlds with features that require a 3rd dimension. For example, I can't really have rolling hills or mountains. What landscape features could be added that don't require faking a 3rd dimension? One answer could be to add rivers, but that's an obvious one.

# Answer
Vary landscape types (texturing, vegetation), i.e. have multiple "biomes" such as:

* Rainforest / jungle
* Desert
* Savanna
* Swamp
* Tundra
* Mediterranean
* Temperate forests
* Boreal forests
* Rocky areas (could simulate some kind of mountains without real height)

You should not have very many biomes of one kind and keep the individual biomes rather small to avoid repetition.

You can see some biomes in the complete zelda map: http://zs.ffshrine.org/link-to-the-past/maps/light\_world-1.png Although there is quite a lot of the general forest, e.g. on the bottom there is desert, different kind of grassland and a water world.

Some features to add to the biomes:

* Water: ocean (with islands), lakes, ponds and rivers
* Forests: try different densities and noise functions / parameters
* Undergrowth: different kinds of bushes, rocks, flowers
* Structures: a lone house, farm, watchtower, ruins, statue
* Settlements: villages, castles, tent camps
* Roads, pathways and bridges

Again, avoid repetition: only have e.g. one tent camp, even if you generate different kind of camp each play-through. You should, however, have the player encounter some kind of landmark very frequently, so if your world is big and you need e.g. many villages, try to alter the house style between them (e.g. one has wooden houses, another one has them made of stone).
> 6 votes

---
Tags: 2d, procedural-generation
---


title: LibGDX Swipe Detection Left and Right

text:
# Question
Title: LibGDX Swipe Detection Left and Right
I have displayed an image at the center of the screen with libgdx. If I swipe left, the image should move to the left; and, if I swipe right, image should move to the right.

Subsequent swipes to the left should move the image left. The same should happen for right. I used `GestureListener`.

It works to some extent in the sense if I swipe left first image moves left. But after that if I try to swipe right the image still moves left.

So how do I implement the expected behavior?

```
class MyGestureListener implements GestureListener {
    @Override
    public boolean fling(float velocityX, float velocityY, int button) {
          if (velocityX>0)
              iX += 20;
          else
              iX -= 20;
          System.out.println("iX: "+iX);
          return true;
    }
}

// ...
Gdx.input.setInputProcessor(new GestureDetector(0.0f, 0.0f, 0.0f, 5f, new MyGestureListener()));

// ...
batch.draw(splashTexture, iX, iY);

```

# Answer
> 11 votes
There are a few potential problems here. Lets take a look at your code first:

```
if(arg0>0)
   iX += 20;
else
   iX-=20;

```

arg0 is the velocityX of the last known horizontal velocity of the finger in pixels per second. Here's the method signature for fling():

> **fling**
>
> boolean fling(float velocityX, float velocityY, int button)
>
> Called when the user dragged a finger over the screen and lifted it. Reports the last known velocity of the finger in pixels per second.
>
> ```
>  Parameters:
>       velocityX - velocity on x in seconds
>       velocityY - velocity on y in seconds
>
> ```

So, the method is not taking in ALL the data of the swipe, it's merely taking the final position info. What happens if you ended your swipe without any horizontal velocity? According to your code, the answer would be, **move left** because the X velocity in the final position would be zero.

```
if(arg0>0)
   iX += 20;
else   // This includes X == 0 because you only checked greater than!
   iX-=20;

```

What happens if you swipe upwards? According to your code, the final position would be **move left**, because arg1 has the upwards movement and is being ignored. What happens if you swipe downwards? According to your code, the final position would be **move left**. What happens if you swipe a little to the right and a little to the left? **Move left**.

I think what you want to do instead is something along the following lines:

```
   @Override
   public boolean fling(float velocityX, float velocityY, int button) {
           if(Math.abs(velocityX)>Math.abs(velocityY)){
                   if(velocityX>0){
                           iX+=20;
                   }else if (velocityX<0){
                          iX-=20;
                   } else {
                     // Do nothing.
                   }
           }else{

              // Ignore the input, because we don't care about up/down swipes.
           }
     return true;
    }

```

A few additional notes:

* **Debugging**: For debugging, I recommend that you log not only the resulting iX, but also the incoming arg0 (velocityX) values. I strongly suspect that a few minutes of looking at the input data will resolve the issue. In particular, you're going to want to know if this method is receiving zero values (which with your code will move the image left), if it's receiving non-negative values when it should be receiving negative values, and so forth.
* **Set the MaxFlingDelay**: A word about fling(): fling() is not always called. You need to set the maxFlingDelay in the GestureDetector constructor for the amount you want to trigger a fling(), otherwise it uses a default value, which you may not be happy with.
* **Consider Pan and Other Alternatives**:Consider alternatives to fling() including pan(). As has been noted by Benjamin, you may want pan() instead (or something else). That's an excellent suggestion and possible solution.
* **Run a Gesture Detector Test**: To help decide on whether to use fling() and to see if fling() is giving the right values, play around with this gesture detector test.
* **Consider the Return Boolean**: When you `return true` in this method, you're signalling that the input has been handled and shouldn't be processed further. That's not descriptive of the code sample I gave you (where up/down flings are ignored, for example). You may want to modify it to put the proper return trues/return falses in the appropriate places, so you don't run into unexpected behavior later if you implement other touch handling for nearby entities.
* **Variable Names**: This is just a minor pet-peeve. It makes things much easier to read if you use descriptive variable names (like velocityX, velocityY, above) instead of Arg0, Arg1, iX, and so on. You asked above why you received a downvote. Don't know why somebody gave it, but sometimes code with bad naming conventions rubs people the wrong way.

# Answer
> 0 votes
Looking at an example I found online, it seems you might be extending the wrong class. It looks like the preferred class to extend is GestureDetector rather than GestureListener (although I am not sure the exact difference) the example I am looking at has a pretty good implementation for fling handling (although it is pretty similar to the answer provided by Cameron Fredman). My other suggestion was to consider switching from fling, to pan (as this is usually used for panning around an image which it seems like you are trying to do.) If possible can you give us some debug information for flinging around? just what values are returned from a sequence of calling fling 2 times in each direction should work.

---
Tags: android, libgdx
---


title: How to load a custom SpriteFont?

text:
# Question
Title: How to load a custom SpriteFont?
Is there any possible option where you can open a custom SpriteFont? Because I need to add to my game a font that is not in Windows already. I saw this page Custom Sprite Fonts and it's like I want it, but there's no explanation on how to do it...

# Answer
> 2 votes
From the page you've linked:

> Now save the bmp, and add it to your xna content (Add \>Existing Item \> select your bmp file). Then you need to click on the bmp in the Solution Explorer, and in Properties change it under Content Processor from “Texture – XNA Framework” to “Sprite Font Texture – XNA Framework”.

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


title: What is the Box2D coordinates system?

text:
# Question
Title: What is the Box2D coordinates system?
I know that for Box2d I need to translate pixels to meters which is easy peasy. However my problem is what is the orientation of Box2D coordinates system? Is this the same as screen one (right += x, bottom += y) or it is like cartesian (right +=x, bottom -= y) ?

Also, does Box2D coordination system use negative values?

Thank you.

# Answer
> 3 votes
According to a post I located on the Box2D forums here, it uses your renderer's coordinate system, with some coefficient relating world space units to renderer units.

The testbed for Box2D supposedly uses OpenGL, in which Y+ is up, X+ is right, and Z+ is projecting out from the monitor's surface.

Also, an article I found here mentions the SCREEN\_TO\_WORLD and WORLD\_TO\_SCREEN global parameters, and provides an implementation of a Camera class to overcome the challenges of the somewhat-poor *intentionally-separated* implementation of this in Box2D. Even if you're already past this point, it may provide further insight into what you're trying to accomplish.

Sorry if this isn't really a true answer, but I hope I've at least pointed you in the right direction.

# Answer
> 2 votes
Note, that there is **nothing like "left - right orientation"** in mathematics. When you have vector spaces, everything works perfectly without having to define, what is left and what is right. It depends only on how you draw it (e.g. gravity vector (0, -1) and Y going "up" is equivalent to gravity vector (0, 1) a Y going "down").

---
Tags: box2d, coordinates
---


title: 2D triangle with OpenGL ES on Android

text:
# Question
Title: 2D triangle with OpenGL ES on Android
I am trying to draw a triangle on OpenGL ES. I followed a tutorial to do it. even though everything seems to be fine it does not work. Everytime I run my code it sends me back to main menu.

this is my GLExample.java class:

```
public class GLExample extends Activity {
    GLSurfaceView ourSurface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        ourSurface = new GLSurfaceView(this);
        ourSurface.setRenderer(new GLRendererEx());
        setContentView(ourSurface);
    }

    @Override
    protected void onPause() {

        super.onPause();
        ourSurface.onPause();
    }

    @Override
    protected void onResume() {

        super.onResume();
        ourSurface.onResume();
    }
}

```

this is my GLTriangleEX class:

```
public class GLTriangleEx {

    private float vertices[] = {
            0f, 1f, // p0
            1f, -1f, // p1
            -1f, -1f // p2
    };

    private FloatBuffer vertBuff;

    private short[] pIndex = { 0, 1, 2 };

    private ShortBuffer pBuff;

    public GLTriangleEx() {

        // her bir float için 4 byte gerektiğinden length * 4 oldu
        ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4);
        bBuff.order(ByteOrder.nativeOrder());
        vertBuff = bBuff.asFloatBuffer();
        vertBuff.put(vertices);
        vertBuff.position(0);

        ByteBuffer pbBuff = ByteBuffer.allocate(pIndex.length * 2);
        pbBuff.order(ByteOrder.nativeOrder());
        pBuff = pbBuff.asShortBuffer();
        pBuff.put(pIndex);
        pBuff.position(0);

    }

    public void Draw(GL10 gl) {
        gl.glFrontFace(GL10.GL_CW);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertBuff);
        gl.glDrawElements(GL10.GL_TRIANGLES, pIndex.length,
                GL10.GL_UNSIGNED_SHORT, pBuff);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    }
}

```

and this is my GLRendererEx.java class:

```
public class GLRendererEx implements Renderer {

    private GLTriangleEx tri;

    public GLRendererEx() {
        tri = new GLTriangleEx();

    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
        gl.glDisable(GL10.GL_DITHER);
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
        gl.glClearColor(.1f, 0f, .9f, 1f);// set background color
        gl.glClearDepthf(1f);
    }

    @Override
    public void onDrawFrame(GL10 gl) {

        gl.glDisable(GL10.GL_DITHER);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);

        tri.Draw(gl);

    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);
        float ratio = (float) width / height;
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glFrustumf(-ratio, ratio, -1, 1, 1, 25);

    }

}

```

and my LogCat:

```
02-08 12:11:01.244: I/ActivityManager(58): Starting activity: Intent { cmp=com.android/.GLExample }
02-08 12:11:01.305: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 1143 objects / 82584 bytes in 39ms
02-08 12:11:01.393: D/libEGL(328): egl.cfg not found, using default config
02-08 12:11:01.393: D/libEGL(328): loaded /system/lib/egl/libGLES_android.so
02-08 12:11:01.534: I/DEBUG(30): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
02-08 12:11:01.534: I/DEBUG(30): Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF91/43546:eng/test-keys'
02-08 12:11:01.534: I/DEBUG(30): pid: 328, tid: 334  >>> com.android <<<
02-08 12:11:01.534: I/DEBUG(30): signal 11 (SIGSEGV), fault addr 00000000
02-08 12:11:01.534: I/DEBUG(30):  r0 00001403  r1 00000003  r2 00000000  r3 00001403
02-08 12:11:01.534: I/DEBUG(30):  r4 00239480  r5 00000000  r6 00000003  r7 00239480
02-08 12:11:01.534: I/DEBUG(30):  r8 00000000  r9 00000000  10 00000000  fp 0012fbb8
02-08 12:11:01.534: I/DEBUG(30):  ip 00000000  sp 45f03d20  lr ac40604c  pc ac40503c  cpsr 60000010
02-08 12:11:01.594: I/DEBUG(30):          #00  pc 0000503c  /system/lib/egl/libGLES_android.so
02-08 12:11:01.594: I/DEBUG(30):          #01  pc 00006048  /system/lib/egl/libGLES_android.so
02-08 12:11:01.594: I/DEBUG(30):          #02  pc 00020618  /system/lib/libandroid_runtime.so
02-08 12:11:01.594: I/DEBUG(30):          #03  pc 00013974  /system/lib/libdvm.so
02-08 12:11:01.594: I/DEBUG(30): code around pc:
02-08 12:11:01.594: I/DEBUG(30): ac40501c e5900548 e3a05b05 e2853003 e1500003
02-08 12:11:01.604: I/DEBUG(30): ac40502c e2419003 1a000023 e1a05002 e3a0a000
02-08 12:11:01.604: I/DEBUG(30): ac40503c e1d510b0 e1a00004 ebffff6e e1d510b2
02-08 12:11:01.604: I/DEBUG(30): ac40504c e1a07000 e1a00004 ebffff6a e1d510b4
02-08 12:11:01.604: I/DEBUG(30): ac40505c e1a06000 e1a00004 ebffff66 e5971020
02-08 12:11:01.604: I/DEBUG(30): code around lr:
02-08 12:11:01.604: I/DEBUG(30): ac40602c e59fe0ac e1a00007 e1a01006 e084400e
02-08 12:11:01.604: I/DEBUG(30): ac40603c e0845105 e1a02008 e1a0e00f e595f2c0
02-08 12:11:01.604: I/DEBUG(30): ac40604c e8bd81f0 e8bd81f0 e597098c e3a01b01
02-08 12:11:01.604: I/DEBUG(30): ac40605c e281c008 e150000c 1affffe1 eafffff7
02-08 12:11:01.604: I/DEBUG(30): ac40606c e3a01c05 e1a00007 e2811001 e8bd41f0
02-08 12:11:01.604: I/DEBUG(30): stack:
02-08 12:11:01.604: I/DEBUG(30):     45f03ce0  45f03d34
02-08 12:11:01.604: I/DEBUG(30):     45f03ce4  80834ab3  /system/lib/libdvm.so
02-08 12:11:01.604: I/DEBUG(30):     45f03ce8  8086deac  /system/lib/libdvm.so
02-08 12:11:01.604: I/DEBUG(30):     45f03cec  80846dad  /system/lib/libdvm.so
02-08 12:11:01.614: I/DEBUG(30):     45f03cf0  00000001
02-08 12:11:01.614: I/DEBUG(30):     45f03cf4  0012fbb8  [heap]
02-08 12:11:01.614: I/DEBUG(30):     45f03cf8  43e460f8  /dev/ashmem/mspace/dalvik-heap/2 (deleted)
02-08 12:11:01.614: I/DEBUG(30):     45f03cfc  00239480  [heap]
02-08 12:11:01.614: I/DEBUG(30):     45f03d00  ac41b858  /system/lib/egl/libGLES_android.so
02-08 12:11:01.614: I/DEBUG(30):     45f03d04  00001100
02-08 12:11:01.614: I/DEBUG(30):     45f03d08  00000077
02-08 12:11:01.614: I/DEBUG(30):     45f03d0c  ac908e2c  /system/lib/libpixelflinger.so
02-08 12:11:01.614: I/DEBUG(30):     45f03d10  428a0ee8
02-08 12:11:01.614: I/DEBUG(30):     45f03d14  00000000
02-08 12:11:01.614: I/DEBUG(30):     45f03d18  df002777
02-08 12:11:01.614: I/DEBUG(30):     45f03d1c  e3a070ad
02-08 12:11:01.614: I/DEBUG(30): #00 45f03d20  ac41b008  /system/lib/egl/libGLES_android.so
02-08 12:11:01.614: I/DEBUG(30):     45f03d24  ac41b018  /system/lib/egl/libGLES_android.so
02-08 12:11:01.614: I/DEBUG(30):     45f03d28  00000003
02-08 12:11:01.614: I/DEBUG(30):     45f03d2c  00239480  [heap]
02-08 12:11:01.614: I/DEBUG(30):     45f03d30  00000000
02-08 12:11:01.614: I/DEBUG(30):     45f03d34  428a0ee8
02-08 12:11:01.614: I/DEBUG(30):     45f03d38  428a0ed0
02-08 12:11:01.614: I/DEBUG(30):     45f03d3c  ac40604c  /system/lib/egl/libGLES_android.so
02-08 12:11:01.614: I/DEBUG(30): #01 45f03d40  00118d78  [heap]
02-08 12:11:01.624: I/DEBUG(30):     45f03d44  00000003
02-08 12:11:01.624: I/DEBUG(30):     45f03d48  00000000
02-08 12:11:01.624: I/DEBUG(30):     45f03d4c  00000004
02-08 12:11:01.624: I/DEBUG(30):     45f03d50  45f03d80
02-08 12:11:01.624: I/DEBUG(30):     45f03d54  ad32061c  /system/lib/libandroid_runtime.so
02-08 12:11:02.084: I/BootReceiver(58): Copying /data/tombstones/tombstone_09 to DropBox (SYSTEM_TOMBSTONE)
02-08 12:11:02.094: D/Zygote(32): Process 328 terminated by signal (11)
02-08 12:11:02.174: D/dalvikvm(58): GC_FOR_MALLOC freed 2585 objects / 653024 bytes in 89ms
02-08 12:11:02.184: I/WindowManager(58): WIN DEATH: Window{4400b600 SurfaceView paused=false}
02-08 12:11:02.184: I/WindowManager(58): WIN DEATH: Window{4400b9c0 com.android/com.android.GLExample paused=false}
02-08 12:11:02.184: I/WindowManager(58): WIN DEATH: Window{43f5e388 com.android/com.android.Menu paused=false}
02-08 12:11:02.184: I/ActivityManager(58): Process com.android (pid 328) has died.
02-08 12:11:02.203: I/ActivityManager(58): Start proc com.android for activity com.android/.Menu: pid=335 uid=10040 gids={3003, 1015}
02-08 12:11:02.343: I/UsageStats(58): Unexpected resume of com.android while already resumed in com.android
02-08 12:11:02.354: I/ActivityManager(58): Displayed activity com.android/.Menu: 168 ms (total 1103 ms)
02-08 12:11:02.564: W/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 328 uid 10040

```

# Answer
Did you try adding the activity on the Android Manifest too?

```
<activity
        android:name="com.example.PROGRAM_NAME.GLEXAMPLE"
        android:label="@string/app_name" >
    </activity>

```
> 0 votes

---
Tags: android, opengl-es
---


# Question
Title: Matrix Translation Transformation Question
I've been reading a lot about computer graphics lately and because of it I'm building my own math library's for fun. I was reading about Matrix Translation and Homogeneous Coords, and was wondering if these two both translate the x factor by 3.

```
{ 1, 0, 0, 3 } = { 1, 0, 0, 0 }
{ 0, 1, 0, 0 } = { 0, 1, 0, 0 }
{ 0, 0, 1, 0 } = { 0, 0, 1, 0 }
{ 0, 0, 0, 1 } = { 3, 0, 0, 1 }

```

I guess what i'm really asking is if I wanted to preform a translation would both of these be exceptible or only the first?

# Answer
> 2 votes
Both are valid and the difference is that your first is a column-major translation matrix whereas your second is row-major. The difference lies in the order you multiply matrices and in how you perform the final position transform. I'd encourage you to research more on the terms "column-major" and "row-major" for further info.

---
Tags: mathematics, graphics-programming
---


title: Camera Math for Directions

text:
# Question
Title: Camera Math for Directions
I have a Camera object that has the variables:

```
class Camera : Object
{
    public:
        float positionX, positionY, positionZ;
        float directionX, directionY, directionZ;
        int speed;
}

```

The positions are what I will draw my scene's position based on, the direction is a value between 0 and 1 that I will multiply for the speed to get the next position:

```
if(keyboardInput.GetKeyState(Key::ArrowUp) == KeyState::Pressed)
{
    _viewCamera.positionX = _viewCamera.directionX * _viewCamera.speed;
    _viewCamera.positionY = _viewCamera.directionY * _viewCamera.speed;
    _viewCamera.positionZ = _viewCamera.directionZ * _viewCamera.speed;
}

```

The problem is the rotation direction, which I'm calculating with:

```
if(mouseInput.GetButtonState(Button::RightButton) == ButtonState::Pressed)
{
    //Here I get how many pixels the mouse moved between the X and Y axis with mouse sensitivity accounted for
    float rotationX = mouseInput.GetMouseMoveX();
    float rotationY = mouseInput.GetMouseMoveY();

    _viewCamera.directionX = sin(rotationX * 3.1415/180);
    _viewCamera.directionY = sin(rotationY * 3.1415/180);

    _viewCamera.directionZ = cos(rotationX * 3.1415/180);
}

```

There is something missing here, but I can't get it right. The direction when I'm looking to the left or right works fine, but when I look up or down I'm not taking into account the rotationY for calculating the Z direction.

This means, if I'm looking straightly down, I'm not supposed to move forward or backwards, just down along the Y axis. But I'm going forward/backward because I'm not calculating the rotationY in the directionZ.

I tried subtracting the cos(rotationY) to directionZ, but the movement didn't felt right (was pretty weird actually).

What's the proper math so I get the correct movement along all axis?

# Answer
```
float rotationX = mouseInput.GetMouseMoveX();
float rotationY = mouseInput.GetMouseMoveY();

const float radius = 3.0f;
_viewCamera.directionY = radius * sinf(rotationY);
float r = radius * cosf(rotationY);
_viewCamera.directionZ = r * cosf(rotationX);
_viewCamera.directionX = r * sinf(rotationX);

```

To make it look properly you need to consider point you look at as some point on the sphere with longitude/latitude. You may need to adjust sensitivity/make it opposite directions if needed by changing 3.0 to -3.0.

But you will most likely run into problems when your longitude reaches PI. This example from Microsoft will help you to implement camera properly. (BasicCamera/LonLatController)
> 3 votes

---
Tags: c++, camera
---


title: Stars coming out of screen

text:
# Question
Title: Stars coming out of screen
I am pretty new to Graphics Programming. I am currently using OpenGL. I have got some hands-on in last few days. I have knowledge of Texture Mapping, Cubemap, Multitexturing. But somehow I am not able to bridge the gap between my understanding and actual coding

What I am trying to do is create a demo of a stars coming out of screen. It should look realistic.

Now, my questions are:
1. Is Cubemap capable of doing this?
2. Do I need to write particle engine for this?(Really, don't want to at this stage)
3. This is kinda most needed for me. May I See some code..? In some tutorial / just code would also do.. but i think if its similar to my requirement then only it will Help

# Answer
What you're asking for is sometimes called the starfield effect, named after the infamous screensaver. That should give you a nice starting point for searching.

A lot of tutorials recommend "faking" the effect in 2D, that is, start by putting a dot near the centre of the screen, then moving them away from the centre and towards the edge. Sometimes an acceleration is included to simulate the perceived motion of stars that are moving almost directly at the camera. This is indeed the "easiest" way, but it is not realistic, and I prefer another:

## Use 3D particles

Represent each star as a 3D point, starting from some location in front of the camera, and moving in the general direction of the camera. That is, if the z-axis was forward/backward with respect to the camera, you would generate stars with an initial z coordinate, and random x/y coordinates, and animate the stars by subtracting a constant speed from the z coordinate.

Here's some code to get you started (illustrative purposes only, does not compile, you didn't specify the language, not using best practices):

```
class Star
{
    float x, y, z;
    void Move() { z -= STAR_SPEED; }
    void Draw();
    bool IsVisible();
};

main()
{
    list<Star> stars;
    for (int i = 0; i < MAX_FRAMES; i++)
    {
        if (i % MAKE_STAR_PERIOD == 0)
        {
            stars.append(Star(random(), random(), INITIAL_Z));
        }
        for (star : stars)
        {
            star.Draw();
            star.Move();
            if (!star.IsVisible())
            {
                stars.remove(star);
            }
        }
    }
}

```

The advantages of this approach are:

* Realistic 3D motion (2D approximations suffer from weird motion for very-far-away or very-close stars)
* Realistic distance modelling (finding the distance to the star is trivial, so you can modify the luminosity of stars based on distance etc)
* As with all particle systems, you can choose any arbitrary drawing method for each star. Draw nebulae, galaxies!

Finally, to answer your specific questions:

1. Is Cubemap capable of doing this?
    * I assume you mean using textured surfaces. Yes you can do this, but it won't look good because unless you have many layers of transparent textures, viewers will quickly discern the surfaces themselves, plus it's making the problem harder than it needs to be
2. Do I need to write particle engine for this?(Really, don't want to at this stage)
    * I recommed the 3D particle approach. Why not? An "engine" is as hard as a string is long.
3. This is kinda most needed for me. May I See some code..? In some tutorial / just code would also do.. but i think if its similar to my requirement then only it will Help
    * I gave you some code, you can search for more tutorials, really it's just points in 3D space flying in the same axis.
> 0 votes

---
Tags: opengl, 3d, textures
---


# Question
Title: Are there still advantages to using gl_quads?
OK, I understand that gl\_quads are deprecated, and thus we're not 'supposed' to use them anymore. I also understand that a modern PC when running a game using gl\_quads is actually drawing two triangles.

Now, I've heard because of that a game should be written using triangles instead. But I'm wondering if, due to the specifics of how OpenGL makes that quad into two triangles, it is ever advantageous to use quads still?

Specifically, I'm currently rendering many unconnected quads from rather large buffer objects. One of the areas I have to be careful is how large the vector of floats I'm using to make/update these buffer objects get (I have quite a few extra float values per vertex, and a lot of vertices in a buffer - the largest buffers are about 500KB).

So it strikes me that if I change my buffer objects to draw triangles this vertex data is going to be 50% larger (six vertices to draw a square rather than 4), and take 50% longer for the CPU to generate.

If gl\_quads still work, am I getting a benefit here, or is the 50% extra memory and CPU time still being used on OpenGL's automatic conversion to two triangles?

# Answer
Test your actual game. If quads are faster, use those. If not, don't.

One can reason that they're slower in some cases because some hardware doesn't support quads, so the driver has to do a lot of work to "fix" quad draw calls. Some hardware does support quads, doing the split to triangles in some fixed-function input assembly step, so it works with no significant overhead. There's also questions regarding how quads are submitted indexed vs non-indexed, as you raised, and which makes better use of limited bus transfer bandwidth and CPU generation time. Folk wisdom says to avoid quads, which is good advice if you're starting from nothing, maybe not so much if your code already works. folk wisdom says that a lot of things murder performance despite real, well-performing games doing those things.

In short, test. Don't assume, and don't ask the Internet for performance advice. We may be right sometimes but more often we'll either feed you out of date data, data based on some specific circumstance you're not in, or outright garbage we ourselves acquired second-hand from the Internet or colleagues (who themselves may not have first-hand experience).
> 6 votes

# Answer
What are the alternatives? Well, one alternative is to use Geometry Shaders, passing a `GL_LINES_ADJACENCY` primitive (4 vertices) and having the GS convert this primitive into a triangle strip. However, that's going to be slower to render, because one should assume geometry shaders are *always* slower to render.

A better method is to use indexed rendering. Here, you have two alternatives: `GL_TRIANGLES` and `GL_TRIANGLE_STRIP` with primitive restarting. The latter will result in a slightly shorter index buffer (one index for every quad). You can reuse the same index buffer for any quad rendering, so you won't need to update or modify the index buffer.

I would also suggest using unsigned shorts as the index type. If you need to render more than 16384 quads at once, then make multiple rendering calls, using glDrawElementsBaseVertex to offset the indices.
> 3 votes

---
Tags: opengl
---


# Question
Title: synchronizing view state between nodes in a rendering cluster
I'm building a display wall demo application.

The environment:

* N machines, each driving up to six displays
* Wired gigabit switch
* OpenTK application to draw the pretty pictures, running 1 copy on each node

Each node runs an identical copy of the demo executable. Each node also has some config data containing the resolution of the entire wall and the relative position of that node's displays within that space. When rendering, a scale/translation transform is applied after the projection matrix (effectively zooming in on the part of the view that the node is responsible for rendering).

The nodes have a "mode" switch set in a startup script that puts them in "send" or "receive" mode. All but one node is in "receive." (Switching a node to "send" causes all others to switch to "receive").

The demo app is a basic FPS-type fly through of some primitive geometry (grid, icosahedron, etc). On each update, the sender node broadcasts a UDP datagram containing some state information (camera translation/rotation, transforms for moving objects).

Listeners asynchronously receive these datagrams, deserialize the state and update their local copies.

The net effect is that I run the app on my laptop and fly around, and the wall nicely follows along. This all works pretty well.

However, I'm concerned that as the system scales (from 10 displays to, say, 500), that network latency will be an issue. I've also thought that, rather than spamming state across the network this way, it would be nice to stuff it into a database and have each node just pull from there, but I doubt any off the shelf databases are going to be up to a 60FPS * 500 nodes cycle.

Suggestions? What's the best way to share state between a lot of nodes really, really fast?

# Answer
> 1 votes
**Sounds like a job for multicast.** (Sounds like you're already doing that?)

Certainly a database pull is a *terrible* idea for this kind of scenario. You still have to send out the same amount of data - but now you have a lot more overhead!

Really the problem you have to worry about, more than lag, is synchronisation. You want all the displays to match each other - even if they are all many milliseconds behind the actual simulation.

In particular, a database will exacerbate the problem by serialising your updates to clients (in the "not parallel" sense of the word). Each update must be sent to clients one-by-one. If you pump out an update's UDP packets in a burst, they should stick fairly close together. Database requests will introduce potentially huge timing gaps. (Multicast moves the problem of serialisation out to the router - which may or may not be a good thing.)

Of course, your client should have some kind of "lag buffer" - where it saves up some number of input frames and then interpolates between them for output. Normally this allows games to cope with network jitter and dropped packets.

With a lag buffer, this then becomes purely a clock synchronisation problem: As long as all of your clients can select the *exact same* frame within the lag buffer to display, they will all appear to be in-sync.

Synchronising your client's clocks may be as trivial as using NTP from a local network source and using the real time to select the frame to play back. Wikipedia suggests accuracy of 1ms on a LAN - more than good enough. But if that doesn't work, you may have to create your own clock-synchronising protocol.

---
Tags: c#, networking, synchronization
---


# Question
Title: Grouped enemy movement out of sync after changing directions
Im working on a Galaxian/Space Invaders Inspired game. Im working on the enemy movement and am running into an issue where the enemies get out of sync when changing direction.

My setup is that I have a global variable enemyHorizontalDirection. Its initially set to left and any time an enemy hits the left or right side of the screen its set to whatever direction the enemies should go in. While this works Im running into an issue where the enemy that triggers the global variable enemyHorizontalDirection gets out of place. Below is a video of the behavior. http://www.youtube.com/watch?v=3kRlT9\_Dt1Q&feature=youtube\_gdata\_player

The enemies are created from left to right from a 2d array. Each enemy is added to a List at creation. I am looping through the list end to beginning at the moment. The problem occurs on the left side. When I loop through from beginning to end the problem occurs on the right side.

Here is the enemy Update Method:

```
if(groupedMovement)
{
    // When hitting right side of the screen set direction to left
    if(this.x > (Futile.screen.halfWidth - GMain.instance.gameScreenOffset) - (this.width / 2))
    {
        GMain.instance.enemyHorizontalDirection = "left";
    }

    // When hitting left side of the screen set direction to right
    else if(this.x < (-Futile.screen.halfWidth + GMain.instance.gameScreenOffset) + (this.width / 2))
    {
        GMain.instance.enemyHorizontalDirection = "right";
    }

    if(GMain.instance.enemyHorizontalDirection == "left")
    {
        this.x -= 4f;
    }

    if(GMain.instance.enemyHorizontalDirection == "right")
    {
        this.x += 4f;
    }
}

```

Here is where I loop through the enemies and call their Update();

```
for(int p = _player.Count-1; p >= 0; p--)
{
    Player player = _player[p];
    player.UpdateLocalVertices();

    Rect playerRect = player.GetTextureRectRelativeToContainer();

    if(_player.Count == 0) break;

    // Handle player/enemy collisions
    for(int e = _enemies.Count-1; e >= 0; e--)
    {
        GSpriteEnemyGameObject enemy = _enemies[e];
        enemy.UpdateLocalVertices();

        if(enemy.active)
        {
            Rect enemyRect = enemy.GetTextureRectRelativeToContainer();

            if (enemyRect.CheckIntersect(playerRect))
            {
                CreateEnemyDeathEffect(enemy, true);

                enemy.RemoveFromContainer();
                _enemies.Remove(enemy);
                PlayerHit();
            }
        }

        if(enemy.y < -Futile.screen.halfHeight)
        {
            enemy.RemoveFromContainer();
            _enemies.Remove(enemy);
        }

        if (_debug) DebugLineDraw.drawHitBox(enemy, Color.red);

        enemy.Update();
    }
}

```

Im hoping someone can point me in the right direction. Im not sure of the exact cause of this or how to approach a fix for it.

Any help much appreciated!

# Answer
You are looping through the enemies effectively from right to left. Every time the leftmost enemy hits the left side, it changes the movement direction, *then moves according to the changed direction* whereas the previous ones did not.

To fix this, defer the change until the end of the frame. There are many ways to do this; one is to have a second variable which stores the movement direction for the next frame, which you copy to the current direction variable at the beginning or end of each frame.

Another way would be to have a queue of deferred events which are dispatched after the enemies are looped through; this might be useful if you have many pieces of state that need treatment like this.
> 0 votes

# Answer
The *correct* solution is to code *exactly* what you mean. You want the enemies to move as a single collective - so they should not have individual positions at all! (Or at least not update their own positions independently.)

By coding exactly what you mean, you completely eliminate the potential for this kind of bug. In fact, a good coding philosophy is that you are describing your intentions to the machine - and to other people - so it pays to be precise.

Personally I would make your enemy's positions *parametric*. That is to say - determined by an algorithm that takes some number of parameters (for example: the current time, and the enemy's position in a row) and outputs a position.
> 0 votes

---
Tags: c#, movement
---


title: HTML5 Game (Canvas) - UI Techniques?

text:
# Question
Title: HTML5 Game (Canvas) - UI Techniques?
I'm in the process of building a JavaScript / HTML5 game (using Canvas) for mobile (Android / iPhone/ WebOS) with PhoneGap. I'm currently trying to design out how the UI and playing board should be built and how they should interact but I'm not sure what the best solution is. Here's what I can think of -

Build the UI right into the canvas using things like drawImage and fillText Build parts of the UI outside of the canvas using regular DOM objects and then float a div over the canvas when UI elements need to overlap the playing board canvas. Are there any other possible techniques I can use for building the game UI that I haven't thought of? Also, which of these would be considered the "standard" way (I know HTML5 games are not very popular so there probably isn't a "standard" way yet)? And finally, which way would YOU recommend / use?

Many thanks in advance!

# Answer
Both solutions (drawing on your canvas VS. traditional HTML/CSS) are totally valid and will work just fine. Some things to consider:

* If you're already using a canvas-based library, your code may be cleaner/more organized by continuing to use canvas instead of having additional (DOM-based) methods for UI.
* If your UI is extremely text-heavy (with dialogs etc.) then it may be simpler to implement via HTML/CSS. For instance, it's pretty trivial for text to flow in a DOM element (with stuff like wrapping and paragraph spacing) and comparatively difficult to implement in canvas.
* Depending heavily on the library you're using, it could be much easier to implement click handling on DOM elements than within your canvas. For example if you want to detect a click on an "Ok" button, that's a trivial task in HTML/JS world. But in canvas you'd need to listen to the click on a different element and check its coordinates to see where the click took place.
* Some user agents (especially mobile devices) can be tricky when using DOM elements containing text. For example, Mobile Safari may want to pop up a modal with the tools to copy/paste. Preventing this behavior might be difficult and would probably be easier in canvas land.

Some of this will be subjective; a developer I know **always** prefers using canvas since he just finds DOM to be ugly and verbose. Since either solution will work fine, I'd pick a simple single screen in your app, quickly develop it separately using both methods and see which one feels easier/better.

Best of luck!
> 18 votes

# Answer
I've been using easeljs for my canvas interaction.

It's pretty good and facilitates solid design. One of the key features that made me choose it was the facility to sync the position of your canvas objects and dom elements.

This makes it easy to do CSS speach bubbles and static UI elements like the hud frame and that kind of thing.

The advantage this has for browsers is that you get the rich canvas but you get to pawn off the smaller and static things to the dom to keep performance in check.
> 5 votes

# Answer
Canvas is slow on mobile platforms, at least mobile safari is anyway, so you'll want go use CSS based positioning of objects on those. Specifically use "translate3d" which will turn on the hardware accelerated rendering of objects.

Check out the CAAT library for canvas though, it's fast and you can use CSS backed "actors" and not change the game logic.

I cannot post links yet but here are some pseudo links http://labs.hyperandroid.com/animation
> 4 votes

# Answer
Have to agree about canvas slowness on iPhone 4. Pretty sure safari canvas is not being backed by GL. My cheezy game runs fast on iPhone 3GS and android but on iPhone 4 I think the retina display has too many pixels, or if canvas isn't riding on GL, this would explain why it drags. I like the canvas development model, haven't tried the css translate3d option yet. In particular I used GWT and the gwt-g2d canvas wrapper (optimization/obfuscation). http://www.photonjunky.com/shootout.html
> 2 votes

# Answer
I would suggest keeping your controls as html elements such as `menu` and `command` for accessibility reasons. Using a bit of CSS you can display elements over a canvas, and not lose out on the pre-built functionality of HTML.
> 1 votes

# Answer
I know this is an old question, but today (March 2013) we know better. I decided to answer in case someone else stumbled in here like I did. I have to disagree with most of the other answers. They are probably valid for web browser development, but not for mobile. It makes a great difference which path you choose (DOM or canvas animation). The Android webview is completely useless (slow, stuttering) in itself, which makes Phonegap useless for Android game development, unless you can apply hardware acceleration, which is currently only possible using canvas animation and a suitable framework. For more info, see this reply.
> 1 votes

# Answer
You can do it a million ways. However you feel most comfortable and your engineers feel most confident.

If you're looking for inspiration or a code example then, here's one way that I do it. I have a function that repeatedly draws a menu until a button is pressed. When the button is pressed, the game loads and the old menu click event listeners are removed and new game click event listeners are added. I also end the old draw loop of the menu and start a new game draw loop. Here's some selected snippets to give you the idea of how its done:

```
Game.prototype.loadMenu = function() {
  var game = this;
  var can = this.canvas;

  // now we can use the mouse for the menu
  can.addEventListener('click', game.menuClickEvent, false);
  can.addEventListener('touchstart', game.menuClickEvent, false);

  // draw menu
  this.loop = setInterval(function() { game.drawMenu() }, 30);
};

Game.prototype.drawMenu = function() {
  // ... draw the menu
}

Game.prototype.loadLevel = function(levelstring) {
  // unload menu
  var can = this.canvas;
  var game = this;
  can.removeEventListener('click', game.menuClickEvent, false);
  can.removeEventListener('touchstart', game.menuClickEvent, false);

  if (this.loop) clearInterval(this.loop);

  // ... other level init stuff

  // now we can press keys for the game
  //can.addEventListener('click', game.gameClickEvent, false);
  can.addEventListener('touchstart', game.gameClickEvent, false);
  can.addEventListener('keydown', game.gameKeyDownEvent, false);

  this.loop = setInterval(function() { game.tick() }, 30);
}

// called from tick()
Game.prototype.draw = function(advanceFrame) {
  // ...
}

```

This way I'm able to separate out game drawing and game events from menu drawing and menu events. It also gives me leeway to use game/animation elements in my menus should I want to make them look real pretty.
> 0 votes

---
Tags: gui, javascript, html5, mobile, html-canvas
---


# Question
Title: How to give parallax backgrounds more depth
I have 3 tiled images of some sort of galaxy/space in the background of a 2D Game: The first one has an alpha of 100%, the second an alpha of 80% and the last one has an alpha of 60%. I scroll the the one in the background slower than the other ones of course. classic parallax. In the foreground I have some particles flying towards the player to simulate some dust / stars flying by. (I know that stars don't fly by, but I think we all have seen this in a lot of games). But I can't quite achieve the depth effect I am looking for. I want it to look "deeper".

I did read something about using blending modes for the backgrounds, but that would require to render them as objects right?

So the question is: What is a good technique to do a scrolling parallax background in GameMaker?

# Answer
> 1 votes
Perhaps your technique is not the problem, but your art assets. Things that are farthest away (stars, galaxies, nebula, etc) should be in the back most layer. Where near things (gas clouds, dust, meteors, ship wreckage, etc.) should be in the top most layer. If you're putting stars in the top most layer, it may defeat the effect of parallax.

# Answer
> 0 votes
I am working on something similar, I found that a good way to make things look further away is to use a blur on the furtherest away images

Particularly in Photoshop I used filter \> blur \>gaussian blur

If things are flying towards you, you could also try adding a layer which has a gradient starting with your background colour, fading to opacity 0

Tutorial here

This will give the impression the stars are gradually coming into view

Hope that helps

---
Tags: windows, game-maker
---


# Question
Title: Creating Input layouts for different vertex types
I'm still in the planning phase for a hobby abstract renderer, and i'm wondering how i should handle multiple vertex types and different shader inputs. (This is my first graphics project, so cut me some slack for lack of knowledge :) ).

What I want to to do is have the vertices be typeless, and have my model file specify "channels" of attributes EX: position, color, normal, binormal, tanget, etc. These channels would have string identifiers and stride values. On the shader side, i would like each shader program to specify which "channels" it requires via the identifier. Vertex Buffers would be compatible with the shaders if they had all the attributes required by the shader.

this is all abstract so I must be able to implement the functionality in most API's. However, taking a look over at D3D11, it looks like i would have to create a new Input layout per Vertex Buffer/ Shader COMBINATION. It would also mean some sort of goofy cataloguing system that goes, "if you have this specific combination of attribs, and the shader requires this specific combination of attribs, then use this layout", which makes me a little queasy thinking about it :\ . The number of input layouts would grow exponentially with more combinations.

The other solution would be to create and delete a new input layout EVERY time you wish to render. same queasiness -\_-. Was D3D11 intentionally trying to force every vertex buffer in your design to have the same type?

Does anyone have a better suggestion? the main parameters i would like are the channel based vertex buffers, and the channel receiving shaders.

# Answer
This sounds like you are talking about a Flexible Vertex Format (FVF). This allows you to define you vertexes as you would like, though this is for D3D9 rather than for D3D11.

One thing to keep in mind is not to have things *too* dynamic. The reason is, the more vertex formats that are the same, the more models that share the same texture/shader/material etc... the faster things can be rendered.

If you are going to use standard model formats, a common FVF should be all you need:

XYZ UV

Regarding shaders, they are custom built for specific models and vertex formats. For best performance, they expect things to be precise, rather than, "Which FVF am I using?"

Performance is King.
> 2 votes

---
Tags: c++, architecture, directx11
---


# Question
Title: Character movement relative to cursor position
I want my top-down shooter character to move *towards the mouse* when pressing the up arrow and *strafe relative at right angles to it* when pressing the left and right arrow keys.

I can't figure out how to do this.

Here is my code (The character is `character_mc`):

```
import flash.events.MouseEvent;
//Event Listners
stage.addChild(crosshair_mc);
crosshair_mc.mouseEnabled = false;
crosshair_mc.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor);

function fl_CustomMouseCursor(event:Event)
{
    crosshair_mc.x = stage.mouseX;
    crosshair_mc.y = stage.mouseY;
}
Mouse.hide();

stage.addEventListener(MouseEvent.MOUSE_MOVE,facecursor);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_KeyboardDownHandler);
//Functions
function facecursor(event):void
{
    character_mc.rotation = (180 * Math.atan2(mouseY - character_mc.y,mouseX - character_mc.x))/Math.PI + 90;

}

function fl_KeyboardDownHandler(event:KeyboardEvent):void
{
    trace("Key Code Pressed: " + event.keyCode);
    if (event.keyCode == 38)
    {
        character_mc.y = character_mc.y - 5;
    }
    if (event.keyCode == 40)
    {
        character_mc.y = character_mc.y + 5;
    }
        if (event.keyCode == 39)
    {
        character_mc.x = character_mc.x + 5;
    }
        if (event.keyCode == 37)
    {
        character_mc.x = character_mc.x - 5;
    }

}

```

I'm new to actionscript, so example code would be helpful.

# Answer
> 0 votes
The direction to the cursor is given by cursor - character position (in screenspace). This is the direction you want to move towads when moving 'forward'.

So, you would add this direction to your characters position to move towards the mouse cursor. You would then move your character like this:

```
//assuming scaleFactor is a variable with value < 1.0
character_mc.x = character_mc.x + scaleFactor * (crosshair_mc.x - character_mc.x);
character_mc.y = character_mc.y + scaleFactor * (crosshair_mc.y - character_mc.y);

```

.. if the 'move forward' key is pressed

But, using this vector directly will move/warp your character directly to the mouse cursor, so you might want to scale it down a bit. Ofc, if you where using vectors, this would be easier (e.g. you could multiply the normalized direction by a speed instead of using a scaleFactor).

To move to either the side, you would need to move to a direction -90° or 90° from the forward direction.

Edit: The distance between the character and mouse cursor influences the above formula, thus the character moves faster the further the mouse is away.

This can be changed to be a constant speed by either calculating a constant direction from the characters rotation (using trigonometric functions) or by normalizing the direction vector. In both cases, the result is multiplied by the characters speed and added to her position.

For more information about vector algebra, see e.g. here: http://www.euclideanspace.com/maths/algebra/vectors/vecGeometry/index.htm

---
Tags: 2d, movement, vector, control, shooter
---


# Question
Title: Career in game development move: hone developper skills, go indie, or a mix?
## Question

**When you have a current stable job as a developer in another field, what is the best course of action to enter the game industry?**

* Wait (indefinitely?) for an opportunity to sell your skills to an already established game studio (aiming at the ones with a wide employee base).
* Go indie and start making games with a few artist friends, living on your savings.
* The middle road: try to find a company that will hire you in your current sector part-time, and use the rest of the week to start an indie game project.

## Some extra background information

I am currently employed as a software developer, working on banking-related systems. While this pays decently, it's not a very glamorous occupation, and I often wish I would be working on more creative projects. Sadly, my limited free time leaves me with little opportunities to take side projects.

I'm now at a turning point of my career, as I'm about to switch companies. I'm wondering if I shouldn't use this opportunity to start my own (indie game) thing.

Being hired by an established game studio is difficult, as I'm a good software developer in my current field, with some experience in management, but my experience does not translate well to the gaming industry (little knowledge of the tools specific to that sector). I would have to go back in terms of salary and responsibilities, and this would both mean not keeping my current lifestyle, and give up on the team management side for a while. Both things I'd rather not do.

**If you happen to be working in the game development field (big studios, editors, or indie), and started as a software developer in another sector, I would very much like to know about your experience.**

# Answer
Quitting your job and starting to develop your own game while living on your savings is a big financial risk. You never know if your game will sell (especially when it's your first), and when it doesn't, the move could ruin you.

It's also easy to underestimate the time you will need to finish your game. Your savings might run out before you have a marketable product. You will need to take a real job again to survive, your product will be delayed for years, and when you ever complete it, the market will have moved on and nobody will care about your game anymore.

I would recommend you to keep your job so you keep your stable income and develop your game idea in your spare time. Maybe arrange a part-time agreement with your employer so you have more time, provided that you still make enough money to come by.

When you are sure you have a product which would sell (active community, hundreds of thousands of downloads of the alpha version, people you never had contact with already blogging about your game), you can still decide to quit your job and work on your game full-time.
> 6 votes

# Answer
It depends on what you want from it. If you're in gamedev for fun, go ahead and build your own team. If it's both money and fun you're equally interested in, you may want to join an existing team.

I'm in this for fun, and I know for a fact that most teams exist for profit, or don't meet my personal requirements (*they make boring stuff*), so I'm alone on this for now, but I may start working together with some people, if they share my enthusiasm.

---

On a side note, if you're wondering what kind of game you should make first, remember that the greatest games in history were those which took quite some time to make. That probably includes previous experience in gamedev, but not necessarily. Take Minecraft for instance. There are different ways to create games, some don't assume to release a fully working version. Valve updates TF2 constantly. So if you have a great idea for a game, take all the time you need to understand how it should work, find out which tools to use, but don't forget to pay your rent and eat sometimes ;)
> 0 votes

# Answer
there is certainly a change in thought process when working with game development. so some practice there would be a requirement

but ultimately like any form of creative work a portfolio would be your strongest asset
> 0 votes

---
Tags: game-industry, career
---


# Question
Title: Where does the light come from, using Maya/Panda3D?
Total noob to Maya. Total noob to Panda3D. Planning on becoming really good at both as soon as I have free time to do so, but right now I have an assignment due in a few hours which requires this:

(The part which confuses me is bolded.)

> * Model and texture a vehicle and two different obstacles
> * Build a scene graph in Panda with a plane, the vehicle, several copies of each of the obstacles, and (at least) a direction light
> * Program vehicle movement, constrained to a plane (no terrain)
> * **Working headlights**
> * Vehicle collides with obstacles

How do I attach a light source to a model? I'm assuming this is done in Panda3D but I'm sufficiently new to this that I wouldn't be astonished to hear it's part of the model.

# Answer
In Panda3D, a light is represented by a node in the scene graph, just as a geometry node represents a geometry mesh. A light source is typically attached under a specific node in the scene graph (in your case, under a node representing the vehicle, so that the light moves with the vehicle). Then, the light is explicitly enabled on the nodes that it needs to illuminate (usually `render`, to illuminate everything), using `render.setLight(yourLight)`.

Since the .egg format presently does not support lights, it is not currently possible to export lights from Maya to Panda3D through the .egg format. You will need to create the light objects in Panda3D and attach them to your vehicle node in the code.

It is however possible to create an empty node in Maya to indicate where the light should be positioned, and then extract the position of that particular node in Panda3D, so that you don't need to hardcode the specific coordinates that the headlights should be positioned at.
> 1 votes

---
Tags: lighting, maya, panda3d
---


# Question
Title: How can I fix these errors with Panda3D's sample projects?
I just installed the latest Panda3D packages on a Mint 12 32-bit virtual machine. Then I downloaded and configured Eclipse and tried to run the Asteroids sample project. The window is created properly. But after rendering the scence once the game freezes. This happens with the other sample apps, too.

Here's the error log:

```
DirectStart: Starting the game.
Known pipe types:
  glxGraphicsPipe
(all display modules loaded.)
:display:gsg:glgsg(warning): Occlusion queries advertised as supported by OpenGL runtime, but could not get pointers to extension functions.
OpenGL Warning: glXChooseFBConfig returning NULL, due to attrib=0x6, next=0xffffffff
:display:glxdisplay(warning): No suitable FBConfig contexts available; using XVisual only.
depth_bits=16 color_bits=24 alpha_bits=8 stencil_bits=8 accum_bits=64 back_buffers=1 stereo=1 force_hardware=1
AL lib: pulseaudio.c:331: PulseAudio returned minreq > tlength/2; expect break up
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4654 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4654 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3057 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3057 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
OpenGL Warning: No pincher, please call crStateSetCurrentPointers() in your SPU
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3661 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 3661 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 4765 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid enumerant
:display:gsg:glgsg(error): at 5703 of panda/src/glstuff/glGraphicsStateGuardian_src.cxx : invalid operation
:display(error): Deactivating glxGraphicsStateGuardian.

```

What can I do to fix the problem ?

# Answer
OpenGL driver emulation in virtual machines tends to be very unreliable, and more often than not plain useless. You may need to turn down the framebuffer requirements in Panda3D to get it to work, for instance by putting `framebuffer-alpha #f` in your Config.prc file in order not to request an alpha framebuffer. But given the general unreliability of these drivers, you should consider that it may be virtually impossible to get it to work at all.

However, you could choose to avoid OpenGL and use software rendering by putting `load-display tinydisplay` (or, depending on your Panda version, `load-display p3tinydisplay`) in your Config.prc file, but rendering will not be slower and you will not be able to use more advanced features.
> 3 votes

---
Tags: opengl, python, linux, eclipse, panda3d
---


# Question
Title: Why does matrix multiplication lead to different result if it's done on CPU, compared to GPU(shader)?
If I'm calculating a "camera space" on the CPU, by multiplying the view with the projection matrix on the CPU , and afterwards multiplying the world to the result my vertices do not pass to the pixel shader (probably because they are thrown of the screen space).

On the other hand if I'm multiplying the world with the view and the result with the projection, all on the GPU the result is right.

What exactly happens on the GPU that doesn't happen when multiplying on the CPU?

# Answer
> 0 votes
After tweaks and many, many matrix multiplications done by hand I figured it out. When passing data to shader DirectX implicitly transposes it, therefore:
A\*B on CPU sent to shader becomes (A\*B)t (where t denotes transposed).
(A\*B)t according to formal math is Bt\*At(observe the change in order of operation).

In order to premultiply your matrices (View and Projection) in my case I had to apply transpose to their product, not each one.
WRONG: At\*Bt sent to GPU becomes (At\*Bt)t=Btt\*Att=B\*A
RIGHT: (A\*B)t sent to GPU becomes (A\*B)tt=A\*B
Check the wikipedia article on Transpose

# Answer
> 1 votes
What do you use as the W component for vertex positions in CPU-based calculations? To apply the translation part of the matrix, you have to use 1 for W. GPU adds that W=1 for you while converting less than 4-component vertex position data streams to 4-component vectors.

I assume that all of the other math is correct, though. There are many ways to mess things up with multiple non-commutative operations (like matrix-matrix/matrix-vector multiplication), it could also be possible that there might be wrong order of operands somewhere...

---
Tags: mathematics, directx, hlsl
---


# Question
Title: Adding Shader Model 3.0 support to my Direct3D9 app
So far, we've only used pixel shaders because we never needed to do any custom processing at the vertex shader level. However, the 3.0 model shader forces you to define a vertex shader. And that's where I get lost.

That's because our pixel shaders have this signature:

```
sampler2D Texture0;

struct PixelShaderInput{
        float2 TexCoord : TEXCOORD0;
        float4 Color : COLOR;
};
struct PixelShaderOutput {
    float4 color : COLOR0;
};
PixelShaderOutput PixelShaderFirstPass( PixelShaderInput input ) {
        //Magic happens here
        //We use the tex2D function to sample Texture0
}

```

From what I've read about vertex shaders, the vertex shader output is the pixel shader input. So I added this:

```
struct VertexShaderInput{
    float4 Position : POSITION;
}

PixelShaderInput MyVertexShader( VertexShaderInput input  ){
     //At a loss here...
}

```

I don't know how to map the vertex shader input to the pixel shader input. All examples I found on the web just have the vertex shader return a float4, which is what their pixel shader expects.

# Answer
> 0 votes
A vertex shader can map the TEXCOORD0 semantic input. So I just receive it and return it unchanged for the pixel shader to use. Same for COLOR. But the vertex shader is required to process the POSITION input (I got an error saying so when I compiled the effect). So I ended up with this (currently working, and the speedup was small but noticeable):

I also noticed my pixel shaders were not using their COLOR input, so I removed it (they obtained the pixel color by sampling the texture at the given coordinates).

```
sampler2D Texture0;
float4x4 g_matProjection;
float4x4 g_matView;
float4x4 g_matWorld;

struct VertexShaderInput{
    float4 Position : POSITION;
    float2 TexCoord : TEXCOORD0;
};
struct VertexShaderOutput {
    float4 Position : POSITION;
    float2 TexCoord : TEXCOORD0;
};
VertexShaderOutput BasicVertexShader( VertexShaderInput input ) {
    VertexShaderOutput output;
    output.Position = mul( input.Position, g_matWorld );
    output.Position = mul( output.Position, g_matView );
    output.Position = mul( output.Position, g_matProjection );
    output.TexCoord = input.TexCoord; //Just pass it along
    return output;
}

struct PixelShaderOutput {
    float4 color : COLOR0;
};
PixelShaderOutput PixelShaderFirstPass( VertexShaderOutput input ) {
        //Magic happens here
        //We use the tex2D function to sample Texture0
}

```

Another thing I learnt is that when you implement your own vertex shader, D3D calls that set the transform matrices are ignored. So, for example, I had to replace `m_pd3dDevice->SetTransform( D3DTS_WORLD, pNewVal )` with an effect `SetMatrix` call that updates the `g_matWorld` effect variable. Same for view and projection matrices.

---
Tags: hlsl, directx9
---


# Question
Title: How do I implement an AutoParallax Background in AndEngine GLES1?
I'm using AndEngine GLES1. In my game, I use AnalogOnScreenControl to move a sprite and when it moves vertically, the background image also moves vertically. I want to do something like this: that is in this link. I know that AutoParallax Background or BackgroundParallaxScrolling may be used. But how do I use it in my game?

# Answer
Have you looked at the AutoParallax example code in AndEngine? It creates the parallax background layers iike this:

```
final Scene scene = new Scene();
final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack, vertexBufferObjectManager)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid, vertexBufferObjectManager)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront, vertexBufferObjectManager)));
scene.setBackground(autoParallaxBackground);

```

You can read the rest of the code here.
> 1 votes

---
Tags: android, andengine, parallax-scrolling
---


title: 2D car physics and high speed turning

text:
# Question
Title: 2D car physics and high speed turning
I've been looking at the following page, which has been very helpful: http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html but have come into problems with the high speed turning section (about two thirds down the page)

He gives the following function to calculate the slip angle:

but it looks as if `Vlat` and `Vlong` are both vectors, and I can't see how putting vectors into the `arctan` function or the `sgn` function (which I assume is a function which returns -1 or 1 depending on the value of the sign) works.

The immediately below this he talks about `F n,lat` which he describes as "normalized lateral force for a given slip angle", but I am not sure how to calculate this value.

I'm not sure of any of the maths below this either, but this may be because I have not yet worked out the above bits, so if you wish to explain things below it then I would be grateful but it is not necessary.

I am writing the code using C# and XNA if this is important.

Thanks

# Answer
I believe those are the lateral and longitudinal components of the velocity. Because those values are aligned (side and forward, respectively) to the direction of the car, they don't need to be vectors at all. They can be described as a simple scalar value, where their direction is abstracted into the overall reference frame of the car.

Those values will always be at right angles to each other, composing the net velocity. Your values are being modified by the weight distribution, and the whole value between the parenthesis can be any value. Regardless, arc-tangent can accept values beyond the -1 to 1 range, because the tangent can produce values approaching +infinity and -infinity.

Bonus fact: is is preferred to call the inverse of tangent `arctan` rather than `tan^-1` because `(1 / tan(x))` is very different from running the `tan` function backwards. It's about avoiding confusion.

```
arctan(tan(x)) == x
tan^-1(x) == (1/tan(x))
tan^-1(tan(x)) == (1/tan(tan(x))) != x

```

**Edit:** *The review of the car physics tutorial*

I think the physics guide you are following should be studied with a lot of skepticism. There are several instances where the analysis is plainly wrong. The author strings together unrelated physics, and draws wrong conclusions from them. Here are a few examples:

1. He confuses the idea of center of mass with something he calls "center of geometry", sometimes even in the same sentence. Center of mass is very important to the study of statics and dynamics, but the measured distance from one point to another is **not** a valid way to determine the center of mass. The author makes this mistake, and even the formula posted in the question relies on that bad assumption.
2. The author describes pitching of the car during braking and acceleration, based on some height value (which should be the center of mass but is not determined at all), but does not relate it to relative position or the total forces applied to the car. If this calculation were to be done correctly, it would require 3-dimensions, which the author claims not to do.
3. He multiplies a constant by an angle. Both are unitless numbers. He somehow equates that to a force. In all physics, all the time, units must be conserved.
4. He equates the rate of increase in angular velocity to the amount of torque applied from the engine through the geartrain, etc. He divides the value by a ***very*** rough calculation of the moment of inertia of the wheels. This would only be valid if the car were suspended in the air, not contacting the ground. It is absurd to apply the concept to drive wheels.

So! That leads to point you asked about, which is when to apply either of the two subsequent calculations. He describes that one is for small angles, and the other is not, but he doesn't explain why. (It's the transition from static to sliding friction, by the way). I think that is the point where the guide become utterly useless, and goes from a poor understanding of physics to pure bullshit.

The guide gets one thing right. The forces applied in the direction of travel of the car affect the car's speed. The lateral forces applied to the wheels affect the angular momentum of the car. Almost everything else should be thrown out.
> 7 votes

---
Tags: 2d, mathematics, physics
---


# Question
Title: Collision Response: game character vs. density function
## Introduction

I am working on my own "novelty" game-engine project, where the **world is represented by a continuous density function**. It has only one interface, a function that returns the density at a given point:

`float sample(float x,float y,float z);`

I triangulate this density into an **iso-surface for density == 1.0** using marching cubes. The iso-surface is then rendered using OpenGL to display the result on screen.

I have made a function using newton's method to approximate the nearest point in the volume with density equal to 1 (within an error margin) for a certain direction, like this:

`vec3d hitTest(vec3d &origin, vec3d &direction);`

I can use this to perform collision ***detection*** between my main character and the volume, by seeing if the character has transitioned from "outside" to "inside" of the volume during update. I am also able to find the normal at the hit point by doing 3 hit-tests and doing some simple vector math "(a-b).crossProduct(a-c)" or some such.

## Question

How would I be able to calculate the proper collision ***response***?

I am no expert in collision detection/response, so what I am after is a **clear and consise explanation** of what makes a "physically correct" impulse collision under my foretold circumstances.

**Source code** in pseudo/C++ is a big bonus!

Thanks!

# Answer
> 2 votes
Common physics engines only need collisions defined by:

* the position of the point of contact
* the surface normal
* the position/velocity of the moving body (managed b the engine itself)

Therefore, you should be able to use a stock physics engine, as long as it supports plugging in custom collision shapes. I recommend doing so, as it gets you a lot of flexibility to add more interesting physics.

---
Tags: collision-detection, collision-resolution
---


# Question
Title: How should we determine which portions of the game to develop first?
We are developing an action RPG and have listed out the following modules/subsystems that we're going to need to make:

* HUD(Heads-up Display) System
* EXP/Leveling System
* Combat and Navigation System
* Character Controller System
* Skill System
* Monsters and NPC (AI)
* Levels (Missions) System

The combat system is real time and we planned to include a puzzle type game in some (60%) of levels. We also have a game plot. Which modules should we develop first?

# Answer
> 13 votes
As Byte56 said in the comment, whatever you choose to do first, goes first. There is no single rule that everyone should follow when it comes to developing a project. Different teams have different capabilities and needs. You might not have the available resources to do module A, but while you're working on getting the resources, you can do module B and save lots of time. If you build them properly, with a great enough degree of re-usability and independence, it won't be a problem at all.

Since we're pretty much in the same situation (right from the top, down to Unity 3D and Blender), I can tell you a few things. It might not do the job for you, even though it did for my team. And it would be best if you treated them as pieces of advice from someone else out there in the trenches.

* Build a test level, not related to your actual game content, and work on different module prototypes & features here. See what works and what does not. Only include the things that work in your actual game. If you're not sure about a particular feature, keep on testing it in-between schedules even if the team moved on to other things. Knowing what NOT to add to your game is just as important as knowing what to add to it.
* Concentrate on most of the player - environment interaction. Get the player's character to respond to the player's commands, and make sure he's able to interact with the world: pick up objects, examine objects, use objects, drop items etc. Unity's editor will help you a lot in this case: before you actually get to work with dynamic content, you can see how things go with static content, inserted via the editor. Basic dialogues go here too. While working on the dialogue system, the player can talk to a rock. It does not matter that much.
* If you've got a specialized programmer in the area of AI, get him a list of all of the AI behavior you're expecting to have in the game. Then, ask him to prepare a list of algorithms and methods to solve the given problems. While you go on with the player-environment interaction, the AI can be prototyped on paper. Or, as a library, outside your game.
* Leave the actual storyline and game content for later, when you've got at least a solid base built.
* This might be obvious: DON'T waste time asking your 3D artists to do extremely good looking models, until you've got the solid base I've been talking about earlier. Use ugly (or somewhat good looking, heh) placeholders for everything. Those X hours you save this way can be used to get yourself and the team to concentrate on other, more important things. Like the **solid base**.

This is a rough outline to get you started. You're saying that your game is comprised at around 60% of puzzles. Perhaps while someone else is prototyping the AI and combat, you can get those puzzles to be doable in the test level? As an indie developer, this can offer you tremendous advantages: you get to show people a PLAYABLE game, even if comprised only of puzzles and some basic GUI. You can consider getting some financing (on-site donations or kickstarter) this way.

Short version to always keep in mind: split your game in lots of smaller games, or iterations. Every time you add something to the game, try to obtain a playable *something* from it. You've built some traps? Try to make a real world, puzzle-like level with traps, and see how well they work. You've built a system that combines items? Try to invent a few simple puzzles that require the combination of items, and see how it feels. These are both playable somethings. Or playable parts of your grand game. Furthermore, at any point during development, you'll be having a playable something to look forward to, and a playable something which you built a short while back, that shows your actual progress. It helps with staying focused and keeping the morale of the whole team high.

# Answer
> 4 votes
I'd suggest focusing on things that allow the game to play tested early... and then continually prioritising on expanding out *playable* game elements from there.

This ensures effort isn't waisted on elements that are determined to be either not fun or not important to the fun.

A very common curse, especially amongst the enthusiastic, is to get side tracked on the detail rather than the pragmatic overall end effect. (e.g. grand game engine features, overly complex models / textures, rolling symphonies)

This doesn't mean that people can't contribute good design / architecture etc features that will never directly be experienced / noticed by the player... but it has to be as an iterative task in response to what gameplay testing has discovered.

# Answer
> 1 votes
To paraphrase Lewis Carroll:

> "Begin at the beginning, go on till you come to the end, then stop."

---
Tags: rpg, project-management, planning
---


# Question
Title: How to check the device type using Adobe AIR for iOS
How do I check what kind of device the user is running my Adobe AIR app on?

Example: `if(device == ipad3) { stagestuff.width = 300; }`

# Answer
http://forums.adobe.com/thread/745385

At this link, it shows the following:

'Hi all,

I am sharing some of my library of iOS specific stuff in the hope that the community can suggest improvements and that it may be useful to others.

The following code can determine iPhone, iPodTouch and iPad based on screen res and geolocation (iTouch has no GPS). If anybody can help with code that can narrow the selection (i.e. determine between 3G, 3GS, 2nd gen, 3rd gen etc) that would be most welcome!

edit: hmm. Just realised that the iPhone 1st gen also didn't have GPS, so i can't use that to distinguish iTouch from iPhone...

```
package com.pixelthis.frameworks.ios

{

     /**

      * ...

      * @author Peter Vullings

      */

     public class DeviceType

     {

          import flash.system.Capabilities;

          import flash.sensors.Geolocation;

          // ------------------------------------------------------

          // CONSTANTS

          // ------------------------------------------------------

          public static const IPHONE : int = 1;

          //public static const IPHONE_3G : int = 2;

          //public static const IPHONE_3GS : int = 3;

          public static const IPHONE_4 : int = 4;

          public static const IPODTOUCH : int = 100;

          //public static const IPODTOUCH_2GEN : int = 101;

          //public static const IPODTOUCH_3GEN : int = 102;

          public static const IPAD : int = 200;

          // ------------------------------------------------------

          // PROPERTIES

          // ------------------------------------------------------

          public static var _currentDevice : int = 0;

          // ------------------------------------------------------

          // METHODS

          // ------------------------------------------------------

          /**

           * Determine the current device type

           * @return The device type

           */

          public static function get currentDevice():int {

               // If we have already calculated it, return it. The device

               // isn't exactly going to change at run-time is it!

               if (_currentDevice>0) return _currentDevice;

               // Screen size

               var w : int = Math.max( Capabilities.screenResolutionX, Capabilities.screenResolutionY );

               var h : int = Math.min( Capabilities.screenResolutionX, Capabilities.screenResolutionY );

               if (w <= 480){

                    if (Geolocation.isSupported){

                         _currentDevice = IPHONE;

                    }else{

                         _currentDevice = IPODTOUCH;

                    }

               }else if (w<=960){

                    _currentDevice = IPHONE_4;

               }else{

                    _currentDevice = IPAD;

               }

               return _currentDevice;

          }

     }

}'

```
> 1 votes

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


title: Y and X - Am I doing it wrong?

text:
# Question
Title: Y and X - Am I doing it wrong?
I sometimes run into small issues when doing my JavaScript projects. That is because most build in functions of JavaScript run X,Y if positions are needed. (In that order).

But when I build a 2D Array I start out with Y, it seems more logical for me to to run the X axis horizontal. If I am bad at explaining it, let me show you:

So my loops look like this:

```
for(var y = 0; y < 10; y++){
    for(var x = 0; x < 10; x++){
        console.log("Doh!");
    }
}

```

Is this so insane? I would like to convert to the normal practise so that I have an easier time while building my game and don't have to do constant switcherroos.

So why is it X before Y ?

Edit: Here is another example, and probably the main reason for my confusion: X is Horizontal, and Y is Vertical in my books..

```
[
[0,1,2,3,4],
[0,1,2,3,4],
[0,1,2,3,4],
[0,1,2,3,4],
]

```

# Answer
> 8 votes
No, if it's working for you, you're not doing it wrong. If you'd like to switch, than do so. The order you process rows/columns is sometimes arbitrary, sometimes not. **Which order you use depends entirely on the algorithm you're using.**

There's multiple different combinations for processing X,Y. It's up to you to choose which one is correct for your algorithm. **In the case where the each iteration is independent of any other, you can choose which ever one you want.** You can switch which is in the inner loop and you can also switch if the loops go from min to max or max to min.

I imagine the default is:

```
for xmin to xmax
    for ymin to ymax

```

because this is often how the data is arranged in memory. (Not necessarily true for all languages as the order of the index can change).

For example, an array `A[3][3]` (`A[X][Y]`):

Where the `y` value is in the inner loop increments first and then "rolls over" to increment the `x` value. Other than that, (X,Y) is the standard way to write it in mathematics.

# Answer
> 4 votes
You are doing it wrong...sort of. The wrong thing you are doing is correlating the order in which coordinates are written with the order in which loops are nested. Those are totally different ideas!

More specifically, the wrong thing is that your coordinate system is tied in a strong (and brittle) way to your implementation of your data storage. That means you are designing bad code from an OO standpoint. The data storage should be opaque to the thing that uses it, and the thing that uses it should not care how the data is stored. The user of the data only needs to know how to get the piece of information that it wants.

What you should do is find a way to abstract away your nested array data structure, and hide it in a method like `getPoint(x,y)`. Then you do not have to worry about which array is nested in which order. You could leave your backwards data structure exactly as it is, as long as your getter method knows to first find array y, and then seek within it for element x. But whatever code is calling `getPoint()` does not know that. It only needs to know the two coordinates it is interested in.

# Answer
> 1 votes
It does not matter! I also always write Y first (looks more natural). When you have your matrix in array as rows, you can even do some optmization. Instead of this:

```
for(var y=0; y<h; y++){
    for(var x=0; x<w; x++){
        m[y*w+x] = a;
    }
}

```

you can use this:

```
for(var y=0; y<h; y++){
    var i = y*w;
    for(var x=0; x<w; x++, i++){
        m[i] = a;
    }
}

```

and avoid lots of multiplications! :)

---
Tags: javascript
---