title: Rendering metallic look

text:
# Question
Title: Rendering metallic look
I would really like to get the same metallic reflection look as in CSR Racing for my game in the simplest way possible. It doesn't have to be top-notch, but right now my rendering looks horrible and is in need of some serious improvement. Metallic reflection rendering seems pretty complex (for instance looking at this), so I need some advice on what to try.

I realize CSR Racing renders using some type of environment mapping. Can I cheat using spherical env maps, or do I need cube maps? (Nonetheless I will use static images, it's too much work to generate on the fly, and I'll keep each level in the same "tone" so I think it will work well enough.) How should I map my UVs for the env map? Or should I use the normals? If so how to tranform 3D-normals to 2D? What texture transformation to use? I tried to use the camera transformation with the same UVs I'd have used for a diffuse texture (and using `glEnable(GL_TEXTURE_GEN_S)`), and there was some... result, but I think that's on the wrong track?

Do I need to use specular maps, even for a shiny, clean metallic surface? When I look at what specular maps are used for it seems like they hold information of what is matte and what is shiny. Any tips and tricks highly appreciated!

# Answer
> 2 votes
The first thing you need to get into is that phong is not going to cut it. Phong looks nice on mostly matte objects, but once the shininess approaches perfect reflection it starts to look odd. One good model is for example Heidrich–Seidel shading equations.

The next bit is of course environment mapping. Either you build the env map on the fly or you use a canned cube map, but there must be something that reflects off the surface or it will look odd.

If you need specular maps depends on the object you want to model. If you object is uniformly "painted" you don't need a secular map. If your object contains other bits, such as rubber you may want specular maps. But in that case you want to use a totaly different material; one that uses for example oren-noyar shading.

---
Tags: opengl, reflection-rendering
---


title: Quaternion Look At with Up vector

text:
# Question
Title: Quaternion Look At with Up vector
I have implemented a "look at" method for my screen elements and it almost works how I want it to work.

The ScreenElement class uses a R3 Vector and a Quaternion to determine the position and orientation. As a convenience function I implemented a "look at" method. I am not the biggest expert on linear algebra, so my solution was an adaption of stuff I found on forums; but it was the only solution I understood.

The current approach is as follows:

```
void SceneElement::look_at(const mx::Vector3f& target, const mx::Vector3f& up)
{
    mx::Vector3f forward_l = mx::normalize(target - position);
    mx::Vector3f forward_w(1, 0, 0);
    mx::Vector3f axis  = forward_l % forward_w;
    float        angle = mx::rad_to_deg(acos(forward_l * forward_w));

    mx::Vector3f third = axis % forward_w;
    if (third * forward_l < 0)
    {
        angle = - angle;
    }
    orientation = mx::axis_angle_to_quaternion(angle, axis);
}

```

As you can see the `up` vector is not used and as a result the orientation is so far correct, that it looks as the target, but the up orientation is all over the place.

I have tried different approached to integrate the up vector. The "best" (i.e. it still mostly looked at the target) was to make the same approach with a orthonormalized up vector.

Just as a note, the up vector is expected to work like gluLookAt, that is used as a baseline but it needs to be projected into the local coordinate system, this I did as:

```
mx::Vector3f right = mx::normalise(forward % up);
mx::Vector3f up_n  = mx::normalise(right % forward);

```

Just to complete the info, the math lib I use is my own mathex and the basterised modulo (%) operator is the R3 cross product.

# Answer
I solved it. I was on the right track... The final solution is:

```
void SceneElement::look_at(const mx::Vector3f& target, const mx::Vector3f& up)
{
    mx::Vector3f forward_l = mx::normalize(target - position);
    mx::Vector3f forward_w(1, 0, 0);
    mx::Vector3f axis  = forward_l % forward_w;
    float        angle = mx::rad_to_deg(acos(forward_l * forward_w));

    mx::Vector3f third = axis % forward_w;
    if (third * forward_l < 0)
    {
        angle = - angle;
    }
    mx::Quaternionf q1 = mx::axis_angle_to_quaternion(angle, axis);

    mx::Vector3f up_l  = mx::transform(q1, mx::normalize(up));
    mx::Vector3f right = mx::normalize(forward_l % up);
    mx::Vector3f up_w  = mx::normalize(right % forward_l);

    mx::Vector3f axis2  = up_l % up_w;
    float        angle2 = mx::rad_to_deg(acos(up_l * up_w));

    mx::Quaternionf q2 = mx::axis_angle_to_quaternion(angle2, axis2);

    orientation = q2 * q1;
}

```

The only open issue I have is I am not sure in which cases the commented out code is necessary.
> 3 votes

---
Tags: mathematics, quaternion, orientation
---


title: Basic developing in python?

text:
# Question
Title: Basic developing in python?
I have basic experience in Python, and I want to know which is the best library to use in development. I was looking originally at Pygame but found it a bit lacking in tutorials. Are there any good ones for Pygame? And if not, is there any nice alternative to the Pygame library, or Python itself?

# Answer
> 4 votes
I always found Pyglet to be a very nice alternative to PyGame. To me it felt more Pythonic and came with an good programming guide (next to the API documentation, of course) that almost always helped me get along.

# Answer
> 3 votes
There's also the original Cocos 2D, as well as Panda 3D.

Haven't done a lot of game programming in Python. I just know that if you want to try anything more than the absolute basics with audio in Python that you should avoid pygame like the plague, or at least find an alternate sound module.

# Answer
> 0 votes
A good tutorial on pygame is http://www.youtube.com/watch?v=0xgn-HKzZes.

---
Tags: python, pygame
---


# Question
Title: How is the gimbal locked problem solved using accumulative matrix transformations
I am reading the online "Learning Modern 3D Graphics Programming" book by Jason L. McKesson

As of now, I am up to the gimbal lock problem and how to solve it using quaternions.

However right here, at the Quaternions page.

> Part of the problem is that we are trying to store an orientation as a series of 3 accumulated axial rotations. Orientations are orientations, not rotations. And orientations are certainly not a series of rotations. So we need to treat the orientation of the ship as an orientation, as a specific quantity.

I guess this is the first spot I start to get confused, the reason is because I don't see the dramatic difference between orientations and rotations. I also don't understand why an orientation cannot be represented by a series of rotations...

Also:

> The first thought towards this end would be to keep the orientation as a matrix. When the time comes to modify the orientation, we simply apply a transformation to this matrix, storing the result as the new current orientation.
>
> This means that every yaw, pitch, and roll applied to the current orientation will be relative to that current orientation. Which is precisely what we need. If the user applies a positive yaw, you want that yaw to rotate them relative to where they are current pointing, not relative to some fixed coordinate system.

The concept, I understand, however I don't understand how if accumulating matrix transformations is a solution to this problem, how the code given in the previous page isn't just that.

Here's the code:

```
void display()
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClearDepth(1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glutil::MatrixStack currMatrix;
    currMatrix.Translate(glm::vec3(0.0f, 0.0f, -200.0f));
    currMatrix.RotateX(g_angles.fAngleX);
    DrawGimbal(currMatrix, GIMBAL_X_AXIS, glm::vec4(0.4f, 0.4f, 1.0f, 1.0f));
    currMatrix.RotateY(g_angles.fAngleY);
    DrawGimbal(currMatrix, GIMBAL_Y_AXIS, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f));
    currMatrix.RotateZ(g_angles.fAngleZ);
    DrawGimbal(currMatrix, GIMBAL_Z_AXIS, glm::vec4(1.0f, 0.3f, 0.3f, 1.0f));

    glUseProgram(theProgram);
    currMatrix.Scale(3.0, 3.0, 3.0);
    currMatrix.RotateX(-90);
    //Set the base color for this object.
    glUniform4f(baseColorUnif, 1.0, 1.0, 1.0, 1.0);
    glUniformMatrix4fv(modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(currMatrix.Top()));

    g_pObject->Render("tint");

    glUseProgram(0);

    glutSwapBuffers();
}

```

To my understanding, isn't what he is doing (modifying a matrix on a stack) considered accumulating matrices, since the author combined all the individual rotation transformations into one matrix which is being stored on the top of the stack.

