# Question
Title: How do I pass vertex and color positions to OpenGL shaders?
I've been trying to get this to work for the past two days, telling myself I wouldn't ask for help. I think you can see where that got me...

I thought I'd try my hand at a little OpenGL, because DirectX is complex and depressing. I picked OpenGL 3.x, because even with my OpenGL 4 graphics card, all my friends don't have that, and I like to let them use my programs. There aren't really any great tutorials for OpenGL 3, most are just "type this and this will happen--the end".

I'm trying to just draw a simple triangle, and so far, all I have is a blank screen with my clear color (when I set the draw type to GL\_POINTS I just get a black dot). I have no idea what the problem is, so I'll just slap down the code:

Here is the function that creates the triangle:

```
void CEntityRenderable::CreateBuffers()
{
    m_vertices = new Vertex3D[3];
    m_vertexCount = 3;

    m_vertices[0].x = -1.0f;
    m_vertices[0].y = -1.0f;
    m_vertices[0].z =  0.0f;
    m_vertices[0].r = 1.0f;
    m_vertices[0].g = 0.0f;
    m_vertices[0].b = 0.0f;
    m_vertices[0].a = 1.0f;

    m_vertices[1].x =  1.0f;
    m_vertices[1].y = -1.0f;
    m_vertices[1].z =  0.0f;
    m_vertices[1].r = 1.0f;
    m_vertices[1].g = 0.0f;
    m_vertices[1].b = 0.0f;
    m_vertices[1].a = 1.0f;

    m_vertices[2].x =  0.0f;
    m_vertices[2].y =  1.0f;
    m_vertices[2].z =  0.0f;
    m_vertices[2].r = 1.0f;
    m_vertices[2].g = 0.0f;
    m_vertices[2].b = 0.0f;
    m_vertices[2].a = 1.0f;

    //Create the VAO
    glGenVertexArrays(1, &m_vaoID);
    //Bind the VAO
    glBindVertexArray(m_vaoID);

    //Create a vertex buffer
    glGenBuffers(1, &m_vboID);
    //Bind the buffer
    glBindBuffer(GL_ARRAY_BUFFER, m_vboID);
    //Set the buffers data
    glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertices), m_vertices, GL_STATIC_DRAW);
    //Set its usage
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex3D), 0);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex3D), (void*)(3*sizeof(float)));

    //Enable
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    //Check for errors
    if(glGetError() != GL_NO_ERROR)
    {
        Error("Failed to create VBO: %s", gluErrorString(glGetError()));
    }
    //Unbind...
    glBindVertexArray(0);
}

```

The Vertex3D struct is as such...

```
struct Vertex3D
{
    Vertex3D() : x(0), y(0), z(0), r(0), g(0), b(0), a(1) {}

    float x, y, z;
    float r, g, b, a;
};

```

And finally the render function:

```
void CEntityRenderable::RenderEntity()
{
    //Render...
    glBindVertexArray(m_vaoID);
    //Use our attribs

    glDrawArrays(GL_POINTS, 0, m_vertexCount);

    glBindVertexArray(0); //unbind
    OnRender();
}

```

(And yes, I am binding and unbinding the shader. That is just in a different place) I think my problem is that I haven't fully wrapped my mind around this whole VertexAttribArray thing (the only thing I like better in DirectX was input layouts D:).

This is my vertex shader:

```
#version 330

//Matrices
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
//In values
layout(location = 0) in vec3 position;
layout(location = 1) in vec4 color;
//Out values
out vec4 frag_color;
//Main shader
void main(void)
{
    //Position in world
    gl_Position = vec4(position, 1.0);
    //gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
    //No color changes
    frag_color = color;
}

```

Here is the fragment shader:

```
#version 330
//In values
in vec4 frag_color;
//Out values
out vec4 out_color;
//main shader
void main(void)
{
    out_color = frag_color;
}

```

As you can see, I've disable the matrices, because that just makes debugging this thing so much harder. I tried to debug using glslDevil, but my program just crashes right before the shaders are created... so I gave up with that. This is my first shot at OpenGL since the good old days of LWJGL, but that was when I didn't even know what a shader was. Thanks for your help :)

I'd also like to add this, I only saw it in one tutorial:

```
m_defaultShader->BindAttrib(0, "position");
m_defaultShader->BindAttrib(1, "color");

```

BindAttrib looks like this:

```
void IShader::BindAttrib(int index, char* name)
{
    glBindAttribLocation(m_shaderProgram, index, name);
}

```

I thought maybe that may be an issue

# Answer
### Nitpicks

Things that aren't actually your problem but you should correct anyway.

First, `Vertex3D` is not a POD, by the C++03 rules defining POD structs. As such, C++03 offers no guarantees of the layout of such a struct, so you can't just shove it into OpenGL.

Now, that being said, your struct will likely work. Most compilers will provide the expected layout for this struct. And C++11 extends the rules of layout such that this struct *is* guaranteed to have the expected layout.

Next, `m_vertices = new Vertex3D[3];`. I don't see a `delete[]` anywhere. Now yes, `m_vertices` is likely a member variable, but there's no reason to keep this array around. What happens if someone calls `CreateBuffers` twice?

Indeed, there's no reason to use a naked array at all. Use a `std::vector<Vertex3D>` instead. That way, it'll be properly scoped and everything; you won't have to worry about when it goes away.

Next:

```
glVertexAttribPointer(1, 4, GL_FLOAT, GL_TRUE,  sizeof(Vertex3D), (void*)(3*sizeof(float)));

```

There is no such thing as a normalized *float*. Normalization specifies how *integer* values are interpreted as floats. The byte value 255, when interpreted as a normalized unsigned byte, will become 1.0f. When interpreted as a non-normalized unsigned byte, it will be 255.0f.

This won't actually cause an error; it'll just be ignored because it makes no sense. But you still shouldn't do it.

### Actual Problems

Things that are actual problems, but may not be your *real* problem.

```
glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertices), m_vertices, GL_STATIC_DRAW);

```

That doesn't do what you think it does. `m_vertices` is a `Vertex3D*`. Therefore, `sizeof(m_vertices)` is... 4. Or 8 if you're compiling in 64-bit mode.

You probably wanted the size of the array. This is yet another reason to use `std::vector`; it's much easier to compute. In that it's actually *possible* to compute it ;)

```
glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex3D), &m_vertices[0], GL_STATIC_DRAW);

```

### Your Code Problem

Your Code Problem

This is your vertex position data:

```
m_vertices[0].x = -1.0f;
m_vertices[0].y = -1.0f;
m_vertices[0].z = -5.0f;
m_vertices[1].x =  1.0f;
m_vertices[1].y = -1.0f;
m_vertices[1].z = -5.0f;
m_vertices[2].x =  0.0f;
m_vertices[2].y =  1.0f;
m_vertices[2].z = -5.0f;

```

Notice that all of the Z values are at -5.0f. Since you are using no matrix transforms, this means that the clip-space vertices that you get will be at -5.0f in the Z direction.

Clip-space (or to be technical, Normalized Device Coordinate space) only extends from \[-1, 1\] in all directions. That includes Z. Your -5.0f Z coordinate places your vertex positions *outside* of the world.

I would suggest 0.0f for the Z.

### Your Real Problem

Your Real Problem

It's this:

> I'd also like to add this, I only saw it in one tutorial:

The thought behind you making this statement is the source of your problem. You aren't coding; you're copying and pasting bits of code extracted from various online sources.

If you understood what, for example, OpenGLBook.com, was saying about `layout(location)`, and then read what another tutorial was saying that `glBindAttribLocation` does, then you would quickly realize that they *both set the same thing*. There's no sense in using both of them for the same shader. It's like having a getter for a *public* variable; there's no point to it and it only ends up confusing the user.

You should *never* do anything just because you "saw it in one tutorial". You use it because you *understand* what it does and see a need to do that in your application.

I would say that you have a strong case of "I want to do X"itus. This is a common disease found among many programmers who are new to something. They see something and want to perform some specific task. So they go online and find information. But since none of that information tells them how to do *exactly* what they want to do, they just find bits of code and copy them into their code, building up a Frankenstein's Monster of an application.

It may *live*, but it's not the most pleasant form of life.

For example, I have my own series of GL 3.3 tutorials. I think they're pretty decent. But they will not teach you how to write exactly what you're writing. If you try to copy and paste from them, you won't get anything more useful than you'll get from other tutorials.

