# Question
Title: Solving 2D Collision Detection Issues with Relative Velocities
Imagine you have a situation where two objects are moving parallel to one-another and are both within range to collide with a static wall, like this:

```
  => 20m/s     => 40m/s
+==========+ +==========+          +======+
| Object A | | Object B |          | Wall |
+==========+ +==========+          +======+

 |-- 1m --|   |-- 1m --|  |- 1m -|

```

A common method used in dynamic collision detection is to loop through all objects in arbitrary order, solve for pair-wise collision detection using relative velocities, and then move the object to the nearest collision, if any.

However, in this case, if object A is checked first against B, it would see that the relative velocity to object B is -20 m/s (and would thereby not collide this time frame). Then it would see that the object A would collide with the static wall, and the solution would be:

```
+==========++==========++======+
| Object B || Object A || Wall |
+==========++==========++======+

```

And the red object passes through the blue one. So it appears to be a matter of choosing the right order in which you check collisions; but how can you determine which order is correct? How can this passing through of objects be avoided? Is ignoring relative velocity and considering every object as static during pair-wise checks a better idea for this reason?

# Answer
> 5 votes
This is a very complicated problem, and is better known as the "box stacking" problem. Even without moving objects, a stack of boxes will jitter and collapse in all simple physics engines.

There are a number of steps to a proper solution. The most important is to use an iterative solver.

That means that you don't just resolve the collisions in single pass. You do multiple passes, accumulating the impulses necessary to push the boxes apart. The end result will still be imperfect, but the amount of error will be much smaller, possibly unnoticeable.

The math is a bit trickier as you do need to deal with impulses and forces rather than just pushing the boxes apart and adjusting velocity. You *can* do it by just adjusting the values, but it's unlikely to work satisfactorily for any cases but the simplest.

Erin Catto has done a number of talks and papers on the basic techniques, which i believe are available on the Box2D website (http://box2d.org/) if you dig around enough.

# Answer
> 2 votes
this is really 2 different conditions that you are asking about:

> "how do I know if a collision was supposed to happen, but didn't"

and

> "how do I resolve multiple collisions on the same object from different sources"

for bother there are 2 different approaches that come to mind to either avoid, or mitigate the situation: adding a pre-collision raycast system, and grouping collisions together.

for the pre-collision raycast this basically uses the objects current velocity, and uses that as a ray-length, and if another object touches that ray then next frame there "might" be a collision between them. I say might because if both objects are movable then there is a chance that the object will move out of the way, but this should be a trivial concern if have a multipass collision handling system.

for the grouping of collision this can either be used independently, or in conjunction with the pre-collision raycasting, or can be taken from a spacial-partitioning/hierarchy system. where if there is at least one collision then the objects that are around that collision by a determined value (this could be found statistically, or by trial, and error), and they are included in the collision system, and the entire system is solved (or attempted to be solved) all at once.

on the immediate situation I would say that the pre-collision raycasting would be most beneficial.

Though if your completely convinced that pre-collision raycasting is unusable, or to much overhead, and the case of objects passing each other is of great concern then you could log the position of each object the frame before, and then determine if a collision happened somewhere in the middle. though what I have found is that this in the long run is more costly, and only works a fraction of the time. not to mention having the problem that you are making your collision resolution system do a "lot" of guess work on how to resolve the collision that it does not have solid data on.

# Answer
> 2 votes
> A common method used in dynamic collision detection is to loop through all objects in arbitrary order, solve for pair-wise collision detection using relative velocities, and then move the object to the nearest collision, if any.

An alternative solution I employ in a game I am working on, is having a sorted event queue (sorted according to time). When calculating the next frame, I simply fast-forward the game-time to the first event in the queue, handle the event, and add any new events resulting from this event to the queue. This is repeated until the time is equal to the current frame time.

If the event is a 'collision' event, I find the first intersection time between the colliding object and any other object, and return this new event. This event then gets added to the queue, and this event will be evaluated first, instead of the event that was invalidated.

I then allow objects to keep track of collision events involving themselves, and when they collide, all of these events are marked as 'invalid' (e.g. removed from the queue, or ignored when they are evaluated in the key).

This creates a deterministic system in which events will always happen as expected.

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


# Question
Title: Can game designers or developers be addicted to online games?
Do game designers/developers play as much as hardcore gamers, and could they be considered addicted? In the clinical addiction sense. If yes, is it good or bad? If not, is it called enthusiasm?

I'm asking to know how developers / designers feel about the question is video game addiction.

# Answer
> 3 votes
Hardcore gamers and game developers, of course! As with many aspects in life, there's some overlap. See above. (note, the center area does not mean they develop hardcore games, it means *they are hardcore*.)

The latter part of your question is discouraging. Faith in humanity discouraging. **Clinical addiction of any kind is bad**. You seem to think it's some kind of joke. It's not. Even though you're talking about games. Addictions to computer games, like addictions to other things, tears families apart and ruins people's lives. Would you call that enthusiasm? Nope.

---
Tags: game-design
---


# Question
Title: Make a CCSprite come up from bottom of the screen in intervals
I have a cocos2d iOS app. I have a CCSprite that I need to come up from the bottom of the screen every few seconds (like 2 or 3 seconds). How would I do this?

# Answer
> 1 votes
Read these tutorials (the beginner ones). Your question sounds like you're getting ahead of yourself. If you don't know how to move a sprite, or time things or do things in intervals, you shouldn't be asking how to do all three at the same time. Take a step back, get comfortable with the basics. If you have a specific issue you're having trouble with, post another question here and we can help.

---
Tags: iphone, cocos2d-iphone, cocos2d, ccsprite
---


title: iPhone game development

text:
# Question
Title: iPhone game development
I am new to the iPhone game development. How can I develop a simple game by using cocoa2D. and I want to know more about Cocoa2D.

# Answer
How To Make A Simple iPhone Game with Cocos2D Tutorial http://www.raywenderlich.com/352/how-to-make-a-simple-iphone-game-with-cocos2d-tutorial
> -2 votes

---
Tags: cocos2d-iphone
---


# Question
Title: How do I determine if one polygon completely contains another?
I have 2 polygons. I know the vertex coordinates of both polygons. What's the best way to check if one is completely inside the other? For example, the algorithm should only recognize the *black trapezoid* below as being contained:

# Answer
There are tons of source snippets for a method that performs a test for "point inside polygon". The principle comes from Jordan's curve theorem for polygons (http://www-cgrl.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Octavian/compgeom.html).

The naive way would be: having that method, call it `PointInsidePolygon(Point p, Polygon poly)`:

```
  bool isInside = true;
  for each (Point p in innerPoly)
  {
    if (!PointInsidePolygon(p, outerPoly))
    {
      isInside = false; // at least one point of the innerPoly is outside the outerPoly
      break;
    }
  }
  if (!isInside) return false;
  // COMPULSORY EDGE INTERSECTION CHECK
  for each (innerEdge in innerPoly)
    for each (outerEdge in outerPoly)
    {
      if (EdgesIntersect(innerEdge, outerEdge))
      {
        isInside = false;
        break;
      }
    }

  return isInside;

```

Theoretically, it shouldn't miss any scenario for your polygons, but it's not the optimal solution.

**"Edge" case remarks**

* `PointInsidePolygon(..)` must return true if the point is on the border of the polygon (either lies on an edge or is a vertex)
* `EdgesIntersect(..)` must return false if the `innerEdge` is a subset (geometrically-wise) of the `outerEdge`. In this case, the edges obviously intersect, but for the purpose of the algorithm, we need to indicate that the intersection is not breaking the semantics behind the `isInside` variable

**General Remakrs**:

* without edge vs edge intersection checks, as pointed out in the comments, the approach might return false positives for some concave polygons (e.g. a V shaped quad and a rectangle - the rectangle might have all of its vertices inside the V shape, but intersect it, thus having at least some areas outside).
* after one checks for at least one of the vertices of the inner polygon to be inside the outer one, and if there are no intersecting edges, it means the sought after condition is satisfied.
> 6 votes

# Answer
Try doing a line intersection with each red line. In pseudocode:

```
// loop over polygons
for (int i = 0; i < m_PolygonCount; i++)
{
    bool contained = false;

    for (int j = 0; j < m_Polygon[i].GetLineCount(); j++)
    {
        for (int k = 0; k < m_PolygonContainer.GetLineCount(); k++)
        {
            // if a line of the container polygon intersects with a line of the polygon
            // we know it's not fully contained
            if (m_PolygonContainer.GetLine(k).Intersects(m_Polygon[i].GetLine(j)))
            {
                contained = false;
                break;
            }
        }

        // it only takes one intersection to invalidate the polygon
        if (!contained) { break; }
    }

    // here contained is true if the polygon is fully inside the container
    // and false if it's not
}

```

However, as you can see, this solution will get slower as you add more polygons to check. A different solution could be:

* Render the container polygon to a pixel buffer with a white color.
* Render a child polygon to a different pixel buffer with a white color.
* Mask the container buffer over the polygon buffer with a XOR mask.
* Count the number of white pixels; if it's greater than 0 the child polygon is not fully contained by the container.

This solution is very fast, but it depends on your implementation (and what you want to do with the result of your check) what solution works best for you.
> 2 votes

---
Tags: collision-detection, vector, geometry
---


title: Javascript Audio solution

text:
# Question
Title: Javascript Audio solution
still has issues. Flash works but... requires flash (an issue for iOS). What do you use in Javascript for audio?

# Answer
I tried HTML5 audio on my first game but I could not get it to work perfectly (lag for the first time the sample is played etc).

SoundManager2 looks ok and I tried it a bit in a demo. For the next game I will use it as it has functionality to fall back to HTML5 audio in case Flash is not available.
> 4 votes

# Answer
From what I gather, HTML 5's audio potential has a long long way to go. Firefox 4 Beta apparently has a cool audio API but it's going to be a little while before we see the major browsers provdie comprehensive support for the W3C Web Audio API Standard
> 4 votes

# Answer
As of recent Google Chrome updates (13.0.782.32) the HTML5 audio tag has been working perfectly for me.
> 2 votes

# Answer
Both Webkit (specifically chrome) and Firefox have come a long way since this question was asked:

http://chromium.googlecode.com/svn/trunk/samples/audio/index.html

https://wiki.mozilla.org/Audio\_Data\_API#Working\_Audio\_Data\_Demos

Google's recent recreation of the moog synth using webkit's audio context API made me decide to finally try to build something for webkit. They used a flash fallback for other browsers, and I may do that or I may just wait until the browsers standardize an API for audio and then adapt to whatever that is. The real question is: how soon does this need to be ready? For me, it's experimental and for fun and resume building, so I don't care if I don't have a shippable product for a year or so. But if you need it to work on all browsers NOW, flash is the safest bet. See this article regarding the IE dev team and why they had to use flash audio for Cut the Rope:

http://creativejs.com/2012/01/why-cut-the-rope-uses-flash/
> 2 votes

---
Tags: javascript, html5, audio, browser-based-games
---


# Question
Title: How to determine counter-clockwise vertex winding
I've been causing myself some confusion lately with regards to vertex winding in a mesh class that i'm writing.

Currently, the mesh contains the appropriate structures for:

* vertices (vector3)
* indices (vector3 - actually a custom struct of 3 ints)
* normals (vector3)
* colors (vector4)

Starting out simple, i'm trying to model a cuboid with 24 vertices and 12 indices. What is causing me confusion at the moment is how vertex winding is determined for each face. OpenGL-ES seems to be set to counter clockwise winding by default (which can be changed) but i'm really not sure how CCW is determined in 3 dimensions?

It was my understanding that the "front" and "back" of an object would be defined by the direction of the vector for each vertices normal, rather than the ordering of each vertex that defines a "face". It would seem however that this isn't true. Either that, or (more likely) my code isn't entirely correct.

If this isn't the case, how is CCW defined in 3 dimensions? How does this translate for the 6 faces of a cuboid? If I use the same logic for the back face of the cuboid as the front face, surely one of the faces would point inwards?

I'm really struggling to get my head around this when manually defining vertices for my mesh. The confusion really kicks in when I try to work out how vertex data is stored in a model/mesh file created by MAYA or Blender etc. Are all faces oriented outwards when an object is exported?

Or perhaps my original assumption was correct whereby the normals define what is to be determined as the front of each face, but then why does OpenGL have a flag for specifying the vertex winding order?

Also, considering the three vectors A, B and C; surely the same winding (regardless of orientation) could be achieved in three different ways, i.e: A-\>B-\>C or B-\>C-\>A or C-\>A-\>B?

Is there a simple way for determining such things or have I completely missed the mark somewhere?

# Answer
> 3 votes
OpenGL actually has two sets of normals for every face: one you supply with the `GL_NORMAL` vertex attribute and one it determines with the winding. This second normal is used to discard faces in backface culling and is determined through the following formula:

```
// http://glm.g-truc.net - OpenGL Mathematics library

glm::vec3 a, b, c;
glm::vec3 ab = b - a;
glm::vec3 ac = c - a;
glm::vec3 normal = glm::normalize(glm::cross(ab, ac));

```

If you are confused about the winding of your vertices, try calculating this normal yourself and rendering it on your faces. You can then easily spot where you made a logical error.

**EDIT:**

Suppose you have a set of vertices and you absolutely have to make sure what the winding is.

Given the face `P` with vertices `a`, `b` and `c`.

```
// calculate three axes

glm::vec3 axis_x = glm::normalize(b - a);
glm::vec3 axis_y = glm::normalize(c - a);
glm::vec3 axis_z = glm::cross(axis_x, axis_y);

// construct a transform matrix from our axes

glm::mat3x3 object_transform;
object_transform[0] = axis_x;
object_transform[1] = axis_y;
object_transform[2] = axis_z;

// invert the matrix

glm::mat3x3 object_to_world_transform = glm::inverse(object_transform);

// transform the outward normal using the matrix

glm::vec3 normal = object_to_world_transform * axis_z;

// check winding

if (normal.z > 0.f)
{
    // Counter-clockwise winding
}
else
{
    // Clockwise winding
}

```

Note: I didn't have time to check this! I might have reversed the check for winding at the end. I'll edit when I get home.

# Answer
> 4 votes
It isn't a 3 dimension problem really. The triangle lies on a plane. When visualizing winding order, you change (in your mind's eye) from a 3 dimensional world, to the 2 dimensional world **of the plane** that the triangle lies on.

