title: How can I use remote playtesters?

text:
# Question
Title: How can I use remote playtesters?
I'm working on a website for asynchronous two-player games (mostly board games); as part of the site's development I'm hoping to use it to playtest new games I design. The good news is that this offers a much larger pool of playtesters; the bad news is that they'll be remote, so I have no easy way of gauging reactions or of directly watching them play. Obviously I can get a lot of useful information just by extracting metric data (e.g. How many moves games take, who wins more often, average margins of victory, etc.), but I'm wondering how much I can go beyond this too:

* What data particularly should I be looking to extract from completed (or even in-progress) games?
* What are effective means of collecting information from the participants themselves rather than just the games? In particular, will surveying players (e.g. with email or web forms) do me any good?
* What sort of essential information should I *only* expect to be able to garner from ‘local’ playtests?

# Answer
You could ask them to record their play sessions with a video capture software like Fraps or GameCam. Additionally, you could also ask them to wear a headset with microphone and comment verbally on their game experience (the results would be similar to a "Let's play" video). The advantage of verbal commenting is that it is more spontaneous and honest than any written feedback.

It's also easier to gauge the emotional reaction of testers when hearing them thinking aloud while trying to perform a task. When a tester writes *"Usability Issue: Start game button hard to find"* it's hard to estimate how critical this really is. But when you hear a tester stumbling around the game screen mumbling *"Let's start a new game... where is that... button... maybe... no... or here... or maybe I have to... damn, where is that f###ing button"* it's much more obvious how large that problem really is and how the user expects it to be solved.
> 5 votes

---
Tags: game-design, web, playtesting
---


# Question
Title: Rendering Unity across multiple monitors
At the moment I am trying to get unity to run across 2 monitors. I've done some research and know that this is, strictly, possible. There is a workaround where you basically have to fluff your window size in order to get unity to render across both monitors.

What I've done is create a new custom screen resolution that takes in the width of both of my monitors, as seen in the following image, its the 3840 x 1080:

How ever, when I go to run my unity game exe that size isn't available. All I get is the following:

My custom size should be at the very bottom, but isn't. Is there something I haven't done, or missed, that will get unity to take in my custom screen size when it comes to running my game through its exe?

Oddly enough, inside the unity editor, my custom screen size is picked up and I can have it set to that in my game window:

Is there something that I have forgotten to do when I build and run the game from the file menu? Has someone ever beaten this issue before?

# Answer
> 4 votes
There are ways of emulating the resolution and you are on the right tracks with your customised resolution in nVidia for your two monitors (as this is the way I have done it and made it work.)

You can use some third party tools to enable a dual screen setup in your Unity game. This unfortunately will not be something that will be packaged with your Unity3D game and so is not the most conventional solution for anyone that plays the game without these applications, however it is a workable solution.

The details I found in someones answer on the Unity Answers board where they were attempting to use multiple video outputs instead of using the Normalised Vieport Rectangles on one output spanning multiple monitors:

Using Multiple Monitors Video Outputs

In order to acheive a custom resolution when you are running the game, to make your workaround a little more flexible for different multi monitor setups you can try to use the Screen.SetResolution method to set the game to your custom resolutions. I am not sure if this will span your multiple monitors however so I'm not confident on its compatibility yet. I will test this out on my own project when I can.

Let me know if this helps or if you have any solutions already.

---
Tags: unity, rendering
---


# Question
Title: Snapping of irregular images in iphone puzzle app
I am working on puzzle app in which i need to snap irregular shapes as they come in contact of one another as i am new to game development so i dont have any idea how to achieve this functionality in my app.Any suggestion would be highly appreciated.

# Answer
It's true that each image has an irregular shape, but you don't need to snap that shape. It also does have a bounding box, and you know where that bounding box should be in the solved puzzle. Note that those bounding boxes can collide but it doesn't matter at all! so you just need to check if the bounding box almost as it's rightful position, and if it is, you just need to move it to it's exact position and lock it.
> 3 votes

---
Tags: cocos2d
---


title: XNA draw 3d graphics in 2d game

text:
# Question
Title: XNA draw 3d graphics in 2d game
I am programming a simple pool game in XNA. I am using Farseer for simple 2d physics but I want to use 3d graphics. My problem is I can't get the rendering to work.

I have one model for the ball and one for the table, both exported from Cinema 4D into .fbx. I am able to load them and even display them, but not on the correct position. Farseer is using standart coordinate system (X+ to the right, Y+ down) and I need to somehow convert the position from farseer and display the models on the right place on the screen and with the correct size (this should be easy to achieve using scale matrix).

I need help finding what my projection, view, and world matrices I should use?

# Answer
> 0 votes
You may want to consider turning on DEBUG VIEW in farseer, if you haven't already done so. I also had a difficult time lining up my Farseer objects with my 2D world objects. The following is the code I used to get the objects to line up:

```
Matrix proj = Matrix.CreateOrthographicOffCenter(0f, Viewport.Width, Viewport.Height, 0f, 0f, 1f);
Matrix view2 = Matrix.CreateScale(32);
view2 *= view;
_worldDebug.RenderDebugData(ref proj, ref view2);

```

The "view" above, is the matrix used when drawing everything else.

I suspect this may help solve your issue, it would most likely be a matter of adjusting the Scale matrix.

---
Tags: xna, 3d, projection
---


# Question
Title: ios screen design -> how to target multiple devices
I am writing an IOS Game, landscape only and I am having a conceptual issue with my artwork. The screens are all different sizes. Retina, non-retina as well.

Non Retina ipads + ipad mini is 1024 x 768.

Retina ipads are 2048 x 1536.

So how big do I draw my art? What concept am I messing up? Any screen templates I can download to help me. i.e, learn the boundaries, etc?

# Answer
Generally you should create your art for the highest-resolution you're planning to support and then scale it down (there are tools out there that do this automatically).

That eliminates the resolution-problem and leaves you with the problem of the *aspect-ratio*. There's no definitive solution to this problem, you'll have to figure out what works best for your game (scaling/cropping, letterboxing etc.). Here's a similar question.

When your screen-sizes have significant differences in size (eg. a desktop-computer vs. a smartphone), then you'll have to adapt your design to these different sizes. Text that's perfectly readable on a big screen might become unreadable on a mobile-device. On the other hand a HUD/GUI of a mobile-screen applied to a large screen might look clunky and not appropriate for the device.

Please note that I'm talking about physical-size and not resolution here. I'm aware that a iPad 4 has a higher resolution than most desktop-computer monitors, but these pixels are so dense, that you still design your layout for 1024x768.
> 1 votes

---
Tags: ios, art, screen
---


# Question
Title: Include a custom font when publishing in Visual Studio XNA
I have a custom font called "Gold Box Games" that I want to use in a game I'm making. I have the font installed on my computer and it works just fine in the program when I run it in test. However, when I examined the publish settings I noticed I could not include that font with the things the publish-created installer makes.

How do I include a custom font to be pushed along with the rest of my files built with the Publish Wizard? This font will also need to be installed when another user runs my program (installed during that first 'setup' phase when they run the game the first time.)

# Answer
If you are referring to your in-game fonts, you do not need to install the custom fonts in order to use them with your compiled game. When compiled, your fonts get converted to .XNB files, which are packaged in in your /bin directory and are used to draw in game.
> 3 votes

---
Tags: xna-4.0, fonts, publishing
---


# Question
Title: Detecting collision with a 3D array of boxes
I am at the stage of my development process where I want to implement collision. Now I can think of a simple way of doing it, if the camera's x, y or z are inside the position of a certain cube then don't let the camera move in the direction it hit the object. Seems simple enough.

The thing is I think this will be pretty intensive for collision detection. I am using a 3D array for my cubes, and I think there maybe is a way to simplify it by using this array. I just don't know how. If there isn't a way because the camera can move freely is the idea that I suggested a good way of doing collision? It will only be run on one group of cubes, the one you are above at X point in time. Cubes are static at every point in time.

# Answer
Depends on which type of bounding box you're talking about.

Axis-aligned bounding cubes are one of the fastest ways to do a rough first-pass collision test, before sending those that pass to a more precise collision check. Edit: This is especially true when you have multiple moving objects that may collide with one another.

Oriented bounding cubes require more, and more complex, operations, and wouldn't usually be my recommendation for a first pass collision check, but could be used for the second pass if your game objects occupy the majority of that cube. Which, in this case, they actually are cubes, so that fits perfectly. This case would be an exception where if you have a manageable number of cubes, this could be the only check you need to run. However, if you find your game loop slowing down as the number of objects increases, you'll probably want to find another method to prune some number of objects from the list before running this type of test. (Assuming it's the collision that's slowing the game down, and not some other method that's also running on those objects each frame.)

Other than AABB's, and because the cubes are static, you could also use some form of collision tree. In 3D space, look at Octrees. If visualizing the octree isn't easy at first, look at 2D Quadtrees and then come back to 3D. For static objects, the greatest improvement in performance requires either building the tree offline and storing it in a file, or increasing your level load time by building it at run-time. This is just something to be aware of, and unlikely to be a deal-breaker.

My recommendation, because of the specific scenario you described, would be to try OBB's, because your objects actually are cubes and thus this will be the most accurate test possible. See if the game can handle it without slowing down. If so, no need for anything else. If not, AABB's are relatively easy to implement, try nesting your collision such that you check against the AABB first and only if you find an AABB collision would you attempt the OBB collision check. If that's still not enough, scrap the AABBs, look into Octrees and run your OBB collision only if you find a hit within the tree.
> 2 votes

---
Tags: java, collision-detection, lwjgl, bounding-boxes
---


# Question
Title: Does it matter where I initialize Directx11's shader constant buffer?
Should I initialize it before `Map()` or before \`Unmap()? Does it make a difference?

# Answer
There is no need to initialize a constant buffer with default values, simply ensure you have created it initially by calling CreateBuffer() on the d3d device. You then have to call Map() before you can copy any data into that buffer, and then Unmap() to return control of it to the GPU. It is good practice to initialize object members to default values on construction, but with a buffer it would simply depend on the context.
> 1 votes

---
Tags: shaders, directx11, index-buffer
---


# Question
Title: Using AdMob with Games that use Open GLES
Can anyone help me integrating Admob to my game. I've used the badlogic framework by MarioZencher ... and My game is like the SuperJumper. I am unable to use AdMob after a lot of my attempts. I am new to android dev...please help me..I went thru a number of tutorials but not getting adds displayed ...

I did the following...

1. get the libraries and placed them properly
2. My main.xml looks like this

android:layout\_width="fill\_parent" android:layout\_height="wrap\_content" android:text="@string/hello" /\>

1. My Activity class onCreate method:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

```
RelativeLayout layout = new RelativeLayout(this);
adView = new AdView(this, AdSize.BANNER, "a1518637fe542a2");
AdRequest request = new AdRequest();
request.addTestDevice(AdRequest.TEST_EMULATOR);
request.addTestDevice("D77E32324019F80A2CECEAAAAAAAAA");
adView.loadAd(request);
      layout.addView(glView);
      RelativeLayout.LayoutParams adParams =
              new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                              RelativeLayout.LayoutParams.WRAP_CONTENT);
      adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
      adParams.addRule(RelativeLayout.CENTER_IN_PARENT);
      layout.addView(adView, adParams);
      setContentView(layout);

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                     WindowManager.LayoutParams.FLAG_FULLSCREEN);
glView = new GLSurfaceView(this);
glView.setRenderer(this);
//setContentView(glView);