But if you *read* them, then they will try to teach you how to be a graphics programmer. The first three chapters covers most of the mistakes and problems your codebase has. It explains about Normalized Device Coordinate space and the extents thereof. It explains how to use `glBufferData` (though it's still up to you to pass in the correct size). It doesn't explain normalized attributes, but that's because it sticks with floats; it says to leave it as `GL_FALSE`.

To put it another way, forget about what you *want* to learn from any tutorial. Simply learn whatever lesson it is intending to teach you. Once you understand the material, you don't need to copy their code at all; you can just write it yourself.
> 25 votes

---
Tags: opengl, shaders
---


title: Is game development Subcontracted?

text:
# Question
Title: Is game development Subcontracted?
I was having a conversation with someone who believed that components of a games code where subcontracted out to programmers in different countries where it would be cheaper, then assembled by the local company. I understand that people often use pre-built engines but I would think that making the actual game would require people to work closely in the same studio.

I couldn't find much clear information on this when I looked, does anyone know?

# Answer
> 6 votes
It happens. They are still "companies" so any kind of business move can be possible, including paying some foreigners to do a module of the game.

A recent famous example are the boss fights in Deus Ex : Human Revolution. They were made by another company than the Eidos team.

However, it is not common in the gaming industry, because it's harder to maintain coherency with a lot of people that are foreign to the core team. It happens mostly on very big projects where outsourcing graphics is not a problem for example, or outsourcing some modules like graphic rendering.

# Answer
> 3 votes
Yes, in some companies subcontracting is very common. Particularly in Japan. Tose does contract work for an unbelievable number of companies - some Japanese studios consist only of concept artists and designers. Mistwalker outsources almost their entire engineering process.

From Gamasutra's *Interview: Tose: Game Development Ninjas*:

> GS: How many people do you employ?
>
> MA: 800 in Japan, 200 in china.
>
> GS: How come we've never heard of you until right now?
>
> Koichi Sawada: Well we're based in Kyoto, right? So we're ninja. You can't find us! But in the past 26 years we've worked on 1,100 games. Including partial games.
>
> ...
>
> GS: Do you have a breakdown of what percentage of your staff does what?
>
> SC: Our Chinese operation has a higher percentage of partial work, whereas the Japanese studios do more full development. Companies come to us if they need models, or maybe some animation. Right now, we're also making all of our artists in China hybrid artists. Which means they can do both 2D and 3D, so that at the end of the year, every artist should be able to do 3D art.
>
> GS: How many dedicated 2D artists do you still have in China at this point?
>
> SC: Maybe about 40.
>
> GS: In Japan what are the majority? Programmers?
>
> MA: Programmers and artists.

From *Return Of The Ninja: Tose's Stealthy Outsourcing Progress*:

> How many developers are working at Tose, now that you've opened more studios?
>
> It's 1,000 in Japan, 200 in China, and two in the U.S.
>
> ...
>
> Are there any plans to do any more original IP out of Tose in the near future?
>
> We already make original games for publishers, but we will not own the IP of that project.
>
> Will it be based on ideas generated from Tose, or from the publisher?
>
> From both. It depends on the project.

Note that Tose isn't doing mobile and web games, for which outsourcing is well-known - they're doing A to AAA games, sometimes the entire game, and having the publisher take credit for it.

# Answer
> 2 votes
It does happen, though it's rare that it is done to save costs by outsourcing to cheaper countries, as with business software. In games it is usually one of the following:

* An entire studio located in a different country to make franchised games based on an existing engine (eg. Ubisoft Shanghai making half the Splinter Cell games). This is indeed cheaper, but the result is not 'assembled' back home - the whole product, more or less, is handled by the other studio.
* Studios with specific skills being contracted for specialist work. (eg. the Deus Ex: Human Revolution example where the boss fights were given to an FPS AI company.)
* A studio might just be too small to finish the work on time, so they pay for another studio to take on some of the work (I have been involved in this myself), often one located nearby or owned by the same publisher.

I've seen cases when art assets were contracted out to companies on the Indian subcontinent, and heard of them being outsourced to China too. But I've never heard of part of the game code being contracted out like that - I think game code is considered a core competency of game developers and when you start subcontracting your supposed core competency to a cheaper place, that would indicate that you have some problems with your whole business.

---
Tags: game-industry
---


title: Creating a 2D Line Branch (Part 2)

text:
# Question
Title: Creating a 2D Line Branch (Part 2)
Yesterday i asked this question on how to create a 2D line branch; Creating a 2D Line Branch

And thanks to the answered provided, i now have this nice looking main branch; \*coloured to show the different segments in the final item.

Now is the time now to branch things off as discussed in the article; http://drilian.com/2009/02/25/lightning-bolts/

Again however i am confused as to the meaning of the following pseudo code;

```
splitEnd = Rotate(direction, randomSmallAngle)*lengthScale + midPoint;

```

I'm unsure how to actually rotate this correctly. In all honesty i'm abit unsure what to-do completely at this part, "splitEnd" will be a Vector3, so whatever happens in the rotate function must then return some form of directional rotation which is then * by a scale to create length and then added to the midPoint.

I'm not sure. If someone could explain what i'm meant to be doing in this part that would be really grateful.

# Answer
> 2 votes
Instead of asking a series of questions on specifics (normally the right thing to do on StackExchange, yes), you would be far better served by simply learning the basics of the linear algebra that you're running up against.

To give a slightly more directed answer, the Rotate function must perform a basic 2D rotation of the direction vector by the angle randomSmallAngle. This can be done with some very simple math, explained in most of the links above, or you can just use the XNA Matrix.CreateRotationZ() method to create a rotation matrix to transform the direction vector by.

The rotation does not return "some form of directional rotation" but in fact just returns a regular vector. It's taking the original direction, rotating it slightly left or right, and returning that. The lengthScale multiplication just scales that vector, changing its lengths. Finally it's added to the midPoint, giving a vector that's a position relative to the midPoint.

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


# Question
Title: What is a better abstraction layer for D3D9 and OpenGL vertex data management?
My rendering code has always been OpenGL. I now need to support a platform that does not have OpenGL, so I have to add an abstraction layer that wraps OpenGL and Direct3D 9. I will support Direct3D 11 later.

**TL;DR:** the differences between OpenGL and Direct3D cause redundancy for the programmer, and the data layout feels flaky.

For now, my API works a bit like this. This is how a shader is created:

```
Shader *shader = Shader::Create(
    " ... GLSL vertex shader ... ", " ... GLSL pixel shader ... ",
    " ... HLSL vertex shader ... ", " ... HLSL pixel shader ... ");
ShaderAttrib a1 = shader->GetAttribLocation("Point", VertexUsage::Position, 0);
ShaderAttrib a2 = shader->GetAttribLocation("TexCoord", VertexUsage::TexCoord, 0);
ShaderAttrib a3 = shader->GetAttribLocation("Data", VertexUsage::TexCoord, 1);
ShaderUniform u1 = shader->GetUniformLocation("WorldMatrix");
ShaderUniform u2 = shader->GetUniformLocation("Zoom");

```

There is already a problem here: once a Direct3D shader is compiled, there is no way to query an input attribute by its name; apparently only the semantics stay meaningful. This is why `GetAttribLocation` has these extra arguments, which get hidden in `ShaderAttrib`.

Now this is how I create a vertex declaration and two vertex buffers:

```
VertexDeclaration *decl = VertexDeclaration::Create(
        VertexStream<vec3,vec2>(VertexUsage::Position, 0,
                                VertexUsage::TexCoord, 0),
        VertexStream<vec4>(VertexUsage::TexCoord, 1));

VertexBuffer *vb1 = new VertexBuffer(NUM * (sizeof(vec3) + sizeof(vec2));
VertexBuffer *vb2 = new VertexBuffer(NUM * sizeof(vec4));

```

Another problem: the information `VertexUsage::Position, 0` is totally useless to the OpenGL/GLSL backend because it does not care about semantics.

Once the vertex buffers have been filled with or pointed at data, this is the rendering code:

```
shader->Bind();
shader->SetUniform(u1, GetWorldMatrix());
shader->SetUniform(u2, blah);
decl->Bind();
decl->SetStream(vb1, a1, a2);
decl->SetStream(vb2, a3);
decl->DrawPrimitives(VertexPrimitive::Triangle, NUM / 3);
decl->Unbind();
shader->Unbind();

```

You see that `decl` is a bit more than just a D3D-like vertex declaration, it kinda takes care of rendering as well. Does this make sense at all? What would be a cleaner design? Or a good source of inspiration?

# Answer
You're basically running into the kind of situation that makes NVIDIA Cg such an attractive piece of software (aside from the fact that it doesn't support GL|ES, which you said you're using).

Also note that you really shouldn't use glGetAttribLocation. That function is bad juju from the initial days of GLSL before the folks in charge of GL really started to grok how a good shading language should work. It's not deprecated as it has the occasional use, but in general, prefer glBindAttibLocation or the explicit attribute location extension (core in GL 3.3+).

Dealing with the differences in shader languages is by far the hardest part of porting software between GL and D3D. The API issues you're running into regarding vertex layout definition can also just be looked at as a shader language problem, as GLSL versions before 3.30 don't support explicit attribute location (similar in spirit to attribute semantics in HLSL) and GLSL versions before 4.10 iirc don't support explicit uniform bindings.

The "best" approach is to have a high-level shading language library and data format that encapsulates your shader packages. Do NOT simply feed in a bunch of raw GLSL/HLSL to a thin Shader class and expect to be able to come up with any kind of sane API.

Instead, put your shaders out into a file. Wrap them up in a bit of meta-data. You could use XML, and write shader packages like:

```
<shader name="bloom">
  <profile type="glsl" version="1.30">
    <source type="vertex"><![CDATA[
      glsl vertex shader code goes here
    ]]></source>
    <source type="fragment"><![CDATA[
      glsl fragment shader code goes here
    ]]></source>
  </profile>
  <profile type="hlsl" version="sm3">
    <source type="fx"><![CDATA[
      hlsl effects code goes here
      you could also split up the source elements for hlsl
    ]]></source>
  </profile>
</shader>

```

Writing a minimal parser for that is trivial (just use TinyXML for instance). Let your shader library load up that package, select the proper profile for your current target renderer, and compile the shaders.

Also note that if you prefer, you can keep the source external to the shader definition, but still have the file. Just put file names instead of source into the source elements. This may be beneficial if you plan on precompiling shaders, for instance.

The hard part now of course is dealing with GLSL and its deficiencies. The problem is that you need to binding attribute locations to something akin to HLSL semantics. This can be done by defining those semantics in your API and then using glBindAttribLocation before linking the GLSL profile. Your shader package framework can handle this explicitly, with absolutely no need for your graphics API to expose the details.

You can do that by extending the above XML format with some new elements in the GLSL profile to explicitly specify attribute locations, e.g.

```
<shader name="bloom">
  <profile type="glsl" version="1.30">
    <attrib name="inPosition" semantic="POSITION"/>
    <attrib name="inColor" semantic="COLOR0"/>
    <source type="vertex"><![CDATA[
      #version 150
      in vec4 inPosition;
      in vec4 inColor;

      out vec4 vColor;

      void main() {
        vColor = inColor;
        gl_Position = position;
      }
    ]]></source>
  </profile>
</shader>

```

Your shader package code would read in all the attrib elements in the XML, grab the name and the semantic from them, look up the pre-defined attribute index for each semantic, and then automatically call glBindAttribLocation for you when linking the shader.

The end result is that your API can now feel much nicer than your old GL code likely ever looked, and even a bit cleaner than D3D11 would allow:

```
// simple example, easily improved
VertexLayout layout = api->createLayout();
layout.bind(gfx::POSITION, buffer0, gfx::FLOATx4, sizeof(Vertex), offsetof(Vertex, position));
layout.bind(gfx::COLOR0, buffer0, gfx::UBYTEx4, sizeof(Vertex), offsetof(Vertex, color));

```

Also note that you don't strictly *need* the shader package format. If you want to keep things simple, you're free to just have a loadShader(const char\* name) kind of function that automatically grabs the name.vs and name.fs GLSL files in GL mode and compiles and links them. However, you're absolutely going to want that attribute metadata. In the simple case, you can augment your GLSL code with special easy-to-parse comments, like:

```
#version 150

/// ATTRIB(inPosition,POSITION)
in vec4 inPosition;
/// ATTRIB(inColor,COLOR0)
in vec4 inColor;

out vec4 vColor

void main() {
  vColor = inColor;
  gl_Position = inPosition;
}

```

You can get as fancy as you're comfortable with in the comment parsing. More than a few professional engines will go so far as to make minor language extensions that they parse out and modify, even, such as just outright adding HLSL style semantic declarations. If your knowledge of parsing is robust, you should be able to reliably find those extended declarations, extract the extra information, and then replace the text with the GLSL compatible code.

No matter how you do it, the short version is to augment your GLSL with the missing attribute semantic information and have your shader loader abstraction deal with calling glBindAttribLocation to fix things up and make them more like the easy and efficient modern GLSL versions and HLSL.
> 8 votes

# Answer
Firstly, I'd suggest using `VertexBuffer<T>` to improve type safety, but secondly, I think the differences between the two APIs are too much at this level. I personally would fully encapsulate the renderers behind an interface which does not deal with things like vertex declarations or setting shader attributes.
> 5 votes

# Answer
Personally, I'd establish (and enforce) a standardized convention for attribute indices. GL index 0 is the position. GL index 1 is the color. Index 2 is a normal, with 3 and 4 for tangents and binormals (if needed). Index 5-7 are texture coordinates. Maybe 8 and 9 are for bone weights. 10 can be a second color if needs be. If you're not able to use `GL_ARB_explicit_attrib_location` or GL 3.3+, then you should also establish a standardized attribute *naming* convention.

That way, D3D has conventions and OpenGL has conventions. So the user doesn't even have to ask what the index of a "position" is; they know it's 0. And your abstraction knows that 0 means, in D3D land, `VertexUsage::Position`.
> 2 votes

---
Tags: opengl, directx9, vertex-arrays
---


# Question
Title: what is the simplest 3d software for unity?
Ive heard a lot about Daz studio, Poser, Maya, K-3d, Anim8or, Blender, and all the rest.

My question is which one is the best choice in terms of simplicity and quality. price is not an issue really. I'm programming games in java for android mobile devices at the moment but i will eventually move onto larger platforms. I would like to utilize unity3d for the game programming itself and utilize a 3d modeling software just to create the game objects.

I just need to know the best one to get started with from scratch or should i use a combination of multiple ones? Any insight for this would be great, thanks!

# Answer
> 13 votes
# TL;DR

In short.. Get Blender! Since you're a beginner it's not worth pouring k's into a software you have no idea how to fully utilize.

# Simplicity explained

Well, simplicity is a relative term. For one Blender will be simple, for the other guy Maya. But in the end it depends on how much you use the tool. For example, if you start with Blender, as time passes you'll get better with it, developing it into a habit, and therefore, widening the margin to transition into Maya freely.

# It's the format that matters

Almost any 3D software will do, the only difference is in how you export your model and whether Unity3D supports it.

For sure, the de-facto standard for some time has been Autodesk's FBX, hence most developers use Autodesk software. And, yes, Unity supports it, plus it's recommended to use FBX.

Then there is COLLADA. Rumors say that Unity3D doesn't have a full support for COLLADA.

But, yes, Unity has wide support for importing not so universal formats- \*.3ds, \*.max to name a few.

Haven't been working with Unity lately and haven't used other software than 3DS Max, therefore I cannot precisely say what formats Unity supports. But I've tried \*.3ds and \*.max- more or less, but they work.

### Urgent:

> Formats like COLLADA and FBX are meant to be used by default. Developers have put a lot of effort in these formats, meaning, that they will not only export/import with mesh, but with animations, that you can bake in and all the other stuff the actual model will posses.
>
> Plus, they are software independent. You can work with Blender, your friend with 3DS Max and an outsourced modeler with Maya or XSI and FBX will provide almost 100% support for every tool.
>
> It's strongly encouraged to use these universal formats.

As for the software itself, everything will be OK as long as they support FBX and/or COLLADA.

I'd recommend one of these:

* Blender
* 3DS Max
* Maya (from what I've heard, Maya is more complete than Max, but then again, it's more complex than Max)

Since Blender is Open-Source it's free for everybody, everything and forever. It has huge community, lots of plugins and so on and so forth. In short, a free, packed 3D software for almost everything you can imagine.

Autodesk products on the other hand are better developed, they're commercial products, therefore higher quality product, plus, relatively better community- resulting in more plugins and 3rd party tools.
Autodesk software is not cheap tho', but provides educational license for every single tool they have there for an exchange of stripped down license.
One more bonus for Autodesk would be the infinte amount of quality and really helpful plugins/3rd party software. But the plugins tend to not be cheap either.

### Details

As rojcyk mentioned, there are tools such as ZBrush (Sculptris is the stripped down, free version of ZBrush). These are mostly meant to be used for details, like, when you need to add that quality 6 pack to your Rambo guy.

There is a bonus for this, you only have to make a reference model, and ZBrush will allow you to add that extra detail much faster and more precise than the plain ol' modelling tool, hence they fell into the category of "Sculpting tools".

# It's not the tools it's the carpenter

The information above should be enough, but yes, modelling as for everything else in this world, doesn't just "happen". Takes a lot of time and a lot of knowledge to end up in something really usable.

### Good luck and have fun!

# Answer
> 4 votes
Well I would say it depend on the platform you are using and what exactly you are trying to accomplish. Because every software you mentioned does something different. For example Daz studio is more about posing and making animations, scenes and not about modeling itself. So is Poser. Maya, K-3d and Blender are about modeling.

I think you don't want answer like this but I would say the best choice is the one you like working with the most. Some people prefer Maya over Blender, some people prefer 3DS Max over Maya, its about preferences and how does the software suite you.

People like to combine modeling software with Zbrush to add texture to their creations. If money is not an issue. I would go with Maya and Zbrush, but my preferences might differ.

# Answer
> 2 votes
3DSMax is almost a video game standard (and you can even include .max files directly in Unity3D)!

But, and this is just my opinion, you should go with what you or whoever works for you knows best as long as it can export files exploitable by Unity3D.

# Answer
> 1 votes
I have used a lot of 3D software (such as: 3DS Max, Mudbox, Zbrush, DAZ 3D, Rhino, Modo, Cinema 4D). If you're after power and simplicity of use, I recommend Modo. It's a very affordable program with an easy interface which is really able to do anything from modelling to posing, rendering, and animation.

---
Tags: 3d, graphics, unity, animation, models
---


title: Why can't I create direct3d objects?

text:
# Question
Title: Why can't I create direct3d objects?
I've been programming professionally for years using languages like VBScript, JavaScript, and C#. As a hobby, I'm getting into some c/c++ and games programming with DirectX.

I am running into an issue where I cannot create direct3d objects. I am using Visual C++ 2010 Express. After I installed vc++2010express I then installed the June 2010 release of DirectX.

I am trying to include DirectX via #pragma statements. This is the code I have so far in my winmain.cpp source file:

```
#include <Windows.h>
#include <d3d11.h>
#include <time.h>
#include <iostream>
using namespace std;

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")

// program settings
const string AppTitle = "Direct3D in a Window";
const int ScreenWidth = 1024;
const int ScreenHeight = 768;

// direct3d objects
LPDIRECT3D11 d3d = NULL; // this line is showing an error

```

The type `LPDIRECT3D11` is showing an error:

```
Error: Identifier "LPDIRECT3D11" is undefined

```

Am I missing something here to get VC++2010Express to recognize and load the DirectX libs?

Thanks for any help.

# Answer
As the compiler accurately tells you, there is no type called `LPDIRECT3D11` defined by D3D11's interface. Creating an `ID3D11Device` must be done through an `IDXGIFactory`, and there are a couple of one-step helper functions, but there is no equivalent to `IDirect3D9` in D3D11.
> 2 votes

---
Tags: c++, directx
---


# Question
Title: How does Minecraft compute lighting for it's non-block objects?
I was wondering how the creator of Minecraft went about lighting the objects (player and pickaxe) based on the lighting level around the player. I have implemented the ability to light the *blocks* around the player but I can't really think of anyway to implement with objects. Also, when I the player moves and the lighting values change will I have to rebuild it's vertexbuffers? Or is there some other way?

Any ideas?

# Answer
> 9 votes
Simplest option is to grab the lighting from the block your standing on (or if possible the lighting on the block in the air that corresponds to the block the pickaxe is in) and use that for lighting the pickaxe/player. Or in other words, calculate the lighting for the pickaxe as if it was a block in that position.

To get more realistic shadows you would need to look up Shadowmapping or similar techniques, but given the nature of the project I expect using the previous one will give you good results.

# Answer
> 0 votes
(Expanding on my older comment...)

From observation while playing the game, I believe that Minecraft's lighting works in the following way:

* The world grid includes a light level for each cell. This is used to determine the base brightness of an entity whose origin lies in that cell. You can see that if you walk into a lighting glitch, your tool becomes dark, and if an entity enters an opaque block (this can happen with minecarts and arrows) it turns black.
* In addition, there is global directional lighting (in classic OpenGL style), which causes adjacent faces of objects to not have exactly the same color, adding definition to corners.

Thus the final displayed color of a textured surface would be

```
     worldBrightness * directionalLight * texel

```

---
Tags: xna, lighting, minecraft-modding, voxels
---


title: Tile transitions - external vs internal

text:
# Question
Title: Tile transitions - external vs internal
I've been looking at a couple of games and noticed that the transitions between tiles are handled somewhat different.

I was wondering which methods are to be used in different situations and why. I'm currently using internal edges in a top-down game, and it's working out so far. But I don't want to run into problems later on, and have to redo the whole tileset.

I noticed that platforming games mostly use the internal edges, and top-down games mostly use external and hybrid transitions. I can see how these tiles are used to create "depth" in top-down games, where the player apears to be standing in front of a wall for example. But it seems unlikely that such a small feature decides the entire method for tile transitions. You could always alter the bounding box to create the same effect.

# Answer
On the one hand, your distinction between internal and external transitions looks like kind of a false dichotomy to me. In both cases what you have is tiles depicting a transition from two types of terrain, say sand and water. The only difference is how much sand is depicted vs. how much water. That isn't any sort of technical distinction, just a difference in how the artists choose to draw the tiles.

That said, the main technical difference I would expect from different tiling choices would be in collision detection. For example, if the character moves through water but not sand, then is this transition tile considered water or sand? However this is similar to the case you pointed out in your question, a technical situation that could easily be addressed by altering the bounding box of the tiles.
> 4 votes

---
Tags: tiles, tilemap
---


# Question
Title: How do I move a sprite around using tile based movement in Java?
So, I'm new to Java and I want to get a sprite to move around the screen, like a tile-based movement. I really would like some help and some resources or tutorials could work. I've done a little C#, but I couldn't seem to get it.

# Answer
> 1 votes
Might as well learn it from Stanford right? The video lectures there are rather good for someone just starting out. You'll use Karol the Robot as your guide to learning to program. Once you get more comfortable with the higher level concepts you can dig into the source for Karol and learn how actually do the drawing and moving around.

# Answer
> 0 votes
This is relatively a language independent question. though my java is a little light, but the logic is the big thing here.

Tile systems are relatively straight forward, but still equally as difficult as continuous motion, in that instead of incrementing with respect to time

`x += 5*time;`

you instead add a fixed amount

`x += tileWidth;`

so for example if you have a character that holds a position you would just have.

```
if(button.press.up){
    character.position.y -= tileHeight;
}
if(button.press.left){
    character.position.x += tileWidth;
}

```

and the reverse for the other directions. the big thing here is instead of moving with respect to time, or some counting your moving with respect to fixed numbers. though this is primarily for rectangular tiles (square if `tileHeight` = `tileWidth`). if your doing different shape tiles (hexagonal, triangular, etc...) then your going to have different math, but the concept of moving at fixed increments is the key here.

---
Tags: java, sprites, movement
---


# Question
Title: Virtual screen size with libgdx and GLES 2
I've been trying to use a virtual screen size for my libgdx desktop-android game. I'd like to always use a 16:9 aspect ratio but with a virtual screen size so everything would adapt automatically depending on the device size.

This post illustrates the process pretty well but my game crashes when camera.apply(Gdx.Gl10) is called. This is because I'm using GLES 2.0 (for not having to use multiple of 2 texture sizes). As stated in the OrthographicCamera doc, the apply method only works with GLES 1 and GLES 1.1.

Is there another way of applying my GL transformation to the camera so I can use a virtual screen resolution? Having to resize everything manually it's a total pain.

Thanks a lot.

# Answer
Answer at here: http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=3915
> 1 votes

---
Tags: java, android, libgdx, screen
---


# Question
Title: Finding the endpoint of a named bone in Irrlicht
I'm making a tank game that will have multiple tanks. I want to be able to define the weapon placements using bones that I can add right inside the modelling program (Blender to be exact).

All tanks will have a bone called Body and a bone called Turret, and then names like Cannon0 and PickupGun for where the shots will be fired from that are attached to the Turret bone. Is there some way to find the absolute end position of a bone that I choose by name?

# Answer
I figured it out. I'm using IrrlichtLime and I do this:

```
AnimatedMeshNode.GetJointNode("muzzle").RelativeTransformation

```

to get the transformation relative to the model origin.
> 0 votes

---
Tags: models, irrlicht, skeletal-animation
---


# Question
Title: In some games, we just let the main() loop be the Player object or Table object?
I was thinking that let's say if there is a game of Blackjack or MasterMind, then we should have a class called `Dealer` or `ComputerPal`, which is how the computer interact with us (as a dealer for Blackjack or as the person giving hints for MasterMind).

And then there should be a Player object, and the way to play one game is

```
aPlayer.playGame

```

but I noticed that a book was just using the `main()` loop to act as the player (or as the Controller of the game), calling the Dealer methods to dealer the cards, ask for player's action, etc...

1) Is this just a lazy way to model all the proper objects?