No matter what order you set the indices, on one side of that plane the winding is CW, the other, it is CCW.

Whichever side has the winding order the graphics device is expecting, that side only will be drawn.

---
Tags: opengl-es, vertex
---


# Question
Title: Is it possible to index different vertex attributes with different index buffers?
Let's say I've got a vertex which is part of many triangles. I can just reference those with an index buffer. But is it possible to share it's position but have different texture coords for each triangle? e.g.

```
+--+--+
|\ |\ |
| \| \|
+--X--+
|\ |\ |
| \| \|
+--+--+

```

The center vertex, X, is shared. If I want each square to have a different texture then I would need to store four distinct UV coordinates for the centre vertex. Is this only possible by creating it four times?

# Answer
No, this is not possible.

A vertex is defined as a set of properties:

* 1 position
* 0 or more texture coordinates
* 0 or more normals

Unfortunately, you can only use 1 index per vertex. You cannot have an index for positions, an index for texture coordinates and an index for normals.

So if you want to share a vertex between two triangles, where the only difference is the texture coordinate, you will have to create two vertices: one for each triangle.
> 2 votes

# Answer
No, it isn't. The GPU only supports the concept of a single index buffer being bound at a given time; graphics APIs expose this fact by only providing scalar methods for setting index buffers (that is, they only let you set one at a time).

In general this isn't a concern, although it seems wasteful at first glance. Most complex 3D models wouldn't be able to share a significant portion of their non-position vertex attributes anyhow -- things like cubes are a pathological case.

It also shows up when you're building grid planes for things like tiled backgrounds in 2D games, but in such games the footprint of your geometry overall is generally much smaller so the minor waste that occurs in the data duplication isn't usually worth noting. If it ever does become problematic there are higher-level approaches to reducing the geometry set that can be applied (such as rendering fewer tiles).

The architecture of GPUs has advanced to a point where theoretically this wouldn't be a terribly difficult feature to support in some new hardware, but the sheer lack of demand for it from any major players means the cost/benefit ratio isn't in anybody's favor.
> 1 votes

---
Tags: xna, textures
---


title: Best way to use Raknet from C#?

text:
# Question
Title: Best way to use Raknet from C#?
I am trying to learn Raknet with C# and I found it extremely confusing.

The Raknet tutorial seems to work well in C++. I have already made the chat server from the tutorial.

I am looking to do something similar in C# but I'm having trouble.

So my main question is **what is the best way to use Raknet from C#?**

The following information would also be very helpful:

* A good tutorial for Raknet *and* C# together
* Sample C# code for Raknet

I've done a lot of research but I'm still stuck.

Maybe Raknet isn't what I need after all? Comments with more C#-centric alternatives would also be appreciated.

# Answer
Everything you need can, more or less, be found on the official site,