glGraphics = new GLGraphics(glView);
fileIO = new AndroidFileIO(getAssets());
audio = new AndroidAudio(this);
input = new AndroidInput(this, glView, 1, 1);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "GLGame");

```

}
2. My Manifest file looks like this ....

```
    <activity android:name="com.google.ads.AdActivity"
      android:configChanges="keyboard|keyboardHidden|orientation|smallestScreenSize"/>

</application>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk android:minSdkVersion="7" />

```

When I first decided to use the XML for admob purpose ..it showed no changes..it even didn't log the device id in Logcat...

Later when I wrote code in the Main Activity class.. and run ... Application crashed ... with 7 errors evry time ...

The android:configChanges value of the com.google.ads.AdActivity must include screenLayout.

The android:configChanges value of the com.google.ads.AdActivity must include uiMode.

The android:configChanges value of the com.google.ads.AdActivity must include screenSize.

The android:configChanges value of the com.google.ads.AdActivity must include smallestScreenSize.

You must have AdActivity declared in AndroidManifest.xml with configChanges.

You must have INTERNET and ACCESS\_NETWORK\_STATE permissions in AndroidManifest.xml.

Please help me by telling what wrong is there with the code? Can I write code only in xml files without changing the Activity class ... I will be very grateful to anyone providing support.

# Answer
You need to add the admob activity to your android manifest.. The following question has a good example:

https://stackoverflow.com/questions/10214308/android-admob-how-to-declare-adactivity-in-manifest

```
        <activity android:name="com.google.ads.AdActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

```
> 1 votes

---
Tags: android, platformer
---


# Question
Title: What does a typical game designer do every day?
I am doing a project in class and i need to know what a person in the game designing career does every day. I have been looking and i can not find anything. If you answer this that would be greatly appreciated.

# Answer
The answer is complicated. Depending on the studio size, number of people, and task specialization, game *developers* do a lot from day to day. (I'm going to assume you mean game *developer* instead of just game *designer*, since developer is the broader term, and encompasses just about anyone who puts work into making a game, whereas designers are the ones that effectively tie the work together to make the finished product, or who come up with arrangements of elements and game mechanics to make the overall experience.)

In a smaller studio, game developers wear many hats. On any given day, one could be making art assets, recording or making sounds, writing code, creating levels, producing or proofreading story, or doing housekeeping or production activities, which could be anything from taking out the trash to burning CDs to doing accounting or marketing work. Small studio models produce people who are broad generalists; because the tasks are so plentiful compared to the number of workers, a smaller game studio requires that each person be able to contribute multiple skills to the game, and that they balance their work efforts so as to not neglect something that is needed for forward progress.

This all goes out the window when looking at large game studios. At a large game studio, there are usually more people than tasks (keeping to realistic development schedules), so subject fields (art, sound, programming, modeling, animation, game design, level creation, writing, business, and so on) typically each have their own divisions within the studio, and these are sometimes broken up even further based on individual skills or subsets of related knowledge (game programming vs. engine/tool programming, or character modeling vs. weapon modeling vs. environment modeling). In large studios, the type of person that is produced is a narrow specialist, or (in better studios) a "T-shaped" specialist. These people become very knowledgeable and productive in one or a few closely-related and specialized areas of expertise, and are also called subject matter experts.

Now, if you want a job description of a game *designer*, rather than a game *developer*, the game designer is the person whose job is to come up with the general design of a game, selecting and tying together features or aspects which will lend toward the intended experience delivered to the player, planning and distributing content creation tasks, and taking produced content and tying it together into a game. If they don't share responsibilities of content creation of their own (usually, they can double as programmers, level designers, artists, or writers), then they typically use a high-level tool (either a third-party one, like Unity or Unreal, or an in-house one for custom engine work) to bring together and manage the content of the game. They also generally produce documentation about what features and style the game should have, and ensure that everyone on the team has a shared vision of what the final product should look and feel like.

I hope this helps; I've learned all of this from a combination of online resources and developers' conferences, as I haven't gotten to produce any full games of my own just yet, outside of school projects. If you want more reliable sources, look for the proceedings for game developer's conferences and summits, and that should give you a good place to start. Remember to cite your *actual* sources!
> 1 votes

---
Tags: game-design
---


# Question
Title: How do I visualize parallax layers in a level editor?
I'm making a 2D game in Unity, but this would apply to any 2D game engine.

If I implement multiplane parallax with orthographic cameras, it is difficult to lay out the background layer's sprites and know where they will line up with sprites in other layers.

My first instinct was to use multiple cameras, one for each layer, and scale down the movement speed of cameras for background layers. This avoids having to move all background sprites every frame. The problem is that a layer that moves at half speed will take up half the space of the main layer when viewed in the editor. So it is difficult to know where to place sprites as you're laying out the game. The problem gets exponentially worse as you increase the number of layers.

How do I get around this? I've tried inversely scaling the layers by their intended movement speeds while working with them in the editor. That puts all background sprites in the correct locations relative to the main layer, but they're horribly distorted.

Do I need to just suck it up and constantly switch between the editor and the running game to test the parallax backgrounds?

# Answer
I'm unfamiliar with Unity, so I cannot help you with specifics, but it sounds like what you need is to implement a GUI means of fine-tuning those values during run-time with, say, a set of sliders or numeric fields. It would be fairly simple to implement fields to alter whatever values you're determining (scale, speed, etc) during run-time which gives you immediate feedback. For placement, you could use either fields or manual placement with click-dragging (which might be slightly harder to implement, but much more intuitive).

This gives you complete control without compiling and running the code for every small fraction of a change. When you finally arrive at a look and feel with which you're happy, use those values in your list of constants. If this is too daunting because of the number of variables you're editing (say, numerous sprite locations in numerous levels), you would want to implement it in a level editor, I imagine, with the same functionality of manual adjustment but with the result of creating and storing the data adjusted.
> 1 votes

# Answer
An idea: I would think a camera for the front layer is enough. Placing sprites a distance away from that on the z plane, and lerping the distance gives you a fraction on which to move that back layer.

For example, an object distance 10 from the front camera moves 1/10 in the background layer. An object of distance 2, would move 1/2 in its respective layer, etc.
> 1 votes

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


title: Irrlicht mouse input

text:
# Question
Title: Irrlicht mouse input
I am trying to make a chess game at this moment, using Irrlicht.

It will be a 3D Chess game but apart from most chess games it has one special quality: Free movement of the camera.

The Chess game is found in a closed room, the player can move into that room as in a MMORPG or such ( w,a,s,d move and hold right-click to rotate the camera ). It can move anywhere he wants but there will be collision detection between the player and the pieces/board/walls.

Now,I want to make the pieces move when the player click on them.Untill now I basically got the coords of a squeare ( the window ones ) And I checked the coords of the mouse click.But considering my moveable camera the coords of a squeare will never be the same, so how should I make the game realise which square I click?. My board is an obj object made in blender.

Question: How to get the mouse input in order to realise which squeare has been clicked?

**Edit due to comment:**

I have looked upon the tutorial for collision detection don't worry. The main ideea is that I am not sure how to "draw" a ray from my mouse to the square or the first thing it his, or how to determine if it hit a square or not the "wooden" thing around it.

This is how the game begins:

It happens that you can move around and click where u want to.So it can be from a diffrent angle such as this:

Or even from under the table:

The main ideea is that i want to know which square he hit, and if he hit a square an not the wooden thinggy + the mouse isn't always clicked from the middle of the screen such as in the tutorial, it can be clicked from anywhere.

# Answer
Since the board will always be at the same y coordinate, you could convert mouse co-ordinates to game world co-ordinates and then work out which square is hit. core::line3d getRayFromScreenCoordinates(const float pX, const float pY, IrrlichtDevice \*device ) { core::line3d ln(0,0,0,0,0,0);

```
    irr::scene::ICameraSceneNode* camera = device->getSceneManager()->getActiveCamera();

    if (!camera)
        return ln;

    const scene::SViewFrustum* f = camera->getViewFrustum();

    core::vector3df farLeftUp = f->getFarLeftUp();
    core::vector3df lefttoright = f->getFarRightUp() - farLeftUp;
    core::vector3df uptodown = f->getFarLeftDown() - farLeftUp;

    const core::rect<s32>& viewPort = device->getVideoDriver()->getViewPort();
    core::dimension2d<u32> screenSize(viewPort.getWidth(), viewPort.getHeight());

    f32 dx = pX / (f32)screenSize.Width;
    f32 dy = pY / (f32)screenSize.Height;

    if (camera->isOrthogonal()) {
        ln.start = f->cameraPosition + (lefttoright * (dx-0.5f)) + (uptodown * (dy-0.5f));
    } else {
        ln.start = f->cameraPosition;
    }
    ln.end = farLeftUp + (lefttoright * dx) + (uptodown * dy);

    return ln;
}