2) If more objects are to be added, who should call the `aDealer.dealCards` and then ask for `aPlayer.askForAction`? (because it is strange to let the Player handle all the logical steps). Should there be a `Table` object that handle all these logic and then to play one round of game, use `aTable.playGame`? What is a good object design for such game?

# Answer
> 2 votes
Having the `Player` class run the game would be a bad way to go about things. As the book you read was probably explaining, you should have some sort of game loop that handles updating logic and drawing the graphics. To answer your questions:

1. No, this isn't the correct way. You would not want to give the `Player` object responsibility over the entire game as it is outside of the scope of a "player".
2. The game loop should call an update function periodically. Inside this `update()` is where you should call all of your logical functions. Like this:

```
void update(){
    aDealer.dealCards();
    aPlayer.playHand();
    aOpponent.playHand();
}

```

Responsibility for managing the game belongs outside of the `Player` class. Perhaps consider writing a `GameManager` class with a similar update function. In your game loop, call `aGameManager.update();`.

---
Tags: design-patterns, game-loop, objects
---


title: 3D RTS pathfinding

text:
# Question
Title: 3D RTS pathfinding
I understand the A\* algorithm, but I have some trouble doing it in 3D to suit the needs of my RTS

Basically, in the game I'm making, there will be agents with different sizes of OBB collision boxes.