* **raknet.com/raknet/manual/**

There, they also have an official tutorial for using RakNet in C#, which is based on SWIG (just like raknetdotnet):

* **jenkinssoftware.com/raknet/manual/swigtutorial.html**

You may be interested in lidgren, which is written in C#:

A basic but complete tutorial for starters can be found here:

Good luck!
> 7 votes

---
Tags: c#, raknet
---


title: Change density of the body dynamically

text:
# Question
Title: Change density of the body dynamically
In my game, I want to change density of my body object when it collide with other objects. I found something like following to change density but further I could not able to find any hint for this. So someone please help.

```
Fixture fixture = goldenBoxArrayList.get(i)
                                        .getGoldenBoxBody()
                                        .getFixtureList().get(0);
                                fixture.setDensity(0.5f);

```

After setting fixture data I could not able to set it to the body.

EDIT : I want to change my object body density when physics world in simulation

# Answer
> 4 votes
I'm not sure about AndEngine but in Box2D you can call the following functions:

```
fixture->SetDensity(5.0f); //this fixture is attached to body below
body->ResetMassData(); //must call this after changing density

```

AndEngine's physics is just a JNI wrapper around Box2D so it should support all or a subset of Box2D features.

Also check *7.4 Using a Body* of Box2D manual, its possible to override mass data calculated from fixtures on a body using:

```
void SetMassData(const b2MassData* data);

```

---
Tags: java, android, physics, andengine
---


# Question
Title: What cryptography algorithm I can use in my game?
In my game I have data like items, enemies, tools, craft formulas, etc. I want store this information on disk securely. What algorithms I can use for free? I currently store my data using the JSON format.

I'd also like to encrypt the data I transmit for my multiplayer mode to keep it safe.

# Answer
> 4 votes
How do you store your data now? Presumably you have a bunch of setting files or even XML. Let's say your data looks like this:

```
<Character name="Jim-Bob the Peasant">
    <Item name="Shirt">
        <Protection>1</Protection>
        <Weight>1</Weight>
    </Item>
    <Item name="Belt">
        <Weight>1</Weight>
    </Item>
    <Item name="Pants">
        <Protection>1</Protection>
        <Weight>2</Weight>
    </Item>
    <Item name="Shoes">
        <Speed>2</Speed>
        <Weight>1</Weight>
    </Item>
</Character>

```

Before you go out and start encrypting your datafiles, I would strongly suggest you first establish an intermediate format like the one I gave you. Why? Because then you have a file that you can read and edit using any text editor. When you have an encrypted file, you can only access it using your game and any tools you write.

But on to the question at hand: how do you protect this data from tampering in a multiplayer game?

Remember the golden rule of multiplayer programming: **Never trust the client.** Clients lie, all the time.

So the first step would be to verify that the server's datafile is exactly the same as the client's datafile. An easy implementation would be to hash the file using MD5. If the hashes don't match, the client has tampered with his file.

You'll note that the datafile we have now is very high "noise-to-signal": a lot of the bytes aren't for data, but for human-readability. We can improve that by compressing the file until only the raw data is left, by making a binary format.

* First, let's write a header for our custom format. Let's write the bytes "ITE" to show that this is a ".items" file.
* Next, write the name of the character and end with a 0.
* Then, write the properties of each item: name, protection, weight, speed.

Here's what it looks like in 010 editor:

You can see (with a bit of trouble) that every string ends with 0 and that for every item, we have a byte for protection, weight and speed.

Our datafile just went from 327 bytes (intermediate) to 58 bytes (binary)! But it came at a high price: it's now very hard to read what's going on and even harder to add new properties. But it gives us access to all kinds of neat tricks:

* Encoding the data with a XOR-key, so only if you have the key will you be able to read the data.
* Compressing the data further with run-length encoding, zlib or some other custom implementation.
* Shuffling the bytes around.

However, each of these encryptions comes at a cost: you first have to decrypt the file in memory before you can use it. And that's fine for files that are 58 bytes, but if you have 5 MB files and you have 100 of them, that could become a problem.

P.S. Your English is fine. ;)

# Answer
> 5 votes
If you're interested in cryptography, run over to Coursera and sign up for Dan Boneh's Cryptography class. It'll teach you all about the fundamentals, how to secure various forms of communication, etc.

Key take-away points:

* do not invent your own algorithms
* use an existing crypto library
* use existing crypto techniques

# Answer
> 1 votes
Possible duplicate of this question ?

First of all, you may try to serialize your data structure and save it in a binary format, probably also try to obfuscate it with some useless data. Now, the client must try to reverse engineer it.

Of course, that is not enough, and now it's time to encrypt this data. I believe that ANY cryptographic library would do, as you don't really need anything tailored to gamedev. You can test it and see if you should focus on size or speed. For example, in C++, you can use these libs:

* stackoverflow.com/questions/2250650/encryption-of-objects-stored-to-disk-using-c-for-a-java-developer
* cryptopp.com

You can use a (private) tool to convert the serialized data into a human-readable form, simplifying your work :)

# Answer
> 0 votes
Like others have mentioned: You can't trust the client. All MMOs, Battlefield \*, Diablo 2&3, etc, all store their characters online because there is no way to secure the client's files against malicious users.

Hackers, and the like, will always try to find the weakest point to make their modifications. In this system, I can already tell that the weakest point would be memory injection, and memory injection is easy stuff. Changing your gold, your XP, and other numeric values is trivial. There are only 3 ways to fight against memory injection that I know of.

1. Use VAC or PunkBuster
2. Don't trust *anything* the client says, *ever*, and store sensitive information on a server, *and* actually run the game on the server (like any MMO, BF\*, and D2/3). If the server is running the game, the clients can only send commands like "attack this thing" or "move here". The server inputs these commands into the game, and *the game* hands out XP and money and all of that other good stuff.
3. Put your game on a locked-down hardware device knowing that *most* users won't have access to your precious files, but those people who have unlocked their device will be the same group of people who are able and willing to hack your game.

Encrypting the client's files will only stop people from using a text editor, but so will simply compressing the data in a zip file. I would simply recommend that you store your data files in a binary file, maybe compress it or use a simple encryption algorithm to fend off casual tinkerers. It would still be harder to crack open that file than it would be to open up TSearch and give myself a million dollars.

---
Tags: encryption
---


# Question
Title: Can't export Blender model for use in jMonkeyEngine SDK
I have a scene rendered in blender called "civ1.blend" which contains multiple materials (for example, I have one called "white"). I want to use this model in jMonkeyEngine, so I used the OGRE exporter to create .scene and .material files. This gives me, for example, a civ1.scene file and a white.material file.
However, when I then try to import civ1.scene into the jMonkeyEngine SDK, I get an error along the lines of "Cannot find material file 'civ1.material'". Like I said, I have a white.material file, but I do not have a civ1.material file. Did anyone encounter this problem? How do I fix this?

# Answer
For those who had the same problem I did, where you've installed the OGRE exporter in Blender 2.6 but still don't get .material files, the reason for this is in the configurations. When you are in the export menu (File \> Export \> Ogre3D), in the lower-left corner there are configurations. By default, "Separate Materials" is checked. Uncheck this and you're ready to go!
> 5 votes

---
Tags: ogre, blender, jmonkeyengine
---


# Question
Title: How would I move an object using its velocity on a closed curve?
I want that an object follows a path, in Peggle game there are some pegs that have movement in a closed path. How can i get the same result? I guess that I can use parametric curve but I need use the velocity and not the position (x, y).

I use NAPE and I have this in my gameloop:

```
//circunference
angle = angle + 1*(Math.PI / 180);
movableBall.position.x = radius * Math.cos(angle)+ h;
movableBall.position.y = radius * Math.sin(angle)+ k;

```

It works but I can not control the velocity, each `movableBall` must have its own velocity. Besides, from docs of NAPE:

> "Setting the position of a body is equivalent to simply teleporting the body; for instance moving a kinematic body by position is not the way to go about things.."

I want to use:

```
movableBall.velocity.x =??
movableBall.velocity.y = ??

```

The final idea is to follow others paths like the Lemniscate of Bernoulli.

# Answer
> 1 votes
You can just fake this by finding the next point along the curve for some t increment, calculating the velocity vector to get to that point, and going from there. You'll need to tweak the t increment values to get smooth looking animation, but it'll work. Your objects should not be moving so fast that they'll skip over even sharp turns in your paths, even with the estimates t values.

You can do it the "right way" by actually calculating the desired t value for a given linear speed. Then youll get the exact point to aim for for next frame. You'll need to do some heavy math to solve this though, alon the lines of https://www.math.lsu.edu/~madden/M2057s2004/speed.pdf. Personally, I'd go for the hacky estimation solution, since this is a game and not a scientific particle simulation.

Remember, games are rarely about being physically correct; they're about looking correct enough to fool the player into thinking they're physically correct. :)

# Answer
> 1 votes
A parametric curve sounds OK. At specific `t` calculate the `x` and `y` coordinate for the object. Then update the object's position. The velocity will control the interval you update this. I think this should make your object follow the parametric curve.

---
Tags: curves
---


title: Which techniques to study?

text:
# Question
Title: Which techniques to study?
Just to give you some background info, I'm studying a programming major at a tertiary level and am in my third year, so I'm not a newbie off the street. However, I am still quite new to game programming as a subset of programming. One of my personal projects for next semester is to design and create a 2D platformer game with emphasis on procedural generation and "neato" effects (think metroidvania). I've written up a list of some techniques to help me improve my personal skills (using XNA for the time being). The list is as follows:

1. **QuadTrees:** Build a basic program in XNA that moves basic 2D sprites (circles and squares) around a set path and speed and changes their colour when they collide. Add functionality to add and delete objects of different sizes (select a direction and speed when adding and just drag and drop them in).
2. **Particles:** Build a basic program in XNA in which you can select different colours and create particle effects of those colours on screen by clicking and dragging the mouse around (simple particles emerging from where the mouse is clicked). Add functionality where you can change the amount of particles to be drawn and the speed at which they travel and when they expire. Possibly implement gravity and wind after part 3 is complete.
3. **Physics:** Build a basic program in XNA where you have a ball in a set 2D environment, a wind slider, and a gravity slider (can go to negative for reverse gravity). You can click to drag the ball around and release to throw it and, depending on what you do, the ball interacts with the environment. Implement other shapes afterwards.
4. **Random 2D terrain generation:** Build a basic program in XNA that randomly generates terrain (including hills, caves, etc) created from 2D tiles. Add functionality that draws the tiles from a tileset and places different tiles depending on where they lie on the y-axis (dirt on top, then rock, then lava, etc).
5. **Randomised objects:** Build a basic program in XNA that, when a button is clicked, displays a randomised item sprite based on parameters (type, colour, etc) with the images pulled from tilesets. Add the ability to save the item as an object, which stores it in a side-pane where it can be selected for viewing.
6. **Movement:** Build a basic program in XNA where you can move an object around in an environment (tile-based) with a camera that pans with it. No gravity. Implement gravity and wind, allow the character to jump and fall with some basic platforms.

So my question is this: **Are there any other commonly used techniques that I should research**, and can I get some suggestions as to the effectiveness of the techniques I've chosen to work on (e.g., don't do QuadTree stuff because *\[insert reason here\]*, or, do *\[insert technique here\]* before you start working on particles because *\[insert reason here\]*)?

I hope this is clear enough and please let me know if I can further clarify anything!

# Answer
> 2 votes
I think you are looking at it from the wrong angle, ie if you were planning a trip, you would be placing the horse cart ahead of the horses.

Game design is not about programming, some people enjoy programming and some programmers are in part responsible for great games but game design and more so indie game design is not about programming. It is about designing an experience, not about writing a game loop.

The fact that you can get to your goal by doing several things, drawing art, making music, designing game levels and character(monsters / traps) behavior and programming, does not meant that programming and game design overlap substantially.

2D game design

1. Draw some mockups of the game and the levels of the game.
2. Place the monsters inside those mockups.
3. Make some music that fits the atmosphere of the game.
4. Think how you want the monsters/traps/challenges to behave? write that down.
5. Think up a short story if a story fits this game. Write it down.
6. Making a serious game can be a lot of work, especially by yourself. Think of what you will need for the game and see if some of that code already exists or if there is an existing framework that does the work for you. Making a game from scratch does not make you a better programmer, it makes you \*Waste time you could be investing in making the gameplay better. (nobody cares how good the code of a game is and how much of it you have written on your own, unless the code hurts performance)
7. Like I said, making a cool game is probably lots of work, think up the reasons why you would be truly and utterly committed to making the game you chose, why is this game worth making and not some other game idea you have? Write those reasons down and start working on the game. :)

If you are serious about making your first game, start from what you want to make, not from some code demos. If you want to practice programming, write demos. Programming does not equate game making just like spilling water on clothes does not equate doing laundry.

Good luck

# Answer
> 0 votes
There is no good answer to your "question". Anyway, all the points you have mentioned are very important and some of them are not so "trivial" to catch. With that knowledge you will have the perfect starter kit imho.

You should change the title by "the perfect starter kit for 2D platformer" :)

---
Tags: xna
---


# Question
Title: Issues with networking in my Java game, Client crashes when I try and read from the server input
A buddy and I have been programming a code game over the last 2 weeks, it is intended to be a multiplayer game with the ability to have 2 players play against each other.

I am running into an issue when I try and implement the server-client relationship. My client crashes when it tries to receive information from the server.

The main issue is in the **GameplayState.java** file. the **getTile() method** makes the client crash, so I am assuming the issue lies with how I'm handling the information being sent from the server.

Is there a way to fix this and prevent the crashing? would there be a better way to achieve what I am trying to do?

We are using the lwjgl, Slick2d libs

Specifically its the call: `serverIn.readLine();` that makes crap go crazy.

Finally receive an error

> Wed Jun 13 21:03:58 ADT 2012 ERROR:For input string: ",B6,W5,B2,W7,B,B,W,W" java.lang.NumberFormatException: For input string: ",B6,W5,B2,W7,B,B,W,W" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at GameplayState.getTile(GameplayState.java:168) at GameplayState.update(GameplayState.java:124) at org.newdawn.slick.state.StateBasedGame.update(StateBasedGame.java:268) at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:657) at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:408) at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:318) at CodaClient.main(CodaClient.java:34) Wed Jun 13 21:03:58 ADT 2012 ERROR:Game.update() failure - check the game code. org.newdawn.slick.SlickException: Game.update() failure - check the game code. at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:663) at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:408) at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:318) at CodaClient.main(CodaClient.java:34)

*Relevant server source code below:*

*Because I'm getting flak for putting all the code in, for ease, I will bold the statements that say what files the issue arises in*

**Client Code**

**Server Code**

# Answer
Error stacks go from the most recent call to the least recent, so the most recent line is what happened, and all the rest are what it happened within, what method that was called from, what method *that* was called from, and so on.

```
Wed Jun 13 21:03:58 ADT 2012 ERROR:For input string: ",B6,W5,B2,W7,B,B,W,W"
java.lang.NumberFormatException: For input string: ",B6,W5,B2,W7,B,B,W,W"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at GameplayState.getTile(GameplayState.java:168)
    at GameplayState.update(GameplayState.java:124)

```

Or to break it down...

```
// this is the exception time & message
Wed Jun 13 21:03:58 ADT 2012 ERROR:For input string: ",B6,W5,B2,W7,B,B,W,W"
// this is the exception itself. It's a NumberFormatException, meaning the number
// was of an invalid format. Which is obvious, since the string here isn't a number.
java.lang.NumberFormatException: For input string: ",B6,W5,B2,W7,B,B,W,W"
// the NumberFormatException was created within this method (obviously a helper for
// creating NumberFormatExceptions)
    at java.lang.NumberFormatException.forInputString(Unknown Source)
// this method ^ was called by the following method, which was given an invalid input
    at java.lang.Integer.parseInt(Unknown Source)
// ... which was in turn called by this one ...
    at java.lang.Integer.parseInt(Unknown Source)
// the above parseInt was called within YOUR getTile method, leading to the exception
    at GameplayState.getTile(GameplayState.java:168)
// which was called within your normal game update.
    at GameplayState.update(GameplayState.java:124)
// and so on.

```

You called parseInt with an invalid input it obviously can't turn into a number (because it isn't a number), so of course it's going to throw an exception saying it can't do that - that's exactly what's supposed to happen.

Let's see what you're doing in `getTile()` which is the method that parseInt is called within.

```
private void getTile() {

    //System.out.println(serverResponse);
    if(serverResponse != "")
        currentTile = new Tile(Integer.parseInt(serverResponse.substring(1)), serverResponse.charAt(0));
}

```

`String.substring(1)` returns the string from position 1 (i.e. after the first character) to its end, which in this case ends up as something like `,B6,W5,B2,W7,B,B,W,W`. Here's how you stop getting your error: don't do that.

If you meant to just take the first digit, use:

* `serverResponse.substring(0, 1)`, or
* `serverResponse.charAt(0)`, or
* `serverResponse[0]` (this would be the neatest way to do that in Java, if it's allowed).

If you meant to do something else, well, it's doing this currently. Code it to do something else instead. You have a logic error which means it's up to you to figure out how to get it to do what you want it to do.

### Your lesson:

* Read the stack trace
* Debug your code
* Remember *your logic* could be the problem (it is not perfect)
> 5 votes

---
Tags: java, networking, game-loop, lwjgl, slick
---


title: Setting a Box2D Bodies Center?

text:
# Question
Title: Setting a Box2D Bodies Center?
How do I set the center of a fixture/body consisting of multiple shapes (triangles)?

# Answer
> 1 votes
From the box2d manual:

> A body has two main points of interest. The first point is the body's origin. Fixtures and joints are attached relative to the body's origin. The second point of interest is the center of mass. The center of mass is determined from mass distribution of the attached shapes or is explicitly set with b2MassData. Much of Box2D's internal computations use the center of mass position. For example b2Body stores the linear velocity for the center of mass. When you are building the body definition, you may not know where the center of mass is located. Therefore you specify the position of the body's origin. You may also specify the body's angle in radians, which is not affected by the position of the center of mass. If you later change the mass properties of the body, then the center of mass may move on the body, but the origin position does not change and the attached shapes and joints do not move.

```
bodyDef.position.Set(0.0f, 2.0f);   // the body's origin position.
bodyDef.angle = 0.25f * b2_pi;      // the body's angle in radians.

```

So it seems you can either set the origin, or the center of mass through the MassData.

---
Tags: box2d, physics, actionscript-3
---


title: SV_POSITION in pixel shader

text:
# Question
Title: SV_POSITION in pixel shader
What are the uses for SV\_POSITION in the pixel shader? Previously this was the POSITION semantic and it wasn't readable in the pixel shader, but now that it is, what can it be used for?

In an SM2 deferred renderer, you'd typically take the texture coordinates, transform them to the \[-1, 1\] range and then use an inverse view/position matrix to get the world position of a pixel. Would SV\_POSITION be usable here to reduce any of the calculations? And if so, how would you do that?

# Answer
> 7 votes
SV\_Position in the pixel shader gives you the the center point of the pixel being shaded, in a \[0, bufferWidth\] x \[0, bufferHeight\] range. (It can also be used in centroid mode with MSAA to get the centroid of the covered samples.) This value can be passed directly to Texture2D.Load to retrieve the corresponding pixel from a texture the same size as the screen. So it may not be necessary to pass screen-space UVs in an interpolator, for things like the G-buffer in deferred shading.

For reconstructing the world space position you would still need to load from the depth buffer, convert it to linear depth and combine that with the screen-space position. SV\_Position wouldn't really help you with that part. (FYI, you don't need to do a full matrix multiply in the pixel shader, though; you can do most of the math in the vertex shader and reduce the pixel shader part to linear depth * an interpolated vector + camera position.)

---
Tags: directx, hlsl, directx11
---


# Question
Title: Game engine that allows for objects being placed in-game
I am looking for a game engine with multiplayer support that allows for players to place objects in the terrain. (eg. in TF2 one can place teleporters, etc... or in minecraft one can place blocks). I don't need the placeable objects to be interactive like in TF2, but I just need an engine that won't make me code this from scratch. I have decent knowledge of Python, PHP, HTML, C++ and C# (and a small knowledge of Lua scripting, although I have only been at it for a few months) so I should be able to handle most engines. So far I have looked at UDK and Cryengine, and wasn't thrilled with either.

# Answer
I would like to thank everyone for their feedback, but ultimately I have settled on the Torque engine due to the good networking capabilities which I hope will make accomplishing my goals easier. It also offers scripting in "TorqueScript" which seems very easy to learn and it seems to be capable of accomplishing what I desire to make with the engine.
> -1 votes

# Answer
http://cubeengine.com/

Cube is one of the first engines I recall seeing that had great multi-user editing capabilities.
> 0 votes

# Answer
This question probably needs to be closed for being "inappropriate" or, at least, needs to be converted to CW since there is no right answer.

In the spirit of sharing relevant information: Unity is one of *many* engines that can support client-side creation of objects. Networking is fairly straight forward for setting up a P2P connection and the `Network.Instantiate()` function makes it pretty simple to make objects that all connected players can see.
> 0 votes

---
Tags: networking, multiplayer, terrain, udp
---


# Question
Title: How would I translate screen coordinates to Isometric coordinates?
I have a function `isoToScreen(x, y)` that converts Isometric coordinates to Screen coordinates.

```
var tileW = 16;
var tileH = 16;

var isoToScreen = function(x, y) {
    var posX = (x - y) * tileW;
    var posY = (x + y) * tileH / 2;

    return [posX, posY];
};

```

But how would I make a function that converts screen coordinates back to Isometric coordinates?

```
var pos = screenToIso(16, 8);
pos[0] = 1; // Iso X
pos[1] = 0; // Iso Y

```

# Answer
```
var screenToIso = function(screenX, screenY)
{
  var isoX = screenY / tileH + screenX / (2*tileW)
  var isoY = screenY / tileH - screenX / (2*tileW)

  return [isoX, isoY];
}

```

To get this function you need to rewrite the original math

```
screenX = (isoX - isoY) * tileW
screenY = (isoX + isoY) * tileH / 2

```

Starting with the first line you get the following:

```
screenX = (isoX - isoY) * tileW
screenX / tileW = isoX - isoY
screenX / tileW + isoY = isoX

```

The second line:

```
screenY = (isoX + isoY) * tileH / 2
2*screenY = (isoX + isoY) * tileH
2*screenY / tileH = isoX + isoY
2*screenY / tileH - isoX = isoY

```

Now the two lines look as follows:

```
A) isoX = screenX / tileW + isoY
B) isoY = 2*screenY / tileH - isoX

```

Then substitute isoY in the line A, with the formula derived from line B:

```
isoX = screenX / tileW + 2*screenY/tileH - isoX
isoX+isoX = screenX / tileW + 2*screenY/tileH
2*isoX = screenX / tileW + 2*screenY/tileH
isoX = screenX / (2*tileW) + screenY/tileH
isoX = screenY/tileH + screenX / (2*tileW)

```

And finally, substitute isoX in line B, with the formula derived from line A:

```
isoY = 2*screenY / tileH - screenX / tileW - isoY
2*isoY = 2*screenY / tileH - screenX / tileW
isoY = screenY / tileH - screenX / (2*tileW)

```

Solving linear equations comes very much in handy for a lot of programming, especially graphics or game related programming. Pick up a book on Algebra or read some online tutorials, you will thank yourself later.
> 8 votes

# Answer
Just reverse the order of operations:

```
var tileW = 16;
var tileH = 16;

function screenToIso(x, y)
{
    var posX = ((y * 2 / tileH) + (x / tileW))/2;
    var posY = (y * 2 / tileH) - posX;

    return [posX, posY];
}

```
> 3 votes

---
Tags: mathematics, isometric
---


# Question
Title: how do i make the JS/jquery tic tac toe squares only clickable once?
As i have it now my script makes the 3x3 grid clickable, and I dont know exactly how to turn on the click once it has been clicked. This is using jQuery and a simple if else statement to switch between turns.

```
    $(document).ready(function(){
  var turn = 0;
    $("#cell11, #cell12, #cell21,  #cell22, #cell13, #cell23, #cell31, #cell32, #cell33, ")
            .click(
            function(){
                var cell = $(this);
                if(turn===0){
                    turn = 1;
                cell.css("background","url(images/o.png)");
                }
                else{
                    turn = 0;
                    cell.css("background","url(images/x.png)");
                }
            })
});

```

# Answer
You should keep track of which cells have been clicked on. Either make a 3x3 array and store the state in there, or store the state directly on each cell. Then in the click event, check to see if the state is the default (0 should be fine) then proceed. Otherwise, just exit the onclick event

Something like this should work:

```
$(document).ready(function()
{
    var turn = 0;

    $("#cell11, #cell12, #cell21, #cell22, #cell13, #cell23, #cell31, #cell32, #cell33").click(function()
    {
        var cell = $(this);

        if(cell.attr('data-state') == 0)
        {
            if(turn===0)
            {
                turn = 1;
                cell.css("background","url(images/o.png)").attr('data-state', 1);
            }
            else
            {
                turn = 0;
                cell.css("background","url(images/x.png)").attr('data-state', 2);
            }
        }
    })
});

```
> 1 votes

# Answer
I would suggest you use a class attribute to keep track of which cells are clicked. Then you can move your styles to your css file. This would make your javascript code a little cleaner.

So, for example, in your javascript:

```
$(document).ready(function(){
    var turn = 0;
    $("#cell11, #cell12, #cell21,  #cell22, #cell13, #cell23, #cell31, #cell32, #cell33, ").click(function(){
        var cell = $(this);
        if ( !cell.hasClass("x") && !cell.hashClass("o") ) {
            if(turn==0){
                turn = 1;
                cell.addClass("o");
            }else{
                turn = 0;
                cell.addClass("x");
            }
        }
    });
});

```

Then somewhere in your css file:

```
.o {
    background: url(images/o.png);
}
.x {
    background: url(images/x.png);
}

```
> 1 votes

---
Tags: javascript, html5
---


title: 3d Picking under reticle

text:
# Question
Title: 3d Picking under reticle
i'm currently trying to work out some 3d picking code that I started years ago, but then lost interested the assignment was completed (this part wasn't actually part of the assignment).

I am not using the mouse coords for picking, i'm just using the position in 3d space and a ray directly out from there. A small hitch though is that I want to use a cone and not a ray.

Here are the variables i'm using:

```
float iReticleSlope = 95/3000; //inverse reticle slope
float baseReticle = 1; //radius of the reticle at z = 0
float maxRange = 3000; //max range to target
Quaternion orientation; //the cameras orientation
Vector3d position; //the cameras position

```

Then I loop through each object in the world:

```
Vector3d transformed; //object position after transformations
float d, r; //holder variables

for(i = 0; i < objects.length; i++) {

    transformed = position - objects[i].position; //transform the position relative to camera
    orientation.multiply(transformed); //orient the object relative to the camera

    if(transformed.z < 0) {

        d = sqrt(transformed[0] * transformed[0] + transformed[1] * transformed[1]);
        r = -transformed[2] * iReticleSlope + objects[i].radius;

        if(d < r && -transformed[2] - objects[i].radius <= maxRange) {

            //the object is under the reticle

        } else {

            //the object is not under the reticle

        }

    } else {
    //the object is not under the reticle
    }
}

```

Now this all works fine and dandy until the window ratio doesn't match the resolution ratio. Is there any simple way to account for that

# Answer
I ended up changing the reticle to be rendered by the game instead of the GUI. All is well now and glad my math was solid from the beginning.
> 2 votes

---
Tags: opengl, 3d, raycasting, picking
---


# Question
Title: How to select an image on the J2ME Canvas
I am working on J2ME. I have got a canvas, with a layout of a Checkers board. At the position of pieces, I have placed images. The point at which I got stuck is, how to select/highlite a piece's image for a move. I can't figure out the appropriate commandListener and how to handle this keyPressedEvent. I understood the logic of this game from: Draughts AI

Any suggestions?

# Answer
> 0 votes
there's always an array like DS representing the chess, always a current position, always a target position. always highlight the current position. after press a button, you change the status of the chess, and then you select another position ..... basically what I suggested is you need to think in state machine based model.

---
Tags: java, graphics-programming, html-canvas, image
---


# Question
Title: Can I create a SDL_Surface as I do with Allegro?
Using allegro I can create a Bitmap to draw just doing:

```
BITMAP* bmp = NULL;
bmp = create_bitmap(width,height); // I don't remember exactly the parameters

```

I'm using SDL now, and i want create an `SDL_Surface` to draw the game level (that is static). I create an `SDL_Surface`, draw the tiles on it, then just blit this surface to the screen instead of drawing the tiles directly on screen (I believe this will require more processing);

Is there a way to create a blank `SDL_Surface` as I did with Allegro to draw before I blit it?

# Answer
> 2 votes
You are looking for this function:

```
SDL_Surface* SDL_CreateRGBSurface(Uint32 flags, int width, int height, int bitsPerPixel,
             Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask);

```

Check the docs to see what to pass as each argument.

# Answer
> 1 votes
Normally you set up an

```
SDL_Surface * screen;

```

which is a pointer to a spot of memory that stores pixel information for a given resolution and color depth. You create one as a screen initially and manage it with a SetVideoMode function. You can then blit all of your images onto screen and flip the buffers at the end of your main loop.

You may also want to look into SDL\_Image to make loading and working with various image files easier. Also as someone else mentioned, I highly recommend Lazy Foo's Tutorials. There is information on his site about setting up and using SDL\_Image.

---
Tags: sdl
---


title: Selecting all the points in a ray

text:
# Question
Title: Selecting all the points in a ray
So I'm accustomed to Lightwave where selecting a point in orthographic view selects all the points along that ray from the viewport. I've been watching videos of people using older versions of Blender and it seems like that was the default behavior before. Am I just missing a setting?

Steps to reproduce the problem using the latest version available on the site:

1. Open new project
2. Set view to ortho and front
3. Hit tab to enter edit mode on default Cube object
4. Right mouse click the top right vertici

Only the front most vertex is selected, rather than both.

# Answer
Older versions of Blender did have a toggle for this. I haven't found it in the new version. However, when I want to select multiple vertices behind, I use the box selection. Hit `b` for box selection mode, then click and drag around the forward most vertex. This will select everything in the box, including those behind.

Alternatively, you can hold shift and double right click, but that may only work with the front most and rear most vertices
> 1 votes

# Answer
Closest thing to what you want that I know of is to activate circle select mode (keybind C), you also need to deactivate "limit selection to visible" if you want to use it in solid draw mode however. To change the circle size use your mousewheel.
> 0 votes

---
Tags: blender
---


# Question
Title: Database & Physics in hand. How do render through web?
I'm developing a football management game.

It is to be browser based.

For the moment a turn based strategy that in the future I'd like to develop with more javascript interactivity.

I am competent with mySql and Php set ups and currently the game logic is set out for Php. (where the ball is, where the player should be etc etc)

But as it is my first game I'm not sure how to render the information as a sequence of animations?

Shall I look into SVG and XML manipulation? Then output it as frames?

Let me know if I am asking the wrong questions or info is lacking.

# Answer
> 0 votes
When moving from a webserver background into gameprogramming it can be a natural first step to make a game with HTML5, this allows you to leverage your prior knowledge about HTML and Javascript. Other possibilities would be Silverlight or Flash.

To get started with an HTML5 game, look up the Canvas element and some gamerelated tutorials, you can use XmlWebRequest or the HTML5 Web Sockets to connect to your backend to make fairly advanced games before you need to look at other technologies.

# Answer
> 0 votes
I think there are a lot of possible implementations. Some which I can think of (but I do not necessarily recommend any of them)

1. Render the pitch serve-side as a sequence of images (e.g. PNG) and animate them using client-script.
2. Send vector information (somehow) to the client, with time-data, and have the client render it using SVG
3. As (2) except render it using a canvas element
4. As (2) render it using other HTML elements (not canvas or SVG)

The first option is attractive as it means you need minimal client-side programming (i.e. complexity) and the game will appear the same on every device. On the other hand, it's very bandwidth inefficient and will use more server resources to render many frames.

I would personally not recommend SVG as it has rather limited client-support, particularly on non-desktop browsers. Canvas has widespread support for its core features (albeit very variable performance)

---
Tags: rendering, turn-based-strategy
---


# Question
Title: Rotate 3D camera relative to what's on screen (in threejs)
I'm trying to have a camera in Threejs react to respective left/right/up/down/forward/backward keys, always based on the direction the camera is currently facing. It works fine left/right (camera.rotation.y) and up/down (camera.translateZ) but rotating forward-down/ backward-up (camera.rotation.z) won't work correctly once the camera is already facing up/ downways. Any help please?

Thanks!

# Answer
> 0 votes
Thanks to WestLangley for this working answer!

```
// "Up-less" Camera Controller
// Rotations are with respect to the camera's internal frame of reference.
// Only use this controller if your scene has no sense of "up". If there is a horizon, for example, this kind of
// camera controller can be very disconcerting.
// WestLangley

var mesh;
var container;
var camera, scene, renderer;
var geometry, material;

var speed = 10, radians = .025;

onKeyDown = function( event ) {

    switch( event.keyCode ) {

        case 87: // w (move forward)
        camera.translateZ( -speed );
        break;

        case 83: // s (move backward)
        camera.translateZ( speed );
        break;

        case 37: // left arrow (look left)
        camera.matrix.rotateY( radians );
        camera.rotation.getRotationFromMatrix( camera.matrix ); // r49
        //camera.rotation.setEulerFromRotationMatrix( camera.matrix, camera.eulerOrder ); // dev50
        break;

        case 39: // right arrow (look right)
        camera.matrix.rotateY( -radians );
        camera.rotation.getRotationFromMatrix( camera.matrix ); // r49
        //camera.rotation.setEulerFromRotationMatrix( camera.matrix, camera.eulerOrder ); // dev50
        break;

        case 38: // up arrow (look up)
        camera.matrix.rotateX( radians );
        camera.rotation.getRotationFromMatrix( camera.matrix ); // r49
        //camera.rotation.setEulerFromRotationMatrix( camera.matrix, camera.eulerOrder ); // dev50
        break;

        case 40: // down arrow (look down)
        camera.matrix.rotateX( -radians );
        camera.rotation.getRotationFromMatrix( camera.matrix ); // r49
        //camera.rotation.setEulerFromRotationMatrix( camera.matrix, camera.eulerOrder ); // dev50
        break;

    }

    render();

};

document.addEventListener( 'keydown', onKeyDown, false );

init();

//animate();
render();

function init() {

    // renderer
    renderer = new THREE.CanvasRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    // scene
    scene = new THREE.Scene();

    // camera
    camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.z = 100;
    scene.add( camera );

    // geometry
    geometry = new THREE.CubeGeometry( 20, 20, 20, 1, 1, 1 );

    // mesh
    for ( var i = 0; i < 500; i++ ) {

        material = new THREE.MeshBasicMaterial( { color: 0xFFFFFF * Math.random(), wireframe: true } );

        mesh = new THREE.Mesh( geometry, material );
        mesh.position.set( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 );
        mesh.position.multiplyScalar( 1000 );

        scene.add( mesh );

    }

}

function animate() {

    requestAnimationFrame( animate );
    render();

}

function render() {

    renderer.render(scene, camera);

}

```

# Answer
> 1 votes
In general mathematics there are two ways to do this, treejs might have some functions that make this easier, but it's nice to see the math

(note that I'll be using a right-handed coordinate system here, OpenGL and XNA use this system but DirectX uses a left-handed system, in that case the math is different)

**Using the view matrix**

Also note that if I say MatrixName.M12 I'll mean the value at the first row in the second column.

Given a view matrix V you can always obtain the right, up and backward vector quite easily:

```
right = (viewMatrix.M11, viewMatrix.M21, viewMatrix.M31);
up = (viewMatrix.M12, viewMatrix.M22, viewMatrix.M33);
backward = (viewMatrix.M13, viewMatrix.M23, viewMatrix.M33);

```

This gives:

```
left = -right;
up = -down;
forward = -backward;

```

Now if you want to move something forward you have to take all 3 axises in to account:

```
position.X += forward.X * speed;
position.Y += forward.Y * speed;
position.Z += forward.Z * speed;

```

**Using a forward pointing vector**

We can also construct a vector that points forward by substracting the current camera position from the camera look-at, and then use the cross product to find the other axis, however this works well if we don't touch up (say for an FPS camera):

```
up = (0,1,0);
forward = camera.LookAt - camera.Position;
right = forward CROSS up;

```

This again gives:

```
down = -up;
backward = -forward = camera.Position - camera.LookAt;
left = - right;

```

Again you'll have to take all 3 axises into account when moving something forward (or along any other axis).

**Arcball camera**

I could also interpret your question as if you want a camera that keeps focused on a single object while you rotate around it. In that case you're looking for an arcball camera. I hate to plug my own stuff but here is an implementation that you can reference when making your own for threejs.

---
Tags: 3d, three.js
---


# Question
Title: Pass information between states in slick 2d?
I am making simple game in java using Slick 2d. My question is how many ways of passing information between states are available in Slick 2d. I am having a Hero class that holds all the hero stats and carry them between states using Singleton pattern- aka creating a single instance of the object and accessible from everywhere . Are there any possible solutions and workarounds ? Some XML-alike solutions ? Is there DB option ? Is it worth the effort ?

**\[Edit\]** Put it simple I want instance of my class hero to be accessible from every state. For example my hero goes to the market and buys some armor. That should change his stas in all states. My question was if there is another way to do that like storing the hero stats not in a class but a XML or data base.

# Answer
I have elaborated on my comment suggestion, but the answer to your questions are:

Yes, there are alternatives to a singleton. I present one shortly.

Whether you want to serialize your information to xml, a database, yaml, or whatever is up to you. I do not recommend serializing to your chosen method each time your character drinks a potion or whatever, but having a method to serialize out your game data is a good idea. Slick does not provide an api for writing to XML, just reading from it. YAML is a good alternative. SQLite might also be an alternative.

---

**The solution I use:**

Here is an example of how to share game data between states. This is an edited version of code I use as the basis of all of my own slick projects.

At the root, I have an abstract class ClientBase (client in this context means game client)

```
public abstract class ClientBase<T> extends StateBasedGame {

    private T gameData = null;

    public ClientBase(String name, T theGameData) {
        super(name);
        setGameData(theGameData);
    }

    private void setGameData(T theGameData) {
        gameData = theGameData;
    }

    public T getGameData(){
        return gameData;
    }

}

```

And I have a GameStateBase class to encapsulate individuals states:

```
public abstract class GameStateBase<T, U extends StateBase> implements GameState {
    private U state;
    private ClientBase<T> client;

    public GameStateBase(ClientBase<T> theClient,U theState){
        setClient(theClient);
    }

    private void setState(U theState) {
        state = theState;
    }

    public U getState(){
        return state;
    }

    private void setClient(ClientBase<T> theClient) {
        client = theClient;
    }

    public ClientBase<T> getClient(){
        return client;
    }

    @Override
    public int getID() {
        return getState().getValue();
    }

    @Override
    public boolean isAcceptingInput() {
        return getClient().getCurrentState()==this;
    }

    /* also contains stubs for other GameState methods */
}