core::plane3d< f32 > ground(core::vector3d<f32>(0, 0, 0), //plane through 0,0,0
                        core::vector3d<f32>(0, 1, 0)); // plane on y axis

core::vector3df convertMousePositionToWorld(float x, float y) {
    core::line3df line = getRayFromScreenCoordinates(x, y, &device);
    core::vector3d< f32 >startintersection;
    ground.getIntersectionWithLine(line.start,line.end,startintersection);

    return startintersection;
}

```
> 1 votes

---
Tags: c++, mouse, irrlicht
---


# Question
Title: XNA windows phone release black textures
i just made a 3d game in XNA for windows phone 7. I build it in release mode on visual studio 2010 and suddenly when I run game there is no textures on models - 2 models are black and one is transparent. Models are in .X format exported from 3dsmax and have textures in .jpg also added to game content. I set build action to none and all worked fine in debug mode. When I change to release mode - black textures. When I set build action to compile it gives me warning:

Asset was built 2 times with different settings: using TextureImporter and TextureProcessor using TextureImporter and TextureProcessor, referenced by...

and still no textures.

What can I do?

# Answer
Try to delete the photo texture of the visual studio and try again it happened to me im using a .fbx format and work fine the first time ill try it it give me and error when it read the texture so I delete it and it work fine also make sure you export option in 3dmax. hope it work for you xD.
> 1 votes

---
Tags: xna, textures, windows-phone-7
---


# Question
Title: Looking for very simple implicit integration example
I am trying to design a robust cloth system. I have no problem at all simulating things like that using forward integration such as euler, midpoint, runge-kutta, verlet, etc. However, I just can't wrap my head around implicit methods.

I don't understand how you formulate the equations in linear algebra terms. I'd really like to see a VERY simple tutorial, and an actual example of how to construct the equations, and then solve for a very simple system (for example, 3 particles connected by 3 springs).

I looked into David Baraff's Large Steps in Cloth Simulation, and I can kind of follow it, but going from equations to code is a weak spot of mine.

I can use a package like eigen to solve, but I'd also really like to see some code for something like conjugate gradient descent. I don't care about efficiency at the moment, I just want to be able to clearly understand what's going on.

Thanks

# Answer
> 1 votes
So, as per Mr. Geerkens suggestion, for the sake of completeness, here is the answer to the question.

A fantastic example of cloth simulation using a variety of integration methods can be found here. It has explicit and implicit methods, IMEX, FEM, runge-kutta and verlet. It comes with complete source code that is easy to understand and easy to compare to other methods.

A fantastic resource that anyone interested in physical simulation should check out.

A tip of the hat to teodron for finding it.

---
Tags: physics
---


# Question
Title: How would one render dynamic vertices in OpenGL ES 2.0 like in a 3D modeling program?
Is there an easy way to re-render dynamic vertices in OpenGL ES 2.0 so that one could, for example, make a modeling program?

I understand how to make a dynamic vertex array, but what I don't understand is how to re-render a dynamic array, I've only seen examples where you have to re-compile a shader each time you make an array.

I did find the function:

```
glBufferSubData();

```

does this update the data without having to recompile the shader?

# Answer
The simple answer is YES. You re-render those dynamic vertices once per 'frame' and it is easy. Making a modeling program will be far from easy however.

You don't have the right notion about shaders and vertices. I think you've misunderstood the examples that you've seen. A shader is the program that draws the fragments that make up the screen. That program has two parts, once that is executed once per vertex, and one that is executed once per fragment.

Look at those examples again and trace the code better. Or put a NSLog or printf by the compile call. You'll see that it only compiles it once. If not you need to look for better teaching exaples.

Compiling a shader is something you can do ONCE at the beginning of an app. You can do more often but I never do. I have several general purpose shaders and I compile each at the start and bind the one I need to use when I need to use it. Binding a shader and compiling it are two different things.

Changing vertices dynamically is easy. I have a flag program that applies physics to a grid of vertices that make up a 'cloth' flag. I update the flag once per cycle and then to draw it I call:

```
    glDrawElements(GL_TRIANGLES, testFlag.m_NumIndices, GL_UNSIGNED_INT, testFlag.m_Indices);

```

I think you need to do a lot more research on how open gl es 2 works.

If you wanted to write a modeling program you'd have a stack of objects and properties for each one that tell how many vertices and indicies, etc. We call this type of organization a 3d Engine. Then allow users to mod them. But that will be quite the undertaking. Good Luck!
> 0 votes

---
Tags: android, opengl-es2, 3d-meshes
---


# Question
Title: I have an "amoeba" game mechanic. Any idea on how to implement it?
Outside of a tetris clone, a crappy 2D top-down shooter, and some messing around with stuff like Unity and Flixel, I realize that I have yet to complete a *single*, polished, bells-and-whistles game. I want to change this, and I have an idea for my next project.

The idea is that you're an amoeba. Amoebas have these eye-like cores (or something like that, I don't know biology), and you have two of 'em. You control one with `W``A``S``D` and the other with `I``J``K``L`. There has to be a constant radius of *stuff* around each of the cores:

And the area of the amoeba has to stay constant. So if you move a core in one direction, you increase the amoeba's area, but that increase is compensated by a decrease somewhere else:

Aaaaaand I'd like to implement a *vagination* mechanic. You absorb things by engulfing them, like a boss. Maybe even an extra core, or a needle that pops you and causes all your inner stuff to start *gushing* out:

But here's the problem: I don't know how to make this. However, I would like some ideas on how to implement it. Should I explore physics libraries like Box2D? Or maybe something involving fluid physics? Any help would be much appreciated.

P.S. Feel free to steal this idea. I have plenty of ideas. If you do, please tell me how you made it so I can try it myself.

# Answer
> 16 votes
Off the top of my head, the clause that sticks out to me is that you want the area to be constant. That strikes me as the pain in all of this, so let's try and come up with a easy solution to that.

Take a piece of string and tie the ends together to make a circle. I may be wrong, but my intuition says that the inside of that string has a constant area, or would act an awful lot like your amoeba boundary.

So I would say: implement the string. ;) Most physics libraries can do springs (in Box2D this looks like the distance joint), and the easiest way to make a string is to connect lots of strings together. Join the last one up to the first to create a loop. Make sure the springs in the string have a high enough spring constant to not get stretched apart - you want them to be quite rigid and move in unison, not to expand out.

Next, create forces to act on the string. Trivially, your two cores/eyes/control points create forces onto the points that make up the string. Make the force fall off with an inverse square function:

```
float forceOnPoint(point, ball)
{
  float d = distance(point, ball);
  return K / (d*d);
}

```

And make the direction of the force directly away from the control eye/ball, like a repellent force emanating from the ball. Tweak K to control the strength of the force. Make sure that K isn't too high - you don't want it to just be pushed out massively by the force, just keep it away from the balls. Leave plenty of slack in your string.

With just those two you will probably end up with quite a uniform shape, so I'd also suggest you create some weaker forces around in the surrounding 'soup' to change the shape of the amoeba. You can make these random places, change their force regularly (you could make it a sinusoid function for nice movements) and make them work in the same way as the balls.

Vagination(fnarr): this is the difficult one. You cause it to envelop an object by checking to see if two non-adjacent points on the string have managed to get close enough, and if so you need to:

Measure the distance between the points on the string. Count the number of spring sections. Find the 'shorter' path from A to B.

Break the string and re-join it with the two points adjacent. In other words, directly join point A to point B and discard all the stuff inbetween.

Re-insert the missing number of points (plus any bonus points if you want to expand in size by eating something) into the string in the other side - i.e, the side from B to A. If you insert them equally along the length and make them shorter than the desired distance between points, you should get a nice springy-expandy effect.

I think that covers everything. By the way: idea sounds awesome.

# Answer
> 8 votes
In order for you to simulate endocytosis (the process of the cell eating external cores), each core, both inside and outside of the amoeba, would repel the boundary of the amoeba. The cores inside of the amoeba will have a moderately strong repulsive effect, while the ones outside will have a small repulsive effect. This is illustrated below.

As the outside core (red) approaches the amoeba, it's repulsive field will create a circular indentation in the amoeba. Eventually, the two sides (highlighted green) will touch each other. When a collision like this is detected, the circular indentation is erased and whatever inside of it is consumed.

This mimics the process of endocytosis quite well, and gives a nice visual effect.

As for simulating the boundary of the amoeba, I like Matt Kemp's idea of using a very large number of connected springs. This does not maintain a constant area, but a constant perimeter. In real life, water can flow freely in and out of a cell membrane (the amoeba boundary), so cells do not have a constant volume.

---

Some other ideas to make the game realistic would be being able to modify the salt content of cells somehow. When the salt concentration of the inside and outside of a cell do not match up, water rushes through the cell membrane towards the place with the higher salt content in a process called osmosis. If the amoeba has a high salt content, it would have a larger volume, but the perimeter would not change. In the game, this could be simulated by giving the inside cores a higher repulsive effect if the salt content is higher.

Since a higher salt content would give the cores a higher repulsive effect, it have the advantage of making the amoeba easier to control. Having a lower salt content would cause the amoeba to flex and bend under the influence of the environment easier. This has the advantage of being able to eat other cores easier, since the amoeba would be able to surround it easier.

# Answer
> 4 votes
Well to do the graphical effect you would most likely use metaballs (theres plenty of tutorials online for them)

# Answer
> 2 votes
Well I know of an educational game called CellCraft (no relation to Minecraft though) which involves controlling cell-like creature that has very similar movements to what you need. The game is free and probably more important is that they stated on their site clearly that they intend to make the ***source code available for free*** and it was made in ActionScript 3 and is a flash based game.

http://www.cellcraftgame.com/Home.html

# Answer
> 1 votes
The way I would go about this is to simulate a string loop similar to the way Matt Kemp suggested, but fill the interior with particles that repel each other and the string. this way you will ensure approximate volume conservation. You will have to take care to ensure large forces do not knock the particles outside.

Look up "smoothed particle hydrodynamics" for simulation of the particles, and "verlet integration" for simulating them (and the string). Verlet is a position-based technique so it is very simple and stable.

To keep things efficient I would suggest a "uniform grid spatial partitioning" system. Again, easy to implement and yeilds great speedups.

You could also use metaballs to visualise the object instead of using the string. But then you have the problem that particles might separate into separate clumps. Look up "Van der Waals forces" for attraction/repulsion balance leading to clumping.

Another approach would be to provide a small 'inflate' force to the string particles in the direction of their 'outward' normals. This will simulate a kind of internal pressure. The result is that the loop will try to maintain a circle shape. That's what I used for this.

Hope it helps.

---
Tags: game-design
---


# Question
Title: XNA - How do I change the texture of a 2D object?
I am on to make a table game, I successfully figured out how to make the arrow and to move the cursor on it (by tiles). Now I wanna find out how to make that if I hit the Enter key the tile's texture change to another. I tried like this:

```
if (input.KeyPressed(Keys.Enter))
{
    cell[X,Y].Cell_texture = tile_texture;
}