My understanding of a matrix is that they are used to take a point which is relative to an origin (let's say... the model), and make it relative to another origin (the camera). I'm pretty sure this is a safe definition, however I feel like there is something missing which is blocking me from understanding this gimbal lock problem.

One thing that doesn't make sense to me is: If a matrix determines the difference relative between two "spaces," how come a rotation around the Y axis for, let's say, roll, doesn't put the point in "roll space" which can then be transformed once again in relation to this roll... In other words shouldn't any further transformations to this point be in relation to this new "roll space" and therefore not have the rotation be relative to the previous "model space" which is causing the gimbal lock.

That's why gimbal lock occurs right? It's because we are rotating the object around set X, Y, and Z axes rather than rotating the object around it's own, *relative* axes. Or am I wrong?

Since apparently this code I linked in isn't an accumulation of matrix transformations can you please give an example of a solution using this method.

So in summary:

* What is the difference between a rotation and an orientation?
* Why is the code linked in not an example of accumulation of matrix transformations?
* What is the real, specific purpose of a matrix, if I had it wrong?
* How could a solution to the gimbal lock problem be implemented using accumulation of matrix transformations?
* Also, as a bonus: Why are the transformations after the rotation still relative to "model space?"
* Another bonus: Am I wrong in the assumption that after a transformation, further transformations will occur relative to the current?

Also, if it wasn't implied, I am using OpenGL, GLSL, C++, and GLM, so examples and explanations in terms of these are greatly appreciated, if not necessary.

The more the detail the better!

Thanks in advance.

# Answer
I'm not sure of a good way to preface this, other than I hope it ties together nicely by the end. That said, let's dive in:

A rotation and an orientation are different because the former describes a transformation, and the latter describes a state. A rotation is *how an object gets into an orientation*, and an orientation is *the local rotated space of the object*. This can be directly related to how the two are represented mathematically: a matrix stores transformations from one coordinate space to another (you did have that correct), and a quaternion directly describes an orientation. The matrix, therefore, can only describe *how the object gets into an orientation*, through a series of rotations. The problem with this, though, is Gimbal Lock.

Gimbal lock demonstrates the difficulty of getting an object into an orientation using a series of rotations. The problem occurs when at least two of the rotation axes align:

In the left image above, the blue and orange axes make the same rotation! This is a problem, because this means one of the three degrees of freedom has been lost, and additional rotations from this point may produce unexpected results. Using quaternions solves this because apply a quaternion to transform the orientation of an object will directly put the object in a new orientation (that's the best way I can say it), rather than breaking the transformation down into roll, pitch, and yaw operations.

Now, I am actually skeptical about accumulating matrices being a complete solution to this, because accumlating matrices (therefore accumulating rotations) are exactly what can cause the Gimbal Lock problem in the first place. The proper way to handle transformation by a quaternion is to either perform quaternion multiplcation on a point:

```
pTransformed = q * pAsQuaternion * qConjugate

```

or by converting the quaternion to a matrix and transforming the point using that matrix.

A plain matrix rotation (such as a 45 degree yaw) will always be defined in global space. If you want to apply the transformation in local space, you would have to transform your transformation into that objects local space. It sounds strange, so I will elaborate. This is where the importance of the order of rotations comes in. I recommend grabbing a book here so that you can follow along with the transformations.

Start with the book flat, its cover facing up at the ceiling, oriented as if you were about to open it and start reading. Now tilt the front of the book up 45 degrees (the front cover should roughly be facing you):

```
glutil::MatrixStack bookMatrix;
bookMatrix.RotateX(45);

```

Now, let's say you wanted to adjust the yaw of the book 45 degrees (I think I'm assuming a right-handed coordinate system, so this will be changing heading to the left), and you want this to apply to the book's local coordinate space, so that the cover of the book will still face you:

```
bookMatrix.RotateY(45);

```

The problem is, this rotation occurs in the global coordinate space, so the book's cover will end facing over your right shoulder. In order to have this change in heading occur in local coordinate space, you should have applied it first!

```
glutil::MatrixStack bookMatrix;
bookMatrix.RotateY(45);
bookMatrix.RotateX(45);

```

Try it out! Start the book facing up at the ceiling again. Change its yaw 45 degrees, and then pitch it 45 degrees along the global X axis (running from your left to right). This the orientation you expected with a pitch of 45 and yaw of 45 in the book's local space.

What does this mean? All it really comes down to is that the order of the operations matters. Transformations done first become local transformations in the context of transformations done afterwards. It becomes a lot to wrap your head around, and this is how quaternions save a lot of trouble. The skip all the order-dependent stuff.

The other huge advantage that quaternions provide is that they allow for the interpolation of orientations. Trying to interpolate between Euler angles is almost impossible because of the order dependencies. The mathematical properties of the quaternion allow for a well-defined spherical linear interpolation between them.

To wrap things up and address your original question: accumulative matrix transformations really will not solve the Gimbal lock problem, unless the transformations are carefully chosen and applied in a precise order. Therefore, always use quaternions, and apply quaternions to points using quaternion multiplication.

Hope this helps :)
> 12 votes

# Answer
Matrix accumulations can in fact solve Gimbal lock. By accumulating rotations, you are adding gimbals, allowing any arbitrary rotation. The diagram that ktodisco provided shows a gimbal lock in the left diagram. The matrix for this orientation can be defined as:

```
glutil::MatrixStack bookMatrix;
bookMatrix.RotateX(90);
bookMatrix.RotateY(90);
bookMatrix.RotateZ(90);

```

Because of the y gimbal rotation, X and Z gimbals are now locked, so we've lost one degree of movement. At this point we have no yawing (local y, global z) using these three gimbals. But by adding another gimbal, I can rotate locally around the y:

```
glutil::MatrixStack bookMatrix;
bookMatrix.RotateX(90);
bookMatrix.RotateY(90);
bookMatrix.RotateZ(90);
bookMatrix.RotateY(90);

```

For every new roll, pitch, and yaw, just add another gimbal, ACCUMULATING them into one matrix. So every time another local rotation is needed, a rotation is created and multiplied to the accumulation matrix. As the chapter mentions, there are still problems, but gimbal lock is not one of them.
> 1 votes

---
Tags: opengl, rotation, transformation, orientation, gimbal-lock
---


title: 2D Top down acceleration vector

text:
# Question
Title: 2D Top down acceleration vector
I have been wanting to solve the issue of movement once and for all... with all that I have learnt and read through, should be a piece of cake one would have thought... , seems it isn't. Having rummaged through stackoverflow, I have found this link https://stackoverflow.com/questions/7312773/mathematical-vectors-and-rotations-topdown-java-game-dev-physics-problem and the bottom solution which explains how I exactly how I want acceleration to act as a 2D vector.

Moving on to the fact that the answer lies in the last post; that is having two vectors totaling to the acceleration vector, I am now faced with a simple yet unanswerable problem with the code I am using. The problem lies in the fact that considering an angle of 0 and 360 degrees both pointing north respectively, I cannot for the life of me figure out why moving up will not keep the angle constant to 0. (apart from the fact that this angle is given through Math.toDegrees(Math.atan2(y, x)))

If we take this code for example ( a direct result of the last thread on stackoverflow )

```
double secondsElapsed = deltaTime / 1000.0;

double forwardDirection = velocity.angle() + 90;
double leftDirection = forwardDirection + 90;

double forwardAccel = 0;
if (up)
   forwardAccel = 100;
if (down)
   forwardAccel = -100;

double leftAccel = 0;
if (right)
   leftAccel = 100;
if (left)
   leftAccel = -100;

double fDir = Math.toRadians(forwardDirection - 90);
double lDir = Math.toRadians(leftDirection - 90);

Vector2D forwardUnitVector = new Vector2D (Math.cos(fDir), Math.sin(fDir));
Vector2D leftUnitVector = new Vector2D (Math.cos(lDir), Math.sin(lDir));

Vector2D acceleration = forwardUnitVector.scale(forwardAccel);
acceleration.add(leftUnitVector.scale(leftAccel));

Vector2D deltaV = acceleration.scale(secondsElapsed);

velocity.add(deltaV);
position.add(velocity.scale(secondsElapsed));
angle = velocity.angle() + 90;

```

the angle and motion with the upwards press is set to give acceleration on the x axis (which is fine considering my angle is 90 degrees pointing east). Now realizing that we want a forwardUnitVector of (0,-1) (to get me poiting to the north) I was thinking something along the lines of a resulting degree of 270 (Math.sin(Math.toRadians(270)) = -1 which would be used along the y axis to create motion in the top direction. However, having set the forwardDirection to 360 which would give me the desired result of forwardUnitVector(0, -1) I am given a velocity and an angle which acts as a rotation instead of a simple magnitude on the y axis.

Can anyone please explain to me why my concept of having motion towards the north is flawed?

Thanks for bearing with me!

# Answer
> 2 votes
A couple things are off. First, note that the "standard mathematical" coordinates are "X goes right, Y goes up." You are using "X goes right, Y goes south" There isn't anything wrong this this per-se, as long as you remember to translate appropriately.

Next, "standard math" libraries use radians for everything. You seem to be using degrees. Again, this is okay only if you remember to translate all units appropriately. For example, your left vector is definitely wrong because of the lines `double forwardDirection = velocity.angle() + 90;
double leftDirection = forwardDirection + 90;` Since `velocity.angle()` returns a radian, adding `90` gives a meaningless value.

Also, you don't need fDir, lDir, forwardDirection, or leftDirection; you can calculate `forwardUnitVector` and `leftUnitVector` directly:

```
Vector2D forwardUnitVector = velocity;
forwardUnitVector.normalize();
Vector2D leftUnitVector = new Vector2D(-fUnit.Y, fUnit.X);

```

---
Tags: java, movement, vector
---


title: How to simulate early politics?

text:
# Question
Title: How to simulate early politics?
I'm making a historically accurate game where the player can interact with past times and shape the future. The entire game is scientifically generated with math and real physics. (no, it won't have dragons! lol) The game will run real time and simulate the entire Earth (at first, then at level 56 the player unlocks universe mode where the whole universe is simulated). The player can build anything they want and it will use physics to simulate each creation based on the materials it's made of. Like they could build a rocket with solid fuel and it will launch realistically, as long as they shaped the nozzle correctly.

Anyway, I'm at the point where I'm simulating the dinosaurs and I want to make it accurate. I know we can't ***know*** exactly what the political structure of the dinosaurs was since most of the writings were destroyed in the comet strike, but most people know that our political system is based off theirs.

I was considering just modeling our political system and then applying mathematical regression to the algorithm to regress it 100 million years. However, I'm worried about the limitations of floating point numbers and I think that errors will compound. That would leave me with a political system that's really inaccurate. What strategies can I use to develop a political system from scratch?

P.S. I'm mostly talking about American dinosaurs, because they had the most impact on world politics.

# Answer
> 3 votes
like most beginners to MMO game development, you are making it seem much harder than the actual task really is. Based on your previous answers, you already seem to have a working apple simulator, so all it takes is one small change:

```
paper_2d_behaving_apple.Location = "AMERICA";
paper_2d_behaving_apple.Timestamp = -6311582168472000;
paper_2d_behaving_apple.RegisterPoliticalTypeMapping(typeof(Dinosaur));
paper_2d_behaving_apple.IsApple = false;

```

---
Tags: mathematics, procedural-generation, simulations
---


title: Simple browser game help