```

(to make the enum based method a little clearer, let me include StateBase here)

```
public interface StateBase {
    int getValue();
}

```

And that concludes a simplification of the plumbing....

Now, to actually USE this stuff:

Here's a simple example of a States class, which implements the StatesBase interface.

```
public enum States implements StateBase{
    SPLASH(0),
    MAIN_MENU(1);
    private int value;
    States(int theValue){
        value = theValue;
    }
    @Override
    public int getValue() {
        return value;
    }

}

```

And a concrete class for my client:

```
public class Client extends ClientBase<GameData> {

    public Client(String name) {
        super(name, new GameData());
    }

    @Override
    public void initStatesList(GameContainer arg0) throws SlickException {
        addState(new SplashState(this, States.SPLASH));
        addState(new MainMenuState(this,States.MAIN_MENU));
        /* other states go here*/
    }

}

```

And finally one of the game states itself:

```
public class SplashState extends GameStateBase<GameData,States>{

    private static final int ELAPSED_INITIAL = 0;
    private static final int ELAPSED_FINAL = 5000;
    private int elapsed;

    public SplashState(ClientBase<GameData> theClient, States theState) {
        super(theClient, theState);
    }

    @Override
    public void keyPressed(int theKey, char theCharacter) {
        if(theKey==Input.KEY_ESCAPE){
            elapsed = ELAPSED_FINAL;
        }
    }