```

but it doesn't really work.

# Answer
In your `cell` class change `Cell_texture` to a `byte`

Add 2 variables

```
public static Texture2D Texture1;
Tpublic staticexture2D Texture2;

```

And your switching logic

```
 if (Keyboard.GetState().IsKeyDown(Keys.Enter))
 {
      cell[X,Y].Cell_texture = 1;
 }

```

And in your draw method

```
if (cell[X,Y].Cell_texture == 0)
    //DRAW TEXTURE1
else (cell[X,Y].Cell_texture == 1)
    //DRAW TEXTURE2

```

This will allow you to have multiple cell types, and have a global Texture2D for better memory usage.
> 1 votes

# Answer
try this:

Varibles:
Texture2D tile1;

Texture2D tile2;

```
 if (Keyboard.GetState().IsKeyDown(Keys.Enter))
 {
    tile1 = tile2;
 }

```
> 0 votes

---
Tags: xna, textures
---


# Question
Title: Alternative ways to make a battle system in a mobile indie game more fun and engaging
I'm developing an indie game for mobile platforms, and part of the game involves a PvP battle system (where the target player is passive). My vision is simple: the active player can select a weapon/item, then attack/use, and display the calculated outcome. I have a concept for battle modifiers that affect stats to make it more interesting, but I'm not convinced this by itself will add enough of a fun factor.

I've received some inspiration from the game engine that powers Modern War/Kingdom Age/Crime City, but I want more control to make it more fun. In those games, you don't have the option to select weapons or use items, and the "battling" screen is simply 3D eye candy. Since this will be an indie game, I won't be spending $$$ on a team of professional 3D artists/animators, so my edge needs to be different.

What are some alternatives to expensive eye candy that you or others have used to make a non-3D PvP game more fun and engaging? Did the alternative concepts survive the release?

# Answer
How about the attacking player gets to be able to say where on the body he is going to attack and the defending player gets to be able to say where he is going to block or dodge the attack. It has been done before, it is somewhat oldschool, but i think it is still a fun function.
> 1 votes

# Answer
The best way to handle asynchronous play with fun/engagement would be similar to designing any feature in any game: allow for interesting meaningful choices. Specifically, allow both players to make decisions, which means the "defending" play must be making preparatory decisions.

In order to prepare for attacks of unknown variables, either allow the defender to prepare a challenge for an attacker to overcome, or allow the defender to offer more than one defense setup for possible attacks. For example, either allow the defender to prepare a defended "base" that is attacked or allow the defender to respond to, say, three different attack scenarios with defense scenarios.

This methodology allows for both attackers and defenders to have more active participation and make more meaningful choices, which you'll often find results in more fun despite the asynchronous nature of the fighting.
> 0 votes

---
Tags: game-design, mobile, pvp
---


# Question
Title: Playtesting Own Game - How To Be Objective?
I am currently working on an iPhone game and am having trouble playtesting to find out which parts of the game are fun and which need to be reworked. As I sit down to play the various iterations, my feeling towards the gameplay and mechanics shift as I work through the same parts of the game over and over... and over. Some parts that I think are super fun might be tedious to someone new to the game and vice versa. My goal would be to create a game that maintains good pacing, advancement and skill progression for someone who just picked up the game, but I'm not sure how to test for that.

I try to keep an objective mindset and I do have one quality assurance technician (my wife), but she is playing the game almost as much as me and thus loses that "newbie" mindset. I don't have the resources to find and use third party testers (yet) and I would like to have my game be in a more completed state before I have even a closed beta test.

Does anybody have any tips or ideas on how to find out if my game really is fun or if it's just my mind playing tricks on me after the 1000th round?

# Answer
> 16 votes
You can't be objective in playtesting your own game. Do play your own game frequently to make sure features work, but to test "fun" you should be recruiting new people.

`I don't have the resources to find and use third party testers`

You are probably stuck thinking that playtesting requires some elaborate setup (eg. a testing lab with a two-way mirror and cameras) but that isn't really the case.\* Honestly, even if I had that kind of a setup at my disposal I would prefer to just hand my phone to someone and then take notes while they play the game. Don't stress out about who you're getting to play the game, because in the early stages you'll get lots of useful info from anyone at all playing your game. Seriously, anyone at all.

Once past the initial testing and onto beta testing, look at a service like TestFlight. That makes it really easy to find people who will beta test an iPhone game for free.

\*refer to the book "Don't Make Me Think" for the section about low-difficulty user testing

# Answer
> 6 votes
You can't, not because you ain't honest to yourself, but because your experience playing the game is completely different from everyone else's. By the time you can do gameplay testing you are an expert in your own, nothing is going to surprise you or amuse you, 'cause you know everything that is going to happen, you know how to beat every part of it, and you probably ain't going to have a lot of fun. Your experience will be more like replaying the game for the 20th time.

You ain't going to find that the interface is bad, 'cause it's second nature to you. You ain't going to find that the game doesn't give you a vital piece of information, 'cause you know everything you need to know as a player, and a lot more. You ain't going to find out where the game is too hard, 'cause you are so good at it that it's hard for you to tell the difference between easy and normal difficulty level, they are both off-the-scale easy to a master.

The best testers are people who know nothing about your game, and do remember not to spoil this property of your testers. If you at the least sign of doubt tell them what to do you will never know if they would have figured themselves in 5 seconds or if they were genuinely stuck.

# Answer
> 2 votes
I find the other answers odd, not because they are necessarily wrong, but that they ignore that any developer is (or at least *should* be) playtesting their own game far more than they would ever have the time or resources to find testers. Clearly, finding individuals completely unfamiliar with the game is necessary, and should never be overlooked. However, no matter what the situation, no matter what your resources, you-as-developer should be playing your own game constantly, so any way to decrease familiarity with the systems would be useful.

To answer how one might decrease familiarity, I would utilize a game-specific version of the classic art method Nailer mentions in his comment. Turning a work of art upside down decreases familiarity, which is the reason one's mind has difficulty thinking critically about a work. Game-specific methods would entail ways to change or alter the game so your mind cannot utilize conditioned responses and thoughts.

Ideas to start out:

* Create a mirrored GUI.
* Utilize different random textures
* Utilize no textures
* Isolate systems from the game as a whole
* Create "caricatures" of mechanics, exaggerate them (larger, smaller, single actions made repetitive, repetitive actions performed only once)
* Play without aspects of typical input methods (play with no mouse, with no keyboard, with only one hand)

In other words, metaphorically "turn the game upside down" by looking at every facet of the game you can in different ways, in different directions. While testers are invaluable, you mustn't assume that your own playtesting should be ignored or undervalued.

---
Tags: playtesting
---


title: pygame performance issues

text:
# Question
Title: pygame performance issues
I'm trying to make a tactics game using python and the infamous pygame library. I use threading for networking and pathfinding. The game uses a p2p lockstep architecture, with one of the players acting as a host. The server starts 2 threads (send / receive) for every connected player. All the connected clients also start 4 threads during their lifetime, 2 for networking, one for the main game loop and a new temporary thread for each pathfinding request.

My problem is that the program uses a lot of CPU and memory, even for very small maps, even when not blitting any sprites with transparency or running any pathfinding algorithms the program is slow and CPU intensive.

The map in my game is built out of tiles, which are 96x96 pixel pygame surfaces, which map sprite images are blitted to

```
# draw the map
for element in self.atlas.all_objects:
   try:
       self.map_surf.blit(self.map_sprites[element.sprite], element.rect)
   except:
       pass

```

The map, along with any units are finally blitted to the screen, simply

```
self.screen.blit(self.map_surf, self.map_surf_rect)

```

A very small map surface, with 8x8 tiles will make my CPU (amd 8 core 3.10ghz) run at 25%, with 70mb memory used per client (the cpu-fan goes crazy). The frame rate is still normal at this point.

A slightly larger map, 16x16 tiles shows a drop in frame rate, down from the desired 60 to around 48.

A map of what I'd want to be small/normal size for a real game, 40x40 tiles, brings the fps down to 12 and uses a surprising 215mb memory (all the spritesheets combined are 22mb, and I'm only using a basic green tile for testing), with the same CPU utilization as before.