text:
# Question
Title: Simple browser game help
As my first "real" project, I'm working on a game that I intend to be single-player, web-based, and primarily in text. I need the ability to save choices the players make, and to have certain variables increase based on those choices. (Like bravery increasing after a heroic choice is made, for example.) There's a very small inventory; not RPG-style elaborate. The big thing about it is the choice aspect; every choice impacts where the player can go/future success or failure in other situations/etc. So I really have to be able to save those. (Choice input was being done by simple buttons, but I'm not married to that.) I'd like the player to be able to close the browser, then come back to it later where they left off- so, a login system, too.

My biggest problem is that I feel like I'm getting jerked left and right on which language(s) to use for this. I started off with Python a few months ago and started getting comfortable in that, but then didn't like how hard it was to integrate it in to a website afterward. (Hard for me, anyway. I might just be stupid, or failing to find the right tutorials on it.) I got a book on Javascript ("The Good Parts"), but found it unhelpful for what I was trying to do and my skill level. Then I got a book on PHP and MySQL ("PHP and MySQL Web Development") and started getting used to that, thinking it would be useful for saving player choices, but now all I see when I google specific questions about mySQL with games is people saying, "You don't want to use MySQL for games." So have I been wasting my time on that?

What language would you use for a single-player web game that was text-based and had to save many player choices? Or was I already going the right direction to start with?

# Answer
Short answer: JavaScript is a perfectly suitable choice for this. Ultimately you want it to be browser based, browsers run JavaScript. You want it to be able to be single player and store player choices, JavaScript has local storage up to ~5MB that you can use. If you want player choices to be stored on your server and not their machine, there is a light-weight JavaScript server side software system called Node.js that you can get started with fairly quickly. If you are going to have to learn a language to do this, you might as well only have to learn one.

Could you do this with Python, PHP and/or MySQL? Absolutely. If you knew these languages to begin with it might be easier than starting from scratch. If you are starting from scratch, JavaScript starts you the closer to the goal line for a web-based game.

Side note: You see people say not to use MySQL for games because to do that is to leverage the might of a powerful relational database that was designed to store, cross-reference and retrieve large sets of data efficiently for the purpose of storing "player is at x=10 and y=20". It's usually overkill, and it's usually not as fast or scalable as you would like because it was not designed for small rapid communications.
> 3 votes

# Answer
You might want to look at the Flask framework. I've been working on a freelance project where I've been working on an existing flask system and I've been fairly impressed with how simple it is for working on the web in Python. I haven't had the free time, yet, but I've definitely been interested in using it for developing a game.

In my experience it does a good job of bridging some of the difficulties posed by getting started with a Python project on the web, and that's one of your important tasks.

Addressing the concept of making optimal choices starting out, it sounds like you haven't gotten too deep into any one language yet--or at least not any language you perceive as appropriate to the task. You can always refactor your code later to change how you're saving data if you find the method you used is too slow for your game. This is going to be a triangulation between how often you find it necessary to perform queries, inserts, and how many players you have active at a time. While I agree with the warnings you've been given about MySQL, these warnings ignore the value of getting a working, playable game.

You'll have a much better chance of success in the broader project of "creating a game" once you get something vaguely game-like which you can then refine and shape, rather than spinning your wheels attempting to build only with most-optimal technologies up front. It might mean more work in the long run, but it's better than losing steam trying to find your sea legs with unfamiliar technologies someone has told you are "best" for what you're doing.
> 0 votes

---
Tags: text-based
---


# Question
Title: Has anyone got the Krypton Lighting Engine working in MonoGame for Windows 8?
I've converted the core of the Krypton Lighting Engine so that it's compatible with Windows 8.

The trouble I'm having when actually using it is that it can't load the `KryptonEffect.xnb` file. I'm aware that MonoGame doesn't have XNA content processors, so I'm compiling the KryptonEffect.fx file in an XNA Content project.

When I try to load the `Effect`, I get an exception saying `The MGFX file is corrupt` in the `ReadEffect` method in MonoGame. The header should be `MGFX` but it's a seemingly random byte array.

I then came across this page that says to use a tool named `2MGFX`. I tried this, but the tool reports: `The effect must contain at least one technique and pass`. From what I can see from KryptonEffect.fx the file, it does.

Has anyone got the Krypton Lighting Engine working on MonoGame for Windows 8? Or has anyone been able to load any kind of Effect file under Windows 8?

# Answer
> -1 votes
Change Content Processor To "MonoGame Effect".

---
Tags: xna, lighting, xna-content-pipeline, monogame, windows-8
---


# Question
Title: Is it possible to earn money with GameMaker if your game is good enough?
I'm a graphic designer and will be graduated from school in 6 months. I would like to start developing my own game. I don't know any coding language but I'm familiar with the methods of it. When I play a game, I can understand the hole code in detail behind it theoretically.

My plan is to make a game as soon as posible and earn some cash for my coding training.. I believe I can make a simple, good looking, fun and unique game.

This may sound cheapy but I do believe in this project. So how can I earn money with it?

I have a game project written down and can create beta version of it with Game Maker in a month. But I think that wont make me earn money at all. GameMaker provides ios publishment with 199$. That I can afford but can I make money with it? Does GameMaker take percentage from your profit on ios sellings?

Can I make a beta version of this project on GameMaker and show it on Kickstarter so I can afford my future expenses like buying new laptop, attend coding classes and improve the project so people can play it on different operating systems?

Making games and earn my living with it is my dream. But turning dreams into real isn't free. If I can make roughly 45,000$ pledged for the project, in 2 years I can become self sufficient game developer and publish the game.

The project I'm talking about doesn't need physics, complex coding or anything like that. I dont think a good and addictive game have to be complicated. There are lots of financially succesfull games which are really can easy to create.

Anyway, I can design a game from scratch but can't code it entirely.. So please help me find a way for my dream. Any usefull advices will be appreciated.

**My main questions are;**

**1.** Is it possible to earn money with GameMaker if your game is good enough?

**2.** Does GameMaker take percentage from your profit on ios sellings?

**3.** Is it ok to show your game made with gamemaker on kickstarter? Or will it look like deficient?

Thanks.

# Answer
> 2 votes
You should consider finding a programmer and work *with* him (as opposed to making him work *for* you) to make games.

Regardless of what no-coding-required-game-engine vendors want to make you believe, programming is a complex discipline, and game programming is especially difficult. People study Computer Science for decades, dedicate their entire lives to programming, yet not all get to master the hundreds of topics that are required to competently make games.

You can certainly dedicate time to "coding training", and you can probably pull out a few games by coding them, or by using those no-coding-required-game-engines, but do you really want to dedicate your time to programming and debugging your code? (remember that even if you use a graphical tool, you *will* be debugging your game)

If you do, then by all means go learn programming (I've been doing so for 19 years and there are still tons of stuff I can't do). But from what I understand, you want to design games, and make all the graphical stuff in them, so I think it you should do that, and find a good programmer, and work with him to make some awesome games.

But, by no means I'm telling you not to learn programming. Understanding the mindset of a programmer is very useful when communicating with your programmer, as well as understanding the mindset of an artist is very useful for a programmer. I'm just telling you you will be happier, and will make better games if you dedicate to do what you do best. And trust me, there's still a LOT of stuff for you to learn as a graphic designer.

There's a lot of programmers looking for artists, and you will certainly be able to find somebody who shares your vision. If you're competent, and find a competent programmer in the same wave as you, then you're already ahead of the curve.

Now, regarding the "making money" part, I'll have to tell you it's difficult. It doesn't matter how good you think you are, your first game will suck. And the second one will suck too (just a bit less than the first one). Maybe the third one will be good enough, so some people will buy it, but maybe it will be the fourth one that will actually make you some money.

Just making a game doesn't mean it will sell. There's *way* too much to learn on how to make a good game that sells, and finding somebody to work with will get you closer to succeeding as a game creator. But if you'd rather spend your time learning programming from scratch, then go ahead.

---
Tags: software-engineering, publishing, game-maker, graphics-design
---


# Question
Title: How to I rotate a triangle by dragging the mouse in libGDX?
More specifically, I have rotation working in a way I don't like as follows:

```
    //Draw the triangle using this draw method
    //batch.draw(texture, x,                            y,                                          originX,                 originY,                                        width,               height,      scaleX, scaleY, rotation, srcX, srcY, srcWidth,   srcHeight, flipX, flipY)
    batch.draw(triangle, 240 - triangle.getWidth() / 2, (float) (400 - triangle.getWidth() * .289), triangle.getWidth() / 2, (float) ((double) triangle.getWidth() * 0.288), triangle.getWidth(), triangle.getHeight(), 1, 1, rotate, 0, 0, triangle.getWidth(), triangle.getHeight(), false, false);

    batch.end();

    //Touch input
    if(Gdx.input.isTouched()){
        Vector3 touchpos = new Vector3();
        touchpos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(touchpos);
        rotate = touchpos.x;
    }

```

This rotates the triangle around the center of the triangle that is at the center of the screen (the 0.289 corresponds to the height of the middle of an equilateral triangle according to its side length).

The rotation will be equal to the touch position on the screen which works great when the finger is dragged. However, what this code does is moves the rotation to the specific location whenever I touch the window with the mouse. What I would like it to do is to rotate the triangle when the mouse is dragged, but only based on its previous rotation, not its absolute rotation. For example, if I click and drag the mouse from the left side of the window to the right, the triangle will rotate accordingly. When I lift the mouse then click and drag it the same way a second time, I don't want it to reset it's position to my 2nd click, I want it to move the amount I dragged my mouse **from it's previous rotation**.

Can anyone help with this? I've been trying to wrap my head around it for hours. Let me know if you need any clarifications.

# Answer
I fixed my problem by using libGDX's built in input function getDeltaX(). It does exactly what I described that I want it to do. My isTouched() if statement now looks like this:

```
    if (Gdx.input.isTouched()){
        Vector3 touchpos = new Vector3();
        touchpos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(touchpos);
        rotate += Gdx.input.getDeltaX();
        myTriangle.setAngle((int) rotate);
    }

```
> 1 votes

# Answer
```
rotate += touchpos.x;

```

You may want to store the `x` of where the touch "starts" and do something like:

```
rotate += touchpos.x - startTouch.x;

```

(that way a drag that starts at the middle of the screen doesn't imply a large rotation ...). To capture the touch start, use `justTouched()` to determine if this is a new touch.
> 0 votes

---
Tags: java, software-engineering, libgdx, rotation, input
---


# Question
Title: Defining a random irregular shape in a bool array
I need to find out how to populate an array bool\[x,y\] with a random filled shape.

lets say I want a triangle depicted in my array i would define an area within the array and set all points to "true" that exist within the defined by 3 key points.

Now lets say my array is ... bool\[100, 100\] I want to define a shape with N(random) number of sides.

1. Plot N number of points within the array and set their values to true
2. set all points that represent a line between the current point and the next point to true
3. fill the shape by setting all inside points to true

Any ideas? I'm using C# and if it helps anyone Unity too. This is part of a much bigger problem so it doesn't sound like much but it will hugely help.

Thanks guys.

# Answer
There are several things you can try for generating random shapes that are meant to represent islands.

You could modify your algorithm to make sure the resulting shape is convex. Although it's not required for the islands to be convex, I have a feeling that using it vanilla will lead to shapes that look odd as islands.

But more organic shapes are possible. Here are two suggestions:

# Method 1

1. Generate one random point.
2. For each point in the array with at least one empty neighbor that you have not already processed, fill each empty neighbor with some probability.
3. Repeat step 2 until desired.

You can control the shapes and sizes of the islands with the value p that you choose. You need not keep p constant, it may work well to decrease it as you go on. You may also make it depend on the number of neighbors (for instance, make it proportional to the number of neighbors of the pixel you are processing).

You can (probably) make the algorithm more efficient by maintaining a list of border pixels, and another list of processed pixels. It becomes then something like this:

1. Generate a random point, and add it to processed list and border list.
2. While the border list is not empty and some other stop condition is not met: 1 Take the next point in it.
    1. Add the point to the processed list.
    2. For each neighbor of that point *not* in the processed list:
        1. Fill that neighbor with probability p.
        2. Add the neighbor to the border list.
    3. Remove the point from the border list

(Other possibilities are also possible if this is too slow.)

# Method 2

Generate cloudy noise (or Perlin noise, as some people\* mistakenly calls it) in an array of the same size, and then use a threshold function to make the island.

Check this out for generating the noise:

http://devmag.org.za/2009/04/25/perlin-noise/

http://devmag.org.za/2011/06/25/implementing-and-debugging-the-perlin-noise-algorithm/

To generate islands, you can use this algorithm

```
noiseArray = MakeNoise(100, 100)
for each pixel in noiseArray
   noiseArray[pixel] = noiseArray[pixel]^somePower //adjusts the gamma
   if noiseArray[pixel] < someThreshold
      boolArray[pixel] = true

```

You can control the shapes of the islands using the persistence value of the noise, the value of `somePower`, and the threshold value you choose.

You will need to modify it somehow to make sure you only get one island. You will have to play around a bit; one idea is to start in the middle, and do a spiral search until you find a filled pixel, and then make a new array, and fill it with pixels that are filled in the bool array only if they are connected to the first pixel (the one you found in the spiral search).

(\*Including me in the article :( )
> 2 votes

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


# Question
Title: How do I destroy a Box2D body on contact without getting an IsLocked assertion error?
I get this error when attempting to remove a body from the world:

> java: /var/lib/hudson/jobs/libgdx/workspace/trunk/gdx/jni/Box2D/Dynamics/b2World.cpp:134: void b2World::DestroyBody(b2Body\*): Assertion 'IsLocked() == false' failed.

What am I doing wrong?

# Answer
From my little experience with box2d in libgdx, it can sometimes be difficult to isolate and resolve issues with exceptions which was only worsened by the latest port. Pre 2.2.1, I could easily remove bodies from the world without synchronization issues like you are experiencing but after migrating to the libgdx build that supported 2.2.1, I started seeing the same issues. The workaround for me, which was suggested by several people was that you cannot remove bodies from the world while the world is possibly being simulated.

Is there a possibility that you are attempting to remove a body from the world when the world is being stepped? Basically, if you try to do this, box2d doesn't like it so what you have to do is remove bodies outside of the `world.step`. What I did was added a utility class for the body's `.userData` with a bool isFlaggedForDelete which would get checked **outside** the world.step method.

```
public void sweepDeadBodies() {
   for (Iterator<Body> iter = CURRENT_WORLD.getBodies(); iter.hasNext();) {
     Body body = iter.next();
     if(body!=null) {
          YourCustomUserData data = (YourCustomUserData) body.getUserData();
          if(data.isFlaggedForDelete) {
          CURRENT_WORLD.destroyBody(body);
            body.setUserData(null);
            body = null;
          }
     }
}

```

If you run something like this right after your world.step, it should work. In your code where you are trying to destroy the body, just set it's .isFlaggedForDelete to true and it will get removed before the next world.step.
> 23 votes

# Answer
So we have your error:

> /var/lib/hudson/jobs/libgdx/workspace/trunk/gdx/jni/Box2D/Dynamics/b2World.cpp:134: void b2World::DestroyBody(b2Body\*): Assertion 'IsLocked() == false' failed.

## Let's break it down:

Most of the first part of this error is helpful directions to tell you *where* the error is happening.

> **/var/lib/hudson/jobs/libgdx/workspace/trunk/gdx/jni/Box2D/Dynamics/b2World.cpp**

It appears the error is being generated in a source file called b2World.cpp inside the directory structure shown. And it's happening:

> **:134:**

On line 134.

Then it looks like,

> **void b2World::DestroyBody(b2Body\*):**

the function b2World:DestroyBody() which returns `void` and accepts a pointer to a `b2Body` is reporting the error.

That has finished the "where" part of the error, now it's telling us the "what". Looks like it's trying to assert that `isLocked()` is equal to `false`

> **Assertion \`IsLocked() == false' failed.**

But it's failing.

Now I've never used Box2D, but I'm guessing that means the body you're trying to destroy is locked. You'll need to figure out why the body is locked, and how to unlock it.
> 5 votes

# Answer
Libgdx implementation is just bridge to native version so all the same rules apply.

Never try to remove a body/fixture/joint when the simulation is running.

Never try to remove a body/fixture/joint more than once.

Never leave pointers (aka references) to fixtures or joints when you delete the body.

To be extra cautious - maybe even little paranoid - I use this method to remove my bodies:

```
/**
 * Safe way to remove body from the world. Remember that you cannot have any
 * references to this body after calling this
 *
 * @param body
 *            that will be removed from the physic world
 */

public static void removeBodySafely(Body body) {
    //to prevent some obscure c assertion that happened randomly once in a blue moon
    final ArrayList<JointEdge> list = body.getJointList();
    while (list.size() > 0) {
        world.destroyJoint(list.get(0).joint);
    }
    // actual remove
    world.destroyBody(body);
}

```
> 4 votes

# Answer
This is the best way to do it, i read it in the Box2D manual. You have to call this just after CURRENT\_WORLD.step(..,...,...);

```
Iterator<Body> i = CURRENT_WORLD.getBodies();
Body node=i.next();
while (i.hasNext()) {
    Body oBj=node;
    node=i.next();
    YourCustomUserData data = (YourCustomUserData) oBj.getUserData();
    if(data!=null &&  data.isFlaggedForDelete){
        CURRENT_WORLD.destroyBody(oBj);
    }
}

```
> 2 votes

# Answer
The error says it all, you need to check if the world is locked in the moment that you want to remove the body

```
if(!world.isLocked())
     world.destroyBody(body)

```

that worked for me :)
> 0 votes

---
Tags: box2d, libgdx
---


# Question
Title: Errors happen when using World.destroyBody( Body body )
on Android application using libgdx, when I use World.destroyBody( Body body ) method, once in a while the application suddenly shuts down.

Is there some setting I need to do with body collision or Box2DDebugRenderer before I destroy bodies?

Below is the source I use for destroying bodies.

```
private void deleteUnusedObject( ) {
    for( Iterator<Body> iter = mWorld.getBodies() ; iter.hasNext() ; ){
        Body body = iter.next( ) ;
        if( body.getUserData( ) != null ) {
            Box2DUserData data = (Box2DUserData) body.getUserData( ) ;
            if( ! data.getActFlag() ) {
                if( body != null ) {
                    mWorld.destroyBody( body ) ;
                }
            }
        }
    }
}

```

Thanks

# Answer
If you are trying to destroy the body in a CollisonEvent, this happens mid-step so you can't do that. Your best bet is to build a list of objects you would like to destroy and have them removed next frame.
> 4 votes

# Answer
I also face the same problem in libgdx. But I found an alternate solution about this is. The following is the way to work same as destroyBody

```
world.step(0,0,0);
body.setActive(false);

```

this will made body inactive in the physics world and in the dispose method we destroy the body.
> 0 votes

# Answer
Make sure you are not trying to destroy the body inside of world.step(). If you are destroying it from a ContactListener or something similar, you'll have to mark the body to be destroyed later and not during world.setp().
> 0 votes

# Answer
In your render method check if the world is locked, with world.islocked(), if it isn´t locked, and call immediatly the destroy body.

I suppose that you error is an assertion from Box2D

```
render(float arg0)
{
       if(!world.isLocked())
       {
            destroy your bodies here
            .
            .
            .

        }
}

```
> 0 votes

# Answer
This is the best way to do it, i read it in the Box2D manual. You have to call this just after CURRENT\_WORLD.step(..,...,...);

```
Iterator<Body> i = mWorld.getBodies();
Body node=i.next();
while (i.hasNext()) {
    Body oBj=node;
    node=i.next();
    Box2DUserData data = (Box2DUserData ) oBj.getUserData();
    if(data!=null  &&  !data.getActFlag()){
        mWorld.destroyBody(oBj);
    }
}

```
> 0 votes

---
Tags: box2d, libgdx, body
---


title: Distorted edges in model rendering xna

text:
# Question
Title: Distorted edges in model rendering xna
The edges of my model are not rendered smooth in xna. See here. What can i do for this, as when designer renders the same model in maya, edges are smooth. And is it possible to render models in xna which provide same results as Vray pugin renders in maya or max.

# Answer
What you're looking for is called anti-aliasing. Set `PreferMultiSampling` to true in your `Game` class constructor:

```
graphics.PreferMultiSampling = true;

```

You can change the level of anti-aliasing by setting the appropriate `MultiSampleType`, for example:

```
graphics.GraphicsDevice.PresentationParameters.MultiSampleType =
   MultiSampleType.SixteenSamples;

```
> 1 votes

---
Tags: xna-4.0
---


# Question
Title: How to make sure user is running the newest version of mmo client?
In typical mmorpg game, you have a launcher and a client. You first run the launcher to update the client, then you run the client. In every mmo I tried if you run a client without updating first (if update is available), it automatically closes and (usually) starts launcher.

My question is, how can you check if user has the proper version of client? I though about server asking client about its md5 however it's so easy to cheat. I think that there is no safe way of handling it yet every mmorpg I know uses such a system.

So how do mmorpg games handle this problem? To make sure that the client is at the newest version?

# Answer
> 14 votes
I once found a very neat quote on the net that's very, very true for any online game:

> The client is in the hands of the enemy.

As such, you can't really avoid people doing nasty things to your game client. Due to this, don't trust the client at all, i.e. everything important should at least be verified server side (better: calculated there). If this is done properly, the player won't be able to do anything harmful with their manipulated client.

As for your login thing, I'd say it's perfectly fine to keep some magic number in your client determining its version (usually a protocol version or some checksum). This is passed during the login process. If it doesn't match, access is denied.

In addition to that, ensure the game client is started by the launcher. There are several ways to do this, e.g. the actual game client could be a dynamic link library - not a real executable file - which is then loaded and run by the launcher.

Overall, there's no 100% perfect way to avoid manipulations and the like. There's always some way to cheat or modify something (even if it just happens in-memory). Live with it and just fight those really doing something wrong rather than trying to secure everything.

Such checks should only keep the player from accidently connecting with or using some kind of manipulated or broken client. If the player forcefully circumvents such measures, it's their problem in case something goes wrong and their client acts weird, displays wrong things, etc. (i.e. other players must not be affected, but if the player manipulating their game can't play, it's their problem).

# Answer
> 5 votes
> I though about server asking client about its md5 however it's so easy to cheat.

MMOs include a version checking system to help make sure that legitimate (non-cheating) users are using a compatible version, and to help them upgrade to a compatible version if they are not, in short **its to make updating easier for the player rather than for any form of cheat protection**. (Even if a client sends a correct version version identification notice there is nothing preventing future messages between the server and client being compromised).

Probably the simplest way is simply for the client to send a version number and the server to send either a "Yes this is a compatible version" message, or a "No, you need to upgrade from this URL".

# Answer
> 1 votes
I remember that in Tibia they use an updater after client is started and you enter your correct password. If the client version is different, size~ etc. The client enters the patching mode, and it updates itself.

If you won't have the correct client version the auto-updater will not let you inside the game + if it detects any type of bot that got plugged into the working game you will get an auto-ban.

You can do the same as they have done it, check the bytesize of all scripts, and if the file size is different call it to send it over to you. That way you will have the cheater/hacker on a fork - with his account. :)

---
Tags: mmo, client-server, online, security
---


# Question
Title: cocos2d-x export plist from images in windows free tool to use
as i learn to use cocos2d-x in the part on which i need to animate sprite images
all the tutorials shows how to use something that called plist file that maps the coordinates of the images clips .
the problem is i didn't found any free tool in windows that export such file . can someone please point me where i can fins such tool ?

# Answer
There is a project named Sprite Sheet Packer which is designed to create sprite sheets, recently I've wrote a plist exporter and you can download it from here. though you need to compile it yourself.
> 2 votes

---
Tags: cocos2d-x
---


# Question
Title: I need a professional icon for my Android/iPhone game: how should I proceed?
I need a great looking icon for my mobile game.

I have a few questions regarding the process of hiring a graphic designer to do it:

1. Which is (are) the best website to publish the Request For Proposal ?
2. Is it common practice to ask for a couple of logo/icon drafts so that I can pick the one I prefer ?
3. When does the client usually pays the designer (at order, final delivery time?)

Any feedback or advice will be appreciated.

# Answer
Use Elance.com and you can dictate the terms. Generally you would offer 50% of the agreed amount up front and the rest on completion. Elance uses escrow to hold the funds so that both the buyer and professional have peace of mind about the financial transactions. It is also common practice to ask for somewhere around 3 different variations of the design. Again the terms can be entirely dictated by you and people will bid accordingly. I'd say something like 3 variations with 3 revisions total would be good.
> 2 votes

# Answer
My personal favorite is: http://99designs.com/

The basic idea is that you start a logo creation competition where you give the describe what the logo is for, any requirements you have, and how much you will pay for it. Then a bunch of freelance designers will create it for you and you use the prize money to buy the one that you think is best. Just note that buying professional grade logos can get a bit expensive (most are around $300).
> 1 votes

# Answer
Here is a good article that lists several alternatives and pros-n-cons: http://biz30.timedoctor.com/how-to-outsource-graphic-design-jobs/ Also, you should read the comments for community "what worked, what didn't" kind of feedback. I've successfully used 99 Designs for my icons and graphics in the past.
> 0 votes

---
Tags: graphics-design
---


# Question
Title: Driver error when using multiple shaders
I'm using 3 different shaders:

* a tessellation shader to use the tessellation feature of DirectX11 :)
* a regular shader to show how it would look without tessellation
* and a text shader to display debug-info such as FPS, model count etc.

All of these shaders are initialized at the beginning.

Using the keyboard, I can switch between the tessellation shader and regular shader to render the scene. Additionally, I also want to be able toggle the display of debug-info using the text shader.

Since implementing the tessellation shader the text shader doesn't work anymore. When I activate the DebugText (rendered using the text-shader) my screens go black for a while, and Windows displays the following message:

> Display Driver stopped responding and has recovered

This happens with either of the two shaders used to render the scene.

Additionally: I can start the application using the regular shader to render the scene and then switch to the tessellation shader. If I try to switch back to the regular shader I get the same error as with the text shader.

What am I doing wrong when switching between shaders? What am I doing wrong when displaying text at the same time?

What file can I post to help you help me? :) thx

P.S. I already checked if my keyinputs interrupt at the wrong time (during render or so..), but that seems to be ok

## Testing Procedure

1. Regular Shader without text shader
2. Add text shader to Regular Shader by keyinput (works now, I built the text shader back to only vertex and pixel shader) (somthing with the z buffer is stil wrong...)
3. Remove text shader, then change shader to Tessellation Shader by key input
4. Then if I add the Text Shader or switch back to the Regular Shader

## Switching/Render Shader

Here the code snipet from the Renderer.cpp where I choose the Shader according to the boolean "m\_useTessellationShader":

```
if(m_useTessellationShader)
{
    // Render the model using the tesselation shader
    ecResult = m_ShaderManager->renderTessellationShader(m_D3D->getDeviceContext(), meshes[lod_level]->getIndexCount(),
        worldMatrix, viewMatrix, projectionMatrix, textures, texturecount,
        m_Light->getDirection(), m_Light->getAmbientColor(), m_Light->getDiffuseColor(),
        (D3DXVECTOR3)m_Camera->getPosition(), TESSELLATION_AMOUNT);
} else {
    // todo: loaded model depends on distance to camera
    // Render the model using the light shader.
    ecResult = m_ShaderManager->renderShader(m_D3D->getDeviceContext(),
        meshes[lod_level]->getIndexCount(), lod_level, textures, texturecount,
        m_Light->getDirection(), m_Light->getAmbientColor(), m_Light->getDiffuseColor(),
        worldMatrix, viewMatrix, projectionMatrix);
}

```

And here the code snipet from the Mesh.cpp where I choose the Typology according to the boolean "useTessellationShader":

```
// RenderBuffers is called from the Render function. The purpose of this function is to set the vertex buffer and index buffer as active on the input assembler in the GPU. Once the GPU has an active vertex buffer it can then use the shader to render that buffer.
void Mesh::renderBuffers(ID3D11DeviceContext* deviceContext, bool useTessellationShader)
{
    unsigned int stride;
    unsigned int offset;

    // Set vertex buffer stride and offset.
    stride = sizeof(VertexType);
    offset = 0;

    // Set the vertex buffer to active in the input assembler so it can be rendered.
    deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);

    // Set the index buffer to active in the input assembler so it can be rendered.
    deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);

    // Check which Shader is used to set the appropriate Topology
    // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
    if(useTessellationShader)
    {
        deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST);
    }else{
        deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
    }

    return;
}