I can use steering behaviours for avoiding other agents, so I don't need complete dynamic pathfinding. However, there is a problem because different agents have different collision geometry, and structures can be placed in almost any place. This means that there might be a gap between two structures where some agents can go through and some can't.

A solution I have found to this problem is to do a sweep of the collision geometry of the agent from start node of the edge the pf algorithm is currently testing, to the end node of that edge. But this is probably a bit overkill since every edge the algorithm tests would also have to create and test with a collision geometry sweep.

What are some reasonable approaches to this problem? I should mention that I'd prefer not to use navmeshes, I prefer waypoints because my entire system is based on it atm.

# Answer
> 2 votes
Since you're talking about combining waypoint path-finding and steering behaviours I strongly suggest you take a look at the Corridor Map Method (CMM), if you aren't already.

It creates a waypoint graph that includes clearance information which is helpful for constraining the steering behaviours.

A derivative method that just popped in my head, which might be less of a hassle to implement than the CMM (no expensive off-line processing phase), is to use your current waypoint graph and add chokepoint waypoints with clearance data where necessary.

---
Tags: collision-detection, ai, path-finding
---


# Question
Title: std::vector::size with glDrawElements crashes?
`( win32 / OpenGL 3.3 / GLSL 330 )`

I decided after a long time of trying to do a graphical user interface using just opengl graphics to go back to a gui toolkit and so in the process have had to port alot of my code to `win32`.

But I have a problem with my `glDrawElement` function.

my program compiles and runs fine until it gets to glDrawElements then crashes.. which is rather annoying right.

so I was trying to figure out why and I found out its std::vector::size member not returning the correct amount of faces in the unsigned interger vector eg, "`vector<unsigned int>faces;` "

so when I use `cout << faces.size() << endl;`

*I got 68 elements????*

instead of `24` as you can see here in this `.obj file:`

```
# Blender v2.61 (sub 0) OBJ File: ''
# www.blender.org
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
s off
f 1 2 3 4
f 5 8 7 6
f 1 5 6 2
f 2 6 7 3     <--- 24 Faces not 68?
f 3 7 8 4
f 5 1 4 8

```

I'm using a parser I created to get the `faces/vertexes` in my `.obj file:`

```
  char modelbuffer [20000];
  int MAX_BUFF = 20000;
  unsigned int face[3];

   FILE * pfile;

   pfile = fopen(szFileName,  "rw");

   while(fgets(modelbuffer,  MAX_BUFF, pfile) != NULL)
   {
   if('v')
      {
        Point p;

        sscanf(modelbuffer, "v %f %f %f",  &p.x, &p.y, &p.z);

        points.push_back(p);

        cout << " p.x = " << p.x << " p.y = " << p.y << " p.z = " << p.x << endl;
      }

    if('f')
      {

      sscanf(modelbuffer, "f %d %d %d %d", &face[0], &face[1], &face[2],  &face[3]);

         cout << "face[0] = " << face[0] << " face[1] = " << face[1] << " face[2] = " << face[2] << " face[3] = " << face[3] << "\n";

          faces.push_back(face[0] - 1);
          faces.push_back(face[1] - 1);
          faces.push_back(face[2] - 1);
          faces.push_back(face[3] - 1);
          cout << face[0] - 1 << face[1] - 1 << face[2] - 1 << face[3] - 1 << endl;
      }
   }

```

using this struct to store the x,y,z positions also this vector was used with Point:

```
vector<Point>points;

struct Point
{

float x,  y, z;

};

```

If someone could tell me why its not working and how to fix it that would be awesome I also provide a pastebin to the full source code if you want a closer look.

```
http://pastebin.com/gznYLVw7

```

# Answer
I think your error is in the parser. The code after the lines if('v') and if('f') always enter those branches (you're basically saying if(true) two times). So your code basically pushes something back into the vector every time the loop executes (I think this is basically once for every line in your file? I'm bad with C functions).

I think you mean to say something like

```
if(modelbuffer[currentindex] == 'v')

```

etc.

As a bonus, since you're using vector I'm strongly assuming that you have access to a C++ compiler. Please use std::ifstream and getline. Thanks :-)
> 1 votes

---
Tags: c++, vector, obj
---


# Question
Title: Displaying a grid based map using C++ and sdl
I am trying to create a roguelike game using c++ and SDL. However, I am having trouble getting it to display the map, which is represented by a 2d array of a tile class.

Currently, my code is this:

```
for (int y = 0; y!=MAPHEIGHT; y++)
{
    for (int x = 0; x!=MAPWIDTH 1; x++)
    {
        apply_surface( x * TILEWIDTH, y * TILEHEIGHT, mymap[x][y].image, screen );
    }
}

```

However, running this code causes it to both dither for a while before opening the SDL window, and (usually) tell me there is an access violation. How can I display my map?

# Answer
Make sure `mymap` is really a 2-dimensions array of size `MAPWIDTH * MAPHEIGHT`. E.g. if that's a plain old array of `SDL_Surface` pointers, its declaration should be as follows:

```
SDL_Surface* mymap[MAPWIDTH][MAPHEIGHT];

```

Then all the images stored in this array have to be loaded in memory **before** you call this code. That could be a simple loop, assuming you use SDL\_image:

```
for (int x=0; x<MAPWIDTH; ++x)
{
    for (int y=0; y<MAPHEIGHT; ++y)
    {
        mymap[x][y] = IMG_Load( some_function_that_gives_an_image_path(x, y) );
        assert(mymap[x][y]); // to spot if loading fails
    }
}

```

It's very likely that you'll want to share images between different tiles, so make sure you don't mess up and that every pointer in `mymap`points to something real. A debugger might help spotting issues.

Last thing, if you're using some kind of asynchronous loading, you'll have to wait for your images to load before you start rendering them.
> 1 votes

---
Tags: c++, sdl, grid, roguelikes
---


# Question
Title: Adding cards to a vector for computer card game
I am writing a Card game that has a deck size of 30 cards, where each card has to be a unique object, stored in a vector.

Right now, my plan is to add them to a vector one at a time, with four separate (depending on what deck type you choose) sets of thirty .push\_back functions. (ie. 120 push\_back calls, divided into 4 blocks, one for each collection.)

Assuming the collections of cards are not up for customization, is there a quicker or simpler way of doing this, that doesn't involve typing out 120 separate push\_back calls?

# Answer
> 4 votes
Without knowing more about your specific sets of cards, my only suggestion would be to write some loops for the specific types of cards.