    @Override
    protected void enter()
            throws SlickException {
        elapsed = ELAPSED_INITIAL;
    }

    @Override
    protected void render(Graphics theGraphics)
            throws SlickException {
        theGraphics.clear();
        theGraphics.drawString("SPLASH", 0.0f, 0.0f);
    }

    @Override
    protected void update(int theDelta)
            throws SlickException {
        elapsed += theDelta;
        if(elapsed>=ELAPSED_FINAL){
            getClient().enterState(States.MAIN_MENU.getValue());
        }
    }
}

```

Anywhere within a game state that descends from GameStateBase, a call of:

```
GameData theGameData = getClient().getGameData();

```

Will return your shared data.

And what of the class GameData itself?

That's totally up to you. That's why it uses generics.

The pros of this method:

* All of the states have access to the game data
* You aren't forced to use a static singleton
* GameData works as an access layer to whatever storage medium you choose. If the backend is a database or xml file or whatever, GameData talks to it, and the game states don't have to care how it is implemented.

The cons of this method:

* Since any state has full access to the game data, any state can change the data. This might not seem like a big deal, but there are indeed plenty of states, like the Splash state, which does not care in the slightest about much of any thing in the game.
> 4 votes

# Answer
By default there is no possibility to exchange data between states. The reason for this is that the concept of the states is to isolate the the current state your game is in and the data that is needed for each state.

You either need a external class that holds the data you require and you pass the instance of this class to the states that require the data during the construction of the states. Or you use a singleton pattern.

But that should be done rarely as usually every state holds is own data and there is not much data exchanging needed. Any other situation points to a flaw in the design of the games logic and the usage of the game states of Slick.

If you give a more detailed description of your game and what you are doing with the states, we can provide better help for your specific problem. From the little I read there it sounds to me like the problem is the usage of the game states. But at this point I could be wrong.
> 1 votes

---
Tags: java, slick
---


# Question
Title: How to load a terrain of connected caves into bullet-phisics engine?
I have a terrain that can not be represented as height map. Say a mountain with caves. I have it in one large .obj file. How do I load such a terrain into bullet-phisics engine?

Or I shall generate height map, load it as a terrain and then load my caves as a seprate obj file somehow cutting it out from generated terrain?

# Answer
> 2 votes
See my answer to a similar question I asked. Basically one option (that worked well for me) is to implement your own collision listener into Bullet Physics. All you really need to start is a function of your own that tells you whether a specific point in your world is solid. Then as you can see in my answer, you'll just need to override a few objects, and you're done. Most of the code can be copied from the original terrain collision listener, then slightly modified for your game. This is a fairly powerful way to get collision handling working, but it might not be the simplest.

# Answer
> 2 votes
Bullet does support arbitrary meshes; I'm sure Byte56's answer will work but you'll definitely be doing more work than you need to and it'll perform worse than Bullet's built-in solution.

Have a look at the btBvhTriangleMeshShape and btTriangleIndexVertexArray classes; you'll need to load in your obj file to get its vertices and indices, create a btTriangleIndexVertexArray containing those, then create a btBvhTriangleMeshShape from this. That'll give you the collision shape, then it's just a case of attaching that to a rigid body.

Here are Bullet's reference pages for the two classes; there should be enough google fuel in there for you!

http://bulletphysics.com/Bullet/BulletFull/classbtBvhTriangleMeshShape.html

http://bulletphysics.com/Bullet/BulletFull/classbtTriangleIndexVertexArray.html

Bear in mind that Bullet makes it hard to figure out who owns what memory; in this case it expects you to manage both the btTriangleIndexVertexArray you pass into the shape, and the vertex and index arrays you pass to that; it won't take a copy or take ownership of those pointers. So either keep them around as values on the stack or as class members, or make sure to keep hold of the pointers and delete them in the correct order.

---
Tags: c++, 3d, bullet-physics
---


# Question
Title: Implementing game state without switch statements everywhere?
**Executive summary**

Are there any good tutorials on Game State FSMs, particularly OOP/OOD-based and not switch-statement-based?

**Summary**

Is there a practical process for creating a game state engine other than using a switch statement, preferably with examples? Wikipedia's event-driven FSM article only shows a switch statement and the article on FSMs is strictly theory-based with no practical examples.

**Background**

Currently all my games use a very simplistic game state "engine" that uses switch statements everywhere. It's very messy, violates DRY horribly, and does not scale very well.

Each state is treated as a level and must be checked at all three points throughout the game loop, i.e. Input, Processing, and Render. If a level or screen is added it must be added to all the switch statements.

Practical example of recreation of pac-man for educational purposes (seriously, this was a school project a few years ago):

```
enum STATE {
    LOADING,
    TITLE,
    LEVEL_ONE,
    LEVEL_TWO,
    // ...
    WIN,
    GAME_OVER,
    CREDITS,
}GAME_STATE;

