# Question
Title: Which course would be better - architecture (or) games development??
And will the job oppurtunities in games development field be good?? Which course can i prefer in these both??

# Answer
> 8 votes
As others have said, this question isn't entirely meaningful as it stands, however this type of question I've heard many times over the years, so a meaningful answer may still be beneficial to future readers.

The gaming industry is extremely broad, and even moreso recently with the huge growth of game-capable smartphones.

For **web-browser games**:

* Flash/Actionscript (won't work on iPhones, iPads, and a few other devices)
* Unity 3 (won't work on Linux), uses C# (a sub-set of it at least), JavaScript
* HTML5 and WebGL are becoming bigger on the scene. If you learn these now and they become widely used down the road you could find yourself in a good position. Signs are currently pointing to these growing quickly in the next 5 years.

For **mobile phone games**: \- Unity 3 (Android, iOS) \- Objective C (iOS)

For Windows PC games (that aren't web), if you're looking for job opportunities, most of the industry still uses C++. A lot of 3rd Party middleware and Game Engines are written in C++ as well, so if you want to work for one of those companies or work for a company that uses that software, C++ is a good bet. Also DirectX is fairly standard, but some companies use game engines that support OpenGL, which is important if the game is going to be multiplatform.

For **multiplatform PC games**: \- Java (runs on Windows, Mac, Linux) \- Some companies will contract other companies to write wrappers for their game so it can run on other Mac/Linux.

For **OSX games**: \- Java \- C \- Objective C \- OpenGL

I would focus on a part of the gaming field that most interests you, and start researching the pay for particular positions that you could be applying for in the future. Average starting salary in the gaming industry for a programmer is around $50k/year, rising to around $90k/year after 5 years, and can get up to $120k-150k/year for leads and directors. Bear in mind however that the industry tends to be clumped in certain geographical areas. In the US about half of the companies are on the west coast, where cost of living can be very expensive, so a high salary can be somewhat offset.

Also, consider that not all game programmers are programming for the game itself. Many programmers are doing things like writing tools for designers, or writing scripts for automated builds, or creating web interfaces for linking tools, game, and database together. The list goes on. This kind of programming covers many languages, like SQL, Python, PHP, HTML, etc...

---
Tags: game-industry
---


# Question
Title: ContentSerializerRuntimeType required in content pipeline?
I have a problem at the moment loading in a texture for a larger model in the content pipeline. Now it seems that I need to make a proxy object, which is fine, however looking at the SpriteSheet example provided by Microsoft they seem to use the ContentSerializerRuntimeType attribute to bind the proxy class to the real class for use at runtime.

The problem is they sprinkle serialization attributes all over the runtime class, so I was wondering if you HAVE to do it this way or if it is just a recommendation, and is there any other way of getting your proxy class to the real instance?

Ideally I dont want to have to put attributes all over my classes and would be more than happy to write the serialization code myself if there was a way to, but it seems to be an unknown as far as the documentation goes for this area...

So anyone know a way round this, or is this just the only way to do it?

# Answer
> 5 votes
If you want to avoid adding attributes to your classes (required for automatic reading/writing) then you'll want to implement a ContentTypeReader and ContentTypeWriter

---

Here's my runtime class that I want to load:

```
public class ComponentPropertyGetMathExpression : MathExpression
{
    public Type ComponentType;
    public string PropertyName;

    public ComponentPropertyGetMathExpression()
    {

    }

    // methods removed
}

```

I have 2 fields I want to get the values for.

> One interesting thing here is, one of them has the type `Type`, which **doesn't have a public parameterless constructor**. You'd get weird errors if you tried to use the default reader/writer because of this, so this is a real example of when you would need to implement your own.

---

The first thing, is to create a Content version of this class in a seperate project, that will references the project with the runtime type and will be referenced by the content project:

```
[ContentSerializerRuntimeType("FuzzyDuckEntertainment.Entities.Templates.Expressions.ComponentPropertyGetMathExpression, FuzzyDuckEntertainment.Entities")]
public class ComponentPropertyGetMathExpressionContent : MathExpressionContent
{
    public string ComponentType;
    public string PropertyName;

    public ComponentPropertyGetMathExpressionContent()
    {
    }

    // Runtime methods not needed - this class is simply a container of fields/properties
}

```

The ContentSerializerRuntimeType attribute tells the pipeline what type this will represent at runtime.

> Note that the `ComponentType` field was a `Type` at runtime, but here it's a `string`. This is because of the lack of public parameterless constructor as noted above. Another time you might have different types is when the runtime type is something GPU related, for example a `Texture2D` (in which case you might have `ExternalReference<Texture2D>` and use a ContentProcessor).

---

Now we have our 2 types.

> I'm going to use the built in XML Importer to go from an XML file to a `ComponentPropertyGetMathExpressionContent` object and no Processor. A case where you might use your own importer is if you have a heightmap BMP and want to generate vertex data. An example of using a processor is the Font Texture Processor that creates a game Font from a Texture.

Now we need to get from the content type, to the runtime type.

First, lets create the class that writes the `XNB` file at build time:

```
[ContentTypeWriter]
public class ComponentPropertyGetMathExpressionContentWriter : ContentTypeWriter<ComponentPropertyGetMathExpressionContent>
{
    protected override void Write(ContentWriter output, ComponentPropertyGetMathExpressionContent value)
    {
        output.Write(value.ComponentType);
        output.Write(value.PropertyName);
    }

    public override string GetRuntimeReader(TargetPlatform targetPlatform)
    {
        return typeof(ComponentPropertyGetMathExpressionReader).AssemblyQualifiedName;
    }

    public override string GetRuntimeType(TargetPlatform targetPlatform)
    {
        return typeof(ComponentPropertyGetMathExpression).AssemblyQualifiedName;
    }
}

```

Hopefully the above should be self explanatory (note the order we write the fields in).

---

The reader is implemented as below:

```
public class ComponentPropertyGetMathExpressionReader : ContentTypeReader<ComponentPropertyGetMathExpression>
{
    protected override ComponentPropertyGetMathExpression Read(ContentReader input, ComponentPropertyGetMathExpression existingInstance)
    {
        if (existingInstance == null)
            existingInstance = new ComponentPropertyGetMathExpression();

        existingInstance.ComponentType = Type.GetType(input.ReadString());
        existingInstance.PropertyName = input.ReadString();

        return existingInstance;
    }
}

```

Note the order we read things in. Also note that the first thing we read is the string that correspond to the `ComponentType` property. As the runtime type in this case is `Type`, not `string` I need to do some simple translation. Ideally you want any translations like this to be as minimal as possible, as unlike anything before, this will run when the game is loading.

---

See also:

What Is Content? (MSDN)
Using an XML File to Specify Content (MSDN)
Shawn Hargreaves' Blog Index #Content Pipeline

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


# Question
Title: Basic knowledge for 2d gaming and images?
Can anybody refer me some pdf or ebook that i should follow for basic 2d programming and texture ,shaders and other gaming elements details in depth.By which i can easily get through the 2d game programming.

Thanks, Balraj.

# Answer
> 5 votes
Since "2D Programming" is really now just 3D Programming, but with an orthographic viewpoint, what you need to look for is how to draw 2D things in 3D, using OpenGL.

When I did this I found the websites out there were often incomplete, too old or were written for the "wrong" OpenGL.

And that's what you need to choose first - do you want to write things on a Mac, or do you want to write things on an iOS device? Don't try to do both at once - for your first attempt don't even think about porting your code, stay focused on one platform and learn it. If you want to use an iOS device which OpenGL do you want to use? OpenGL ES 1.1 or OpenGL ES 2.0? If you don't understand the difference there's plenty of answers on this site.

Once you've decided all of that, just start Googling for things like "OpenGL orthographic projection" and "2D drawing in OpenGL" etc and find a site that makes sense to you. The key words are "orthographic projection". Also buy the correct OpenGL book which would be a great follow-up question - "What OpenGL book should I get for learning OpenGL "

---
Tags: game-design, shaders, image
---


# Question
Title: Strange 3D game engine camera with X,Y,Zoom instead of X,Y,Z
I'm using a 3D game engine, that uses a 4x4 matrix to modify the camera projection, in this format:

```
 r r r  x
 r r r  y
 r r r  z
 - - -  zoom

```

Strangely though, the camera does not respond to the Z translation parameter, and so you're forced to use X, Y, Zoom to move the camera around. Technically this is plausible for isometric-style games such as Age Of Empires III. But this is a 3D engine, and so why would they have designed the camera to ignore Z and respond only to zoom? Am I missing something here? I've tried every method of setting the camera and it really seems to ignore Z.

So currently I have to resort to moving the main object in the scene graph instead of moving the camera in relation to the objects.

**My question:** Do you have any idea why the engine would use such a scheme? Is it common? Why? Or does it seem like I'm missing something and the `SetProjection(Matrix)` function is broken and somehow ignores the Z translation in the matrix? (unlikely, but possible) Anyhow, what are the workarounds? Is moving objects around the only way?

**Edit:** I'm sorry I cannot reveal much about the engine because we're in a binding contract. It's a locally developed engine (Australia) written in managed C# used for data visualizations.

**Edit:** The default mode of the engine is orthographic, although I've switched it into perspective mode. Its probably more effective to use X, Y, Zoom in orthographic mode, but I need to use perspective mode to render everyday objects as well.

# Answer
> 3 votes
You do not mention a view matrix which is usually used for camera position & rotation while the projection matrix is used for zoom(FOV) & frustum params.

Although these two get combined in the end into a final "camera" matrix to render the object, I've not seen an engine where you have to maneuver the combined result... You always maneuver the view matrix only then re-combine (multiply) it with the projection matrix.

---
Tags: camera, matrix, perspective, view
---


# Question
Title: Are difficult code tests when applying for jobs the norm?
I just did the online tech test for Lionhead and found it a bit defeating. There were questions that required you to work out the answers to recursive algorithms that accepted arrays as arguments and made multiple calls each run through, thus splitting off into exponentially more versions. This all had to be done on paper or in your head.

There were also questions that asked you to evaluate the efficiency of theoretical algorithms and say what Big O notation you think would best describe their scaling, something that I have never been taught or learned.

There were 27 such questions. Is this usual? Is this the standard of entry level games programming? I mean, I've written 3D games, but I found this really hard.

EDIT - I have actually done another tech test for another company now which was considerably easier. I had to write various different linked list algorithms and write a routine in sudo code for how I would mathematically calculate a bot's sight given a world up vector and a forward vector.

# Answer
> 3 votes
A lot of games companies have tests that have questions as difficult as that. Not separate ones for intermediate / advanced levels. You will probably find that they would be expecting a low percentage correct for an entry level programmer, say 40% or something.

Was there a lot easier questions? And even with the harder ones did you attempt them and show how you worked it out, etc.? It is more for them to gauge what you do actually know and your aptitude when trying to attempt to answer them.

At least with an online test you have the advantage of being able to look up things you have forgotten, etc., which is probably another reason for them to make it more difficult.

Do you have a copy of it you could message me by any chance? I would be interested in seeing it.

# Answer
> 12 votes
It is worth noting that there are no industry standards for either the test material or the evaluation thereof, so your mileage may (read: will) vary wildly from that described by the answers here (my own included).

That said, what you describe doesn't sound like an uncommon test structure to me (the number of questions is a bit higher than any test I've ever taken or administered, but that's about it). Both the topics you specifically called out -- complex recursion and Big-O notation -- are topics that are typical of a solid computer science education and can be extremely useful in game development. Their presence on a test is a good way to measure if you are familiar with them, or probe for potential areas of discussion in an in-person interview.

Remember that, as others have noted, a test for a job isn't necessarily like a test in school. Doing poorly may not immediately disqualify you for further interviews. Code tests are just another screening and evaluation metric to help see where you stand in terms of your technical ability and if that would be an appropriate fit for the available position or positions.

Above all, don't be discouraged if you feel you didn't do well. Look at is as an opportunity to grow and perhaps try again later. If you're eventually told that you didn't do well enough on the test, it's worth asking for clarification (sometimes you won't get it, but it can't really hurt to ask) so you know where specifically to focus your continuing education.

# Answer
> 6 votes
This is almost standard in even the smaller software studios now. I haven't applied to any game studios but it's easy to assume they would be at the same level of difficulty if not more in the interview.

They want to know exactly what you said. If you've ever been taught that or not. If you didn't get a degree in computer science or have significant experience in game development, you may find it very hard to get a job at a studio that big, or even smaller ones.

These questions are geared for the entry level by the way. They need something to compare you against with all of the other applicants. If you don't know algorithm efficiency, they are assuming you are less qualified than the entry levels that do, as most CS grads know this stuff well. I use "you" in the general term to mean any applicant.

---
Tags: game-industry, jobs
---


# Question
Title: Why is texturing interfering with my ID-based picking implementation?
Today I came across a tutorial about color picking and I implemented it on my machine. But there is a problem: when I disable the texture and draw the object I want to pick with its picking color, it turns to black (the first colorID) and then switches to the texture which I am placing on pick.

That is the case when I enable the textures after rendering the object. When I enable texturing before rendering my object, as in:

```
void MenuButton::Render(double windowWidth, double windowHeight)
{
    glEnable(GL_TEXTURE_2D);
    gui_OrthogonalStart(windowWidth, windowHeight);
        TextureManager::Inst()->BindTexture(gui_TextureID);
         glBegin(GL_QUADS);
            glTexCoord2f(0.0f, 1.0f); glVertex2f(gui_Position.GetX(), gui_Position.GetY() - 25.0f);
            glTexCoord2f(1.0f, 1.0f); glVertex2f(gui_Position.GetX() + 100.0f, gui_Position.GetY() - 25.0f);
            glTexCoord2f(1.0f, 0.0f); glVertex2f(gui_Position.GetX() + 100.0f, gui_Position.GetY());
            glTexCoord2f(0.0f, 0.0f); glVertex2f(gui_Position.GetX(), gui_Position.GetY());
         glEnd();
    gui_OrthogonalEnd();
}

```

Then the texture cannot be disabled and the color picking isn't working. I hope I explained it well. If the code provided in the link isn't enough tell me and I will post more.

Can this problem be solved in some way?

# Answer
If you want do it this way (render colors for color picking and use texture for texturing in one rendering), I think you have to use frame buffer objects or / and shaders.

You can use only frame buffers but you have to render your scene twice - first use only colors and store output image (render) to frame buffer, then draw scene normally (with textures) and use first render for color picking.

If you use shaders, you can store colors for picking (in frame buffer) and use texturing in the same time. But you have to write your own fragment (pixel) shader.
> 3 votes

---
Tags: opengl, textures, picking
---


title: Developing Kinect game for Xbox360?

text:
# Question
Title: Developing Kinect game for Xbox360?
> **Possible Duplicate:**
> Can you access Kinect motion sensing from XNA?

bunch of questions:

* Is it possible for me to create a Kinect application using XNA and deploy it to Xbox360 platform?
* What should I use, will Kinect SDK for Windows be okay for this task?
* What about licenses, is it free to use or should I pay for licenses?

Thanks for any answer or url...

# Answer
There is no built-in Kinect support in XNA currently, so any Kinect development on the Xbox 360 is out of the question. If it is one day introduced, it may well be similar to the available Windows SDK, but there has been nothing announced.

As for licenses and fees, you can develop for the Xbox 360 if you have a $99 AppHub account, available from http://create.msdn.com/en-US
> 2 votes

---
Tags: xna, .net, kinect
---


title: Why does V8 not run with SDL threads?

text:
# Question
Title: Why does V8 not run with SDL threads?
i was able to compile and link V8 against my game and code interpretation works fine. However I want to divide my code and the game loop should exist in one thread and the scripting engine should run in a second thread alongside my game loop. I am using SDL and therefore tried this code to spawn a new thread

```
SDL_CreateThread(ScriptingEngine::SpawnMain, NULL);

```

where the following code is my test scripting engine:

```
namespace ScriptingEngine {
    v8::HandleScope handleScope;
    v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
    v8::Persistent<v8::Context> context;

    void Setup() {
            // TODO: bind functions to global
            // ...
            context = v8::Context::New(NULL, global);
    }

    int SpawnMain(void *arguments) {
            v8::Context::Scope scope(context);
            v8::Handle<v8::Script> script = v8::Script::Compile(
                    v8::String::New("'Hello World'")
            );
            v8::Handle<v8::Value> result = script->Run();
            context.Dispose();
            return EXIT_SUCCESS;
    }
}

```

However I get an error like `Access violation reading location 0x00000000.` in `api.cc` line 716: `i::Isolate* isolate = env->GetIsolate();`.

Has anyone a clue how I can fix this or what the exact problem is?

# Answer
# ***Solution***

The solution was to use a monitor like `v8::Locker locker;`. Exactly this line must be entered the line before the creation of the `HandleScope` and it should work, although my code up there is crap. I have combined all variables etc. into one method without a `setup` method or the variables in `ScriptingEngine`.

Long story short: the `Locker` object is responsible for thread management as the engine isolates itself for sandboxing purposes.
> 6 votes

---
Tags: c++, javascript, sdl, multithreading
---


# Question
Title: How can I change the splash screen for a standalone game in Unity3D?
I want to change the normal Unity splash screen to be customized for my game and every time I change the splash image in the player setting it does not appear. So how can I do that please?

# Answer
> 5 votes
I'm assuming you don't have unity pro?

If you want custom splash screens for IOS you also need IOS pro.

Check out the licenses page: http://unity3d.com/unity/licenses

# Answer
> 3 votes
There is no splash screen built in for Unity standalone PC/Mac builds. You can change the banner on the config dialog. (See here http://unity3d.com/support/documentation/Components/class-PlayerSettings.html).

If you want a splash screen when the game starts after the config dialog happens you'll have to do it yourself. It's pretty easy, just put the image on a quad and make the camera so it sees the whole thing. You can do fading in/out with lerping the shader color over time, or something similar to that.

---
Tags: unity
---


# Question
Title: Should I use inheritance or composition for modelling game objects?
In terms of game engine modeling, please give your pros and cons for two types of interfacing:

```
class MySceneObject_Model1 : public IRenderable, public IScriptable, public IAnimatable { ... }

class MySceneObject_Model2
{
protected:
   IRenderable* m_ptrRenderable;
   IScriptable* m_ptrScriptable;
   IAnimatable* m_ptrAnimatable;

public:

   IRenderable* GetRenderable();
   IScriptalbe* GetScriptalbe();
   IAnimatable* GetAnimatable();
}

```

What if MyObjects have different variations of supported interfaces? For example one of them can be only Scriptable. Some of interfaces could appear in future. Some of them could be very similar to each other: IAnimatableByMorphing, IAnimatableByBones, etc. Some of them can be very close to each other: IRenderable depends on new object's state after IAnimatable's work. I know it is very basic and very wide question, but tell about your experience!

# Answer
It is generally preferable to prefer composition to inheritance. There are many available resources on the subject if you ask Google about it. According to that principle, your second example is better. If you take the first approach you will have to implement IAnimatable (or whatever) in every concrete game object class, and you may not be able to easily re-use that code unless you take an approach that is far more like the second option anyhow. This will, in turn, imply you have many different game-object level classes that exist only to mix-and-match different interface implementations. You could achieve this more easily, more cleanly, and with less code using the second approach and simply configuring an object with the appropriate interface implementation objects.

Your second example is actually a very primitive component-based architecture, one where the available component set is rigid. What Edward83 was suggesting in the comments is probably the (currently very trendy) evolution of that architecture where objects are composed of a dynamic list of components.

In the second example, if an object does not supporting animation or scripting, the respective components would be null or you would install a dummy component that implements the interface but does so with no-op methods.

As a note, you probably should not have "IAnimatableByMorphing" or "IAnimatableByBones" interfaces (as implies by the 'I' prefix), rather those should be concrete classes that implement IAnimatable.
> 9 votes

# Answer
as others have said, prefer composition over inheritance. you may find Refactoring Game Entities with Components to be of interest.
> 0 votes

---
Tags: architecture
---


# Question
Title: What is the AlphaToCoverage blend state useful for?
Alright, just finished most of my early UI stuff and I wanted the windows to have some transparency. So I expanded my application to initialize and bind blend states so that my UI shader could implement alpha blending. I was initially having no luck but I got the blend state configured to achieve my purpose, however the way it is configured doesn't make sense to me so I must be missing something.

Here is how I initialize my blend state.

```
bool BlendState::StartUp() {
    D11DeviceManager* _pDeviceManager = D11DeviceManager::GetSingleton();

    D3D11_BLEND_DESC _desc;
    _desc.AlphaToCoverageEnable = false;
    _desc.IndependentBlendEnable = false;

    _desc.RenderTarget[0].BlendEnable            = true;
    _desc.RenderTarget[0].SrcBlend               = D3D11_BLEND_SRC_COLOR;
    _desc.RenderTarget[0].DestBlend              = D3D11_BLEND_DEST_COLOR;
    _desc.RenderTarget[0].BlendOp                = D3D11_BLEND_OP_ADD;
    _desc.RenderTarget[0].SrcBlendAlpha          = D3D11_BLEND_SRC_ALPHA;
    _desc.RenderTarget[0].DestBlendAlpha         = D3D11_BLEND_DEST_ALPHA;
    _desc.RenderTarget[0].BlendOpAlpha           = D3D11_BLEND_OP_ADD;
    _desc.RenderTarget[0].RenderTargetWriteMask  = 7;

    return !FAILED(_pDeviceManager->GetDevice()->CreateBlendState(&_desc, &pBlendState));
}

```

Right now my alpha blending only works when the AlphaToCoverage bool is set to false... I thought this was just a bool enabling the pixel fragment blending (which upon retrospection would be redundant considering the BlendEnable flags...) but looking at the MSDN documentation is appears to do this...

> You can use the AlphaToCoverageEnable member of D3D11\_BLEND\_DESC1 or D3D11\_BLEND\_DESC to toggle whether the runtime converts the .a component (alpha) of output register SV\_Target0 from the pixel shader to an n-step coverage mask (given an n-sample RenderTarget). The runtime performs an AND operation of this mask with the typical sample coverage for the pixel in the primitive (in addition to the sample mask) to determine which samples to update in all the active RenderTargets.

Could someone explain this to me and how it differs from when the AlphaToCoverageEnable bool is false? I see that it adds a new mask to the fragment but I don't quite follow what the mask exactly is.

# Answer
When rendering with multisampled anti-aliasing, a coverage value is computed for each fragment; this coverage value is based on the fraction of the pixel that would be covered by the fragment based on the triangle that created the fragment. The net result is that the edges of the triangle are anti-aliased. Because the coverage is based ultimately on what the originating primitive covers, *only* the edges are anti-aliased. Fragments on the interior of the primitive are rendered normally. Blending is applied to those interior fragments, but to do blending properly one must normally sort one's primitives from back-to-front to achieve correct results.

Sprites or other billboarded textures can be sorted (although it's sometimes expensive), but non-billboarded quads are sometimes used for rendering large volumes of grass, foliage or hair and cannot always be effectively sorted back-to-front. Alpha testing can be used in such a scenario (which essentially allows the alpha channel to determine if the fragment is visible or not, without blending it) but creates aliasing.

Alpha-to-coverage attempts to solve the problem by allowing the alpha value of a fragment to be used as its coverage value (the value that would normally be computed based only on the primitive). This allows you to have varying, appropriate coverage values for the fragments within the source primitive and achieve nicer looking anti-aliased transparency when doing MSAA.
> 7 votes

---
Tags: directx11, transparency, blending
---


title: Export Maya Animation Data

text:
# Question
Title: Export Maya Animation Data
I have a pretty simple character rig animation. How can I export the raw data of that animation?

I'm looking for some way to export a raw text array of data that tells exactly what every joint does on every frame. This means rotation, translation, etc.

EDIT: Thanks for the answers so far. We are looking for a way to get something like this: This would be one joint of a 14 frame animation.

```
 <joint>
      <name> rightShoulder </name>
      <xPos>12 14 16 18 19 20 21 24 26 28 32 34 36 38 </xPos>
      <yPos>100 99 98 97 96 95 94 93 92 91 90 91 92 95 </yPos>
 </joint>

```

We are also trying to keep the file lightweight. So we will be ONLY including this data, no meshes, cameras or anything else. I've been looking into .DAE but it seems pretty heavy.

Any suggestions? If nothing standard works, how would one go about writing their own Maya exporter? Does something like this seem possible?

# Answer
I just wrote my own exporter to my own custom format by reading and messing around with stuff from Rob the Bloke's site.

I haven't actually tested exported joints yet but according to my sources and current work they are not stored in the simple XYZ like your mini format prints out. Instead each poly is given a weighted set of transforms and the transforms are what are animated. You could convert it to the format you are looking for but it is generally better to send the bone weights and transforms all to the GPU letting the shader actually transform the triangle. Vertex Blending using Shaders on GP wiki
> 3 votes

# Answer
I've found that the DirectX (.x) model format is pretty nice. It will export the mesh, armature, and animations. The animations can be exported as key frame or every frame. It's not actually the joints that are controlled but the bones. And of course bones are just a matrix transform with a list of vertices and weights.

Don't let the name fool you, this of course can be used for DirectX or OpenGL. It's fairly simple to parse these files to get animation data. The exported files are all in plain text and are easy to follow.

I found some example code for writing an importer here. And a pretty useful explanation of the format in general here, along with animation details at the bottom.
> 0 votes

---
Tags: animation, maya, data
---


# Question
Title: How do you stop OgreBullet Capsule from falling over?
I've just started implementing bullet into my Ogre project. I followed the install instructions here: http://www.ogre3d.org/tikiwiki/OgreBullet+Tutorial+1

And the rest if the tutorial here: http://www.ogre3d.org/tikiwiki/OgreBullet+Tutorial+2

I got that to work fine however now I wanted to extend it to a handle a first person camera. I created a CapsuleShape and a Rigid Body (like the tutorial did for the boxes) however when I run the game the capsule falls over and rolls around on the floor, causing the camera swing wildly around.

I need a way to fix the capsule to always stay upright, but I have no idea how

Below is the code I'm using.

(part of) Header File

```
OgreBulletDynamics::DynamicsWorld *mWorld;   // OgreBullet World
OgreBulletCollisions::DebugDrawer *debugDrawer;
std::deque<OgreBulletDynamics::RigidBody *>         mBodies;
std::deque<OgreBulletCollisions::CollisionShape *>  mShapes;

OgreBulletCollisions::CollisionShape *character;
OgreBulletDynamics::RigidBody *characterBody;
Ogre::SceneNode *charNode;

Ogre::Camera* mCamera;
Ogre::SceneManager* mSceneMgr;
Ogre::RenderWindow* mWindow;

```

main file

```
bool MinimalOgre::go(void)
{
    ...

     mCamera = mSceneMgr->createCamera("PlayerCam");
     mCamera->setPosition(Vector3(0,0,0));
     mCamera->lookAt(Vector3(0,0,300));
     mCamera->setNearClipDistance(5);
     mCameraMan = new OgreBites::SdkCameraMan(mCamera);

    OgreBulletCollisions::CollisionShape *Shape;
    Shape = new OgreBulletCollisions::StaticPlaneCollisionShape(Vector3(0,1,0), 0); // (normal vector, distance)
    OgreBulletDynamics::RigidBody *defaultPlaneBody = new OgreBulletDynamics::RigidBody(
            "BasePlane",
            mWorld);
    defaultPlaneBody->setStaticShape(Shape, 0.1, 0.8); // (shape, restitution, friction)
    // push the created objects to the deques
    mShapes.push_back(Shape);
    mBodies.push_back(defaultPlaneBody);

    character = new OgreBulletCollisions::CapsuleCollisionShape(1.0f, 1.0f, Vector3(0, 1, 0));

    charNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
    charNode->attachObject(mCamera);
    charNode->setPosition(mCamera->getPosition());

    characterBody = new OgreBulletDynamics::RigidBody("character", mWorld);
    characterBody->setShape(   charNode,
                    character,
                    0.0f,         // dynamic body restitution
                    10.0f,         // dynamic body friction
                    10.0f,          // dynamic bodymass
                    Vector3(0,0,0),
                    Quaternion(0, 0, 1, 0));

    mShapes.push_back(character);
    mBodies.push_back(characterBody);

    ...
}

```

# Answer
> 7 votes
I actually just finished writing this for my capsule object yesterday.

You just need to call btRigidBody::setAngularFactor(btVector3(Yaw, Pitch, Roll)); Calling it with all 0s will prevent your object from rotating on any angle.

Here is where I originally found the answer: http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=&f=9&t=2956

(In reply to that thread I have had no issues using Bullet 2.79 and setAngularFactor)

# Answer
> 1 votes
I've never used Bullet, but in Havok you could constrain a model on certain axes. If you can constrain rotation of your model on both horizontal axes that may stop it from falling over. Alternatively Havok let you have a special type of physics called a CharacterProxy, each from you could for it to face straight up, and you could also run your own code for its physics simulation so you could prevent rolling. This is similar to how the JigLib/JigLibX physics engines handle it as well. I'm willing to bet Bullet allows one of these methods.

# Answer
> 0 votes
A capsule shape will fall and roll around according to its physical properties. If you want to couple your camera to a physics object, why not use btBoxShape (or the Ogre equivalent) instead?

I don’t really know what you’re trying to do, but my suggestion would be to have the camera separate from the physics. That way, you’ll be able to move it as you like.

---
Tags: c++, physics, ogre, bullet-physics
---


# Question
Title: Is this aiming mechanic usable in a third-person top-down game?
**Long story short:** I've switched to a third person - top down perspective. The camera is fixed and looks down at the player. How can I implement 3d aiming ? The player needs to aim left and right as well as up and down.

**details:** I've ditched the first person perspective in my current project - I wouldn't call it a game yet, it's more of a test-case. Instead I'd prefer a third person perspective with the user looking down at the player (slightly tilted to the back). The implementation is no problem, the aiming system is. Although the player will be rarely armed there will be situations where he's allowed to return fire.

This is more complicated than it sounds since the player needs to aim up and down. I hope you can envision my problem. In an ego shooter moving the mouse let's the player look up/down and left/right . In a top/down game the mouse points in the direction the player is moving. I'm currently casting a ray from the camera and the player looks at the first collision point of that ray. That means to aim at an enemy the player just needs to hover the mouse over him. Not very comfortable, no skill required at all.

I've thought about this: The player is always centered on the screen, the mouse 2d coordinates are computed to a 2d vector that is used as the player's viewing direction. This way he couldn't look up or down but then again that's only visuals the camera wouldn't be moved in any case. In order to shoot the player presses the right mouse button. The mouse movement is now mapped to the player just as in any common shooter. Mouse up -\> look up. Mouse left -\> turn left. Don't misunderstand me: I don't intend to move the camera only the player charaTo show the player where he's aiming I then draw a line to his target (or a cone for less precise weapons).

What are possible pitfalls ? Have you done something like this and can tell me if it's usable ? I've never played a game that worked this way and just wonder if it's a good idea

**UPDATE**: I've accepted an answer but of course I'm still interested in other options. If you've got a good idea that fits here I'd highly appreciate it.

# Answer
If you're going to ask the user to aim up and down, you need the player to be able to judge those up and down distances. With a static top-down camera, that is virtually impossible, and grossly unfair of you to demand of the player, no matter how you map it to controls.

If you're set on using a top-down camera, then your player character should handle aiming up and down automatically, be generous about allowing the player to fire through floors and ceilings (again, because the player can't judge those firing angles due to of your choice of camera), and only ask the player to aim along the axes that you allow him to view (that is, the flat ones)
> 8 votes

# Answer
Use storyboards and blocked out animations to preview game play changes, both are easy to create and cheap to modify until you arrive at a solution. Movie studios call this "prefiz" and use it to save money and effort.

You can animate several new viewpoints in a day and save a week of coding.
> 2 votes

---
Tags: input, movement, aiming, perspective, third-person-view
---


# Question
Title: Setting variable values in XNA 4.0 from an XML file
I made a program that simulates an assembly line using the XNA 4.0. I made a 3D model, and divided it into 5 positions - start, 3 workstations, and end. These positions represent the places on the model that (in real life) would be covered by some type of sensors. Whenever an object gets to one of these positions, it triggers a method that is binded to that specific position (like "Stop", "Start", "Increment/Decrement Counter"...).

This program has to be able to load a file that describes the behavior of the entire assembly line - meaning, this file has to tell the program when and which method will be triggered (for now it is only Start/Stop methods). To do this, I created a method that serializes the class that contains `bool` variables (these variables determine if the position will be "active" or not - if the value is `true` then the object will trigger the binded method, if it is `false` then it will simply pass that position, without any additional actions being performed).

This is the problem I'm having: My method successfully serializes the class, and creates the .xml file, but if I load this file as Content, it gives me the following error "There was an error while deserializing intermediate XML. Cannot find type "Postavke.PostavkeStanice"."

This is the code of my class:

```
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using System.Xml;
namespace Postavke
{

    public class PostavkeStanice
    {
        public bool radnaStanica1_Stanje;
        public bool radnaStanica2_Stanje;
        public bool radnaStanica3_Stanje;
        public bool kraj_Stanje;
        MemoryStream ms = new MemoryStream();
        public void ClassToXML()
        {

          XmlTextWriter pisac = new XmlTextWriter(ms, Encoding.UTF8);
          pisac.Formatting = Formatting.Indented;
          IntermediateSerializer.Serialize(pisac, this, "Postavke.xml");
        }

        public string XMLToXNA()
        {
            ms.Seek(0, SeekOrigin.Begin);
            TextReader citac = new StreamReader(ms);
            return citac.ReadToEnd();
        }
    }
}

```

Since this class is a part of Game Library, I set the dependencies so that the Game library gets compiled before the main project. When I run the code I get the fore mentioned error. Can you tell me what I'm doing wrong Thank you

# Answer
> 2 votes
Typically you would use the content pipeline to do this automatically. See Customizing the IntermediateSerializer.

Create a library project that has your type in it (with no serialize/deserialise methods). Add a reference to it in the **content project** and your **game project**. Add an XML file to your content project in the appropriate format then load it in game with

```
Content.Load<PostavkeStanice>(RelativeXMLLocationWithoutExtension).

```

See also for an example where the pipeline is customized: ContentSerializerRuntimeType required in content pipeline?

---

The below also might be a solution to your problem, it's certainly a better solution to the problem that the existing answer solves.

---

Somewhere in your class and it's properties/fields there's a type with no parameterless constructor. Probably a member of the `MemoryStream` class.

To serialize any object it instantiates it by finding a parameterless constructor and invoking it via reflection.

**The new security model is stopping it from invoking the non-public parameterless constructor via reflection and is causing the error you're seeing.**

As the other answer says, changing your application's security will solve the issue **but will have other ramifications**, particularly if you use different libraries, or have other classes that use your library.

Add the `[ContentSerializerIgnore]` attribute on ones you want it to ignore (like the `MemoryStream`) and add public parameterless constructors to all classes that are to be serialized (and classes of fields/properties).

# Answer
> 1 votes
Try putting the below above your namespace.

```
[assembly: SecurityTransparent]

```

http://www.simple-talk.com/dotnet/.net-framework/whats-new-in-code-access-security-in-.net-framework-4.0---part-i/

http://www.simple-talk.com/dotnet/.net-framework/whats-new-in-code-access-security-in-.net-framework-4.0---part-2/

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


# Question
Title: Java code for client-server game on Android
I have developed a game on Android. Now I want to play it on wifi or 3G. I have game packets which I want to send form client (mobile) to server then to another client (mobile).

I don't know how to write code in Java to send the playPackets continuously to server and receive the playPacket continuously from the server to the clients.

I guess I have to use two thread one for sending and one for receiving.

Can someone help me with the code, or the procedure to write code for it?

# Answer
Ok lets start from the beginning. I don't know what you are doing and how but when doing with network you have to give it a try to the **REACTOR** pattern.

*Basically* reactor is a way to avoid the use of threads or to defere it where a threaded-task is more decoupled by the core.

The center of the reactor is the ***select*** function: you register your event sources and ask the select to return when **something happends to one of those sources**.

When something appends, the reactor main loop simply finds **What appened** to **What source** reacting by creating an *Event* and dispatch this event to objects interested in those kind of events.

I'm not a Java Guru but i know that you can setup socket (even UDP ones) and you can set them as non-blocking. Along whit this I know there is a class called Selector in a package called NIO. Those stuffs concur to define a multiplexed, non-blocking I/O facility

All you need is simply setup two UDP channels: one for server listening and the other for server talking; register the listening one to the reactor and integrate the reaction step of reactor into your main loop.

Take into account that this kind of approach let you to connect simultaneusly with different channels so you can consider to develop a peer-to-peer game (no server bottleneck and distribuited design... sounds good!)

**P.S.**

Please note that if you are using some sort of GUI tookit/facility, you probably are already using a Reactor...
> 2 votes

# Answer
A good start for client-server programming would be kryo net since its easy to learn and often used/referred in java game develoment. Its event-based, so u will not need any threads here.
> 1 votes

---
Tags: java, android, client-server
---


# Question
Title: Is showing a collision in slow motion computationally relaxing?
In a lot of racing games (Burnout Paradise, for example) when a collision is about to happen, the game play automatically switches to slow motion and carries on in slow sequence until after the collision is complete.

I always thought this was for the effects. You don't want to miss any part of the collision! But one of my friends recently suggested that this is done to make sure there is not an overwhelming rate of processing required when a collision happens.

Now I think it is actually the other way round. When a collision happens, so many details are shown in slow motion, I am sure there is an overhead on the computing and rendering pipeline.

What is correct?

**Does a slow motion scene increase CPU / GPU usage, or decrease it?**

# Answer
> 4 votes
If you're running your physics-simulation with a fixed timestep (as you should), then a slow-motion will put less load on the physics-simulation, because less calculations will have to be made per frame.

Let's assume you're running your physics with 200 updates per second. Eg. one update every `0.005` seconds of simulation time. When running the game with 50 updates per second, that would result in 4 physics updates per render update. Now you would run the game in slow motion, that means you're slowing down simulation time. So if the game still runs at 50 updates per second (`0.02` seconds of simulation time), but you're showing the world in slow-motion (let's say half the speed), then one frame would be equivalent to `0.01` seconds of simulation time. So only 2 physics updates per rendered frame. Meaning less physics-calculations per rendered frame.

So if you're looking at it from the perspective of CPU usage per rendered frame, then slow motion is less CPU heavy (unless you choose to increase your physics simulation rate during the slow-motion). GPU load per frame is of course pretty much constant.

If you're asking about *cumulative CPU/GPU load for the duration of one collision*, then obviously the physics simulation is the same, be it slow-motion or normal-speed. The GPU load will be higher, because you render more frames.

# Answer
> 3 votes
It is *possible* that this could be the case. Unless you're doing physics for the collision on the GPU, it means squat for that. But in terms of the physics itself... it's possible.

If you're simulating the movement of a number of bodies, they tend to move in a very predictable way. Forces and force fields (ie: gravity) are easily predictable. Where things move is quickly computed.

Right up until one thing hits another. See, in physics, you have what is called a timeslice; this is the amount of time that the execution of the physics system covers. If your timeslice covers 1/30th of a second (30fps for the physics update), then each physics update moves objects 33.3 milliseconds into the future.

When objects don't collide, you can just move them from the beginning of that 33.3ms to the end. The physics for doing so are simple and has been well-known for centuries. You just determine the acceleration from the net forces, apply that acceleration for the timeslice to the object, and move it at its new velocity (note: this can be more complex if you want greater accuracy).

The problem is when objects collide. Suddenly, now you have to process physics forces *within* a timeslice, rather than just once at the beginning. If an object collides *twice* or three-times within a physics frame, then that's more physics computations you have to redo.

If you have a lot of collisions within one timeslice, you can really kill your framerate. However, the chance of multiple collisions within a timeslice decreases as the size of the timeslice decreases. High-end racing sims like Forza and Gran Turismo run their physics systems at incredible framerates. I think one of them gets up to 300+fps on their physics update.

Slow-motion is the effective equivalent of that. By decreasing the physics timeslice without also increasing the *rendering* framerate to compensate, the world appears slower. And therefore, you make it much less likely that you get multiple collisions within a timeslice.

That being said, I do doubt that this is why games like this go into slow-motion. In general, it's more for visual flair and dramatic presentation. Those physics systems can generally handle it, performance wise.

# Answer
> 1 votes
First of all, this is done for the visual effect, not for performance reasons.

The standard way of dealing with performance in physics heavy games is to scale the number of objects, scale the object complexity, and fiddle with engine settings to scale between simulation precision and performance. If there is problems you'd drop what you perceive to be the least significant features.

Do remember though, the industry has made pretty realistic car games for the past ~15 years, with modern computers it's not like they have to scale back to 3 wheels to get things running.

**The problem:**
It is true that a collision may cause extra work, how much depends a lot on the specifics of the game, a more detailed physics engine will have a lot of small collisions between different parts that may constitute a significant increase in required computation. But that should be taken into account when the physics is scaled, it's not a problem to get good physics that can still handle some collisions.

If you simply run the physics simulation slower to get slow motion the load will drop proportionately. However, one should note that the requirements for slow motion and real time physics are different, you can afford to have lower precision when stuff happens at racing speed. As long as the player does not notice that the physics engine is wrong it is not a big problem, the slow motion makes the slips much easier to catch, thus the slow motion has a higher precision requirement.

One may choose to use the same physics, scaled to meet both sets of requirements. This solution will require some extra processing power, but it's easy to implement and given modern computers perfectly viable.

Switching physics settings is more complicated, but can potentially result in some gorgeous collisions, not only can one increase the precision, it is also possible to switch the physics models of the cars for better detailed ones that break in more realistic fashion. This mode should end up using approximately the same amount of CPU time for physics as the normal mode, simply because they are both scaled to run at the same minspec configuration.

A middle way is to use a variable step physics engine, those will in general increase the precision when you slow down the simulation, thus solving at least part of the problem. There are other reasons not to use variable step physics, but variable step is still pretty common in the industry.

---
Tags: collision-detection, graphics, rendering
---


# Question
Title: Why does my model render differently with different BasicEffect instances?
I'd like to understand why I get a completely different result when I replace the effects of a model (as suggested by How To: Draw a Model with a Custom Effect) with a BasicEffect that I instantiate myself:

```
var basicEffect = new BasicEffect( game.GraphicsDevice );
basicEffect.EnableDefaultLighting();
foreach (var mesh in _modelHead.Meshes)
    foreach (var part in mesh.MeshParts)
        part.Effect = basicEffect;

```

My goal is of course to use an effect of my own later, but for the moment I'd really like to understand what's going on!? What is different with the predefined BasicEffect from the one I instantiate myself? When I inspect the properties of the two instances they seem to be all the same.

1. How it looks with the "default" BasicEffect
2. How it looks when I instantiate a new BasicEffect

# Answer
> 1 votes
The model file contains data about materials, in this case it looks like the diffuse color or texture. When you create a new `BasicEffect` object it doesn't contain the right colors and such, so you get white.

See here:

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.basiceffect.diffusecolor.aspx

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.basiceffect.texture.aspx

If you want to use the same texture, you can do this (I haven't tested though):

```
foreach (var mesh in _modelHead.Meshes)
{
    foreach (var part in mesh.MeshParts)
    {
        var specificEffect = new BasicEffect(game.GraphicsDevice);
        specificEffect.EnableDefaultLighting();
        specificEffect.Texture = ((BasicEffect)part.Effect).Texture;
        specificEffect.DiffuseColor = ((BasicEffect)part.Effect).DiffuseColor;
        part.Effect = specificEffect;
    }
}

```

Obviously this code can be optimized a *lot* as it becomes redundant after the first call.

EDIT:

Just to explain why the properties seem the same, once your code runs once the effects become the same, so if you're seeing anything but the first call the properties will be the same.

---
Tags: xna
---


# Question
Title: How can I draw a model with a color on WP7?
How can I draw a model with a color (and still be aware of the lighting)?

This is really straight forward when you can use shaders, but on Windows Phone you can't.

# Answer
You might find this property useful: `BasicEffect.DiffuseColor`
> 2 votes

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


# Question
Title: Dot Product Vs Cross Product Turning a Turret Towards A Enemy and firing
http://pastebin.com/iw9DHf7s is code demonstrating dot product turning a turretto a target and firing. It works and chooses best angle to spin.

A problem can occur when game goes faster (better computer) and that threshold no longer applies. Making the threshold bigger obviously stops the turret early.

My friend mentions cross product is the way to fix it. Then he disappears for long periods of time. Doesn't dot product NOT get a inner angle between two vectors? Ok lets just say I agree and dot product doesn't work ever.

So tell me how does vector product do the trick? I'm going from a single scalar that I can get degrees out of to a third orthogonal vector. I've read about cross product and the function and watched a you tube video and I don't get (given the same code pasted) how to use cross product here.

**Update**: Would this work?

```
//towerFacing is the at/forward vector of the cannon
Vector v1 = cannonPos - targetPos ;
Vector v2 = towerFacing - cannonPos ;

//The z plane
double cross = v1.x*v2.y - v1.y*v2.x ;
if (cross > 0) { return Direction.Left ; }
if (cross < 0) { return Direction.Right ; }

```

Obviously the zero is not what we want to use in games. However The difference is now our zero means our at vector and target is perpendicular and on each other which `a x b = 0`. The dot product since it uses cosine I used the right vector which is orthogonal with the `facing( a . b = 0)`.

Am I wrong on how the cross product works by what has listed for answers still?

# Answer
> 3 votes
The dot method you have on the pastebin is fine if all objects are on the same plane and it is essentially a 2d problem (regardless of if the game is 2d or 3d). If, however, you are in a 3d environment where you need to adjust cannon yaw & pitch, then the cross method would be better because it would give both the direction to turn(rotate towards target) and the 3d axis to rotate about.

If you crossed the cannon's barrel direction with the direction to the target, it gives the proper axis. If you normalized both before crossing, it would even give the arc-sine of the angle between them if you needed (in the same way a dot product could give the arc-cosine). When crossing, the axis created will give the shortest rotational direction to the target... so does your dot method... but it fails you when the barrel has to change in two dimensions.

# Answer
> 0 votes
> Blockquote A problem can occur when game goes faster (better computer) and that threshold no longer applies.

For starters this is a huge mistake to make and you will find your life much more difficult if you rely on the CPU processing speed to determine your game's frame rate. At a minimum I would update your game based on the actual progression of time rather than CPU cycles. You can still run into problems where different machines will have different amounts of time to process each frame, but your physics and other gameplay systems should advance time strictly on how much real world time passes each frame.

---
Tags: mathematics, linear-algebra
---


title: Creating a Model out of Math primitives

text:
# Question
Title: Creating a Model out of Math primitives
Here is a litte sample that I drew in Blender to visualize what I am planing to create:

Cone with spheres sample

I already have the code to generate the cone and the spheres as mentioned in my former Post Combine 3D objects in XNA 4.

I thought that it would be nicer to generate a model and add these models to the sceen graph. My problem for now is that I wasn't able to generate a model out of my primitivas. I was planning to create one Mesh for the cone and one for each sphere that I want to attach to the cone and arrange all this in a Model, but there are no constructors for a Model or a Mesh.

So the question is: Is there a way to generate a model out of my primitives?

# Answer
If you want to create Model or Mesh objects, you do so in the content pipeline (via their builder counterparts). They aren't types you can create during run time (unless you run on Windows and willing to include the pipeline builder library in your game project). They're also sealed so no extending them.

Model objects are basically just a collection of meshes, bones, and an optional effect. Meshes are just a wrapper around a vertex and index buffer.

So your options:

* Make your own version of the model/mesh class that can be generated at run-time.
* Look into the content pipeline to pre-build Model objects. It's relatively easy as long as you're okay with having the primitive mesh be unchangeable at run-time.
> 3 votes

---
Tags: xna, c#, 3d, xna-4.0, models
---


title: Game state from Web to iPhone version?

text:
# Question
Title: Game state from Web to iPhone version?
I'm currently in the planning stages for an Web and iPhone game. I'm developing it with Adobe AS3/Air. I was wondering if it's possible for people to be able to play the Web version, save their state of play and then pickup again where they left of on the iPhone version? (and visa versa) how that would be achieved? the Web version will probably be on Facebook, so could I link both versions through their FB UID?

# Answer
> 2 votes
To share persistent state between clients (that could be multiple players, or just multiple platforms for a single player) you need data being stored on a server. Since you will need to host your game on a server anyway for a Facebook app, presumably you can also create a database of player states on that server.

---
Tags: iphone, actionscript-3, facebook
---


# Question
Title: Processing component pools problem - Entity Subsystem
### Architecture description

I'm creating (designing) an entity system and I ran into many problems. I'm trying to keep it Data-Oriented and efficient as much as possible. My components are POD structures (array of bytes to be precise) allocated in homogeneous pools. Each pool has a ComponentDescriptor - it just contains component name, field types and field names.

Entity is just a pointer to array of components (where address acts like an entity ID). EntityPrototype contains entity name and array of component names. Finally Subsystem (System or Processor) which works on component pools.

### Actual problem

The problem is that some components dependents on others (Model, Sprite, PhysicalBody, Animation depends on Transform component) which makes a lot of problems when it comes to processing them.

```
For example, lets define some entities using [S]prite, [P]hysicalBody and [H]ealth:
Tank:   Transform, Sprite, PhysicalBody
BgTree: Transform, Sprite
House:  Transform, Sprite, Health

and create 4 Tanks, 5 BgTrees and 2 Houses and my pools will look like:

TTTTTTTTTTT // Transform pool
SSSSSSSSSSS // Sprite pool
PPPP        // PhysicalBody pool
HH          // Health component

```

There is no way to process them using indices. I spend 3 days working on it and I still don't have any ideas. In previous designs TransformComponent was bound to the entity - but it wasn't a good idea. Can you give me some advices how to process them? Or maybe I should change the overall design? Maybe I should create pools of entites (pools of component pools) - but I guess it will be a nightmare for CPU caches.

Thanks

# Answer
> 2 votes
Disclaimer: Purely going off of my systems class knowledge.

I originally thought, why not just use a hash function on entity ID for your index?

That way you'd get

```
T[A]nk:   Transform, Sprite, PhysicalBody
B[G]Tree: Transform, Sprite
H[O]use:  Transform, Sprite, Health

and create 4 Tanks, 5 BgTrees and 2 Houses and my pools will look like:

OGAGAGGOGGG // Entity pool (letters corresopnding to entity type)
TTTTTTTTTTT // Transform pool
SSSSSSSSSSS // Sprite pool
P P P  P    // PhysicalBody pool
H      H    // Health component

```

Or however it was the entities happened to be placed. You can have pools for all of the components and for entities and use the entity pool as the "master," such that collisions are checked against the entity array. But of course you get the problem of recycling components and entities.

If your game design allows it, you could plan ahead where each type of entity goes so you could get the most efficient packing possible. Say entities 0-20 are reserved for tanks, entities 21-30 for houses, and 31-60 for BGTrees. You might not be able to efficiently spawn infinite baddos, and kinda defeats the dynamism of component systems, but it would solve the problem. I don't see a way to have your cake and eat it too.

I was thinking about ways to maybe speed up the render pass where you have a `RenderingComponent` that contains all the data that the rendering system needs so it's able to just blow through an array of these things, but then there's overhead of copying data. Also, any time you dereference a pointer you're thinking about whether or not it's still in the cache.

If you want a super speedy game, I'd say plan your allocation out. If you want a flexible game architecture, roll out the hashtables and string IDs. Any time you want flexibility you need to build abstraction, and therefore will incur overhead.

**TL;DR;**
Based on what you described, I would create a higher level `RenderComponent` with pointers to `Sprite` and `Transform` components and give it the necessary references when you initialize the entity.

(Apologies for any perceived rambling, I've been thinking about this in my system as well, so this was an opportunity to think through it)

---
Tags: architecture, component-based, c, entity-system, data-driven
---


# Question
Title: Why is my sprite displayed offset from its Box2D body?
I found out about this using a debug renderer. When the game starts, everything is in order. But when a collision happens, the sprite's rotation is way larger than its body. The sprite and body match when the body is completely horizontal.

The sprite's rotation origin seems far distant from where it should be. Here's my code:

```
Sprite sprite = data.sprite;
position = body.getPosition();
sprite.setPosition(
    position.x - sprite.getWidth()  / 2,
    position.y - sprite.getHeight() / 2
);
sprite.setOrigin(position.x, position.y);
sprite.setRotation(MathUtils.radiansToDegrees * body.getAngle());

```

As you can see, I am even trying to set center of its rotation with `setOrigin` without success. How can I fix this?

# Answer
Most APIs represent the Sprite's origin in local space, not in world space. This is supported by libgdx's documentation which states:

> A Sprite also has an origin around which rotations and scaling are performed (that is, the origin is not modified by rotation and scaling). The **origin is given relative to** the bottom left corner of the Sprite, **its position**.

So I think that if you want rotations to happen around the center of the sprite, you should be using the following origin instead:

```
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);

```
> 9 votes

---
Tags: libgdx, box2d, rotation, coordinates
---


# Question
Title: Loading and rendering one large image or many smaller ones
I am working on an android game with a top down style view similar to the original GTA's or a scrolling version of Legend of Zelda.

I have recently begun designing some prototype levels for the game which vary between a corridor style dungeon similar to diablo or an open area with obstacles similar to Zelda. My question is would it be better to have one large background image and draw it once or a relatively small one (size of or less than the view) and draw it multiple times.

My concerns are the memory required to load/store a large background image vs the performance boost of only drawing one image.

Any input would be appreciated.

# Answer
I would also go for loading multiple smaller images in the next way: split your image (5000 x 5000px) into files of 100x100 px for example,

lets say when the game starts the player is in the middle of the map (x: 2500, y:2500) first thing you do is load the tile that matches these coordinates, next you also load the 8 tiles next to the center tile so you now have loaded 9 tiles in a 3x3 layout (the player is on the center tile) When a player is moving to the tile above, you just have to load the 3 next tiles the player could reach when he's still travelling up. The 3 bottom tiles can be unloaded since the player is never going to be able to reach these at the moment.

Is the player moving to the right, you can load these 3 tiles (aligned vertically) and unload the left 3 tiles.

This way, only the tiles the player can reach have to be loaded. I don't know what resolution of device you are targeting, but if you use 100x100 px the entire loaded field has a resolution of 300x300, so you might want to use bigger tiles, or just load a few more
> 0 votes

# Answer
I'd go with drawing smaller ones.

Just one large image drawbacks:

## You might draw something that you're not even seeing.

Ok, you can cut the image and just draw the part you're seeing, but that may be hard to code, and might also be costly to do(depends in your implementation). If you go with smaller ones, just test the object if its position is inside your screen.

## It will get a lot of memory.

Pretend you have a 512x512 map and this map is just 256 32x32 images. If you load this entire map as a 8bpp bitmap, you'll end using 2.097.152 bytes, that is, 2MB.

Well, if you just load a 8bpp 32x32 image you will end up with 8.192 bytes loaded, that is, 8KB. But of course, you have to have the positions stored somewhere, so pretend this is the object structure:

struct object { sprite\* image; // 4bytes int x; // 4 bytes int y; // 4 bytes }

that is, 12 bytes on the structure. As you have 256 objects, 3.072 bytes, that is 3KB.

summing everything, 11KB. Do you prefer to waste 2MB or 11KB? And I'm guessing low, try to use 32bpp images and the difference gets a lot higher! (If i made any wrong calculation, some one can edit please?)

## Collision will be a mess.

You'll have to have one file for each level telling were is collidable, where isn't. This can also get a great memory. Without saying that you'll have to calculate it for every level, it will be a pain.

For our friends smaller images, you just define which sprites are collidable and check the character against them.

## Harder to edit.

Lets say you shipped your game. And oh, there's a object that is in the wrong place on the level X, you'll have to edit the image, the collision file, and update the two big files for the people who already got your game.

in the counterpart, you would just edit the x and the y of your object, and update the smaller file to the people.

**There are a lot of more drawbacks, I just cited some.**

If you're looking for a way to do with smaller images, here is some guidance:

Make a file to store your types. It could be something simple, if you dont understand binary structures, try to look at google.

```
struct SpriteTypeIndex
{
    byte typecount;
    SpriteType types[typecount];
}
struct SpriteType
{
    byte id;
    char filename[32]; //the image name
}

```

To store the objects in a file, you could use some structure like this:

```
struct object
{
    byte type; //The id of the SpriteType
    char name[8]; //just to identify it (optional)
    int x;
    int y;
}

```

Easy huh? Ah, these assume you're not making more than 256 sprite types, and your image names have all less than 32 characters.

Hope it helps you (:
> 1 votes

---
Tags: android, optimization, image
---


title: Creating map files for a 3D game

text:
# Question
Title: Creating map files for a 3D game
I've created plenty of 2D games and now that I've gotten my hands dirty working with 3D in opengl I want to start a game. The issue is I don't know how I can store all the map data. Not only the terrain but the textures and objects in the world, lighting, what's intractable etc. it seems that it'll get way to big if I don't have an efficient system for storing and loading maps. So what methods or articles can you guys suggest on this?

# Answer
Firstly look up basic spacial geometry formats like Octrees and BSPs.

As for your actual map level format, chances are you will want something very customized to your game. Are you using 1 giant mesh for your game world (Like a FPS), a bunch of modular meshes something like an indoor Skyrim area or for the outdoor areas they would also probably have a heightmap (Stored as a texture? maybe a bunch of floats? Maybe inputs for a procedurally generated algorithm). Do you want a massive open gameworld like GTA/Just Cause or a bunch of small detailed areas? Do you need to embed lighting maps or is that done on the fly? Custom meshes/objects or all build from components?

You might actually want to start with something like XML or ASCII and just convert it into something binary at a later point once you have your details hammered out. You might find the XML gives you good enough performance anyway.

idGames actually use plain ASCII for their stuff and in doom3 at least it compiles most of the stuff on load since lighting now doesn't need to be prebaked as it's done on the hardware. It's split over a few different files but I think they are all ASCII (even the 'compiled' stuff). So you don't really need any superefficant packing methods.

You can look at using formats that are outputted from 3D modelling software like 3D Max, Maya, Blender and so on. That way you don't have to make a level editor. But you will have to find a way to embed game information in your 3D scenes.

COLLADA is a very general purpose 3D XML format. But it might be a bit too general and feature rich and requires some parsing and cleaning up. You will also have to fidn a way to gameify it (Maybe 1 file for overall level layout while keeping your mesh stuff in another file or even different format).

Some other random advise would be to give every object a unique id (at least the non-static ones), that way you can easily save/load just the changed data. It would probably also help with network replication for multiplayer.

Other advice would be to split up everything. Don't try and embed textures in your level format. If you do want to pack everything together for redistribution just zip it.
> 5 votes

# Answer
I think looking up BSP's etc is too complicated for a first game.

In a 2D game you basically store everything as an image and access it when you want. spritesheets, tiled maps etc.

In a very basic 3D game, the geometry is more complicated than just one image and is usually embedded in a file just like any other peice of code. You have vertex data describing walls etc.

Just create a level class that is a container for a number of walls and the floor etc, each of which is a class that calls in the right textures.
> 1 votes

---
Tags: opengl, maps
---


# Question
Title: drawing meshes so that they respect the position in space (doesn't draw on top of another mesh if behind it)
How can i make my meshes be drawn taking in account which one is in from of another? i.e. if i have a mesh that is farder than another it should be drawn behind the second.

Is there a way to do this in xna that is more standardized or do i have to calculate for each mesh myself? If i have to calculate for each mesh by myself, from which point do i calculate the distance to the mesh? the camera position?

Here is how i draw them :

```
        Matrix[] transforms = new Matrix[gameobject.model.Bones.Count];
        gameobject.model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in gameobject.model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.Projection = camera.projectionMatrix;
                effect.View = camera.viewMatrix;
                effect.World = transforms[mesh.ParentBone.Index] * gameobject.orientation;
           }
            mesh.Draw();
        }

```

# Answer
Try putting this before the draw code:

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

```
> 2 votes

---
Tags: xna
---


# Question
Title: How can I draw the inside of a box as well as the outside?
I have a 3D box in which I have some holes. The thing is that when I look through the holes, I can't see the wall of the box that should appear as the inner wall.

How can I draw this as well?

# Answer
I think you have backface culling enabled. It can be enabled with this to *None*.

In XNA 4.0 : `GraphicsDevice.RasterizerState = RasterizerState.CullNone;`
> 1 votes

---
Tags: xna
---


# Question
Title: Best Algorithm for attacking in the Risk Game
I apologize in advance for my English.I'll try to explain my problem. I am working on new version of the Risk game. I want to change the attacking algorithm to make it more similar to real life war. The sides which have more armies must have the advantage over the weaker side.

These are the original board game's rules below from Wikipedia:

> Example of matching up attacking (red) and defending (white) dice; in this case the attacker has won the battle. When it's a player's turn to attack, he or she can only attack territories that are adjacent or connected by a sea-lane to his or her own territory. A battle's outcome is decided by rolling dice. The attacking player attacks with one, two, or three armies, rolling a corresponding one, two or three dice. At least one army must remain behind in the attacking territory not involved in the attack, as a territory may never be left unoccupied. Before the attacker rolls, the defender must choose to resist the attack with either one or two armies (using at most the number of armies currently occupying the defended territory\[4\]) by rolling one or two die. Each player's highest die are compared, as are their second-highest die (if both players roll more than one). In each comparison, the highest number wins. The defender wins in the event of a tie. With each dice comparison, the loser removes one army from his territory from the game board. Any extra dice are disregarded and do not affect the results.

I think these rules are not very good for real life situations because we know from history that large number of armies have an advantage over the weaker side. I have to create the right balance between the two sides during the war.

Currently I am using the following algorithm

```
army1 = random.Next(1, 20 + (numberOfSolidersArmy1 / 5));
army2 = random.Next(1, 20 + (numberOfSolidersArmy2 / 5));

```

Then I am comparing army1 and army2 and decrease the number of soldiers by one of the smaller number's side.

What are your suggestions for a better algorithm?

# Answer
> 1 votes
If you want a more realistic equation, then the Lanchester laws have something for you: http://en.wikipedia.org/wiki/Lanchester%27s\_laws

However, they apply differently depending on whether you're simulating hand-to-hand combat or ranged combat, which isn't specified in your question.

A simple way to simulate the linear law is to make the values you compare linearly proportional to the number of armies you use. Roll 1 die for each army, add up the total, and whichever side has the lowest score loses an army. If you're working with large soldier counts instead of small army counts then work out the relative size advantage or disadvantage on one side and multiply that by the random value generated for that side.

---
Tags: c#, algorithm
---


# Question
Title: How can I use orientation to compute position in Windows Phone 7?
I'm using the motion API and I'm trying to figure out a control scheme for the game I'm currently developing.

What I'm trying to achive is for an orienation of the device to correlate directly to a position, such that tilting the phone forward and to the left represents the top left position and back to the right would be the bottom right position.

Here are some photos that should make my intent clearer. The red dot would be the calculated position.

Tilted forward and left, upper left selected.

Tilted back and right, bottom right selected.

I also have to make sure that the algorithm takes into account left landscape and right landscape device orientations (portrait is the default so no calculations would be needed for it).

I've tried using the yaw, pitch, roll and Quaternion readings. Here's a sample of my current attempt:

```
// Get device facing vector
public static Vector3 GetState()
{
    lock (lockable)
    {
        var down = Vector3.Forward;
        var direction = Vector3.Transform(down, state);

        switch (Orientation)
        {
            case Orientation.LandscapeLeft:
                return Vector3.TransformNormal(direction, Matrix.CreateRotationZ(-rightAngle));
            case Orientation.LandscapeRight:
                return Vector3.TransformNormal(direction, Matrix.CreateRotationZ(rightAngle));
        }

        return direction;
    }
}

```

# Answer
> 0 votes
I generally use something like this to rotate a point around another point:

```
Vector3 rotatedVector = Vector3.Transform(vectorToRotate, Matrix.CreateFromAxisAngle(rotationAxis, radiansToRotate));

```

Your approach seems to be similar, but I'm not sure what your `state` value is. I would recommend trying `Matrix.CreateFromAxisAngle(PhoneFaceAxis, radiansToRotate);`, where `PhoneFaceAxis` is the axis represented by the normal vector of the screen of your phone (which may be Z, judging by your code sample', and `radiansToRotate` would be some form of a 90 or 180 degree rotation depending on the phone's orientation.

I've also put information for issues like this at XNAWiki.com. It's a fairly small wiki, but it has some useful information about 3D Vector Math when using XNA.

---
Tags: xna, xna-4.0, windows-phone-7, orientation
---


# Question
Title: Essential skills to be a games programmer
I recently posted a question about the kinds of things to expect in game programming tests for games companies as I found myself unprepared for some of the topics. There are two things I can say about myself, and I think these probably apply to a lot of people. 1. I went and did a course at university that, although got me interested in programming, was poorly taught and didn't prepare me to really get any sort of decent job.. and 2. I'm still completely determined to get into the games industry.

I'm currently working at a little start-up, but I know that if I want to make the games I like playing I have to keep cramming!

My question is this: Can some of you professionals / graduates from better courses enlighten me as to the things I need to learn to become a really solid candidate for programming jobs.

I'm talking about things like Big O Notation, calculating complex recursion, linked lists , matrix / quaternion maths etc.

The first in that list I was not taught, and the second I didn't even know was something I might ever be expected to do. A list of all these and more, plus a good place to start learning about them would be extremely useful, I think to others as well as myself.

(re-tag and re-word this question as appropriate)

# Answer
Alright, I actually just graduated with a Bachelor's degree in Computer Science this December.

I'm going to list what I feel were the important classes and the textbooks we used in them. Other than these and some software engineering courses, the rest of my classes were more focused on subfields like databases, AI, web development, and ethical hacking.

**Data Structures**

http://www.amazon.com/Objects-Abstraction-Data-Structures-Design/dp/0471467553

This class is essentially an introduction to different types of data structures along with their performance characteristics. The class I took was focused around C++ so it discussed STL data structures such as vectors (dynamic arrays), link list, trees, maps, sets, stacks, queues, and hash tables. Touches upon some algorithm analysis stuff too but really only Big O notation for worst case performance scenarios.

**Algorithm Analysis**

http://www.amazon.com/Foundations-Algorithms-Fourth-Richard-Neapolitan/dp/0763782505/ref=sr\_1\_fkmr0\_1?s=books&ie=UTF8&qid=1326899174&sr=1-1-fkmr0

Explores many different types of algorithms and how to measure their performance characteristics. Some types of algorithms include Divide & conquer, dynamic programming, greedy approaches, backtracking, and branch and bounding.

**Distributed Computing**

http://www.amazon.com/Distributed-Computing-Applications-M-L-Liu/dp/0201796449/ref=sr\_1\_1?s=books&ie=UTF8&qid=1326899724&sr=1-1

Discusses networking, interprocess communication, UDP and TCP sockets, and a bunch of distributed computing paradigms (Client-Server, P2P, distributed objects, etc)

**Computer Architecture**

http://www.amazon.com/Structured-Computer-Organization-Andrew-Tanenbaum/dp/0131485210/ref=sr\_1\_1?s=books&ie=UTF8&qid=1326899561&sr=1-1

Self explanatory. Explains how all the hardware works and collaborates together.

**Program Language Concepts**

http://www.amazon.com/Concepts-Programming-Languages-Robert-Sebesta/dp/0136073476/ref=sr\_1\_1?s=books&ie=UTF8&qid=1326899395&sr=1-1

Covers different aspects and characteristics of different languages. Syntax, semantics, variable scope and binding, data types, expressions and assignmnet statements, control structures, etc.

**Operating Systems**

http://www.amazon.com/Operating-System-Concepts-Abraham-Silberschatz/dp/0470128720/ref=sr\_1\_1?s=books&ie=UTF8&qid=1326898989&sr=1-1

Covers from top to bottom all the essential task and concepts behind a operating system. This includes handling processes and threads, scheduling and synchronizing processes, memory (virtual, paging, segmentation, etc), file systems, and IO systems.
> 4 votes

---
Tags: jobs
---


# Question
Title: How can I profile and debug my usage of D3D10?
I've been working on D3D 10 for about 6 months and I have accumulated a basic framework. The thing is I get frame rate spikes.

Even when I have a simple cube on the screen each side with its own texture, every now and the the frame rate drops suddenly.

Any tips to try and find out what is causing it?

# Answer
First of all, you need to establish whether the spikes are occurring on the CPU or the GPU (or both). I'd recommend implementing basic (high-level) CPU/GPU profiling frameworks in your application, so you can measure and display the amounts of time that various operations are taking.

For the CPU, you can use QueryPerformanceCounter to measure timing of high-level operations in your frame, such as updating objects, physics (if any), frustum/occlusion culling, and rendering. For the GPU, you can use queries to get similar timing values out of the GPU. I wrote an article about that; it's written against the D3D11 API, but the same thing works in D3D10 with minor code modifications. Consult the ID3D10Query documentation for further details. Once you do this, you should be able to see the performance spikes in the data, and where in the frame the spikes are taking place. This will help focus further profiling efforts.

There are a few tools that can help drill down for more detailed information. AMD CodeAnalyst is a good free CPU profiling tool, and PIX is a free tool that works with D3D and your app to do GPU performance analysis and debugging.
> 2 votes

---
Tags: c++, directx10, debugging
---


title: Cocos2D Accelerometer Z axis

text:
# Question
Title: Cocos2D Accelerometer Z axis
I am making a 2D scroller game where the player controls an airplane via the accelerometer I would like to know if it is possible to scale in and to scale out the sprite/airplane using the accelerometer z axis. I would like to know how to do this to create a depth illusion.

Any suggestion, tutorial recommendation, and comments are appreciated.

Thanks.

# Answer
> 1 votes
Of course, you can access the Z data from the accelerometer just like you would access the X and Y data.

Sample cocos2d projects show how to use the accelerometer; in a nutshell, you will have a method as follows in the CCLayer subclass that controls your game:

```
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
    NSLog(@"Accelerometer z value is %f\n", acceleration.z);
}

```

Keep in mind that the accelerometer only detects *acceleration* \- it might be a bit tricky for you to achieve exactly the desired effect. For a depth effect graphics-wise, you might want to look into parallalax scrolling.

---
Tags: sprites, cocos2d-iphone, ios, cocos2d, ccsprite
---


# Question
Title: How can I remove inventory items in a Bukkit plugin?
I am making a Bukkit plugin that takes the player to a "FunZone" and allows them to do just about anything. I don't want data transferred between the two worlds. So far I have got most everything stopped. Here's the problem code:

```
            Integer normInvSize = player.getInventory().getSize();
            Integer i = 0;
            for (i=0; i<normInvSize; i++) {
                ItemStack item = player.getInventory().getItem(i);
                pConfig.set(player.getWorld().getName()+"Inv."+i.toString()+".amount", item.getAmount());
                Short durab = item.getDurability();
                pConfig.set(player.getWorld().getName()+"Inv."+i.toString()+".durabillity", durab.intValue());
                pConfig.set(player.getWorld().getName()+"Inv."+i.toString()+".type", item.getTypeId());
                player.getInventory().removeItem(new ItemStack(item.getType(), item.getAmount()));
            }

```

I have everything set up how I want it but I get stray items following me between the worlds. The line

```
player.getInventory().removeItem(new ItemStack(item.getType(), item.getAmount()));

```

does not remove all of the inventory. I want some code that will remove all inventory items (I've handled armor already). I already have a way to restore the inventory later, but my code currently won't remove everything. For example I can end up transfering some stone tools from the "FunZone" to the normal world, which I don't want.

# Answer
You can't clear a list while you're iterating over it, at least not in this way. Let me show you this, we'll assume a list with 5 items:

1. List: 5, Index: 0
2. List: 4, Index: 1
3. List: 3, Index: 2
4. Break condition already met. 2 Items remaining.

What you want to do is clear the whole inventory *after* you've iterated over it.

```
// Cache the inventory instead of a number you'll only use once.
PlayerInventory inventory = player.getInventory();

// Cache the world name
String worldName = player.getWorld().getName();

// Use a foreach instead. Looks better.
for (ItemStack stack : inventory.getContents()) {
    // More cache, String concetanations are expensive!
    String start = worldName + "Inv." + Integer.toString(i);

    pConfig.set(start + ".amount", stack.getAmount());
    pConfig.set(start + ".durability", stack.getDurability().intValue()); // Please be aware that I fixed a typo in durability
    pConfig.set(start + ".type", stack.getTypeId());
}

// And now clear the inventory
inventory.clear();

```

Also, I don't know what `pConfig` is, but the structure smells broken if you need save stuff like this. You use an Object-Oriented language, so if you need to split strings to get *something*, you're doing something wrong. You might want to rewrite that...thing.

For further infos please go to Stack Overflow, f.e.: Efficient Equivalent to Removing while Iterating a Collection
> 0 votes

---
Tags: java, minecraft-modding
---


# Question
Title: Breakout Collision: Detecting the side of collision
I am writing a breakout clone (my first game) and am totally stuck as to how I figure out which side of the brick was hit.

I have a collision detection method that looks like this:

```
DetectCollision(Object a, Object b)

   x = distance(a.x, b.x);
   y = distance(a.y, b.y);

   if (x is smaller than the combined width &  y is smaller is than combined height {
       return true;
   }
return false;

```

This works totally fine, but I need to know the side of the collision, and location relative to the center in order to respond properly.

I've spent the past few days snooping around but am lost.

# Answer
> 14 votes
This can all be gleaned from the position of the ball relative to the position of the brick it collided with.

Once you have detected a collision:

```
if(ballPosition.y <= brickPosition.y - (brickHeight/2))
  //Hit was from below the brick

if(ballPosition.y >= brickPosition.y + (brickHeight/2))
  //Hit was from above the brick

if(ballPostion.x < brickPosition.x)
  //Hit was on left

if(ballPostion.x > brickPosition.x)
  //Hit was on right

```

The first two check to see if the ball is above or below the brick. If neither than it must be next to the brick, so check which side it's on. This will need to be tweeked to fit where you're taking the location from, i.e. brickPosition is the center of the brick or brickPosition is the top left corner.

# Answer
> 10 votes
You could use Vector Math to discover the angles between them!

Here's a short answer:

```
ballToBrick = ballPosition - brickPosition;
ballToBrick.Normalize();
brickFacing = Vector2(0,1).Normalize();

float angle = acos( Dot(ballToBrick, brickFacing) );

```

The Brick facing is a tricky vector, it is the "start point" of the angle calculation. and if you want the vector to point up, make it (0, 1), point left (-1, 0), right (1, 0), point down(0, -1). Assuming you're in OpenGL axis, where up and right are positive.

If you dont know, here's the definitions of each function used:

```
Vector2.Normalize()
{
    float length = squareroot(x * x + y * y);
    x = x / length;
    y = y / length;
    return this;
}

Dot(Vector2 a, Vector2 b)
{
    return a.x * b.x + a.y * b.y;
}

```

(https://en.wikipedia.org/wiki/Dot\_product)

Reference: http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-2/

---
Tags: java, collision-detection
---