```

## RenderShader

Could there be a problem using sometimes only vertex and pixel shader and after switching using vertex, hull, domain and pixel shader? Here a little overview of my architecture:

* TextClass: uses font.vs and font.ps

deviceContext-\>VSSetShader(m\_vertexShader, NULL, 0); deviceContext-\>PSSetShader(m\_pixelShader, NULL, 0); deviceContext-\>PSSetSamplers(0, 1, &m\_sampleState);
* RegularShader: uses vertex.vs and pixel.ps

deviceContext-\>VSSetShader(m\_vertexShader, NULL, 0); deviceContext-\>PSSetShader(m\_pixelShader, NULL, 0); deviceContext-\>PSSetSamplers(0, 1, &m\_sampleState);
* TessellationShader: uses tessellation.vs, tessellation.hs, tessellation.ds, tessellation.ps

deviceContext-\>VSSetShader(m\_vertexShader, NULL, 0); deviceContext-\>HSSetShader(m\_hullShader, NULL, 0); deviceContext-\>DSSetShader(m\_domainShader, NULL, 0); deviceContext-\>PSSetShader(m\_pixelShader, NULL, 0); deviceContext-\>PSSetSamplers(0, 1, &m\_sampleState);

## ClearState

I'd like to switch between 2 shaders and it seems they have different context parameters, right? In clearstate methode it says it resets following params to NULL:

I found following in my Direct3D Class:

* depth-stencil state -\> m\_deviceContext-\>OMSetDepthStencilState
* rasterizer state -\> m\_deviceContext-\>RSSetState(m\_rasterState);
* blend state -\> m\_device-\>CreateBlendState
* viewports -\> m\_deviceContext-\>RSSetViewports(1, &viewport);

I found following in every Shader Class:

* input/output resource slots -\> deviceContext-\>PSSetShaderResources
* shaders -\> deviceContext-\>VSSetShader to - deviceContext-\>PSSetShader
* input layouts -\> device-\>CreateInputLayout
* sampler state -\> device-\>CreateSamplerState

These two I didn't understand, where can I find them?

* predications -\> ?
* scissor rectangles -\> ?

Do I need to store them all localy so I can switch between them, because it doesn't feel right to reinitialize the Direct3d and the Shaders by every switch (key input)?!

# Answer
Based on the debug layer error message you posted in your comment, it appears you are not setting the primitive topology correctly. When switching between shaders, be sure to issue an `IASetPrimitiveTopology` call with the correct topology for the new shader.
> 1 votes

---
Tags: c++, shaders, directx11
---


title: Asynchronous Game server

text:
# Question
Title: Asynchronous Game server
I am building an **asynchronous multiplayer game** (which can be compared whith a chess game) with Unity (up to 4 players in game). But I am stuck at choosing the server side solution.
For me this kind of game, asynchronousby and I also mean no realtime updating, can be handled by only http requests and a database (to maintain a game for example).
All connections to the database are made on the server side of course, not on the client.

What's the difference between a socket server and a http server according to my project. A simple Http server could handle any action and link to the database but it seems to be slower.

I saw that using RPC calls might be better.

Thanks a lot for your help and advices.

# Answer
The client should almost always be ignorant of the database. And if it does know about the database, expect security issues.

As for choosing a server, you do not need a brand name server. You can build your own socket server in any platform under any language you like. You'll need a socket library to extend Unity's functionality unless you have access to Pro. Other than that it's all yours.
> 1 votes

---
Tags: unity, networking, multiplayer, server
---


# Question
Title: Passing multiple colors to a pixel shader in DirectX
I have a pixel shader that sets the output color based on the interaction of an input texture, sort of like:

```
if (case1)
{
    output.Color = float4(0, 0, 0, 0);
}
else if (case2)
{
    output.Color = float4(0.5f, 0, 0, 1);
}
...