On the same 40x40 map, replacing the image sprites with blank 1x1 pygame.Surface objects results in a frame rate of 27 (it's set to 60)

My basic question is this: Is the problem likely to be in my code, or is pygame itself horribly inefficient? If the latter, is there anything short of learning to code c++ that can replace pygame for these purposes?

If the problem is more likely to be in my code, how can I find out what it is?

EDIT: I profiled my code, and here are some of the highest numbers

map size 40 x 40 tiles:

```
4606119 function calls (4606113 primitive calls) in 145.974 seconds

ncalls  tottime  percall  cumtime  percall filename:lineno(function)

127128    0.225    0.000    0.225    0.000 vec2d.py:18(__len__)
218530    1.406    0.000    1.406    0.000 geometrical.py:64(__init__)
253534    0.544    0.000    0.544    0.000 vec2d.py:21(__getitem__)
1400934    2.309    0.000    2.309    0.000 {method 'append' of 'list' objects}
4626   20.189    0.004   20.189    0.004 {method 'fill' of 'pygame.Surface' objects}
2086545   64.417    0.000   64.435    0.000 {method 'blit' of 'pygame.Surface' objects}
1289   10.843    0.008   95.724    0.074 bullet_client.py:714(draw)

```

So it appears a lot of time is spent appending items to lists, but I'm sure not what kind of other, more efficient method of organizing my game there is. As expected however, blitting pygame surfaces trumps the other functions by a huge factor, as shown by the cumtime (whatever that is).

So I guess the question is the same, can pygame be replaced by something, or might there be a more shallow problem in my code still?

# Answer
Ensure your worker threads aren't sitting there spinning and forcing unnecessary time sharing across your CPU. This can be solved using manual resets and signals, rather than a spin lock.

Additionally, consider profiling major portions of your code to identify hot spots, my research brings up the fact that python itself includes a respectable profiler called cProfile (https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script). Use this to profile individual systems, such as your main update, rendering code, path finding algorithms, etc.

Finally, any interpreted language is going to be relatively slow compared to a direct compiled language, but your game hardly sounds intensive enough that it should be causing this problem.

*Extra note* When rendering anything, consider how to minimize the number of render calls. Render calls through a graphics API are expensive to make, and thus all production rendering pipelines provide methods for sorting, and batching entity render calls. An example would be rendering of a particle system. Rather than loop through each particle within a system and allow it to render itself, a system (or collection of systems) would be batched together to limit the number of texture, geometry and buffer transfers to the GPU.
> 3 votes

---
Tags: performance, python, pygame
---


# Question
Title: How was traditional 2D collision detection/resolution being done?
Just out of pure curiosity, I'm wondering how classic 2D games of the 80s/90s (The Legend of Zelda, Super Mario, Warcraft, ...) approached collision detection/resolution.

For some reason I can't picture them doing things like a separating axis test, or using lots linear algebra anyway. Do correct me if I'm wrong, but all that seems to have appeared with 3D graphics.

The alternative I can come up with is the kind of algorithm I came up with in my earlier games; basically some home-grown AABB test. I wouldn't get any information about the time of impact, so to resolve collisions, I had to write some rather fiddly, bug-prone code.

(Thinking a bit about it, I could have made my characters move in fixed step sizes and position all objects as multiples of that, I suppose. Resolving a collision would simply be a matter of undoing the last step. But that seems quite limiting, and a bit difficult to implement with dynamic frame rates.)

Does anybody know how collision detection/resolution was commonly done back in the day?

*Edit:* Came across this, it's quite interesting: http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

# Answer
> 1 votes
First of all, let me say that most calculations were done with integer maths because without FPUs real values were slooooooow.

I'd say that in the vast majority of cases it would be axis aligned rectangles, simply because that is the fastest way, which as Seth pointed out, is just a special case of separate axis testing.

In some cases collisions would be with circles, but when doing that the square of the distances were used to avoid square roots. These were very slow back in the day, and although it's not such an issue today, it's still done this way because why do unnecessary work?

A faster but far less accurate distance measure is using 'manhattan distance', which is simply abs(dx)+abs(dy). This might be used for coarse collsion detection before a more expensive version.

I doubt per pixel testing was ever used since it is very costly, except for simple sampling, such as the ground beneath rodent feet in Lemmings.

---
Tags: 2d, collision-detection, rpg, collision-resolution, platformer
---


# Question
Title: Level of detail algorithm not functioning correctly
I have been working on this problem for months; I have been creating Planet Generator of sorts, after more than 6 months of work I am no closer to finishing it then I was 4 months ago. My problem; The terrain does not subdivide in the correct locations properly, it almost seems as if there is a ghost camera next to me, and the quads subdivide based on the position of this "ghost camera".

Here is a video of the broken program: http://www.youtube.com/watch?v=NF\_pHeMOju8 The best example of the problem occurs around 0:36.

For detail limiting, I am going for a chunked LOD approach, which subdivides the terrain based on how far you are away from it. I use a "depth table" to determine how many subdivisions should take place.

```
void PQuad::construct_depth_table(float distance)  {
    tree[0] = -1;

    for (int i = 1; i < MAX_DEPTH; i++)  {
        tree[i] = distance;

        distance /= 2.0f;
    }
}

```

The chuncked LOD relies on the child/parent structure of quads, the depth is determined by a constant e.g: if the constant is 6, there are six levels of detail. The quads which should be drawn go through a distance test from the player to the centre of the quad.

```
void PQuad::get_recursive(glm::vec3 player_pos, std::vector<PQuad*>& out_children)  {
    for (size_t i = 0; i < children.size(); i++)  {
        children[i].get_recursive(player_pos, out_children);
    }

    if (this->should_draw(player_pos) ||
        this->depth == 0)  {
        out_children.emplace_back(this);
    }
}

bool PQuad::should_draw(glm::vec3 player_position)  {
    float distance = distance3(player_position, centre);

    if (distance < tree[depth])  {
        return true;
    }

    return false;
}

```

The root quad has four children which could be visualized like the following:

```
[] []
[] []

```

Where each \[\] is a child. Each child has the same amount of children up until the detail limit, the quads which have are 6 iterations deep are leaf nodes, these nodes have no children. Each node has a corresponding Mesh, each Mesh structure has 16x16 Quad-shapes, each Mesh's Quad-shapes halves in size each detail level deeper - creating more detail.

```
void PQuad::construct_children()  {
    // Calculate the position of the Quad based on the parent's location
    calculate_position();

    if (depth < (int)MAX_DEPTH)  {
        children.reserve((int)NUM_OF_CHILDREN);

        for (int i = 0; i < (int)NUM_OF_CHILDREN; i++)  {
            children.emplace_back(PQuad(this->face_direction, this->radius));
            PQuad *child = &children.back();

            child->set_depth(depth + 1);
            child->set_child_index(i);
            child->set_parent(this);

            child->construct_children();
        }
    } else {
        leaf = true;
    }
}

```

The following function creates the vertices for each quad, I feel that it may play a role in the problem - I just can't determine what is causing the problem.

```
void PQuad::construct_vertices(std::vector<glm::vec3> *vertices, std::vector<Color3> *colors)  {
    vertices->reserve(quad_width * quad_height);

    for (int y = 0; y < quad_height; y++)  {
        for (int x = 0; x < quad_width; x++)  {
            switch (face_direction)  {
                case YIncreasing:
                    vertices->emplace_back(glm::vec3(position.x + x * element_width, quad_height - 1.0f, -(position.y + y * element_width)));
                    break;
                case YDecreasing:
                    vertices->emplace_back(glm::vec3(position.x + x * element_width, 0.0f, -(position.y + y * element_width)));
                    break;
                case XIncreasing:
                    vertices->emplace_back(glm::vec3(quad_width - 1.0f, position.y + y * element_width, -(position.x + x * element_width)));
                    break;
                case XDecreasing:
                    vertices->emplace_back(glm::vec3(0.0f, position.y + y * element_width, -(position.x + x * element_width)));
                    break;
                case ZIncreasing:
                    vertices->emplace_back(glm::vec3(position.x + x * element_width, position.y + y * element_width, 0.0f));
                    break;
                case ZDecreasing:
                    vertices->emplace_back(glm::vec3(position.x + x * element_width, position.y + y * element_width, -(quad_width - 1.0f)));
                    break;
            }

            // Position the bottom, right, front vertex of the cube from being (0,0,0) to (-16, -16, 16)
            (*vertices)[vertices->size() - 1] -= glm::vec3(quad_width / 2.0f, quad_width  / 2.0f, -(quad_width / 2.0f));

            colors->emplace_back(Color3(255.0f, 255.0f, 255.0f, false));
        }
    }

    switch (face_direction)  {
        case YIncreasing:
            this->centre = glm::vec3(position.x + quad_width / 2.0f, quad_height - 1.0f, -(position.y + quad_height / 2.0f));
            break;
        case YDecreasing:
            this->centre = glm::vec3(position.x + quad_width / 2.0f, 0.0f, -(position.y + quad_height / 2.0f));
            break;
        case XIncreasing:
            this->centre = glm::vec3(quad_width - 1.0f, position.y + quad_height / 2.0f, -(position.x + quad_width / 2.0f));
            break;
        case XDecreasing:
            this->centre = glm::vec3(0.0f, position.y + quad_height / 2.0f, -(position.x + quad_width / 2.0f));
            break;
        case ZIncreasing:
            this->centre = glm::vec3(position.x + quad_width / 2.0f, position.y + quad_height / 2.0f, 0.0f);
            break;
        case ZDecreasing:
            this->centre = glm::vec3(position.x + quad_width / 2.0f, position.y + quad_height / 2.0f, -(quad_height - 1.0f));
            break;
    }

    this->centre -= glm::vec3(quad_width / 2.0f, quad_width  / 2.0f, -(quad_width / 2.0f));
}

```

Any help in discovering what is causing this "subdivding in the wrong place" would be greatly appreciated.

**Edit**

I've checked, and checked again and am almost certain that this is not an issue to do with my Camera code.

# Answer
It's not easy to debug recursive structures, particularly when you're relying on a potentially bugged renderer to inform you. So the question is, Is this a bug in your rendering code, or somewhere else?

Suggestions:

* Ensure that when a larger, parent quad subdivides, you stop rendering it. In other words, render only what are considered to be its leaves. This helps you to *know* what is going on (at least from the renderer's PoV), because I see a lot of overlap in your link, and if that isn't the actual problem, then it's potentially obscuring the problem.
* Minimise your LoD levels down to 2; or even implement a simpler, 2-level dummy LoD for now to see what impact this has.
* Reduce the problem to 2D if possible, and see if you can render a simple view of the 2D version (a single plane of your cube). Then work it back up from there.

I don't like to be the guy that states the obvious, but you'll need minimal test cases to make headway. When all is said and done, break down and simplify each part as much as you can to see where the bug comes in. That means turning off bits of code where you can, or else swapping other, newly-written dummy code in.

I think it will be very hard for anyone to give you a solid answer on what's wrong with your code without executing it, so I (apologetically) provide this as an (interim) answer. I hope I won't be downvoted for trying to help.
> 2 votes

# Answer
I had some similar problems. Maybe the camera is in model space instead of worldspace? That was causing the problem in may project...

Does something like that helps?

```
// Calculate the position of the vertex in the world.
   worldPosition = mul(input.position, worldMatrix);

// Determine the viewing direction based on the position of the camera and the position of the vertex in the world.
   output.viewDirection = cameraPosition.xyz - worldPosition.xyz;

// Normalize the viewing direction vector.
   output.viewDirection = normalize(output.viewDirection);

```
> 0 votes

---
Tags: c++, opengl, procedural-generation, level-of-detail, quadtree
---


# Question
Title: Analytics for PC games: is there anything similar to localytics, flurry, etc?
I would like to know if there exists any service such as Localytics or Flurry but for PC? These ones are mobile focused. It would be really great if they had support for PC too.

In the case there's nothing similar at all, what alternatives or which methods would you recommend for me to keep track of this analytics?

I'm planning to use it in a game and not only to gather generic data such as gender, age, country, etc. What I'd really like is to be able to track gameplay statistics such as: is my game too difficult? (number of deaths per player per level), is my game fun? (number of players who never finish the game and at which point did they stop playing), etc.

# Answer
You can get this with Steamworks. It has an API for putting in gameplay stats-tracking, so you can record things like deaths per location, how many players get to which levels, how long someone plays before quitting, and so on. You can look at the aggregated statistics from all players to get the data you want.

We sometimes use that data for Bayesian inference like "how many deaths does someone typically experience before they have a 50% chance of quitting the game forever" or "how does the frequency of item drops correlate to how often someone logs in to play multiplayer per week."

Note however that getting access to Steamworks requires your game to be accepted via Steam Greenlight first.
> 3 votes

# Answer
If you don't have access to Steamworks as suggested by Crashworks, one alternative is to build you own simple analytics system, as explained in this article: http://www.altdevblogaday.com/2013/02/04/brewing-your-own-game-analytics-service/
> 0 votes

# Answer
Check out Countly \- it has an SDK for Mac OS X and an SDK for C# is underway.
> -1 votes

---
Tags: pc, analytics
---


title: Installing PhysicsFS on Mingw

text:
# Question
Title: Installing PhysicsFS on Mingw
I am trying to install PhysicsFS (icculus.org/physfs/) on my Win 7 with MinGW. But I am having hard time doing it. I googled it as well but still nothing - I have used linux environment and make toolchain before (not CMake though) - but I guess I am a bit rusty.

I tried following all the directions in INSTALL.txt and google - but here is what I managed till now.

I have MinGW installed and manually installed CMake as well. Now I download the src from the site and do `cmake -G "MinGW MakeFiles`

The next this is what bemused me - Well I haven't encountered it before - I do `make` and expect it to make the files but instead it goes into Windows Command Prompt. And then I am lost.

PART 2 -

I am fairly new MinGW - I was wondering if I want to develop do I compile from source or just install the developing package - as I understand compiling from source would give me both ( dev packages as well as binaries/static libs), right? Please correct me if I am wrong.

# Answer
> 0 votes
I finally managed to get it installed. I will list out the things you need to do and proceed further.

As @rioki advised me - I used the cmake-gui to configure and generate the appropriate files.

First make sure that you are making the right kind of file. There are many options available. In my case I was trying to install PhysicsFS in MinGW and I had to learn the hard way that you should make files for **MSYS file system**.

And then use ( in my case I had different compilers) - **Specify Native Compiler**

Then when you finish. If there are any errors in the configuration process the cmake gui will help with it and you can use the gui to specify the path to correct location.

If everything is correct - (No red flags) - Then press "Generate"

Then you can go into the shell window and go ahead with the compilation process.

# Answer
> 1 votes
I recently needed to compile libRocket for MinGW and now I clearly see your problem. It is obvious; I was staring right at the beast and did not see it.

When working with CMake and MinGW you have tow options:

### The Windows Way

In this case you can use cmakegui directly without restrictions. You select the folder to generate and select "Mingw Makefiles" as version. Don't forget to specify the make location. If you are invoking cmake from the command line (cmd.exe):

```
cmake -G "MinGW Makefiles" -D CMAKE_MAKE_PROGRAM="C:\MinGW\bin\mingw32-make.exe" ..\PhyisFS

```

This will create makefile for use with MinGW under cmd, not bash. It will create an install target that (if your project has one) that installs under `C:\Program Files\`.

### The Unix Way

In this case you can not use cmakegui, since it will not find the prerequisite tools. (Maybe if you call cmakegui from MinGW's bash, it may work. But I have not tried.) In this case you create "Unix Makefiles", like so:

```
cmake -G "Unix Files" ../PhyisFS

```

This will create makefile for use under MinGW's bash. Any install target will install under "/usr/local" (or whatever you tell it with `$prefix`). This assumes a full "unix" environment and MSys provides it. So don't forget to install MSys and the MSys development tools.

---
Tags: windows, tools, mingw
---


# Question
Title: XNA Collision is quircky/wobbly, how to improve?
I am sorry if this was already answered but I couldn't find the answer. So I am doing a tile based platformer and when I was making collision I had quiet a struggle I looked here and googled for answers but they all seems to be overcomplicated for such a simple task/game.

I did come up with this code and it works almost fine:

```
Rectangle boundRect = new Rectangle((int)position.X, (int)position.Y,
            (int)(sprite.Texture.Width * scale), (int)(sprite.Texture.Height * scale));

        Vector2 previousPosition = position;
        Vector2 previousVelocity = velocity;

        if (boundRect.Intersects(collider))
        {
            velocity = Vector2.Zero;
            position = previousPosition - previousVelocity;
        }

```

It works almost as good as I want, axcept few things. When I constantly move (i.e.) to left of a collider object(tile) my player sprite is shaking, if thats right word to use, for like 1-3 pixels from edge of object, also in this state I can't move any other direction (i.e. jumping up) till I stop my current movement.

So my question is basicly: "Can I improve this while keeping simplicity, or I need to use better(more complex) approach?"

P.S. Sorry for my English, it is not my native language.

# Answer
You are going to need to do your move/collision in two steps, once for the horizontal direction, and another time for the vertical direction.

1. Move Horizontal
2. Check for horizontal collision - adjust position if needed
3. Move Veritcal
4. Check for veritcal collision - adjust position if needed

Doing the collision check like this should solve your stuttering issue. Checking both directions at once is fine for collision detection, however, when dealing with collision response it is best to do each direction individually.
> 2 votes

# Answer
If it's wobbling like you describe, then the game is drawing both before the collision occurs, and after the collision occurs. Make sure your Update function moves all of your objects first, and then handles collisions before that same Update call returns. That way, only the result of all collisions is drawn.
> 1 votes

# Answer
I think the reason your sprite is shaking is because you're moving it back from the object based on `previousVelocity`. I'm assuming that when you press or hold the movement, it sets the velocity. If this is true, then I think what's happening is:

1. Your player is moving towards an obstacle.
2. Player's next move intersects obstacle. (`boundRect.Intersects(collider)`)
3. You move player in the opposite direction. (`position = previousPosition - previousVelocity;`)
4. Player is holding down button and velocity gets set again since the player is not against the obstacle.
5. GOTO 1

Hence, your player would appear to bounce back and forth.

So, what you need to do is make the player go backwards to the point where they are resting against the obstacle instead of the full velocity. Then, ensure that when they have the button pressed down, the velocity doesn't get set if they are against something or it doesn't get set if there is an obstacle within the initial movement range (i.e. `position + velocity`).
> 0 votes

---
Tags: xna, c#, collision-detection, collision-resolution
---


# Question
Title: 2D Indie : From scratch, engine or maker?
I have been a game design/programming student for two years now, and made some little games using HTML5, most of them from scratch.

I've come to a point where I am frustrated by the coding part : Each time I make a game I have to code a lot of things, which sometimes feel redundant. I am looking for the best way to focus on the game creation and not on the code behind it. In my question I use exemples from web game because this is what I know, but it applies to any kind of platform.

Now I have heard of people creating great games using softwares like Construct 2 or Game Maker. The thing is that when I see these "makers" I feel really limited. I don't have the hand on small implementation details, on special optimisation if I need and more generally on tweaking real code.

Then, there are engines. Like cocos2D for exemple. I haven't really used them yet, but they seem to be really great engines for creating games. But I am still worried about the limitations. Will I, at some point, need something that can't be done with the engine ? Is the workflow (for integrating content, developing modules, features...) good enough and appealing ?

Here I am now, with these three big alternatives : Developing from scratch (big control at every level of the creation but lot of time to spend on low-level implementation), game makers software (ultra high-level speedy creativity, but seems limited when getting out of the box) and game engines which seem to be somewhere inbetween.

I'm looking for some feedback from people who have tried and made great games using any of these three options : What do you prefer using and why ? What would be your advice on starting with a new engine or game maker ?

# Answer
> 2 votes
1. **Generate the requirements for your game**. That includes technology, features, time requirements, etc.
2. **Self assess your own skills and availability**. Coding, artistic, time available, time/desire to learn new tech, etc.
3. **Compare the above to the capabilities/limitations of your different options**.
4. **Make a choice**.

# Answer
> 0 votes
DISCLAIMER: I haven't made any "great" games :P

I have used Game-Maker Studio for a little bit and occasionally make little 2D mini-games(in my opinion Game-Maker is not well suited for 3D games) in it from time to time. I think Game-Maker is a great way to get you started in Game Development however I do not think that it is in your best interest to stick with Game-Maker if you plan on making a career out of Game-Dev.

If you plan on making an engine then I recommend something like SDL + OpenGL or even MonoGame. Even though it might seem like a long time to learn the API's it will eventually pay off in the end.

Anyway since you are looking for the best way to focus on Game Creation then I would recommend Game Maker(or even Unity).

No great game has ever been made with Drag n Drop features(at least to my knowledge). You really can't get around scripting/coding if you want to make a great game.

---
Tags: 2d
---


# Question
Title: Compiler cannot find some DX11 types (but can find DX10)?
my problem is probably trivial but I'm new to DX and have some trouble. I've found a code snippet (of a Shader class) with `ID3D10Effect` and `ID3D10EffectTechnique` types but I'm using DX11 so I changed these to `ID3D11Effect` and `ID3D11EffectTechnique`. But the compiler protested saying that it doesn't know such types. I thought: "maybe there aren't such types actually" but quick google search indicated otherwise. I cannot find any information on which header they're in, though.

So which one is it? I've also found out that there used to be a header called `d3dx10math.h` but there's no `d3dx11math.h`. Why is that? Are there any other headers/types abandoned in DX11?

# Answer
The Effects framework no longer ships and you don't get headers or libs for it. What you *do* get is the entire source code for it (in e.g. C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Samples\C++\Effects11) so you can compile it and link to it yourself.

I expect that this is just provided for use with older programs upgrading to D3D11 however; new programs shouldn't use Effects but should instead call the raw API, as with state objects and cbuffers the old advantages of Effects are gone and in fact there are several *disadvantages* to using it.

The main such disadvantage would be relating to cbuffer updates; these need to be more carefully considered and planned, and by hiding this from you Effects can potentially lead to serious performance issues.

You can still use d3dx10math with D3D11. That's just a software-only math library, and you can use any such math library you wish - even the old d3d9 one, or one written for OpenGL.

There are a handful of other enums and defines that still use D3D10 prefixes but I can't recall them offhand - a quick search through the D3D11 header files should turn them up.
> 3 votes

---
Tags: directx11
---


# Question
Title: My logic in collision detection in diagonal code correct?
I made this code to detect collision from the diagonal(top left). I'm trying to find the problem on what I'm doing wrong. Is it necessary to have a diagonal collision for the wall? Player class:

```
if(key == KeyEvent.VK_LEFT && key == KeyEvent.VK_UP)
  {
      if(checkWallColl(World.player, World.topLeftColl))
      {
        return;
      }

       dx = -2;
       dy = -2;
       move(dx, dy);
    }

```

# Answer
You should describe what isn't working with your code, is it not properly detecting collision? Because then you should look at your collision detection function.

But in general, for 2d you should separate the checking of horizontal and vertical collision. If you do that then there won't be "diagonal collision", just a horizontal collision and a vertical collision.

So for a very basic pseudo example:

```
dx = 0;

dy = 0;

If left pressed and no horizontal collision at x - 2 then dx = -2;

If up pressed and no vertical collision at y - 2 then dy = -2;

doMove(dx, dy);

```

So if the player is pressing up and left, and there's only a horizontal collision, the player will still move up. This will allow snug fits into a corner with a more robust movement system. This isn't the best way to go with implementing movement, but it will serve your purposes with the way you've chosen.
> 2 votes

---
Tags: java, 2d, collision-detection, control
---


title: RPG Logarithmic leveling formula?

text:
# Question
Title: RPG Logarithmic leveling formula?
I'm working on a RPG game, however, I am not the amazing person at math that I wish I was, although someone suggested a logarithmic equation would work well. My current idea is for this:

You start off getting levels relatively quickly (lower xp amounts), then once you get higher up like 20-30 maybe it starts to take longer and longer to level, ending somewhere around 10-15 million experience for level 100. Can anyone offer me an equation or suggestions on how to do this? Thanks :)

# Answer
> 6 votes
If you want a logarithmic levelling formula that would simply be:

```
Level = Math.max( Math.floor( constA * Math.log( XP + constC ) + constB ), 1 )

```

For ~10 million XP at level 100 you should choose something like `constA = 8.7`, `constB = -40` and `constC = 111`.

If the level gap rises too fast for your taste increase `constA`, decrease `constB` if you want the inital level gap to be higher, and finally set `constC ~= exp((1-constB)/constA)`, in order to properly start at level 1.

Note that the appropriateness of any levelling formula depend completely on how fast players can gain XP at any given level.

See also: Algorithm for dynamically calculating a level based on experience points?

---
Tags: rpg, mathematics
---


# Question
Title: How do I use Content.Load() with raw XML files?
I'm using the Content.Load() mechanism to load core game definitions from XML files. It works fine, though some definitions should be editable/moddable by the players. Since the content pipeline compiles everything into xnb files, that doesn't work for now.

I've seen that the inbuild XNA Song content processor does create 2 files. 1 xnb file which contains meta data for the song and 1 wma file which contains the actual data. I've tried to rebuild that mechanism (so that the second file is the actual xml file), but for some reason I can't use the namespace which contains the `IntermediateSerializer` class to load the xml (obviously the namespace is only available in a content project?).

How can I deploy raw, editable xml files and load them with Content.Load()?

# Answer
> 3 votes
You don't. Content is for loading objects compiled by the content processor. However, you can add the xml files to the content project and have the project copy them to the deploy location without compiling them. If you do this you can use relative paths to access the content.

To do so put the XML file in your project as you normally would, change `Content Processor` to `No Content Required`, and then change `Copy to Output Directory` to `Copy if Newer`.

Then you can load the xml as you normally would `XmlTextReader(@"Content\example.xml");`.

# Answer
> 0 votes
On Xbox and Windows Phone you can only use the content pipeline. Everything gets serialized to XNB files and only the those are available on those machines. I don't think there is a special case for audio there and besides there is no way for the users to mod the files on Windows Phone and Xbox anyway.

However on the PC you can use all the .NET classes and more. So you can just load raw xml files using the classes from the System.XML namespaces. For example by using XmlDocument.Load.

# Answer
> 0 votes
Store the user data in a different place like you want...

You can save a copy of the loaded data or only the modifications made...

When the user get into the game next time check if exist that copy or modification, use it else load the default raw data through content load.

---
Tags: xna, xna-content-pipeline, xml
---


title: Calculating buoyancy force

text:
# Question
Title: Calculating buoyancy force
I am trying to simulate a buoyancy force for objects submerged/suspended in a fluid in a 2D environment.

According to `Game Physics: Engine Development: How to Build a Robust Commercial-Grade Physics Engine for Your Game by Ian Millington (Chapter 6, page 99)` (ISBN 987-0-12-381976-5) AND the wikipedia article on buoyancy the actual calculation is: `PVG` where `P` is the density of the fluid. `V` is the submerged volume (area) and `G` is the gravitational acceleration (0.00980665 Kilo-Newtons for Earth, but is variable in the code) and *always* acts in the opposite direction to gravity.

The code I have, below, produces a clean-*looking* result, but obviously the density of *either* the object in question or the fluid is not effecting the calculation, only the mass. If I insert the density of the fluid, say, water, at 1000.0 kg/m^3 the whole system explodes.

Is it something simple that I missed or did I screw up entirely?

The code I have so far:

```
//area_ratio is a scalar ratio of the area inside the defined fluid area (Volume submerged) and the entire object's bounding area (entire volume).
//area_ratio is equal to a value in the interval [0.0, 1.0]
//gravity is a force vector in Kilo-Newtons.
Vector2D current_weight(mass * area_ratio * gravity);

//current_area = The area inside the fluid. (Volume submerged)
Vector2D buoyancy(gravity.Normalize() * -current_weight * current_area);

//Forces and Impulses are automatically converted to Netwons by multiplying the values passed in by 1000.0
object->ApplyImpulse(buoyancy);

```

# Answer
Here's the correct code :

```
Vector2D weight(mass * gravity);
Vector2D buoyancy(immersedArea * fluidDensity * -gravity);
// assuming operator overloading of +
Vector2D totalForces(weight + buoyancy);

object->applyImpulse(totalForces);

```

In your code, you calculate `mass * area_ratio * gravity` but the weight does not depend on the immersed volume (`area_ratio`).

I think you misunderstood the law of physic you mentioned. I don't quite see what you were trying to do with

```
gravity.Normalize() * -current_weight * current_area

```

but the buoyancy of the object is simply *the opposite of the weight of the volume of fluid it displaces*. Therefore, it's equal to the displaced volume times the density of the fluid, times gravity, times -1. Note that the density of the object and that of the fluid are different in most cases so you can't reuse `current_weight`, as the buoyancy has nothing to do with the weight of the object. Also, multiplying by `current_area` will yield Newtons multiplied by squared meters, but we want Newtons! That's where you may have wanted to use `area_ratio` (assuming the rest was correct in the first place).

Finally, you must apply an impulse equal to the *total* of the forces, not just the buoyancy! So, `weight + buoyancy`!!

As a side remark, I suggest you always work with newtons (and standard units in general) unless your use of kilo newtons is justified. That way, you and whoever uses your code will have less needless thinking to do. Also, no more conversion to make in your constructor for Vector2D.
> 2 votes

# Answer
"current\_weight" isn't a function of area\_ratio. Weight is just the force of the mass affected by gravity, F=ma or W=mg. The boat will always have the same weight in the direction opposite gravity, but that force is counteracted by buoyancy.

http://www.engineeringtoolbox.com/mass-weight-d\_589.html

Try removing area\_ratio from your current\_weight calculation.
> 0 votes

# Answer
### Friction

You probably missed friction, in water that is a velocity dependent force working in the opposite direction of the velocity. For light voluminous objects the friction will counteract buoyancy very quickly.

Try pushing a beach-ball either a half or a whole metre under water and let go, you'd think the whole metre would give double the jump height, but the difference is almost non-existent, that is because the beach ball have almost reached terminal velocity in less than half a metre, most of the energy you spent pushing it down is lost to friction before the ball hit the surface.

Long story short, you'll have to deal with friction if you want to make a realistic simulation.

### 2D vs 3D

Also, you are mixing 2D and 3D, so your units don't match, you have a 3-dimensional density, so you need to multiply that by a 3-dimensional volume, in other words factor in a depth for any object or all your real world units will be for nothing.

### Cheating

Finally, don't forget that you are making a game, no one will care how you did it as long as the result seem good, no object needs more than a buoyancy force and some soft speed cap to simulate friction. If I were making the game I would probably not bother with calculating buoyancy, I'd just type in a number and see if the resulting simulation behave to my satisfaction.
> 0 votes

---
Tags: c++, physics
---


# Question
Title: How do I keep my character centred on screen?
I am making a game similar to *Legend of Zelda: Link to the Past* (top-down 2D action-adventure). I want the character to stay centred on the screen when he moves.

Currently, whenever the player wants to move, I move all of the map in the opposite direction. This works, but as I add more objects to the world, moving them all gets more complicated.

Is there a better way of approaching this?

# Answer
> 8 votes
The typical way of handling this is to create a camera object. The simplest form of a camera is just a position. This simple camera defines the "center" of the current view. So you don't modify all the positions of your tiles/entities, you just subtract the camera coordinates from the positions when drawing. In this situation, the camera does not "move".

While the camera and your character will share a position most of the time, you may still want to have them as separate values, so you can, for example, stop the camera from moving when it reaches the end of the world, but allow the player to continue moving.

A slightly more advanced camera does move. All entities and tiles are drawn without offset and the position from which you're rendering changes. This is very similar to the most basic camera, and you can still perform many of the same optimizations for selective rendering (only calling `draw` on what the camera can see), on both. It's essentially just a different way of thinking about it.

# Answer
> 3 votes
**No** this is the wrong way to go about this.

How are you going to do trap detection? What about when the player reaches the edges of the walls? Will your viewing system work for dungeons or will you have to re-write a significant portion of the code?

The world is geometry. The player is geometry. The world doesn't move. The player does. Set the camera's position to center on the player. *Always*. And that's all there is to it.

Don't try and get fancy with "oh if I slide the world, then it will give the *appearance* the player is moving". You're just going to complicate the math with weird coordinate systems at the end of the day.

It is true that OpenGL's rendering *actually* works by "fixing the camera to point down - z, and transforming and rotate all world geometry so it fits in the canonical view volume", ***but you're not meant to think about it that way when programming***. `gluLookAt` has parameters named `eye`, `look`, and `up` for a reason -- so you can think in terms of a sensible coordinate system.

---
Tags: 2d, camera, movement
---


# Question
Title: Texture Shaders vs. Pixel/Fragment Shaders?
My question is a simple one.

Functionally, practically, and performance-wise, what are the differences between using a D3DX Texture Shader, and using a Pixel/Fragment Shader rendered with a full width/height quad to a texture?

```
D3DXCreateTextureShader(
  _In_   const DWORD *pFunction,
  _Out_  LPD3DXTEXTURESHADER *ppTextureShader
);
HRESULT D3DXFillTextureTX(
  _Inout_  LPDIRECT3DTEXTURE9 pTexture,
  _In_     LPD3DXTEXTURESHADER pTextureShader
);

```

Are the above methods just syntactic sugar for performing the same task?

# Answer
Texture shaders actually does not exists on a GPU. They are just emulated in drivers. What it means is, that using them is very slow and you shouldn't use them in a real-time application like game.

If you looking for clearing textures just use clear function. If you want to create texture procedurally i do recommend binding it as a rendertarget and using rendering pipeline
> 2 votes

---
Tags: directx, textures, shaders, directx9, pixel
---


# Question
Title: How to use a physics engine for collision detection?
I want to use Box2D.XNA or Farseer for collision detection in my 2D game, but I don't know how to start. I added Box2D.XNA to my solution, but I don't know how to create rectangles, circles or whatever. The same with Farseer, I don't know how to use it because it's so difficult to find a good beginner tutorial. Does somebody know how to make rectangles or circles with one of the two physics engines? I just want to make some collisions between rectangles and circles.

# Answer
> 0 votes
There are plenty of tutorials for both libraries. For Farseer, I recommend to check out the "Getting started" section of their document, which also links to a Box2D manual for further reading: http://farseerphysics.codeplex.com/documentation?referringTitle=Home

You can then take a look at the Farseer Examples and try to understand how they work. The Basic examples are pretty straightforward. If you still have problems trying to figure it out, you might want to follow a tutorial like this.

Probably the most important thing to note is, that you can't create Rectangle of the size 100x100 Pixel in Farseer. Instead, you'd create a Rectangle that is 100x100 **meters**. This is why you'll find a class like "CoordinateHelper" or "ConvertUnits" in the above tutorials, which you'll use to convert meter to Pixels.

If you notice, that your collisions are really weird (not fitting the real Image), you will have to turn on DebugView, so you can actually see the collison boxes.

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


# Question
Title: Correct utilisation of gameloop (Android)
When using a gameloop like (much simplified)............

```
updateLogic();
render();

```

How does one perform 'single' operations? I mean, things like triggering sounds (which will only be played once), displaying a 'Get ready' graphic at the start of the game etc...

Currently I'm simply using 'flags' so maybe something like: (Pseudo code)

```
if(gameNotStarted==true)
display getReady;

```

This does work, but I end of up with a ton of condition checks in my game Loop.

Being that I can't just stop the game loop (I can't right?) every time I want to perform a single operation, is what I'm doing the correct way or is there something that I'm missing?

Another example might be when a player completes a level. I want to stay within my class/activity (I.E., the game as a whole is contained within one activity), then I move onto a small 'cut scene' which simply displays 'Well done' and plays a little piece of music, before returning to the next level of the game.

How would one handle that situation, again remembering that I'm not starting a new activity for each level (if I did, I could see that being a nightmare to manage).

# Answer
> 2 votes
One option is messaging and event handling. This basically works by setting up objects that "listen" for when the appropriate message is sent out and do something (like playing a noise or even handling game logic) when they receive it.

So essentially you would have a sound listener object that would be in charge of playing sounds. When the action happens you send out a message saying which sound you want to be played along with any other data relevant to that. Then the listener would find the appropriate sound and play it. The message would then be destroyed and you would move on to the next frame.

# Answer
> 0 votes
I have only done minor experiments with Android so this answer will be platform agnostic. Ignore it if you want an Android specific solution.

For specific case of the "Get ready" screen my laziest and favorite way is to load an image into the game window and outside the game main loop. Enter the resources loading code, the image will remain visible as nothing is refreshing the graphics. When resource loading finished and entering the main loop, the typical renderGraphics() call, or whatever you named it, at the end of the loop will get rid of the "Get ready" image during its first execution, as you probably are clearing all pixels to black before draw anything each frame.

For sounds, the audio api calls probably do not block while playing. OpenSL? Your game only needs to be fast enough when queuing buffers to avoid artifacts. Then you only need a class with a play method that let you specify the sound to play by resource name or file name. Something like:

```
SoundService.play(string name, bool loop, bool stream)

```

When stream is true, the file should be big and you want it to be read in chunks and not all at once, or another option is to let the method decide it by examining the file size, and not having a stream parameter at all.

Number of buffers are probably limited like in OpenAL, when streaming the code that checks if new buffers can be queued and read, and probably decodes to PCM, a new chunk of the file to a buffer, can be part of the main loop, something like SoundService.update() at the end of the main loop, or it can reside in a separate thread. Having a thread per audio resource playing is chaotic, better to have a single thread for all audio streaming.

For example, during collision detection and response you will do something like this:

```
If (player.health == 0) SoundService.play("boom", false, false)

```

You can have play calls everywhere but probably you will only need them during collision response, or, in some cases, during input handling.

For other things not audio related. The idea of messaging and event handling was already proposed by another answer. To give an alternative, you can translate the concept of the play method to code that should run like tasks, for example:

```
TaskQueue.add(Task task);

```

Task is a class, that have a run virtual method. Then during main loop you iterate through the task list and call it run method. You enqueue tasks following the same logic that sounds, I mean that you can do it everywhere in you code. Something like this:

```
If (victory condition reached) taskQueue.add(new ScenarioLoaderTask("level2"))

```

ScenarioLoaderTask is a class derived from Task that implements run.

Despite its name, tasks are not mean to spawn threads (while the AudioService may). Also they not must contains loops, because that may block the game for a long time. If you need a task to run in more than one game frame, then implement a way of tell the code calling the run method that you don't want it to be removed yet from the queue. Something like the run method returning a bool.

I called it tasks, but don't get confused to that another pattern that exists, that is not what I proposing here.

The disadvantage of this recommendation again a message system is that with messages, when you post a message you don't know how the game will react to it, you are only informing the game that something happened but how the game will react will depend of what objects are alive at that time listening to that particular message. So messages may be more versatile.

---
Tags: android, game-design, architecture, game-loop
---


# Question
Title: Getting Rotation Values From A Rotation Matrix
I'm trying to get rotation values along the x, y and z axis from a matrix that can include rotation, translation and scale data. Currently I have this function to return the y rotational value:

```
float GetYRotDegree( void )
{
  return D3DXToDegree( asin( m_mMatrix._13 )  );
};

```

What I'm doing to test this is first rotating along the y by 90 degrees, then rotate it by 1 more degree, and this returns 89, not 91.

I understand that this is caused because of using asin, and I did find a Stack Overflow question that was 100% identical to mine, and was solved by doing this:

```
Degree(atan2(orientmatrix[0][2], orientmatrix[0][0]))

```

The problem with this is, it assumes that there's no other rotational, scale and translation in the matrix, however I do have other data in it.

Any help would be great, and I do appreciate any help given!

# Answer
> 2 votes
You can extract the translation by removing the top three elements of the fourth column, (1,4), (2,4) and (3,4);

You can determine the scale by finding the determinant of the top-left 3x3 elements. The determinant of a plain rotation matrix is 1, so any value above or below that is the scale factor. Note that this is only true for uniform scale; per-axis scale is harder.

Once you determine the scale, you can divide the 3x3 top-left elements of the matrix by that amount. That allows you to solve for `θ` and the unit vector `(l,m,n)` by solving this simple system of equations, courtesy of wikipedia:

Keep in mind, this axis-angle form is probably the best you can do. Euler (x, y, z) rotations stack onto each other, which means it may not be possible to separate them once they are combined (this is another facet of the problem that causes gimbal lock). More specifically, there are multiple (infinite?) solutions of Euler rotations to produce a given rotation, so finding the "correct" solution will be difficult.

**OR!**

You could elaborate on why you think you need to get these values from a matrix, and folks could try to offer you a better solution.

P.S. Don't use degrees. Learn radians.

---
Tags: matrix, rotation
---