void Input() {
    // ...

    switch(GAME_STATE) {
        case LOADING:
            break;
        case TITLE:
            break;
        case LEVEL_ONE:
        case LEVEL_TWO:
        // ...
            InputCommon();
            break;
        case WIN:
        case GAME_OVER:
            if(keyboard->KeyDown(KEY_ENTER))
                GAME_STATE = CREDITS;
            break;
        case CREDITS:
            if(keyboard->isKeyPressed())
                quit = true;
            break;
    }
}

void Processing(int dead) {

    // ...

    switch(GAME_STATE) {
        case LOADING:
            break;
        case TITLE:
            break;
        case LEVEL_ONE:
        case LEVEL_TWO:
        // ...
            ProcessLevel();
            if(GAME_STATE == LEVEL_SEVEN) {
                // ...
            }
            break;
        case WIN:
            break;
        case GAME_OVER:
            break;
        case CREDITS:
            break;
    }
}

void Render() {
    // ...

    switch(GAME_STATE) {
        case LOADING:
            break;
        case TITLE:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(0));
            break;
        case LEVEL_ONE:
        case LEVEL_TWO:
        // ...

            // ...
            break;
        case WIN:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(3));
            break;
        case GAME_OVER:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(1));
            break;
        case CREDITS:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(2));
            break;
    }

    //End render process, display to screen.
    _gw->EndRender();

}