```

There can be up to four cases, meaning that the output color will be one of four different input colors, but 90% of the time only one or two colors will be used.

An additional detail that may be important is that the shader has a constant buffer with a few values that can change up to per-frame. These values, and the colors, are selected out of a dictionary that is roughly like:

* StyleID: 1
* Color1: 0, 0, 0, 0
* Color2: 0.5, 0, 0, 1
* ...two other colors...
* Width: 0.8
* ...other properties...

There are around a thousand different styles to select from. My question is: what's the best way of passing these values to the shader, and why? There are two designs that occur to me offhand.

1. On the CPU side, the current style is looked up in the dictionary. It assigns the various properties to members of the cbuffer, including however many colors associated with that style (1 to 4). The shader uses these values.
2. During initialization, the the entire style dictionary is built in to a separate, large constant buffer, something like:

.

```
cbuffer Styles
{
    float4 Color1[n];
    float4 Color2[n];
    float1 Width[n];
}

```

Where n is the number of different styles. Then the CPU just pushes the style ID to a different buffer variable (or perhaps to the unused color semantic), and the shader resolves the colors and properties to used based on this.

I'm using shader model 4.0 level 9\_3.

# Answer
If you only ever change the current color set between frames, then you should be able to do it much easier on the CPU. Smaller constant buffers means less time transferring data between CPU and GPU.
> 3 votes

---
Tags: directx, hlsl
---


# Question
Title: Improving my Roguelike Dungeon generator?
I am looking to find improvements upon my Roguelike Dungeon generator. I find it is not 'roguelike' enough, with dungeons just looking like a mess more than anything. What would improve my generator(images below)? I just can't seem to get it to look 'right'. Reference image for what roguelike should appear as: \[link\]

# Answer
Based on the discussion in comments, I would say that the question you're asking is several steps removed from the question you *should* be asking at this stage of your project. The first and foremost question is, "What do I want my *player experience* of the dungeon to be like?" Do you want the player in near-constant combat, with a sense that they are never actually safe? Or Do you want them to have brief bursts of excitement and action with pauses for recovery in between in order to heighten the next encounter?

After you've ironed out the player experience you want, then you can start asking the next question: "How can I design a dungeon to support the player experience that I'm after?" But be careful here — dungeon design is *much* more than just the layout of the individual units. It also includes issues like encounter density (does every 'room' have something in it? Does every room have a monster in it? What about monsters roaming the corridors?), features (what is my 'special' room set? Should every level have one? What about entire special levels?), global geography (is there just one stairway up and one stairway down per level, or do levels have separate exits to the aforementioned special levels? What about exits that traverse multiple levels? What about traps that might drop the player several levels? Do I have secret doors? What about secret stairs?), and so on.

Once you understand ***what*** your dungeon is trying to provide from a game design perspective and ***how*** its structure supports that design, then you can start to worry about how your code works to build the sort of dungeon structure that you're after — but worrying about the code before you really have a good grasp on your design is putting the cart before the horse here.
> 9 votes

---
Tags: roguelikes, procedural-generation
---


title: Separating axis test glitch help

text:
# Question
Title: Separating axis test glitch help
I'm working on a pretty basic 2D platformer and I'm wondering if I could get advice on an issue I've run into. To keep collision detection simple I'm using AABBs and separating axis tests for collision detection and this works fine for most cases. The problem is that when something is moving too fast my algorithm gets confused and returns a bad correction.

For example; the hero stands at the very edge of a platform (1-5px from the edge) and jumps. When the hero falls back down to the platform he travels through the platform (\> 5 pixels) and then my collision detection moves him beside the platform and the hero falls to his doom. I understand the reason - being on the edge of the platform the hero is penetrating the object more on the y-axis as it its the x-axis and I'm choosing the smaller distance to correct by.

The immediate answer is to change my movement code so it does multiple tests for a few locations between the objects start and end position but the OCD bit of my brain complains about wasted cycles, etc...

Before I start gutting my code I was wondering if there was a more elegant way to solve this problem? Am I wrong in my assumptions? Have I managed to bugger up AABB SAT tests? Should I use a different algorithm?

# Answer
One way that I've found helps alleviate this problem in platforming games is to prioritize which axis gets checked first in your SAT algorithm. For example, even though the x distance is shorter than the y distance, you can adjust your algorithm to always push on the y axis first. That way, even when your character is standing over the edge of a platform, he gets pushed upwards.

Performing multiple collision tests between the start and end positions is a fine solution if you're not having any performance issues. You can optimize it somewhat by moving the maximum distance you can get away with instead of a single pixel at the time. For example if your shape is a circle with radius 40, then moving 20 pixels at a time would work (half the radius so you don't go through thin objects).

If you want a more robust and faster solution, then you should use a continuous collision detection algorithm. Instead of intersecting with objects and then correcting, a continuous algorithm takes velocity into account and determines the time of impact, which you can then you to position the object where it needs to be.

It's actually not too difficult to implement continuous collision detection using SAT (assuming no rotation). The algorithm that you're using probably has you moving the object, then checking for collisions on multiple axes by searching for overlapping ranges. To modify this to be continuous, don't move the object first. Instead, you can calculate collision *time* on multiple axes by finding the distance between the closest points on each axis and dividing by the speed that the object is moving (on that axis). The minimum time will be the time of impact for the object, and if it's less than zero, then the objects are already colliding.
> 2 votes

# Answer
In your game, you will need to separate the logic for collision *detection* and collision *response*. Collision *detection* is the answer to the question "Is object A colliding with object B", which in this case, you're able to identify. Collision *response* is the answer to the question "If object A is colliding with object B, how do I separate them?"

It seems like you're having trouble handling collision response. Depending on your game you will have to figure out what exactly you'd like the player to do in these circumstances. There are a lot of different questions that have been asked with this in mind:

Getting 2D Platformer entity collision Response Correct (side-to-side + jumping/landing on heads)

2D game collision response: SAT & minimum displacement along a given axis?

How do I prevent my platformer's character from clipping on wall tiles?

My personal suggestion would be to take the player's velocity into account instead of simply moving along the least penetrated axis:

* If the player is moving predominantly in the y-direction, `abs(vel.y) > abs(vel.x)`, then move him out of collision in the y-direction.
* If the player is moving predominantly in the x-direction, `abs(vel.x) > abs(vel.y)`, then move him out of collision in the x-direction.
> 1 votes

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


# Question
Title: How to draw different textures on my cubes DrawUserIndexPrimitive with XNA?
I'm having some problem to draw textures with class "**DrawUserIndexPrimitive**" on Xna.

I can draw my cubes / models without problem. But I want to draw **different textures on my cubes**. I loop on each "ID" of a different texture applied to my different cube. But it does not work. I apply every time buffer and vertexPosition with IndexBuffer different from my class "GraphicData."

the final texture to be applied **is the same on all my cubes**

thank you

Here is my code for function "Draw"

```
public void drawWorld(GameTime gameTime)
    {
        if (needToDraw)
        {
            int index = 0;
            foreach (GraphicData data in graphicData)
            {

                effet.LightingEnabled = false;
                effet.VertexColorEnabled = false;
                effet.TextureEnabled = true;
                effet.FogEnabled = false;
                effet.FogStart = arcadia.camera.NearPlane;
                effet.FogEnd = arcadia.camera.FarPlane;
                effet.FogColor = new Vector3(1, 1, 1);
                effet.View = arcadia.camera.View;
                effet.Projection = arcadia.camera.Projection;

                if (index == 0)
                {
                    effet.Texture = Game.Content.Load<Texture2D>("Models\\Ground\\Land\\ground_land_text1");
                }
                else
                {
                    effet.Texture = Game.Content.Load<Texture2D>("Models\\Ground\\Land\\ground_land_text2");
                }
                foreach (EffectPass pass in effet.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    //Initialize et envoie à la carte graphique le buffer et les vertices
                    if (data.vertexBuffer != null && data.indexBuffer != null)
                    {
                        Game.GraphicsDevice.SetVertexBuffer(data.vertexBuffer);
                        Game.GraphicsDevice.Indices = data.indexBuffer;
                        Game.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, data.vertexPosition, 0, data.vertexPosition.Length, data.indices, 0, data.indices.Length / 3);
                    }

                }
                index++;
            }
        }

    }