For example, with a standard 52 card deck, you have 14 faces and 4 suites. If you represent your suites as a simple enum and faces as another enum, with the card objects saved in the vector as a simple struct combining the two, you can have something short and sweet. Given the following explanatory definitions:

```
// definitions for our code
enum Face { ACE, TWO, THREE, /* etc */, FACE_COUNT };
enum Suite { DIAMOND, HEART, CLUB, SPADE, SUITE_COUNT };

struct Card {
  Card(Face face, Suite suite) : face(face), suite(suite) {}

  Face face;
  Suite suite;
};

```

You can use the following simple function to build the deck:

```
// code to build a deck
void build_deck(std::vector<Card>& cards)
{
  for (int face = 0; face != FACE_COUNT; ++face)
    for (int suite = 0; suite != SUITE_COUNT; ++suite)
      cards.push_back(Card(Face(face), Suite(suite)));
}

```

You said you have a 30 card deck, but didn't specify any other details. If there's some kind of way to break down the cards into sets of distinct attributes, however, you should be able to put together some kind of similar loops.

I might also suggest going for a data-driven approach if the cards aren't easily generated automatically. It at least would make it easy to update or change the lists without needing to edit a bunch of redundant code and recompile. Just generate a list for the card names, write one function that can take a name and push back the appropriate object into the vector, and then each arrangement of deck can just read from a different file.

---
Tags: c++, game-mechanics
---


# Question
Title: Optimizing gaussian blur with linear filtering
There's a few (here, and here) gaussian blur tutorials out there suggesting that you can essentially cut the number of texture lookups in a gaussian blur shader in half by exploiting the GPU's hardware linear filtering.

Essentially turning this:

Into this:

It sounds good in theory, but after attempting to implement this, I've come to the conclusion that it can't be done correctly, and I'd like someone to prove me wrong :)

My beef lies with the weights. Take the far left 2 texels in the first image. Their overall contribution to the shader equals:

```
t1 * w1 + t2 * w2

```

In the image, their weights 1 and 4, respectively. Now let us assign abitrary color values to the texels... 10 and 20. This gives their overall contribution, according to the formula, of 90. Great.

Now let us try to work this out with linear filtering.

What we want is essentially a new sampling location and a new weight, such that the value sampled at this new location, multiplied by the new weight, equals our original formula.

```
((t1 - t2 * new_offset) + t2) * w3 = t1 * w1 + t2 * w2

```

Let's make it easy and choose a sampling location halfway between texels 1 and 2, so that the value sampled is 15 (((10 - 20) * .5) + 20). So the new weight MUST be 6, so that 15 * 6 = 90. Ok great.

Now what happens when you change the values...instead of 10 and 20, you use 10 and 30. With the first way, you get 10 * 1 + 30 * 4 = **130**. But with the linear sampling way, you get a linear sampled value of 20 ((10 + 30) / 2), times the weight of 6...**120!** It doesn't match!

Can anyone shed any light on why the linear sampling optimization is thought to work, and what I'm misunderstanding about it? I would be more than thrilled to be wrong about this :)

# Answer
> 8 votes
I don't know why are you choosing 0.5 as offset. The formula is (I'll use o instead of new\_offset):

```
t1*w1 + t2*w2 = ( (t1-t2)*o + t2 )*w3
t1*w1 + t2*w2 = t1*o*w3 - t2*o*w3 + t2*w3
t1*w1 + t2*w2 = t1*(o*w3) + t2*(w3 - o*w3)

```

Form that we see this:

```
w1 = o*w3
w2 = w3 - o*w3

```

From first equation lets get o:

```
o = w1/w3

```

And put it into second equation:

```
w2 = w3 - (w1/w3)*w3 = w3 - w1

```

And you can calculate w3:

```
w3 = w2 + w1 (in your case w3 = 4+1 = 5)

```

And now you can get offset:

```
o = w1/w3 = w1/(w2+w1) (in your case o = 1/5)

```

Let's try with t1=10 and t2=20:

```
t1*w1 + t2*w2 = 10*1 + 20*4 = 90
( (t1-t2)*o + t2 )*w3 = (-10*0.2 + 20)*5 = (-2 + 20)*5 = 90

```

Great! Let's try with t1=10 and t2=30:

```
t1*w1 + t2*w2 = 10*1 + 30*4 = 130
( (t1-t2)*o + t2 )*w3 = (-20*0.2 + 30)*5 = (-4 + 30)*5 = 130

```

Excellent. It works. Right?

# Answer
> 2 votes
The weight of the new sample *must* be the sum of the weights of the two samples that you're replacing. The weights are not determined in isolation: if you vary from the correct value, these two texels will either contribute more or less than they should to the total blur. In other words:

```
w3 = w1 + w2

```

The only degree of freedom that you have is the actual offset of the new sample, which you cannot simply pick arbitrarily. If your equation looks like this:

```
(t1 * offset + t2 * (1 - offset)) * w3 = t1 * w1 + t2 * w2

```