```

# Answer
> 6 votes
If you don't mind a reference to a book, there's an article named "Large-Scale Stack-Based State Machines" in Game Programming Gems 5 which provides a very good implementation of what you seek. I've been using a variation of it for the last few years, and like it a lot. Most of the insights that I got from that article, I've already talked about in this answer, so there's no need to repeat myself.

But since it might not be easy to get your hands on that book, here's a free alternative. The first chapter of the Gamebryo Textbook describes an implementation which is pretty much based on the one presented in Game Programming Gems 5, and you can also find the source code here.

(Update: The links above are no longer valid, and I can't seem to find where they have been relocated. If someone does, please edit this answer)

And finally, despite being in C# and XNA, this sample from Microsoft provides a simple implementation which should be pretty easy to follow and convert to C++.

# Answer
> 1 votes
The first step really is to just move the contents of your switch statements to data files. Level layouts and such should be in map files. Special level logic can be moved to scripts, or at the veryeast moved off into their own functions/classes. You can register these data files or C functions at startup with a level manager, and your switch statements then turn into m\_CurrentLevel-\>update().

Note that a lot of logic really should be common. There's little reason for each level to have its own input handling, since good non-irritating games generally have only one play style. Of course exceptions abound, especially if you implement menus had a game state. Even then, though, abstract things away: have a menu handler that runs for any active menu state, a gameplay handler for game play states, etc.

If in doubt, just think in terms of (good) OOP design.

# Answer
> 0 votes
I would tend to create a Scene object that all the various game states inherit from, and just create a variable called "currentScene" in the Main object. Then instead of a switch statement in the main loop, just call currentScene-\>Update(); each Scene would know what it specifically needs to do for input handling and rendering. To switch the game's state just switch which Scene is in currentScene.

# Answer
> 0 votes
Have a look at the Boost Statechart library. I recently started using it after many years of trying out slightly different ways of implementing FSMs, and it's definitely my current favourite! There are some oddities that stop it from being perfect (see 'state' class vs. 'simple\_state' for example), but it provides some very useful features, and allows you to write state machines that are far more compact and expressive than the equivalent switch-based code.

http://www.boost.org/doc/libs/1\_49\_0/libs/statechart/doc/tutorial.html

# Answer
> -1 votes
Yes, there is also something called a behavior tree, which is used for AI. If you want to research them, I would suggest starting here:

Introduction to Behavior Trees

Björn Knafla explains in very easy terms what is involved with this system. I'm currently implementing this on my internship. The advantage to a behavior tree is that you're making a *decision* instead of setting a *state*.

For instance, let's say you want to build some AI for the ghosts in Pacman. You want them to follow Pacman if they see him and stop following him when they lost sight of him. So, in a behavior tree:

```
Walking
-- Am I following Pacman?
-- -- Have I lost sight of Pacman?
-- -- -- Stop following Pacman.
-- -- -- <End>
-- (Else)
-- -- Do I see Pacman?
-- -- -- Follow Pacman
-- -- -- <End>

```

So, first time we walk the tree:

```
Walking
Am I following Pacman? -> No
Else
Do I see Pacman? -> Yes
Follow Pacman
End

```

Next frame:

```
Walking
Am I following Pacman? -> Yes
Have I lost sight of Pacman? -> No
End

```

The trick is that the behavior tree gets evaluated every frame, but it only affects *behavior*. So, in the case of the Ghost AI, it only determines where to walk to, but it doesn't actually walk to anywhere.

Instead, you have a separate piece of code that looks something like this:

```
if (m_BrainData->target == StateTarget::ePacman)
{
    MoveTowardsPacman();
}
else
{
    MoveRandomly();
}

```

Why is that so significant? Because now you can *blend* between states. Now, if you want a Ghost to run a "scared" animation whenever he sees Pacman powered up, you simply evaluate the Ghost's "brain":

```
if (
   m_BrainData->target == StateTarget::ePacman &&
   m_BrainData->emotion == StateEmotion::ePanic
)
{
    m_AnimationPanic->Render();
    if (m_AnimationPanic->Finished())
    {
         m_BrainData->emotion = StateEmotion::eFleeing;
    }
}
else
{
    m_Animation->Render();
}

```

And you add the states to the behavior tree:

```
Walking
-- Am I following Pacman?
-- -- Have I lost sight of Pacman?
-- -- -- Stop following Pacman.
-- -- -- <End>
-- (Else)
-- -- Do I see Pacman?
-- -- -- Is Pacman powered up?
-- -- -- -- Am I not fleeing?
-- -- -- -- -- Panic
-- -- -- -- -- <End>
-- -- -- -- (Else)
-- -- -- -- -- Flee
-- -- -- -- -- <End>
-- -- -- (Else)
-- -- -- -- Follow Pacman
-- -- -- <End>

```

---
Tags: c++, state, fsm
---


title: Game State with sqlite + MySql

text:
# Question
Title: Game State with sqlite + MySql
I am building out my first android game, after some utility app development.

I want to be sure I am not moving into a direction that is not a best practice, so please (constructively) criticize my plan.

My game will have many NPCs that will be added often (\>150) in increments of 10-15. Each will have their own stats associated with them and the user will have a unique interaction with each.

Is it possible to put all of the NPC character information into a MySql database and have my app download the new information when it understands that the servers contain new information (via C2DM). Including a link to a file I will host containing the png files for each NPC. This way when there are new NPCs to be added to the game, the user doesn't have to grab an update from the market/Google Play.

Furthermore is sqlite/MySql a preferable method to save the user's game state. I want to be able to save it locally so that it can be loaded without a network connection. And periodically updated on the server to allow the user to play the same game both on a phone and tablet for example.

If I sound like I'm on the right track with my plan, what opensource projects exists from which I can learn/analyse the methods they use to accomplish a similar task? I have been unable to find anything like this as of yet.

**EDIT**: by \>250NPCs I mean that the game will start out with perhaps ten enemies. Each has their own stats (health, strength, magic etc). And since I plan on adding more than 150 types of enemies, I'd like the game to be able to update at run time rather than require an update with Google Play - since many users simply do not update their software on a timely basis, they will be missing out on the added value.

The reason I favor SQL is so that I can easily view my game characters and modify their stats/qualities on the fly should I see the game become unbalanced.

# Answer
C2DM should be fine for updating the data.

As for saving data locally using sqlite, sure, that will work. I disagree with stephelton's answer because in practice relational databases are very fast and Android devices are likely to be writing to fast flash memory anyway, so concerns about disk seek speeds are likely to be unfounded.

Generally speaking though, most game developers do not save local game data into relational databases, usually preferring bespoke formats - but that's not a reason for you to avoid the database approach.
> 2 votes

# Answer
Not exactly sure what you're getting at... are you saving detailed game state in sql, or just initial data? And you say \>150 -- 150 what?

Anyway, if you're talking about downloading game data (such as level layouts, enemy definitions, etc.) you're probably ok (but I personally still wouldn't go with sql for this, as it suffer longer loading times than a more packed format without all the sql overhead). If you are doing this, I'd batch your reads as much as possible and keep them in ram.

If you're talking about saving game state, such as current score, object hp, etc., you're probably asking for trouble.

Reading (which is primarily what you'd be doing if it's just game data you're talking about) comes with the same caveats, but the penalties are a bit lower. Waiting for a read from disk can definitely still stall your game.

In general, I'd say that if you are wanting to update a local sql database any more often than once every few seconds, you're likely to start running into problems. And the same if you're wanting to update a remote sql database any more often than once a minute or so.

There is a hefty bit of overhead that goes in to writing to a file, and it can very quite a bit. Writing local sql data includes this same overhead, but also includes its own overhead. Often a single sql save or read can require reading data from multiple locations on the hard drive (multiple seeks and multiple reads/writes) which compounds the problem.

When you're wanting to run a game at 30-60 fps, you have between 16 and 33 milliseconds to handle logic for a single frame and update the display. Writing to a file, even on a fast SSD, can easily stall you for many millis. Worse still, it's very unpredictable and you're very likely to see spikes that jump well past your allotment of 16-33 ms since you're contending for reads/writes to the hard drive with other processes running on the device.

I personally would stay away from sql for any game related tasks except maybe something like high scores / leaderboard type things.
> 0 votes

---
Tags: android
---


# Question
Title: Image 1 becomes image 2 with sliding effect from left to right?
I would like to show a *second image appearing* while a "door" is closing on my character. I've got my character in the middle of the screen and a door coming from the left. When the door passes my character, I would like to have this second image appearing little by little.

So far, I've gotten by with fadingOut the character and then fadingIn my second image of the character at the same position when the door is completely closed, but I would like to have both of them at the same time. **(the effect that image 1 becomes image 2 when the door is sliding from left to right)**. Would you know how to do this with Cocos2d?

Here are the images :

at first, the character is blue, and the door is coming from the left :

Then, behind the black door, the character becomes red, but only behind this door, so it stays blue when the door is not on him, and will become completely red when the door passes the character :

---

EDIT : with this code, the black door hides the red and blue rectangles : (And if i add each of my layers at a different depth, and only use GL\_LESS, same thing)

```
blue.position =  ccp( size.width*0.5 , size.height/2 );
        red.position =  ccp( size.width*0.46 , size.height/2 );
        black.position =  ccp( size.width*0.1 , size.height/2 );

        glEnable(GL_DEPTH_TEST);

        [batch addChild:red z:0];
        [batch addChild:black z:2];

        glDepthFunc(GL_GREATER);

        [batch addChild:blue z:1];

        glDepthFunc(GL_LESS);

        id action1 = [CCMoveTo actionWithDuration:3 position:ccp(size.width,size.height/2)];
        [black runAction: [CCSequence actions:action1, nil]];