```

# Answer
> 1 votes
I used this in a similar situation (drawing a cube, each side with a different texture) and the texture changes properly. It's probably a little sloppy but it works:

```
        effect.Texture = someTexture;
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            mainRoom.DrawFace(GraphicsDevice, frontFaceVertices);
        }

        effect.Texture = someDifferentTexture;
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            mainRoom.DrawFace(GraphicsDevice, backFaceVertices);
        }

//where .DrawFace draws the vertices
    public void DrawFace(GraphicsDevice device, VertexPositionNormalTexture[] vertices)
    {
        // Create the shape buffer and dispose of it to prevent out of memory
        using (VertexBuffer buffer = new VertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, NUM_VERTICES, BufferUsage.WriteOnly))
        {
            buffer.SetData(vertices);
            device.SetVertexBuffer(buffer);
            device.SamplerStates[0] = SamplerState.LinearClamp;
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, NUM_TRIANGLES_PER_FACE);
        }
    }

```

Instead of using the index to check which texture to use, provide your data class with the index of a texture to draw, and use an if statement to determine which texture should be drawn.

Also, loading textures is very slow, it is much better to load them once into a variable.

---
Tags: xna, graphics, textures, vertex
---


title: Pausing and resuming in Unity

text:
# Question
Title: Pausing and resuming in Unity
I've been writing this code quite late so please bear with me. I'm trying to pause the game and show a menu when I'm inside a collider and then when i press a key it should unpause the game and continue but it wont and i cant figure out why.

Here's the very simple (in my eyes) code:

```
var savedTimeScale : float;
var playerStatus : Player_Status;
var inTheZone : boolean = false;
private var startTime: float = 0.1;
var start:GameObject;