(i.e. an offset of 1 is centered on t1 and an offset of 0 is centered on t2; I think this is the opposite of what you're using), then your offset works out to be this:

```
offset = (w1 + w2) / w1

```

---
Tags: opengl, shaders, glsl, blur
---


# Question
Title: How to get the path of a file after publishing my game
I made a "game" for a college project that reads data from .txt file at startup and draws some models according to the data in that file. This is the code I use

```
using (StreamReader sr = new StreamReader(@"C:\Users\User\Desktop\Linije.txt"))
                {
                    String linija;
                    while ((linija = sr.ReadLine()) != null)
                    {
                        red = linija.Split(',');
                        model = red[0];
                        x = red[1];
                        y = red[2];
                        z = red[3];
                        elementi.Add(Convert.ToInt32(model));
                        podatci.Add(new Vector3(Convert.ToSingle(x),Convert.ToSingle(y),Convert.ToSingle(z)));
                    }
                }

```

As you see, this code fills some variables that are then used to define the model that will be drawn and the coordinates where it will be drawn. The problem that I'm having is that I don't know how to distribute that file to other computers (obviously on another computer it would have another path)? Do you have some advices on how to do this? P.S I tried to put it in the Content and set the Build Action on None, and I can see the file in the content directory, but when I change it, nothing happens (the models don't change as they should)

# Answer
> 0 votes
if you just want to put the file in the same directory as the exe, you can simply write:

```
using (StreamReader sr = new StreamReader("Linije.txt"))

```

---
Tags: xna-4.0
---


# Question
Title: How would I achieve diablo like 2D isometric projection?
I am in the process of coming up with an idea for a game, and I would like it to be isometric like Diablo. The problem is I have no idea how it achieves the effect of height like in the following screenshot (on the columns):

Whatever the case, I'm sure it is going to be harder to achieve then creating a traditional isometric game, but any ideas regarding the topic would be greatly appreciated.

# Answer
You can try a traditional height map, which vertical dimension has more than 1 level (Diablo I uses 2 levels iirc). The objects in first level count as obstacles for player's character (and in all other cases when physics is required), but the second one contains "transparent" objects, which are used only to emulate high wals etc.
> 1 votes

# Answer
One method is to split up the graphics so they have square bases, then sort depth based on their vertical position. Lower to the screen has a higher draw depth.

For multiple levels the higher levels have higher depth than any of the previous. You also translate them upward by I think `(height-of-the-tile - (width-of-the-tile / 2))` pixels.

If you're generating the sprites with a 3d modeler, you can also save their depth values. Then just add their position offset to the depth values in your shader. The nice thing about this is that it's per-pixel instead of per-sprite.
> 0 votes

---
Tags: xna, c#, isometric, projection
---


# Question
Title: Search app store for similar games on pc
I want to search the app store for similar games so I can see how much competition there will be for any apps I am thinking of designing.

Knowing how many clones/similar games there are plus there prices and success rate would go a long way in deciding which ideas to take forward.

Is there anyway to do this easily on a pc (I do not have an iPhone)

# Answer
> 1 votes
You can run iTunes and thus browse the store on either Windows or Mac. And actually I think you can browse the store through the iTunes website (not 100% sure of that since I've never tried).

To actually play the games you need an iOS device (iPhone, iPod Touch, or iPad).

---
Tags: competition, appstore
---


# Question
Title: How to make sure that a Point A moving in the direction V reaches at Point B?
Let say I have,

Point A(X1,Y1) moving in the direction V(W, H). I need to make sure that it reaches B(X2,Y2). I think I need to subtract some value in Point A(X1, X2). But not know what? I also sure that the direction is correct.

# Answer
You can get the displacement from `A` to `B` by subtraction. I'm not sure if your direction `V` is normalized or not, but if you normalize the direction and normalize the displacement vector, `A` will reach `B` if those vectors are equal.

```
Vector2 displacement = B - A;
displacement.Normalize();
V.Normalize();

if(displacement == V)
{
    // A will reach B if you get in here
}

```

Note: I'm rusty on my XNA so the specific functions you may need to call may be a little off, but the concept should work.

**Post-clarification Edit:**

```
V.Normalize();
float distance = 10.0f;  //Change this value to whatever distance you want
Point A = B - V * distance;

```
> 1 votes

# Answer
If I understand correctly, you want a point close to `A` such that moving from that point in the direction `v` will eventually reach `B`.

The point closest to `A` is the projection of `A` on the line `(B,v)`. It is computed as follows:

```
newA = B - dot(B - A, V) / dot(V, V) * V;

```
> 1 votes

---
Tags: xna, c++, mathematics, algorithm, vector
---


# Question
Title: How to make a ball fall faster on a ramp?
So, I'm making a ball game. Where you pick up the ball, drop it on a ramp, and it flies off in to blocks. The only problem right now is it falls at a normal speed, then lightly falls off, not nearly fast enough to get over the wall and hit the blocks.

Is there any way to make the ball go faster down the ramp? Maybe even make it go faster depending on what height you dropped it from (e.g. if you hold it way above the ramp, and drop it, it will drop faster than if you dropped it right above the ramp.)

# Answer
> 0 votes
One possibilty would be to use AddForce in the direction of the current velocity of the rigidbody. You could measure the height of the dropping point and use this number to calculate the added force.
*Pseudocode*:

```
var r:Rigidbody = ball.rigidbody;
var power:float = 3.0;
r.AddForce(r.velocity.normalized * power);

```

See AddForce, and Force.Mode.

# Answer
> 2 votes
It sounds like you want to increase the mass of the ball. Play around with the parameters of the *Rigidbody-component* in Unity. Increase the mass, set "drag" to zero etc. Maybe you'll also have to tweak your level a bit for it to work (if your ramp is really steep, then there's probably no way the ball will jump over that.. or you could cheat and apply a force whenever the ball hits the bottom of the ramp).

# Answer
> 0 votes
Increase velocity of the ball in y direction and increase restitution of the wall and ball

---
Tags: c#, physics, unity
---


# Question
Title: How to update the monsters in my MMO server using Node.js and Socket.IO
Currently I am creating an MMO using Node.js and Socket.IO.

The node server needs to handle connections for players, and also use a loop to update all monsters positions in my game and let them attack players in range.

For the loop I read that you can use process.nextTick or use a child process, which option would be the best choice? What are the advantages/disadvantages of using each?

Also, how many times per second should I run this loop for the monsters?

# Answer
> 3 votes
I am assuming here that you're keeping your world data in memory (with occasional load/save).

As it's in memory, you'll need to do the work in the same process, or you won't be able to have a consistent view of the data. So you'll want to set up a timed task on the server to handle MOBs etc.

You don't use process.nextTick, just set a timer using one of the (several) methods to do this in Node.

Because Node is a non-preemptive multitasking environment, you don't need to worry about consistency between threads, the "process monsters" function won't get interrupted unless it sleeps (e.g. doing network IO or something).

How often should you run the ticks? As infrequently as possible. I would suggest starting at 1 tick per second and going from there (the client can still show animations, etc, as much as it wants in between).

---
Tags: mmo, node.js
---


title: Visually coding rpg dialog trees

text:
# Question
Title: Visually coding rpg dialog trees
I am currently using XML to create my dialog trees in my rpg, but doing this by hand for hundreds of different discussions can get very tedious very fast. I was wondering if there is any way I can implement a flow chart/udk kismet like system of visually coding these diolog trees. I still want the end result to be the XML because I already wrote the parsing and other logic around the XML.

EDIT: to give an idea of what I am looking for, here is an example. This was shown to me when I asked this on reddit and it is basically what I am looking for but it is limiting . Really what I am looking for is any dialog software that is already in use for games or software that is graph/flowchart like and can be modified to suit my needs.

# Answer
> 6 votes
I found these

You could also use XML Notepad, which makes editing XML a little more bearable. You could also use Freemind/Freeplane and other mindmap software that would generate XML. You just need to set up some semantics for how to structure data in each node and write your parser accordingly.

# Answer
> -1 votes
Maybe Workflowy could work, with each indentation representing a branch point.

---
Tags: software-engineering, rpg
---


title: Call of Duty 4 Modern Warfare modding?

text:
# Question
Title: Call of Duty 4 Modern Warfare modding?
I'm seeing a lot of Modern Warfare (the first one) mods out there, and I've come across at least one post that says that Activision released official modding tools for CoD4, but I can't seem to find them, or any reference to them on official websites.

Have official tools been released? Or are all these modding tools the result of reverse engineering and clever hacking, ala Diablo 2? I'm interested in getting into modding myself, I used to do Duke3D maps with the Build engine back in the day, even had a book on it, and it'd be great if I could do

# Answer
> 2 votes
They have been released, find them here.

Also, you may want to up your Google skills.

And, here is a tutorial to get you started.

---
Tags: tools
---


title: Quad Rendering Issue

text:
# Question
Title: Quad Rendering Issue
I am fairly new to using Quads, so I'm not sure how I can properly describe this issue in all honesty or to even hazard a guess as to why it's happening, so I have a screenshot to illustrate.

So the white lines are actually Quads, the Red lines are just rectangles. So if you can see the issue, for some reason every "now & again" I will get this issue were I get this somewhat looking "dotted line" which will sometimes be a full end-to-end line.

I'm not too sure what's causing this issue, I have a feeling it has something to-do with the way I'm drawing the quads, I don't think it's an incorrect vertices purely because the because of the thickness of the line, this leads me to believe it's the rendering:

```
effect.CurrentTechnique.Passes[0].Apply();
device.DrawUserPrimitives<VertexPositionColorTexture>(PrimitiveType.TriangleStrip, vertices, 0, totalNumberOfQuads);

```

This is the order I'm adding the vertices:

1. Top Left Segment Corner
2. Top Right Segment Corner
3. Bottom Left Segment Corner
4. Bottom Right Segment Corner

So after getting the vertices in the correct order, things are now even stranger, as this is an image of the current output:

Here's my Current Code, including the rendering: http://pastebin.com/yK5yBZy0

# Answer
> 3 votes
Keep in mind that the order you insert your vertices into your array matters too. Additionally, it looks like you're drawing a `PrimitiveType.TriangleStrip`, not quads. It looks like XNA doesn't have a primitive type for quads. You can index them yourself though, as seen in this tutorial..

If you're using triangles (or quads) to draw lines like your image shows, you can have the issue you're experiencing by essentially having a line that has zero height, or close to zero. I imagine this could happen if you're arranging your vertices for quads but then drawing them as triangle strips. So either use the tutorial I mentioned above, or use triangle strips like in this tutorial.

**EDIT**

The vertices for quads (and triangles) should be defined in clockwise order. Your order is wrong for quads.

You should swap the last two with each other OR the first two with each other, if you want clockwise order. Ensure that you also look at the tutorial I linked. It will describe the proper way to draw the quads.

---
Tags: xna
---


title: Region selection in OpenGL

text:
# Question
Title: Region selection in OpenGL
If I have a mesh of triangles and going to make a selection on it using a region (and *not* rectangle using `Glu.gluPickMatrix(...);`), how can I implement it?

# Answer
> 1 votes
Here's how I would do it: Using the dimensions of the box you've selected on the screen, define a new 'camera' (view and projection matrices) which defines that region of the screen and the frustum that extrudes out from that region into world space.

From there, you can go through your primitives and emulate the rasterization pipeline by converting vertex positions into Normalized Device Coordinates. Anything that falls in the range \[-1,1\] in each of the axes is a primitive which is being selected.

Note that my explanation is really suited for finding selected vertices, and some additional logic would have to be added to determine which triangles were selected.

---
Tags: opengl, selection
---


# Question
Title: How will the velocities of two moving objects change once they collide?
I'm making a small game where things can fly around and collide. Things like boxes and so on. For each object, I have an array of all forces acting upon it, I have it's mass, it's position and it's velocity in both directions (a 2D vector). I know how to detect collision between them, but I just don't know how to react.

I used to calculate their orientation towards each other, it they were on top one another, I would just negate their y speed (`v.y = -v.y`), and if they were next to each other on the x axis I would negate their x speed (`v.x = -v.x`).

Now, this isn't very realistic, so, how do I do it? All objects are rectangles represented by `[x, y, w, h]` vectors.

Objects can't rotate.

# Answer
A quick Google for 'Physics Collisions' yielded the ever-fabulous wikipedia as a starting point.

I'd start with perfectly elastic collisions before moving on to adding an elasticity constant to your objects.
> 3 votes

# Answer
Chris Hecker has written a lot about the subject of rigid-body dynamics in games. The material can be found here. I think these should be good reference material because the first few articles deal with 2D and only in the last one does he extend everything to 3D.

Also, another note: you might want to consider using 4th Order Runge-Kutta integration rather than Explicit Euler as Hecker does in the articles. The 4th order method gives better long-term accurate results.
> 2 votes

# Answer
if you don't let them rotate, that's exactly how you have to implement it. but if rectangles are able to rotate, it's pretty hard to solve equations needed for simulation. though you still are able to solve it yourself, it's much more better if you try using 2D physic engines like Box2D.
> 0 votes

---
Tags: collision-detection, physics
---


# Question
Title: How do you decide upon the price for a game?
I hope this is the right board for the question.

I have this idea for a game, programming Skills with C++ and a licensed Engine. I already made a prototype of the game as proof of concept and a few friends liked it so far.

I don't want to spoil it all, but it is a 2D Robotron Style Precision Shooter in an arena which is set in space.

All you do is beating waves of enemies and when you leveled up, you select a perk to enhance your ship. Examples are making weapons stronger, faster, making the ship more agile, different Weapons as Smartbombs, Mines etc.

Having different maps with this kind of game is quite difficult, since space does not have obstacles. All you can do is make different backgrounds and maybe asteroids etc. Another type of content could be to allow the user to gather some virtual money to unlock goodies that are available at wave 1.

So far for my idea. Now, would this alone already justify asking 5$ for a game? When I compare it for example to puppygames game "Titan Attacks", I say yes, since they do not have more features. On their website the game is 7$, on Steam 4$. Their Ultratron is also 7$, which is also a classic robotron style game. But it does not yield any special features imho ( it is fun nontheless :D ), but has a very adorable artstyle.

Nation Red, which is also an inspiring source for me (Robtron Style 3D Zombie Shooter, awesome game btw), costs 10$ on Steam but also has coop, local and online.

So, how do you estimate the price of your game that you just made so people don't feel ripped off and you still make profit after getting back the investment of licenses?

# Answer
> 10 votes
Pricing is platform dependant. When your competetors are $0.99, you need to have a very superior game to charge $4.99 on an iPhone. But on the other hand, if you price at $4.99 on Steam you are sending a signal to potential buyers about the quality of the game you are offering... a signal that your game is very short/low on content or quality. Different channels have different pricing expectations.

In general you should price your game at a spot that you feel is fair, but offer a variety of promotions and offers to increase visibility of the game. Valve has discussed this on their blog, that developers always make more money when they sell their game at 75% off than they do at full price, because promotions get people interested and raise visibility. But that's not the same as PRICING your game permanently at the 75% off price point... people love deals, and when your game is priced at the lower point it's not a deal, it's just a 'cheap' game.

So find similar games to yours in the channel where you are selling and match their prices, but also offer frequent sales and promotions as this increases visibility and allows you to reach price points that raise your potential audience as well as increasing word-of-mouth about the game.

Finally, here is an interesting point from Gabe about game pricing: *Now we did something where we decided to look at price elasticity. **Without making announcements, we varied the price** of one of our products. We have Steam so we can watch user behavior in real time. That gives us a useful tool for making experiments which you can’t really do through a lot of other distribution mechanisms. What we saw was that pricing was perfectly elastic. In other words, our **gross revenue would remain constant**. We thought, hooray, we understand this really well. There’s no way to use price to increase or decrease the size of your business.*

So take what anyone says here with a grain of salt, because it's quite possible we're completely wrong. Your price point may really do almost nothing to your revenue, good or bad. Real world experiments trump any quantity of theory.

# Answer
> 7 votes
I'd be a little careful comparing to Steam, unless you plan on publishing there as well. Games on Steam have a lot of visibility, and that might skew pricing in some way.

Steam maintains market data for games they've sold in the past, and work with game publishers to set the pricing. From their FAQ:

> Who sets the price for my game on Steam?
>
> Pricing is very title specific, and we've got a lot of data and experience to help you decide on what the best price is for your title. We'll work with you to figure out pricing.

I really don't know a good answer for you though!

# Answer
> 1 votes
Don't. Go to a pay-your-own-price model. Yes, a lot of people will buy it for the minimum allowed price, but you'll significantly increase the visibility of your game (more buyers, more "just interested" people who'll check it for a low price and maybe buy again later, the chance that this is what will give you a spot on gaming news), and that's what will give you the greater gains in the long run.

This has been done by increasing amounts of developers in the last couple of years, and mostly with resounding success.

---
Tags: sales, pricing
---


title: My bullet fails to move as it should

text:
# Question
Title: My bullet fails to move as it should
I'm working on a small game, and as my title states, the bullet is not moving properly. When I click, it simply draws the bullet at the set position, and remains stationary. For some reason, the Update function of the bullet doesn't constantly run. So any help would be appreciated, thanks. Currently, I have two classes (not including the Game1.cs), which are: Bullet class and Humvee(player) class.

Here's the code for my Bullet class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Humvee
{
public class Bullet
{
    // Unique id assigned to each bullet
    int bullet_id;

    public bool bullet_active = false;

    // This declares the position of the bullet upon creation (is changed in constructor for debugging purposes)
    public Vector2 Position = new Vector2(400, 240);

    // This declares the direction of the bullet upon creation (not used for now)
    public Vector2 Direction = new Vector2(0, 0);

    // This declares the speed of the bullet upon creation (not used for now)
    public Vector2 Speed = new Vector2(0, 0);

    // Stores the touch location for each bullet
    public Vector2 Destination = new Vector2(0, 0);

    public Bullet()
    {
    }

    // Constructor that assigns each bullet a unique id, starting position, and a boolean to know whether it's active or not
    public Bullet(int id, Vector2 destination)
    {
        bullet_id = id;
        Position.X = 100;
        Position.Y = 240;
        Destination = destination;
    }

    public void Update(GameTime gameTime, Vector2 touch_location, Vector2 touch_direction)
    {
            // Finds the difference between the location of the touch and the bullet
            Vector2 speed_difference = new Vector2(0,0);
            speed_difference.X = Math.Abs(Destination.X - Position.X);
            speed_difference.Y = Math.Abs(Destination.Y - Position.Y);

            //Update the Sprite and change it's position based on the passed in speed, direction and elapsed time.
            Position += touch_direction * speed_difference * (float)gameTime.ElapsedGameTime.TotalSeconds;

    }

    //Draw the sprite to the screen
    public void Draw(SpriteBatch theSpriteBatch, Texture2D Bullet_Texture)
    {
        theSpriteBatch.Draw(Bullet_Texture, Position, Color.White);
    }
}
}

```

Here's the Humvee class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Humvee
{
class Humvee
{
    // Position of the player
    public Vector2 Position = new Vector2(400,240);

    // Will be used to assign a unique id to each bullet
    public int b_id = 1;

    Bullet testbullet = new Bullet();

    // It creates a new bullet and calls the Update function from Bullet class which causes the bullet to 'shoot'
    public void ShootBullet(GameTime gameTime, Vector2 touch_location, Vector2 touch_direction)
    {
        testbullet = new Bullet(1, touch_location);
        testbullet.bullet_active = true;
        testbullet.Update(gameTime, testbullet.Destination, touch_direction);

    }

    public void Update(GameTime gameTime, Vector2 touch_location, Vector2 touch_direction)
    {
        ShootBullet(gameTime, touch_location, touch_direction);
    }

    //Draw the sprite to the screen
    public void Draw(SpriteBatch theSpriteBatch, Texture2D humveesprite, Texture2D bulletsprite)
    {
        testbullet.Draw(theSpriteBatch, bulletsprite);
        theSpriteBatch.Draw(humveesprite, new Vector2(400, 240), Color.White);

    }

}
}

```

And here's part of the Game1 class code:

```
Humvee testhumvee;

    // Stores the sprites of the objects
    Texture2D background;
    Texture2D bullet;
    Texture2D player;

    Vector2 touch_direction; // Stores the direction of the tap
    Vector2 touch_location; // Stores the location of the tap

    bool shoot_isactive = false;

protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        #region Touch code
        //Touch
        T_Collec = TouchPanel.GetState();
        foreach (TouchLocation tl in T_Collec)
        {
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.Tap)
                {
                    if (tl.Position.X > testhumvee.Position.X && tl.Position.Y > testhumvee.Position.Y)
                    {
                        touch_direction = new Vector2(1, 1);

                    }
                    else if (tl.Position.X < testhumvee.Position.X && tl.Position.Y > testhumvee.Position.Y)
                    {
                        touch_direction = new Vector2(-1, 1);
                    }
                    else if (tl.Position.X < testhumvee.Position.X && tl.Position.Y < testhumvee.Position.Y)
                    {
                        touch_direction = new Vector2(-1, -1);
                    }
                    else if (tl.Position.X > testhumvee.Position.X && tl.Position.Y < testhumvee.Position.Y)
                    {
                        touch_direction = new Vector2(1, -1);
                    }

                    touch_location = tl.Position;
                    shoot_isactive = true;
                 }

            }
        #endregion

            // TODO: Add your update logic here
            if (shoot_isactive == true)
            {
                testhumvee.Update(gameTime, touch_location, touch_direction);
            }
            base.Update(gameTime);
        }
    }

```

# Answer
There are a couple of issues with the layout that could be causing you confusion.

First up is that your Update() method of the Humvee seems to be a rather bad name as its not Updating so much as Shooting a bullet.

Second up is that you are never calling Update on the bullet object anywhere. I can gather that you may have wanted to do it at the start of the Bullet's Draw() method so that it will calculate its new position and then draw itself there. (While not important right now you may want to consider doing the Update elsewhere as you will generally only want to do Draw() specific code when drawing, but that is another matter all together).

Since you are seeing things I am going to assume that at least draw is being done and so my above comment would suffice to get the bullet moving as long as you also adhere to @Gajet's comments. You have seen

```
Position += firedDirection + velocity + elapsedTime;

```

as the way to update bullets, but you need to know that firedDirection is a vector and velocity and elapsedTime should be real values (floats or doubles, whatever you are using). So if you get very unexpected results that would be the next area to look into.
> 1 votes

# Answer
What you want to do is to inherit your `Humvee` and `Bullet` classes from `DrawableGameComponent`, then add them to the `Game.Components` list as you create them.

This way Games base implementation of Update and Draw will call these methods for you, to fire a bullet you would call `Humvee.ShootBullet` directly and Humvee.Update method should no longer call ShootBullet (or you wind up firing a bullet every frame).

Add the following line to `Humvee.ShootBullet`:

```
Game.Components.Add(testbullet);

```

Since this allows you to fire any number of bullets you need to remove them from the Components collection at some point, like when they hit their target or go out of the game area/screen.
> 1 votes

# Answer
Your architecture and you code are flawed.

You forget to update existing bullets. The bullet is updated only through your humvee::update. And each time you update your humvee you shoot a new one.

When you stop updating your humvee you stop updating the last bullet...

You need to update all bullets from somewhere else.
> 0 votes

---
Tags: xna
---


# Question
Title: How do you make game objects (enemies, NPCs) move in interesting, non-linear ways? (e.g. shoot 'em up enemies)
I'm using a series of easing equations to make menus and transitions a little more interesting in my first game. That got me thinking about how game objects (enemies, NPCs, spaceships, whatever) are 'scripted' to move along complex paths. I'm no maths guy, but I've read that paths can be plotted using Bezier curves (define 2+ control points, interpolate to get position values using start, change and duration values). However I'm not exactly sure how to best go about this (in a structured way that works for a variety of different motions).

I already have a bunch of tweening functions, but these are relatively simple linear, quadratic and cubic curves.

An example - say I wanted enemies to appear at a certain point, then spin in an archimedes spiral until they were off-screen. How would this be best accomplished, and indeed, made generic enough so that another enemy of the same type could move along a sin wave-esque path instead?

# Answer
> 3 votes
Suppose the curve you have represents a path of motion (such as fly forward, arc left, arc right). A simple technique in a shoot'em up is to build from these motions, and chain a list of motions into a maneuver. Then chain maneuvers together. Any ship can perform the maneuver. This way you can reuse a library of motions and maneuvers with any combination of ships.

For classic shoot'em up formations of ship, you could chain the ships together so that one ship appears to be following the next, when it spawns at the same position a little later.

For example, look at 'motion', 'maneuver', 'formation' in this C++ code: http://finegamedesign.com/euphonics/glyrus\_behavior.cpp

My code was from Euphonics, a shoot'em up with aliens that changed directions on musical cues. This was a student project with other programmers at USC. Windows demo of these motions is here: http://finegamedesign.com/euphonics

# Answer
> 0 votes
This may not be the best idea, but you could probably define the direction and the speed (if it's not constant) in two different splines. Splines are extremely versatile and their value in a single point is extremely easy to calculate.

The downside is that you may have to write a separate tool that allows you to design a path and creates the spline for you by interpolation.

---
Tags: xna, c#, animation, scripting
---


# Question
Title: Help with a Fast 2D Grid-Based world rendering technique
First I'm going to give you my current situation and explain what I'm attempting. I will then pose my question below. I will attempt to include a "TL;DR" for those of you who prefer things to be concise.

### OVERVIEW OF CURRENT SETUP:

> The current representation of my game world is one where ' Pieces ' of a larger world are represented by three layers of IDs as follows.

```
//This is being done in C++
struct WorldPiece {
   ivec2 pieceLocation;         //Where ivec2 is a vector containing ints
   short backLayer[PIECE_SIZE]; //Where PIECE_SIZE is the size of the grid this piece contains, ie. for a 32x32 grid, this is 1024
   short middleLayer[PIECE_SIZE];
   short frontLayer[PIECE_SIZE];
};

```

The world as a whole is then composed of these pieces, which are loaded (and cached as needed) as the player traverses from piece to piece.

I currently have the data side of this all working. I may change the active data set and move around the camera (zoom in and out as well) and watch it all function.
I have also written a tool to support the loading and saving of pieces, and the painting of IDs across the world.

### I HAVE THIS DATA:

> Each ID within a piece maps to a texture that will be used when that ' cell ' of the piece must be rendered.

### QUESTION:

> How might I go about rendering each piece in such a way as to do this in as few passes as possible? I could render each cell at a time, but that would be slow. I could generate a list of vertices and indices and create massive VBOs, or sets of quads. Or perhaps there is a better way? I would prefer to keep the data separate from the rendering and to keep the size of the data as small as possible (so as to have a small as possible load time while the game is running). If possible, I would like this to be fast enough to render large swaths of tiles, (for example a 3x3 area of 1024 tiles apiece, or more). Since zooming in and out is possible it would be nice to provide this functionality to the player while still maintaining the detail of rendering the world.

If there would be a better setup for the world data to accommodate these requirements, I'm open to suggestions.

### SIDE NOTES:

> Please do not bring collision/physics, or other game-map-related things into this. I have that worked out and it will not be a bottleneck. I am merely concerned with a best approach to a rendering pipeline where speed is the top concern. Please do not suggest API X or ENGINE Y. I have looked around quite thoroughly and nothing available would properly provide what I need or integrate with my current codebase. I will be using a texture atlas.

tl;dr version- I have a grid based world that streams pieces in as needed, I would like suggestions on a fast way to render these pieces and nothing I have found anywhere has a suitable solution for my current situation.

# Answer
> 1 votes
For a 2D grid game, you can keep things pretty low key and still get very good performance.

There are a few ways you can go about things.

1) Create a VBO and index buffer for each world piece. When you draw, draw all visible world pieces. Finding which ones are in your view rectangle should be easy, and if you have a lot loaded at once, using a quad-tree to organize the world pieces will help.

2) Create a single streaming VBO, and fill it with cells each frame. Find the world pieces in the view frustum, then clip their cells to the visible region, and copy the translated position and texture coordinates to the VBO and index buffer for rendering. This will probably be slower than option 1, but gives you some added flexibility.

3) Same as 2, but use different VBOs and index buffers for different textures and shaders. You should minimize the number of each (ideally one shader and one texture), but if you need to use different materials to pull off the look you're going for, this is the way to go.

4) Do the same as option 2 or 3, but use GPU instancing. This will let you get a bit closer to the efficiency of option 1 while retaining the added flexibility.

Of the four, option 1 is both the simplest and (in general) most efficient.

Also keep in mind that the size of your WorldPiece grids can have a big effect. You don't want them to be overly large. In a game I'm working on right now we have a similar setup to you. We found that using chunks that are approximately 1/2 the size of the visible screen worked fairly well. (32x32 tiles, in our case.)

When rendering, atlas your textures. As I mentioned above, you want as few draw calls as possible. That means as few state changes. A single WorldPiece should ideally require only a single texture that has all the tile data on it, and a single shader. Even if you strictly need more than one texture or shader, you want to keep the number small. If you have more than one, you want to use batch all the individual tiles that use the same texture and shader into a single draw call, so use option 2, 3, or 4.

---
Tags: c++, opengl, maps, grid, world-design
---


# Question
Title: Getting one rigidbody to follow another, but still react to stuff Unity3D/C#
Basically what I'm doing is having a ball you can pick up and drop on a ramp. When you pick up the first ball, the second ball follows close behind, and when you drop the first ball on to the ramp the second ball drops on to the ramp as well, rolling down and launching off. The second ball continues to follow the first through the air.

How could I go about getting the second ball to follow the first, while still keeping the rolling-gravity effect?

Thanks.

# Answer
> 4 votes
I'm not sure but maybe you can connect both balls with an spring. if you don't want those two to change their distance you can put a very high value for spring constant. although this way the second ball also will effect on the first ball movement.

# Answer
> 0 votes
As I understand it you want the second ball to follow in the same path as the first ball while you carry the ball around, and then after that be affected by physics.

In this case you want to store the positions of the first ball in a list/queue and simply set the second balls position to these coordinates (ignoring physic responses) at a set distance, or set time, behind it.

For instance:

```
var path = new List<Tuple<TimeSpan, Vector3>>();
path.Add(Tuple.Create(gameTime.TotalGameTime, ball1.Position));

```

Then using `Vector3.Lerp` to set the position of the second ball, either calculating so its a certain time behind, or add up the distance in the path and find the position that is a certain distance behind the first ball.

---
Tags: c#, unity, rigid-body-dynamics
---


title: Animating a jellyfish hardcoding?

text:
# Question
Title: Animating a jellyfish hardcoding?
I have drew a hemi-sphere by myself, and would like to do basic jellyfish animation by animating the vertices of the hemi-sphere. I tried a lot of experiments but it seems I'm doing it wrong. I need hints or idea on about doing it.

This is the code on how to draw a hemi-sphere. I don't know what values actually to play with to animate the sphere as a jellyfish.

```
for(float phi = 0.0; phi < 1.567; phi += factor) {

        glBegin(GL_QUAD_STRIP);

        for(float theta = 0.0; theta < 2*3.14 + factor; theta += factor)
        {
            x = rh * sin(phi) * cos(theta);
            z = rh * sin(phi) * sin(theta);
            y = -rh * cos(phi);

            gl::vertex(Vec3f(x, y, z));

            x = rh * sin(phi + factor) * cos(theta);
            z = rh * sin(phi + factor) * sin(theta);
            y = -rh * cos(phi + factor);

            gl::vertex(Vec3f(x, y, z));

        }
        glEnd();
    }

```

# Answer
> 2 votes
I see. Your update tells me that you are much further from results than I first thought. You're actually looking for an algorithm to define the movement of a jellyfish. That's very complex and is likely thesis level work.

In fact it is thesis level work. See Dave Rudolf's paper (PDF) on the subject. Additionally Marcin Ignac has done some work with the topic.

Perhaps there's some simpler method that I'm not thinking of, but if the linked sites are not suitable for your purposes I think you may be asking for too much. Good luck.

# Answer
> 2 votes
So what you want is a contraction and expansion of the sides in a peristaltic motion to make it look like it's pushing itself. I haven't tried this but the idea should work, it's similar to a cheap waving flag simulation. It is by no means a physical simulation.

First thing you need is a delta Time (dt) to govern how fast the animation will run, and this generates the wave. Second thing you will need is a scale value that you can tweak to make the animation look as good as it can.

What you want to do is modify all your xyz values by a wave based on the values of phi and dt, this will make it change from top to bottom of your hemisphere plus animate over time.

dt is expressed in seconds, a typical frame taking 0.033 to draw. phi ranges from 0 at the top of your hemisphere where you don't want any animation and gets bigger the lower it goes which will make the peristaltic wave larger at the bottom. Scale is needed to tune how big the wave is, a subjective measure of what looks good.

In this example note that x,y and z are all multiplied by the same value. Both sets of your xyz values in the original code would be modified like this each loop.

```
// setup
    dt = 0.033; // modify to make the wave longer or shorter periodicity
    scale = 1.0;  // modify to make the wave bigger or smaller
    modifier = -cos(dt) * phi * scale;;
// in the loop
    x = rh * sin(phi) * cos(theta);
    x *= modifier;
    z = rh * sin(phi) * sin(theta);
    z *= modifier;
    y = -rh * cos(phi);
    y *= modifier;

```

---
Tags: opengl, physics, animation, procedural-generation
---


# Question
Title: Controlling the snake in a snake game with the mouse
I am trying to implement a snake game in C# using the WPF forms. Well I know to implement the snake game, where the snake is controlled by the keyboard. But how would I do it, if I wanted to control the snake using a mouse rather than a keyboard?

# Answer
> 1 votes
On your gamefield element add a `MouseMove` event handler, in this handler add:

```
var pos = Mouse.GetPosition(e.MouseDevice.DirectlyOver);
worm.Target = new Vector(pos.X, pos.Y);

```

And in an appropriate spot in the worm class (such as an update method, or called from the Target/Position setters):

```
var delta = new Vector(Target.X - Position.X, Target.Y - Position.Y);
if (Math.Abs(delta.Y) > Math.Abs(delta.X))
{
    if (delta.Y < 0)
        this.Direction = Direction.Up;
    else
        this.Direction = Direction.Down;
}
else
{
    if (delta.X < 0)
        this.Direction = Direction.Left;
    else
        this.Direction = Direction.Right;
}

```

With this logic it would try to close in the longest orthogonal distance (x or y) first, and then go zigzag to the cursor when the distance is the same in both x and y, other options would be to use a line drawing algorithm to make it go more smoothly towards the cursor.

There is a few other things to consider as well, such as what do we do if the worm reaches the mouse, does it stop, or do we allow it to first pass the cursor and then double back thus hitting itself?

---
Tags: c#, game-design, mouse, wpf
---


title: Path finding with identical values

text:
# Question
Title: Path finding with identical values
I have been reading up about path finding and find it all very confusing, however this is probably the best I have found for a logical explanation:

Path

If the cost of two nodes has the same value, I'm not sure how the path would be worked out though. How would it be worked out?

# Answer
> 5 votes
If two paths have the same value then it doesn't matter which one you pick. There may be multiple paths with the same distance, but you're only concerned with a single one.

In that example diagram it uses `<` for the comparison, which means the earliest shortest path found will be chosen over latter ones.

---
Tags: javascript
---


# Question
Title: Best way to create a level editor in java
I am creating an iPhone game using cocos2d + box2d that needs a lot of levels. My friends and I are creating the game and most of them have no programming experience and end up with nothing to do. I want to make a level creator / editor java applet that can create a level file and then I can parse that file into a box2d level with objective-c

The only problem is that I have never done game programming with java so I'm not sure where to start. I want to create something like this level editor video and let the user add predefined shapes like circles and boxes.

I can do all the objective-c side of things so I just need help with the java side

Any advice? Thanks

# Answer
> 1 votes
Since your game is written in objective-c and you have decided to use Java for the level editor, I assume that the level editor doesn't need to render the levels exactly as the game engine.

I have written many level editors for commercial mobile games with Java, and I can strongly recommend using Java2D, which is part of Java. If you don't need 3D graphics and the editor is not performance critical, you can get things done easily with Java2D. It is a strong 2D graphics library with features such as arbitrary shapes, Constructive Area Geometry, antialiasing, strokes, affine transformations, text rendering, arbitrary clipping and alpha blending. I have found these very useful when creating user interfaces for level editors. E.g. good looking marching ants is easy to implement for arbitrary selection shape. Images can be zoomed and rotated with filtering and there is no need to allocate textures, instead Java2D automatically uses hardware acceleration where possible.

You can also use Swing for creating some of the UI. Menus, toolbars, object choosers, dialogs can be implemented with Swing components with little effort and you can use Java2D inside them wherever you want.

These choices are good when making Java applets, since they don't require any native libraries outside JRE or additional downloadables.

---
Tags: java, box2d, cocos2d, level-design
---