```

# Answer
> 1 votes
I didn't test this solution myself, but I think it should work theoretically. you need a little more googling to find out how to exactly implement it. also note that for the whole process you need to have DEPTH\_TEST enabled.

1. draw player at depth 0
2. draw the wall at depth 2
3. change depth test function to MORE
4. draw the overlay (blue) player at depth 1
5. restore depth test function to LESS

while working with z buffer, what ever you draw will change the depth. Meaning when you start drawing player all it's pixels are marked as z=0. Later when you draw the door, all pixel that are draw above player will be drawn with z=2. At this point we change the depth test function. Depth function determines what are the conditions to draw a new colors in that specific pixel. As I said we change the Depth test function. It means from that point forward OpenGL will only draw objects if they are behind other objects. I guess you can now see where I'm going to. The blue rectangle is behind the wall but it's above the red one. So while drawing OpenGL should just skip all the pixels which are not behind the wall.

**note:** I've just noticed the default `GL_DEPTH_FUNC` value is `GL_LESS` so I've changed instruction 3 and 5

---
Tags: cocos2d-iphone, cocos2d, ccsprite
---


title: Framerate limitation

text:
# Question
Title: Framerate limitation
The most successful competitive game engines like `id Tech`, `GoldSrc`, `Source` and such allow for framerate limitations.

You can play with 30, with 60, with 99, with 72, with 68 etc. In short, you can cap it and control the cap.

I was wondering, how do I limit the framerate?

Not interested in code, but theory.

# Answer
> 7 votes
The theory is: Check when you last rendered a frame, and if it's not time to draw another frame yet, then don't, and wait until it is.

# Answer
> 8 votes
Say you want to limit your framerate to 60fps, that means that every frame has a render time of 1/60s = 16,67ms (rounded)

To limit your frame rate you just check the time at the start of your game loop, you can then compare it with the time at the end of the game loop: if the difference is less than 16.67ms you should stall for that time.

One way to do this is to use:

```
sleep(waittime)

```

However since `sleep(x)` yields the thread for a minimum of `x` miliseconds you don't know for certain if you will get control back in time.

A better way would be to use:

```
while(timediff < 16.67ms){ sleep(0); }

```

This yields the thread and requests control back as soon as possible.

Another solution is to just have a busy wait loop, this gives you the best control but uses the CPU needlessly.

Remember that the OS scheduler can always take away control from your thread so be prepared for some fluctuation.

---
Tags: frame-rate
---


title: Java - 2d Array Tile Map Collision

text:
# Question
Title: Java - 2d Array Tile Map Collision
How would I go about making certain tiles in my array collide with my player? Like say I want every number 2 in the array to collide. I am reading my array from a txt file if that matters and I am using the slick2d library.

Here is my code if needed.

```
public class Tiles {

Image[] tiles = new Image[3];

int[][] map = new int[500][500];

Image grass, dirt, mound;

SpriteSheet tileSheet;

int tileWidth = 32;
int tileHeight = 32;

public void init() throws IOException, SlickException {
    tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight);

    grass = tileSheet.getSprite(0, 0);
    dirt = tileSheet.getSprite(7, 7);
    mound = tileSheet.getSprite(2, 6);
    tiles[0] = grass;
    tiles[1] = dirt;
    tiles[2] = mound;

    int x=0, y=0;
BufferedReader in = new BufferedReader(new FileReader("assets/map.txt"));
String line;
while ((line = in.readLine()) != null) {
        String[] values = line.split(",");
    for (String str : values) {
            int str_int = Integer.parseInt(str);
            map[x][y]=str_int;
            //System.out.print(map[x][y] + " ");
            y=y+1;
        }
//System.out.println("");
x=x+1;
    y = 0;
}
    in.close();
}

public void update() {

}

public void render(GameContainer gc) {
    for(int x = 0; x < 50; x++) {
        for(int y = 0; y < 50; y ++) {
            int textureIndex = map[y][x];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }
}

```

}

Edit - Solved

```
public boolean collision() {
    playerRect = new Rectangle(x,y, playerWidth, playerHeight);

    for(int i = 0; i < tiles.map.length; i++) {
        for(int j = 0; j < tiles.map.length; j++) {
            if(tiles.map[j][i] == 2 || tiles.map[j][i] == 3) {
                tileRect = new Rectangle(i*tiles.tileWidth, j*tiles.tileHeight, tiles.tileWidth,tiles.tileHeight);
                rect.add(tileRect);
            }
        }
    }
    for(Rectangle collision : rect) {
        if(collision.intersects(playerRect)) {
            return true;
        }
    }
    return false;
}

```

# Answer
You have a tile grid, and you have tile dimensions. That's a good start.

You're missing a key piece, though. You're trying to do collision between the player and the tiles (based purely on player location). This is a bit flawed. Instead, you should think about this problem as collision between player **geometry** and tile **geometry**.

To keep it simple, you can represent your player and tiles as rectangles. The player rectangle can be computed given the x location, y location, width, and height (if your player yet have `height` and `width`, you should add them).

Tile geometries (rectangles) can be computed in a similar manner, which should be fairly obvious:

* `x location = tile grid x index * tileWidth`
* `y location = tile grid y index * tileHeight`
* `width = tileWidth`
* `height = tileHeight`

Now do your collision checks. Hint: Have a look `java.awt.Rectangle` or `java.awt.geom.Rectangle2D`. These will help you.
> 2 votes

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


title: Vectors from matrix

text:
# Question
Title: Vectors from matrix
In XNA you can get front/back/left/right vector of Matrix class. How get these vectors without XNA, through C++ using standart 4x4 matrix ? I dont understand what exactly they mean but found them very useful(in XNA).

# Answer
> 1 votes
I'm not familiar with XNA, but front/back/left/right(top, bottom?) vectors could make sense in the context of a rotation matrix.

If that's what they are about, you could get them by simply doing a matrix multiplication with the unit vectors. i.e. multiplying Matrix * \[0,0,1,1\], Matrix * \[0,1,0,1\], Matrix * \[1,0,0,1\] would give you the z,y, and x axes' directions in untransformed space. (the 4th component is necessary, multiplying a 4x4 matrix with a 1x3 vector is not possible)

# Answer
> 1 votes
Im open XNA assembly with reflector and get answer.

```
public Vector3 Up
{
    get
    {
        Vector3 vector;
        vector.X = this.M21;
        vector.Y = this.M22;
        vector.Z = this.M23;
        return vector;
    }
}
public Vector3 Down
{
    get
    {
        Vector3 vector;
        vector.X = -this.M21;
        vector.Y = -this.M22;
        vector.Z = -this.M23;
        return vector;
    }
}
public Vector3 Right
{
    get
    {
        Vector3 vector;
        vector.X = this.M11;
        vector.Y = this.M12;
        vector.Z = this.M13;
        return vector;
    }
}
public Vector3 Left
{
    get
    {
        Vector3 vector;
        vector.X = -this.M11;
        vector.Y = -this.M12;
        vector.Z = -this.M13;
        return vector;
    }
}
public Vector3 Forward
{
    get
    {
        Vector3 vector;
        vector.X = -this.M31;
        vector.Y = -this.M32;
        vector.Z = -this.M33;
        return vector;
    }
}
public Vector3 Backward
{
    get
    {
        Vector3 vector;
        vector.X = this.M31;
        vector.Y = this.M32;
        vector.Z = this.M33;
        return vector;
    }
}

```

---
Tags: xna, c++, matrix, linear-algebra
---


# Question
Title: What graphic programs are used in Wind-up knight
What graphics programs does Android support? i.e. what graphics programs did Robot Invader use to create Wind-up Knight?

Any hints or clues are appreciated.

# Answer
> 1 votes
See http://robotinvader.com/blog/ \- developers blog. I see they mention Unity.

---
Tags: 3d
---


title: How to simulate a water splash effect?

text:
# Question
Title: How to simulate a water splash effect?
I need to achieve the effect of a ball falling down into a pool then splashing in the water.

At first, I made a sensor to detect the collision between the ball and the water and then show the sprite of the spray. But it's hard to change the sprite according to the velocity of the ball and the angle between the ball and pool. So, I want to simulate the physical model of the water.

Now, what I can do is to add a particle system using Cocos2D to show the still water and add physical model to each particle. But, I don't think it is a good solution. Any other I can do it? Waiting for you help.

# Answer
> 1 votes
You could go for a full fluid physics solution, such as the one used in Pixel Junk Shooter (explained in details here).

But that's probably overkill for your needs. You're believing that simulating the physics would be easier than cheating a bit, but I think that doing a bit of research would make you reconsider your position.

What I would do is simply use the two infos you already have: **scale and rotate** your sprite animation (or particle emitter) depending on the **speed and angle** of impact. For good mesure, use a set of effects instead of only one, and alternate randomly between them. Video games are all about smoke and mirrors.

---
Tags: box2d, cocos2d-iphone, ios, cocos2d, objective-c
---