enum Upgrade { None,Main }
private var currentPage:Upgrade;

function Start()
{
    currentPage = Upgrade.None;
}

//function for ontriggerenter and pressing button to show menu
function OnTriggerEnter(collider:Collider)
{
    playerStatus = collider.GetComponent(Player_Status);
    if(playerStatus == null) return;

    inTheZone = true;
}

function OnTriggerExit(collider: Collider)
{
    playerStatus = collider.GetComponent(Player_Status);
    if(playerStatus == null) return;

    inTheZone = false;
}

function Pause()
{
    savedTimeScale = Time.timeScale;
    Time.timeScale = 0;
    AudioListener.pause = true;
    currentPage = Upgrade.Main;
}

function UnPause()
{
    Time.timeScale = savedTimeScale;
    AudioListener.pause = false;
    currentPage = Upgrade.None;
    if(IsBeginning() && start != null)
    {
        start.SetActive(true);
    }
}

function IsGamePaused()
{
    return Time.timeScale == 0;
}

function OnGUI()
{
    if(inTheZone == true && Input.GetKeyDown(KeyCode.E))
    {
        Pause();
    }

    if(Input.GetKeyDown(KeyCode.N))
    {
        UnPause();
    }

    if(IsGamePaused() && !IsBeginning())
    {
        UpgradeMenu();
    }
}

function UpgradeMenu()
{
    BeginPage(200,200);
    GUILayout.Button("Hello");
    EndPage();
}

function BeginPage(width, height)
{
    //GUI.DrawTexture
    GUILayout.BeginArea(Rect((Screen.width-width)/2,(Screen.height-height)/2,width,height));
}
function EndPage()
{
    GUILayout.EndArea();
    ShowBackButton();
}
function ShowBackButton()
{
    if(GUI.Button(Rect(20, Screen.height-50,50,20), "Resume"))
    {
        UnPause();
    }
}

function IsBeginning()
{
    return Time.time < startTime;
}

```

I think it's just a case of a new set of eyes. But by my logic this should work.

# Answer
> 5 votes
The problem is with your Input detection in OnGUI. Using OnGUI to trigger the Pause function can cause it to be called several times in one frame, which sets your savedTimescale to 0, thus UnPause just resets the Timescale to 0.

On my machine Pause (GetKeyDown(E)) was being called 4 times when the key was pressed.

Use Update() for Input checking, add some boolean checks for whether you are paused rather than just the Timescale value or use GUI Buttons for pause/unpause rather than Input key detection.

```
function Update()
{
  if(inTheZone == true && Input.GetKeyDown(KeyCode.E))
  {
      Pause();
  }

  if(Input.GetKeyDown(KeyCode.N))
  {
      UnPause();
  }
}

```

**Addendum** ::

Thinking about it more, you should probably (always?) use a boolean to check if you are paused as well. Hitting 'E' twice would cause the same issue.

```
var paused : bool = false;
function Pause()
{
    if ( !paused )
    {
        savedTimeScale = Time.timeScale;
        Time.timeScale = 0;
        AudioListener.pause = true;
        currentPage = Upgrade.Main;
        paused = true;
    }
}

function UnPause()
{
    if ( paused )
    {
        Time.timeScale = savedTimeScale;
        AudioListener.pause = false;
        currentPage = Upgrade.None;
        if(IsBeginning() && start != null)
        {
            start.SetActive(true);
        }
        paused = false;
    }
}

```

---
Tags: unity, logic
---


# Question
Title: How do I load graphical resources asynchronously?
Let's think platform-agnostic: I want to load some graphical resources while the rest of the game is running.

In principle, I can load the actual files on a separate thread, or using async I/O. But with graphical objects, I will have to upload them to the GPU, and that can (usually) only be done on the main thread.

I can change my game loop to look something like this:

```
while true do
    update()
    for each pending resource do
        load resource to gpu
    end
    draw()
end

```

while having a separate thread load resources from disk to RAM.

However, if there are many big resources to load, this could cause me to miss a frame deadline and eventually get dropped frames. So I can change the loop to this:

```
while true do
    update()
    if there are pending resources then
        load one resource to gpu
        remove that resource from the pending list
    end
    draw()
end

```

Effectively loading only one resource per frame. However, if there are many small resources to load, loading all of them will take many frames, and there will be a lot of wasted time.

Optimally, I would like to time my loading in the following manner:

```
while true do
    time_start = get_time()
    update()
    while there are pending resources then
        current_time = get_time()
        if (current_time - time_start) + time_to_load(resource) >= 1/60 then
            break
        load one resource to gpu
        remove that resource from the pending list
    end
    draw()
end

```

This way, I would only load a resource if I can do it within the time I have for that frame. Unfortunately, this requires a way to estimate the amount of time it takes to load a given resource, and as far as I know, there are usually no ways to do this.

What am I missing here? How do many games get to load all their stuff completely asynchronous and without dropped frames or extremely long loading times?

# Answer
Let's start by assuming a perfect world. There are two steps to loading a resource: first you get it off your storage media and into memory in the correct format, and second you transfer it across the memory bus to video memory. Neither of those two steps actually need to use time on your main thread—it only needs to get involved to issue an I/O command. Both your CPU and GPU can go on doing other things while the resource is being copied. The only real resource being consumed is memory bandwidth.

If you're using a platform without much of an abstraction layer between you and the hardware, the API probably exposes these concepts directly. But if you're on a PC there's probably a driver sitting between you and the GPU, and it wants to do things its way. Depending on the API you *may* be able to create a texture that is backed by memory that you own, but more likely calling the "create texture" API will copy the texture into some memory that the driver owns. In that case creating a texture will have some fixed overhead and some time proportional to the size of the texture. After that the driver might do anything—it might proactively transfer the texture to VRAM, or it might not bother uploading the texture until you attempt to render using it for the first time.

You may or may not be able to do something about that, but you *can* make a guesstimate of the amount of time it takes to make the "create texture" call. Of course, all the numbers are going to change depending on the hardware and software, so it's probably not worth spending a bunch of time reverse-engineering them. So just try it and see! Pick a metric: either "number of textures per frame" or "total size of textures per frame", pick a quota (say, 4 textures per frame), and start stress-testing it.

In pathological cases, you might even need to keep track of both quotas at the same time (e.g. limit to 4 textures per frame or 2 MB of textures per frame, whichever is lower). But the real trick to most texture streaming is figuring out *which* textures you want to fit into your limited memory, not how much time it takes to copy them around.

Also, pathological cases for texture creation—like lots of tiny textures being needed all at once—tend to be pathological cases for other areas as well. It's worth getting a simple working implementation before worrying about exactly how many microseconds a texture takes to copy. (Plus, the real performance hit may not be incurred as CPU time on the "create texture" call, but instead as GPU time on the first frame you use the texture.)
> 7 votes

---
Tags: graphics, assets
---


# Question
Title: How to Fix Some Portion of bound camera?
I want to add Progress bar with my game to display life of player but when i move down through DigitalOnScreen Control the black bar that i want to display is not displayed there. I want to display that bar when i move in any direction it should be constantly displayed

# Answer
You can use HUD.when move your camera, hud is not move that stable.

```
HUD hud = new HUD();
yourCamera.setHUD(hud);

hud.attachChild(yourBar);

public class GameTest extends BaseGameActivity {
private Camera camera;
private Scene scene;
private HUD hud;

@Override
public Engine onLoadEngine() {
    camera = new Camera(0, 0, Helper.CAMERA_WIDTH, Helper.CAMERA_HEIGHT);
    EngineOptions engineOptions = new EngineOptions(true,
            ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(
                    Helper.CAMERA_WIDTH, Helper.CAMERA_HEIGHT), camera);
    return new Engine(engineOptions);
}

@Override
public void onLoadResources() {
}

@Override
public Scene onLoadScene() {
    scene = new Scene();
    hud = new HUD();
    camera.setHUD(hud);

    Sprite blackBar = new Sprite(posX, posY, yourRegion);
    hud.attachChild(blackBar);

    return scene;
}

@Override
public void onLoadComplete() {
}

```

}
> 1 votes

---
Tags: android, game-design, andengine
---


# Question
Title: What is the point of the XNA.Input.Button enum?
I am trying to make an `InputManager` class that will let me basically bridge XNA's various input methods and do a corresponding action in my game. Part of this is designing different keybindings.

Suppose I have a class `GamePadBinding : InputBinding<Button>` \- this is the `Button` enum from XNA.Input and has a variety of different buttons (Left, A, etc). However, to actually check input, I have to call something like `if (GamePad.GetState(PlayerIndex.One).DPad.Left == ButtonState.Pressed)`, and the problem with that is that it uses a struct with readonly values.

How am I expected to store an enum of type `Button` and compare that with this? I really am not seeing the point of this enum.

# Answer
You can check the button state easier using the `GamePadState.IsButtonUp` and `GamePadState.IsButtonDown` methods. These both accept an `Input.Buttons` parameter.

See the MSDN article.
> 1 votes

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


# Question
Title: Can I switch scenes by swipe gesture or drag？
Can I switch scenes by swipe gesture or drag?

In my game, there are three main scenes, each of them has several layers which have some UI elements, these elements have some tap gesture.

I already know some ways to switch scenes, such as `replaceScene`, or by some transitions ways, just like `CCTransitionMoveInT`, so swiping scenes is feasible or not?

If not, why?

If yes, is it possible to cause memory increases that my gameApp crash?

# Answer
> 1 votes
Use the CCScrollLayer class from cocos2d-iphone-extensions project. It does exacactly what you want except for the scene changing part. Though you don't really need to change scenes here, a single scene with multiple layers works just as well.

---
Tags: cocos2d
---


# Question
Title: 3D models on 2D tilemap perspective when scrolling
I am creating a small top-down game, where the player traverses a 2D tilemap, with an illusion of depth provided by 3D models for things like buildings or trees.

Having gotten to the point where I can render models and a basic terrain as a background, I've gotten stuck on the task of joining both together in a way as to seem not too unnatural.

I think an image description of my problem would be best suited for this. For the sake of explanation, the model I am rendering is a transparent cube.

In this position, where the camera has a head-on view, everything looks generally normal. Now, if I shift the model a bit to the right, the following gets displayed:

Not horrible by any means, but it does look a tad bit awkward: the road remains straight while the building seems to be jutting out from the path. The building itself has been panned, but the ground has remained static. Additionally, this has proven rather nausea-inducing during testing, due to the awkward mixing of angles.

The only possible solution that came to me (and hence why I am asking here) would be to render each tile as a model as well. I think that creating a flat rectangle the size of the viewable screen and texturing it with the visible tiles could possible work: that way, since it is a model, it can be rotated and shrunk based on visibility, like the model.

However, I am (very) new to OpenGL, and I fail to see how I could implement this. I know that I can draw a textured rectangle with *one, solid texture*. I don't know how to draw multiple, smaller textures across a face of the rectangle: is it even possible?

Then, considering that I wish to have other things like cliffs, I wondered if cliff tiles could be rendered as being slanted. My map format has a height map, so the slant could be determined by the direction in which the nearest tile with a smaller height resides.

I fear I'm being rather clumsy at explaining this, which is why, using my most Picasso-esque skills I have put together the next image:

Essentially, though the map itself is made up of 2D tiles, by changing the angle they are being rendered at I reckon it would be possible to simulate a 3D effect: the player camera (smiley in the image) would not be able to see the leftmost side (yellow) if they are positioned towards the right.

Regardless, this is all hypothetical and I have no idea where to even begin. Is it possible to render the background as essentially a model in 3D space? If so, how would this be done: via one large cuboid, or multiple smaller ones? Lastly, would slanting textures based on neighbor height work? More importantly, is there a better way to achieve my goals than what I have proposed?

For all it matters, I am writing this game in Java, utilizing the LWJGL OpenGL wrapper.

# Answer
> 5 votes
What you are asking for is completely doable, as you initially wanted: 3d on 2d. You just got the camera angle wrong. For CG cameras, the perspective is almost always linear (as opposed to say, fish-eye) so all you need to do is have the camera looking straight down.

The best example I can think of is the early GTA games, which had simple 3D models for the buildings on top of sprites/tiles for everything else:

# Answer
> 4 votes
As Cong Xu points out it is fully possible to do this effect, as GTA 1 & 2 did. What he fails to mention is that the 2d part is part of the 3D scene. You don't need to fake the 3D effect, you have a graphics card that can compute that on the fly.

How do you do the 2d stuff? Simple you have a quad that contains one texture. So if you have multiple tiles, you render one quad per title. Don't worry about the performance, the graphic card can handle that many. The quads are all in a 2D plane, for example the xy plane. (z=0)

You can also render other 2D objects on top of the ground by rendering more quads where the objects should go. The only thing you need to consider, is that you disable **depth testing** for the 2d stuff. You can also render non square objects by using **alpha blending**. You image has a transparent area, you render the quad and only the bits that are not transparent are added to the scene.

Then for the 3D objects you enable depth testing and render them normally.

At this point the camera angle does not have to be perfectly down. You can slant the camera slightly froward as you showed in your little sketch. Just don't go to far or the 2d effect will be to obvious.

A final note about lighting. To get 3D objects that look 3D you might want to use one or two directional lights. If you do, you need to disable the lighting on the 2d bits, because that will ruin the 2d effect.

---
Tags: opengl, java, 3d, lwjgl, tilemap
---


# Question
Title: What available multiplatform languages are there available for 2D games
I was wondering what multi-platform languages are available that could be used to create and deploy 2D games, please note that im not asking which is the best as I do not want to cause arguments over which people believe to be the best.

Ideally I would like to be able to deploy to as many different platforms as I can (PC, Mac, iPhone, Android, etc..)

I do apologies if this has been bought up, but I could not find anything from the searches that I tried.

# Answer
> 4 votes
* You could also use HTML5 Canvas element and JavaScript (or languages compiled to JavaScript, such as Java, Dart, ClojureScript, TypeScript, CoffeeScript). While not specifically created for games, it's suitable. You can deploy your project on Macs, Linux, Windows, Android, iOS.
* Flash with ActionScript: it used to be standard de-facto for games for web in mid 2000, it's still supported on mobile platforms via Adobe AIR. Macs, Windows, Android, iOS.
* Lua, used a lot in game industry for utility and scripting, but there is number of frameworks, with Corona SDK or LÖVE
* Java is supported almost everywhere except iOS, you should be able to deliver your product (unless you use esoteric bindings) on Linux, Windows, iOS, Android. Libgdx – Is pretty mature framework that supports Android, Windows, Mac OS, Linux and Web. Alternatively, you don't have to use Java, but can use Scala, Clojure or Groovy etc. (or any combination of those) and deploy to JVM.
* /C++ Simply standard de-facto, works everywhere except web. While there is ways to compile C/C++ code to JavaScript and AVM (Flash Player bytecode) I would advise against it. C/C++ is probably most popular languages when we talk about console games.
* C# with MonoGame an Evolution / rewrite of XNA that allows you to port one code base to many platforms. Alternatively, you can look into Unity platform.

There is good reasons for and against each one of them. C/C++ would open to a world of bigger tripple a games if you choose to pursue this carrier. HTML5/JavaScript, Corona/Lua and Flash/ActionScript will allow you to start implementing game really quickly, and rather easy languages to code. Java I guess somewhere in a middle, but it will require full rewrite if you choose to deploy your application on iOS.

---
Tags: 2d, cross-platform
---


# Question
Title: Would a custom mod built for RakNet be automatically usable with Unity?
Context: I'm interesting in developing a security module for servers that handle mobile games, and I'd like it to be usable by the most people possible. So I'm trying to decide what server software I want to build it for.

I'm looking at RakNet, and it's appealing because it's available two ways: independently and as part of the networking solution of Unity3D. So it's software that gets used by developers who want to use Unity3D as well as those who don't.

My question: if I create a modification that implements my security system inside RakNet, will that solution be automatically compatible with Unity also?

# Answer
> 1 votes
No, the Unity usage/implementation of RakNet is not open to the end user of Unity.

---
Tags: unity, networking, security
---


# Question
Title: Actionscript 3: Which side of object is hit?
I have a two objects colliding with each other. I am testing for the collision with `if(ob1.hitTestObject(ob2)){//do something }`. Is there a way to determine which side of the object was hit, i.e. if ob2 is a square, which side of the square was collided with?

# Answer
The hitTest method provided by flash won't give you such an information.

If you have two squares, you can simply calculate the vector between their center-points and use that to determine the side. For arbitrarily shaped objects, this won't work though.

Another option is to have "sensor" points on your object, eg. *top*, *left*, *right*, *bottom*, and do a hit-test for each of these points against the other shape.
> 4 votes

# Answer
What the `.hitTestObject()` function does is compare the position and transformation of objects to see if the object's bounding boxes overlap at all. If you require more precise collision than that, it is usually better to test for collision between an object and various points on the other object using the `.hitTestPoint` function.

For example in your scenario you take collision with certain points to mean that the object has collided against a certain side of the object.
> 3 votes

# Answer
In 2D you can know which side of a segment is a point using the signed area of a triangle.

Let :

* P any point to test against the segment
* AB the segment formed by points A & B.

> ```
> SignedArea = (Bx-Ax) * (Py-Ay) - (Px-Ax) * (By-Ay);
>
> ```

The SignedArea will be positive if ABP are oriented counterclockwise around the triangle, and negative if oriented clockwise.

Thus,

* if **SignedArea is positive**, the point P is on the **LEFT side** of the segment AB (seen from A to B)
* if **SignedArea is negative**, the point P is on the **RIGHT side** of the segment AB (seen from A to B)
* if SignedArea is 0, the point P is on somewhere one the "line" (not necessarily the segment)

---

In 3D you can know which side of a surface is a point using dot product and cross product. But as I guess your problem is a 2D problem, this should not be required.
> 1 votes

---
Tags: software-engineering, collision-detection, actionscript-3
---


# Question
Title: How can I manage large numbers of objects in a physics engine?
MY friend and I are programming a game and I decided to give the physics engine a try. I was able to get a class working where it would calculate out the total force on a model and apply the correct acceleration, velocity, and position during each time step.

My question is how do I implement this over many objects when the game starts to get big. Is there just one class managing all the physics calculations for each object or do you attach the physics engine class to each object in the game so that they update and manage their own physics?

I've looked through some code and I usually see people putting the velocity, acceleration, and position calculations right on the object itself. But somehow I think I'm getting the wrong interpretation of this and I think on a large scale, this would be very inefficient.

We don't want to use a pre-built physics engine because we want to learn about how this all works.

# Answer
> 3 votes
You typically do this with some kind of spatial partitioning. You only check objects against other nearby objects, and you don't need to update any objects that are far away from or behind the camera in many cases.

A relatively easy spatial partitioning scheme to get you started is an octree. Make a box around the world. All objects in it. When the box gets too full based on some pre-determined threshold, break the box into 8 sub-boxes and move each object into the appropriate sub-box (each box is a node in a tree, and only leafs contain objects). Do this recursively down to some reasonable minimum size. Objects can only collide with other objects in the same box or objects in adjacent boxes. When there are enough objects in your world, there will also be a number of divisions in your octree, keeping far-apart objects in separate, non-adjacent boxes.

You can also relatively easily check if any box collides with your view frustrum, and recurse through the tree, marking which boxes are visible, near visible, and completley invisible. You can use this to stop physics processing for areas far away from the camera. You can also use this same information to despawn enemies and items or disable AI updates. Instead of stopping physics/AI, you can reduce them so that they still udpate but take less time.

This information is also very useful to graphics to help you avoid rendering scenery and objects that can't be seen.

There are other, more efficient spatial structures, but which one is best depends on lot on your game. A very different set of techniques is useful for an indoor FPS vs a top-down RTS vs a wide-open terrain FPS, which is why many engines today support more than one, and evne allow mixing them together (e.g. for smooth transitions from the outdoors to indoors, where the algorithms of choice differ). For learning, stick to something simple like an octree. You have far, far more complicated problems to solve in getting 3D physics to work well.

# Answer
> 1 votes
I usually store a 'physicsState' object (mass, momentums, force accum, torque accum) in each movable object and use one physics engine object to crunch everyone's numbers. If the object had zero linear or angular momentum I put it to sleep and stop processing it's numbers until it starts motion again.

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