title: How do you align the edges of sprites?

text:
# Question
Title: How do you align the edges of sprites?
If you have SpriteA and SpriteB.

SpriteB is a child of SpriteA.

Does anyone have a mechanism to come up with the left, right, top, side of a boundingbox() of SpriteA?

What I'd like to do is align SpriteB with the edge of SpriteA. Right now when created, SpriteB is centered with SpriteA.

# Answer
> 0 votes
To position SpriteB to be aligned with SpriteA you just need to do a little math. Getting the bounds will return a rectangle. From that rectangle, you can get the width and height of the bounding box. Combine that with the position and you can get the location of the points you're interested in.

For example, the distance to move the sprite to align it with the left edge can be calculated by finding the distance between the edges. The difference between the purple and blue point can be found with `(A_Post.x - A_Bounds.Width/2) - (B_Pos.x - B_Bounds.Width/2)`. Similarly, you can find something like the right edge difference with `(A_Post.x + A_Bounds.Width/2) - (B_Pos.x + B_Bounds.Width/2)`.

Move the sprite by that amount and you'll have it sharing its left bounds with the bounds of SpriteA.

---
Tags: c++, sprites, cocos2d-iphone, cocos2d, cocos2d-x
---


title: Moller Tri Tri intersection

text:
# Question
Title: Moller Tri Tri intersection
I'm done implementing Moller's tri-tri intersection routine. It gives you the location of where each triangle *edge* intersects the line of intersection between the 2 triangle planes:

Really you get the point location in the form of *t* values along the (really big) purple ray shown above. So you can tell if the triangle intersects if the *t* values are overlapping..?

That's what the paper says. But I can show you scenarios where the t values are overlapping, but the triangles don't intersect:

So I can't seem to figure out which edge value to discard.

The original paper is here: http://fileadmin.cs.lth.se/cs/Personal/Tomas\_Akenine-Moller/pubs/tritri.pdf

# Answer
It's not very clearly explained in the paper, but you can tell which two out of the three edges to look at by seeing which vertices are on which side of the other triangle's plane.

For instance, if triangle 1's vertices are A, B, C, and A and B are on one side of triangle 2's plane and C is on the other side of triangle 2's plane, then AC and BC are the edges that cross the plane, and those two are the edges to look at to get the t-interval for triangle 1. Swap the triangles and repeat the logic to get the t-interval for triangle 2.

You should always get one vertex on one side of the other triangle's plane and two on the other side, since if all three were on the same side of the plane then the triangles don't intersect and this would have been detected earlier in the algorithm.

BTW, there's Moller's sample code for this algorithm on the web (the link in the original paper is dead, but I found this one by following a link from the Real-Time Rendering intersection test table). The relevant part looks like the `NEWCOMPUTE_INTERVALS` macro.
> 3 votes

---
Tags: intersection
---


# Question
Title: Collision detection in games in 3D - edge to edge cross product
I am having trouble understanding why, in a game collision detection, separating axis determination requires checking for the cross product of edges of the two polytopes as additional potential separating axes. In 2D the process is much more intuitive, in that it only checks the edges normals as potential separating axes.

I have been thinking about this very hard but I cannot visualize this at all, nor can I find a good motivating example or explanation.

# Answer
The cross product of two vectors is a vector perpendicular to both, and normal to the plane that they span. If the two vectors are two adjacent edges of a face, their cross product is a vector normal to that face.

Because of this, taking the *cross product of two edges* of a *face* of a polygon in 3D is analogous to taking the *normal* to an *edge* of a polygon in 2D.

Also, in case it helps you to visualise:

* In 2D, you check a series of axes to find one where the projections of the two polygons are disjoint. This means that there was a line, normal to the axis, separating the two polygons.
* In 3D, you do the same, checking axes until the projections of the polyhedra onto an axis are disjoint. This time, this means that there is a *plane* in space, normal to the line, separating the two polyhedra.

In both cases, the projections of the polytopes end up as line segments (intervals), and you just check if they overlap.

N.B.: None of this works for concave polyhedra - think of a ball resting in a cup, not intersecting with it. No matter what axis you project along, the projections of the two shapes intersect, even though the objects are disjoint. This is because there is no plane separating the ball and the cup. Using separating axis tests on non-convex polytopes will give false intersections.
> 2 votes

---
Tags: 3d, collision-detection, mathematics
---


title: Custom rendering inside Awesomium

text:
# Question
Title: Custom rendering inside Awesomium
Is there a way to render something custom inside some html element in Awesomium?

For example: I have inventory screen (that can be moved around) that has 3D avatar playing some idle animation weilding all equipped items. The screen should be html but the avatar is rendered by the game (to some texture) and now i need to display it on html page.

# Answer
How about making use of transparency and render your GUI as a partially transparent layer on top of the game content, i.e. the character animation. I cannot guarantee you that it'll work out of the box, but I know it must be possible in principle.

I've once used a transparent awesomium web window in a C# Windows.Forms application. The standard WinForms control has the "IsTransparent" property. According to the documentation, the control is implemented using the Windowed WebView. The same property exists in the C++ documentation. Worst case, you have to implement your own Surface.

When you set the IsTransparent to true, nothing will happen at first. Within the HTML/CSS code, you have to additionally set

```
html, body {
    background-color: transparent;
    /* other stuff */
}

```

Then everything all html content will be rendered on top of a transparent window. However, font rendering looks quite ugly this way. Either put the real GUI within elements that have a background set, or use a hack. Setting

```
opacity: 0.99;

```

will somehow change the rendering behavior of chromium and respect the transparency when doing font smoothing.

I don't know about the performance of this approach. But everything is handled internally by chromium, which probably makes decent use of gpu acceleration.
> 3 votes

# Answer
You probably can, in theory. Let's assume that you have the following layout:

The avatar above is a simple img tag. The nice thing about images in HTML is that you can assign a data uri scheme as a source instead of an URL.

Now, assuming that you are rendering your avatar into a texture you could:

1. Convert the texture data into a base64 string
2. Pass this data to a javascript method on your page using Awesomium
3. This method assigns the img tag the new data as src.

As I wrote before this should work in theory but **beware, it might be incredibly performance heavy depending on your target framerate.**
> 0 votes

---
Tags: awesomium
---


title: Tweening in 2d side-scrolling RPG

text:
# Question
Title: Tweening in 2d side-scrolling RPG
I'm working on a 2d side-scrolling RPG-ish game. Currently the movement of the main character(hero) is based on the A and D keys, because it's 2d and I don't really care about jumping. I would like to change it to a mouse oriented system. Something like this: if the hero is at position 100(x-axis) and I click at x=200, it would move(tween/ease) to 200px with 50px/s. PS: I'm using java with libgdx.

# Answer
> 2 votes
This is simply a combination of a few simple steps.

First, get the mouse position, `Gdx.input.getX()` will give you the mouse X position. You'll want to get that position at the time the mouse button was pressed.

Now, that you have a target, move your hero towards it. You can do that with something like:

```
float deltaV = deltaTime * speed;
if (Math.abs(target.X - hero.X) > 1) {
    if (hero.X < target.X) {
        hero.X += deltaV;
    }
    if (hero.X > target.X) {
        hero.X -= deltaV;
    }
}

```

You'll want to either add some speed up and slow down functionality in there to arrive exactly at the target, or do something like check to see if the last update put you past the target and if so, set the position to the target position. This code will get you close and if you end up within 1 unit of the target position it will stop.

---
Tags: libgdx, side-scroller, tweening, easing
---


# Question
Title: What caused "falling out of the world" and what fixed it?
A lot of early 3D games had the problem where you'd be trundling merrily along and suddenly everything was black, with an island of what looked like the hollow facade shell of the scene you'd been walking through rising into the distance above. Because you'd fallen out of the world. I remember this being a particular and long-standing problem for Bethesda Softworks, though they certainly weren't alone. It's been a while since I've seen it in the wild, so it seems we've gotten past it. My question is two-part:

1) What was the cause, or causes, of this? (My guess is that it's to do with floating-point-precision related seams between polygons, interacting with point-modeled character position, i.e. floor chunk A ends at position 1.0, floor chunk B starts at position 0.9998 and for a microsecond your position is 0.99992, and boom, you fall through the world. But that's just a guess.)

2) How did it get fixed?

# Answer
"Cracks" in the geometry mostly. These games have a few things in common, they have gravity and they have collision detection.

These anomalies are locations where the collision detection failed in some way. It could have been sharp edges, gaps or a number of other geometry anomalies. Could even been issues with time steps in the physics engine, where the updates desynced and the character was allowed to fall through perfectly good geometry.

This is common when the player does something that wasn't expected by the level designers. Jumping up onto some place they're not supposed to be, or somehow surviving a fall they weren't supposed to. Or, when the player uses features in the game like teleporting or flying to get to places the level designers didn't think players could get to. As recently as Skyrim (video: falling out of the world at 11:25 I suggest muting the audio...).

When the collision detection fails, there's nothing to push back from gravity, so you fall. Just like walking off a cliff.

It's not really "fixed". There are techniques to avoid this, but it's mostly just better tools and geometry creation tools for landscape so these anomalies aren't introduced.
> 14 votes

# Answer
I think it's not possible to say that there is one particular reason why clipping through the world happens. Due to the differences in game engines/ physics procedures between games, any number of reasons can lead to this.

Stemming off this, I'm quite sure that falling out of the world has not been eliminated, necessarily.

Having a few large-scale game engines (Unreal, CryEngine, etc) can lead to less unforseen issues due to the fact that said engines are constantly being worked on. However, there is nothing that stops a developer from adding features/interesting changes to environment that may let world-clipping happen even in the most worked-on game engine.

EDIT: 1. The underlying causes of this, as far as I know, have to do with the fact that game engines that allow for this to happen have a limited method of detecting whether a player is moving wrongly. Earlier game engines probably had more issues with this because the ground plane was frequently just that- a plane. If a player was on said plane, he would not go down. If, for whatever reason, his vertical location went below by a little bit, then he would fall forever. Pretty much what you're saying in regards to floating point calculations. As engines could afford to be more robust and check if a player was in a whole REGION that was off-limits, triggering the error would be less likely.
> 5 votes

# Answer
My guess would be that older engines probably used a quick and simple ray vs triangle test to detect collision with the geometry. That means even the tiniest gap (or a precision error in the calculations) could let the player through occasionally.

More modern games will probably use a more expensive test with a sphere or capsule representing the player, and that simply won't fit through small gaps. Many modern games will also use well tested physics middleware for the purpose instead of writing their own tests.

A large time step in the physics update can definitely be blamed in some cases too. I seem to remember that in at least one of the Elite games you could fly right through a planet in some cases because of that. This is fixable by using continuous collision detection which also costs extra CPU time.
> 5 votes

---
Tags: 3d, 3d-meshes, scene, floating-point
---


title: About Octrees Usage

text:
# Question
Title: About Octrees Usage
I'm studying about Octrees since I've read they're used to organize my elements in space, but I couldn't find any practical example so I'm kinda lost as to their use.

From what I could understand, I'll divide my "space" in 8 cubes, and each cube will divide it's own space in another 8 cubes and so on until my defined "depth" is reached. This is what I could understand from octrees, so now about their uses:

1. Are they done so the check of each cube's with the camera frustum is easier to compute?
2. If I have a open world scenario, do I put **all** the vertexes in it? And related:
3. How often do they get updated? Everytime I insert a new game element, don't I have to re-do all the calculations for the current node and it's subnodes?

If you can share any resource on BSPs/Octrees and their practical usages (not just the concept, which I've been reading a lot), please share!

# Answer
1. The point is that once you cull one octree node, you can stop culling and discard all of its children therein. Consider a binary search for example. Once you know that your key isn't in one part of the array, you can stop searching that part completely. The check itself isn't easier to compute, it just decreases the *number* of calls you may have to make **(as long as you don't use silly depths or in other words use too many nodes for too few objects)**
2. I'm not sure what you mean by vertexes. I'm assuming you mean models/entities, in which case, the answer is maybe. In the end you might have multiple systems of subdividing space and multiple culling systems in order to maximise performance. Generally though, if we're talking about say plain scene objects (e.g renderable vehicle, player characters), the answer is yes. It must be stressed though, you won't be adding individual vertexes, you'll be adding the bounding box belonging to the entity that **contains** the vertexes. You will *still* end up ultimately culling the specific entity you add to the tree if it ends up in the visible **candidate** list, it just allows you to say, if you are at one end of the map, eliminate dozens or even hundreds of entities with a single cull check.
3. It depends on what you mean by 'update'. If you mean 'cull', thereby updating the list of visible candidates (objects that **may** be visible) then yes, otherwise you might run into a situation where an object that should be on the screen isn't rendered.

When you refer to *calculations*, what are you referring to? The insertion of a new element will generally involve recursion, beginning with your root node, adding it to nodes that contain it. (strictly speaking this can be a bit more complex depending on how you produce your visible list - you don't want duplicates) The only calculations you will *have* to perform (not may) will be the bounding box intersection test with each node you recurse for.

Here is some basic pseudo-code (just to give you an idea, not necessarily accurate)

```
void RecurseAddBoundsToOctree(TBoundingBox boundsToAdd, TOctreeNode node)
{
    if node == NULL
        return

    for each child
        RecurseOctree(currentChild);

    //Note: Above we may want to prevent multiple children from containing the
    //same bounding box (you could return a boolean to indicate whether it was added)

    if BoundingBoxIntersect(boundsToAdd, node.BoundingBox)
        node.AddBoundingBox(boundsToAdd)
}

```
> 3 votes

---
Tags: octree, binary-space-partitioning
---


# Question
Title: ParallaxBackground doesn't work well with sprite scaled
I'm trying to set a ParallaxBackground for my AndEngine's game. So I did this:

```
    Sprite montagne = new Sprite(0, 0, RM.montagneBackground, vertex);
    Sprite piante = new Sprite(0, 0, RM.pianteBackground, vertex);
    montagne.setOffsetCenter(0, 0);
    montagne.setScaleCenterY(0);
    montagne.setScale(1.3f);
    piante.setScaleCenterY(0);
    piante.setOffsetCenter(0, 0);
    piante.setScale(1.3f);

    AutoParallaxBackground background = new AutoParallaxBackground(0.384f, 0.411f, 1f, 10f);
    background.attachParallaxEntity(new ParallaxEntity(5, montagne));
    background.attachParallaxEntity(new ParallaxEntity(10, piante));
    scene.setBackground(background);
    scene.setBackgroundEnabled(true);

```

I scaled my two sprites (montagne, piante) by 1.3 f. If i run my application i can notice that when the sprites arrives at the end of the screen it disappears.. So I set the scale's values like this:

```
montagne.setScale(1f);
piante.setScale(1f);

```

And it works very well but the sprites are too small and i can't modify it with Photoshop because the sprites are both 1024 of width and It's the maximum I can store in my TextureAtlas...

So, how can I scale my sprites without having this problem ?

# Answer
> 0 votes
I resolved my problem with this:

```
montagne.setScaleCenter(0,0);
piante.setScaleCenter(0,0);

```

I think is due to the fact that when you scale a sprite you scale both side of it so when it runs, the ParallaxBackground make confusion thinking that the sprite passed the screen and so it's well to remove it.. With this method the sprite are scaled only in one side (the right and the top) and so you avoid this problem.

# Answer
> 0 votes
Don't change the offset or scale center. `AutoParallaxBackground` takes care of positioning the sprites with their scaled values:

```
public void onDraw(final GL10 pGL, final float pParallaxValue, final Camera pCamera) {
    pGL.glPushMatrix();
    {
        final float cameraWidth = pCamera.getWidth();
        final float shapeWidthScaled = this.mShape.getWidthScaled();
        float baseOffset = (pParallaxValue * this.mParallaxFactor) % shapeWidthScaled;

        while(baseOffset > 0) {
            baseOffset -= shapeWidthScaled;
        }
        pGL.glTranslatef(baseOffset, 0, 0);
        float currentMaxX = baseOffset;

        do {
            this.mShape.onDraw(pGL, pCamera);
            pGL.glTranslatef(shapeWidthScaled, 0, 0);
            currentMaxX += shapeWidthScaled;
        } while(currentMaxX < cameraWidth);
    }
    pGL.glPopMatrix();
}

```

Relying primarily on the `getWidthScaled()` method:

```
@Override
public float getWidthScaled() {
       return this.getWidth() * this.mScaleX;
}

```

That means only the width and the scale are taken into account. Changing the offsets will affect how these are positioned, and apparently the parallax code doesn't take that into account.

---
Tags: android, andengine
---


# Question
Title: Locating point on a closed path to maximize sum of distances to a sample of weighted points
I'm doing AI for a simple puzzled game and need to solve the following problem efficiently (less than 1 sec for the range specified since I need to do many iterations in a game).

> A sample of N (1 to 100,000) monsters with strength from 1 to 10,000 are distributed on the sides of a square (0 to 200,000,000) at 1 unit interval starting from the upper left corner. Move hero to a point X on the square to maximize sum of the weighted distances to the monsters. A weighted distance to each monster is calculated by MonsterStrength\*ShortestDistanceToX (by going clockwise or anticlockwise). X must also be on the 1 unit interval mark and the monsters and hero move on the sides of the square only

I have tried several approaches but none are fast or accurate enough.

The possibly complementary of this problem (minimizing the sum of distances to set of points at furthest distance from each corresponding monsters in the original set) seems to related to finding the geometric median, facility location problem, Weber problem etc.

Linear programming is also possible but might be too slow and overkilled.

Does anyone have any idea for a good approach?

---

Here is an illustration on a square of sides of length 3:

```
1-------2(M/3)-------3------4(M/1)
|                              |
12(M/2)                        5
|                              |
11(M/1)                        6
|                              |
10--------9---------8(X)-------7

```

if you put a monster of strength 3 at 2, one with strenth 1 at 4, one with strength 2 at 12 and one with strength 1 at 11 and the hero(X) at 8. the sum of weighted distane is: 3\*6 + 1\*4 + 1\*3 + 2\*4 = 33, which is also the maximum in this case

# Answer
I have found a pretty good solution for this. For anyone who is interested, here is my C/C++ code for unit testing of the algorithm. Input format: N L monster1\_pos monster1\_strength monster2\_pos monster2\_strength ....
Correctness is tested against a bruteforce algorithm on smaller cases
Large cases are generated randomly
Program run from 44 ms to 84 ms on Intel core i3 running Ubuntu Linux for largest test cases

```
#include <stdio.h>
#include <stdlib.h>

#define MAXH 100000

int num_monster, side;
int half, total;
int monster[MAXH][2]; //col0: monster pos, col1: strength
int opp[MAXH][3]; //col0: opp pos, col1: num people in opp monster, col2: index of opp monster
int boundaryMonster = -1;

int min (int a, int b) {
    return a<b?a:b;
}

int getOpp(int pos) {
    return (pos==half)?total:(pos+half)%total;
}

int getDist(int from, int to) {
    return min(abs(to-from), total-abs(to-from));
}

int totalsum(int pos) {
    int result = 0;
    for (int i = 0; i < num_monster; i++) {
        result += getDist(pos, monster[i][0])*monster[i][1];
    }
    return result;
}

//find sorted sequence of pos where monster exists at opposite pos
void oppSeq() {
    int count = 0;
    for (int i = boundaryMonster; i < num_monster; i++) {
        opp[count][0] = getOpp(monster[i][0]);
        opp[count][1] = monster[i][1];
        opp[count][2] = i;
        count++;
    }
    for (int i = 0; i < boundaryMonster; i++) {
        opp[count][0] = getOpp(monster[i][0]);
        opp[count][1] = monster[i][1];
        opp[count][2] = i;
        count++;
    }
}

int main() {
    FILE *input, *output;

    input = fopen("monster.in", "r");
    output = fopen("monster.out", "w");

    fscanf(input, "%d %d", &num_monster, &side);
    for (int i = 0; i < num_monster; i++) {
        fscanf(input, "%d %d", &monster[i][0], &monster[i][1]);
        if (boundaryMonster == -1 && monster[i][0] >= (1+2*side))
            boundaryMonster = i;
    }

    fclose(input);

    if (num_monster == 0) {
        fprintf(output, "%d", 0);
        fclose(output);
        return 0;
    }

    half = 2*side;
    total = 4*side;

    oppSeq();

    int cur_sum = totalsum(1);
    int cur_monster = 0, cur_opp = 0;
    int prev_pos = 1;

    int delta = 0;
    for (int i = 0; i < num_monster; i++) {
        int mid = 1+half;
        if (monster[i][0] > 1 && monster[i][0] <= mid)
            delta -= monster[i][1];
        else delta += monster[i][1];
    }

    if (monster[0][0] == 1) cur_monster = 1;
    if (opp[0][0] == 1) cur_opp = 1;

    int best = cur_sum;
    while (cur_monster < num_monster || cur_opp < num_monster) {
        if (cur_monster < num_monster && cur_opp < num_monster) {
            //going clockwise with both `monster` and `opp` *similar to merge sort merge phase
            if (monster[cur_monster][0] < opp[cur_opp][0]) {
                //update sum going from prev to cur_monster
                cur_sum += delta*(monster[cur_monster][0]-prev_pos);
                //start moving away from cur_monster->update delta
                delta += 2*monster[cur_monster][1];
                prev_pos = monster[cur_monster][0];
                cur_monster++;
            } else if (opp[cur_opp][0] < monster[cur_monster][0]) {
                cur_sum += delta*(opp[cur_opp][0]-prev_pos);
                //starting moving towards opposite monster
                delta -= 2*monster[ opp[cur_opp][2] ][1];
                prev_pos = opp[cur_opp][0];
                cur_opp++;
            } else if (opp[cur_opp][0] == monster[cur_monster][0]) {
                cur_sum += delta*(monster[cur_monster][0]-prev_pos);
                //starting towards opp monster and away from current monster;
                delta += 2*(monster[cur_monster][1] - monster[ opp[cur_opp][2] ][1]);
                prev_pos = monster[cur_monster][0];
                cur_opp++; cur_monster++;
            }
        } else if (cur_monster < num_monster) {
            cur_sum += delta*(monster[cur_monster][0]-prev_pos);
            delta += 2*monster[cur_monster][1];
            prev_pos = monster[cur_monster][0];
            cur_monster++;
        } else {
            cur_sum += delta*(opp[cur_opp][0]-prev_pos);
            delta -= 2*monster[ opp[cur_opp][2] ][1];
            prev_pos = opp[cur_opp][0];
            cur_opp++;
        }
        if (cur_sum > best) best = cur_sum;
    }

    fprintf(output, "%d", best);
    fclose(output);

    return 0;
}

```

---

Here is a brief explanation for the code above:

* We have a sequence of monsters' positions: e.g. 2 4 11 12
* Function `oppSeg()` generates a sorted sequence of positions opposite to that of the monsters in O(N) time by going through the monsters clockwise starting with monsters in the second half of the shape (start with `boundaryMonster` found in input loop)
e.g. we obtained the sequence: 5 6 8 10

Here are the main algorithm after the `oppSeq()` function in `main()`:

* Put the hero at intial position 1 and calculate the initial sum of weighted distance
* Calculate `delta` which is the change in the sum as the hero move 1 step clockwise
* It can be seen that `delta` only changes when the current position of the hero or his opposite position contains monsters.
* Going through the relevant positions (with monsters or monsters at opposite position) by using a procedure similar to the merging phase of merge sort on the monsters positions sequence and the opposite positions sequence
* update `delta`, `cur_sum`, `best` sum so far accordingly
* delta = 2\*monster\_strength\__at\_current\_pos - 2\*monster\_strength\_opposite\_at\_pos
\*start moving away from monsters at current position and towards monsters at opposite position in the next step
* cur\_sum = (current\_position - previous\_position)\*delta

The main part also takes O(N) time and the program uses O(N) space overall
> 1 votes

---
Tags: algorithm, ai, performance, puzzle
---


title: UDP vs TCP in multiplayer mobile game

text:
# Question
Title: UDP vs TCP in multiplayer mobile game
I'm working on a networked multiplayer game, initially for iOS.

Even with TCP\_NODELAY there are large fluctuations in latency. I can't be sure of the reason, but I would not be surprised if it was resends on packet loss due to flaky connections.

Having done no real life server work with UDP as opposed to TCP (which I have lots of experience with), I wonder if there are any significant gains to trying a UDP-based architecture.

Client packets are typically only a few bytes, sent rarely, except when moving, when the player might issue 2-8 commands/s. Server packets are slightly larger and mostly sent as response to a client command.

Connections need to be reliable and ordered.

**ADDITIONAL INFO**

Very early on I did some exploratory tests with TCP versus UDP. I would run connections `Phone -> 3G -> External static IP of router -> Wifi -> Development computer` and `Phone -> Wifi -> Router -> Wifi -> Development computer`.

What I wanted to improve was mainly the very uneven lag one would experience moving around on the map with a non-local connection.

Obviously starting animations can help, but there are (rare but valid) reasons why a move command might be rejected that the client have no way to predict. In addition, much data is hidden from the client, which again gives very little room for predictive responses.

Anyway, my results was the UDP and TCP gave pretty much the same average latency when sending data.

What I didn't look at was the actual spread - for example the maximum TCP latency in face of packet loss. I would have have needed to do some packet recovery mechanism in UDP to figure out if UDP could do better.

**So again** the results I see today with TCP is that usually it works fine, then suddenly a slowdown and a burst of movement as all the other buffered packets are more or less executed at the same time.

# Answer
> 7 votes
It turns out that this is due to how powersavings in mobile phones work.

For my iPhone, sending a steady stream of UDP pings every 200 ms will keep the interface open, and give me a RTT of 80-100 ms. Reducing the ping frequency will drastically increase the RTT, to an average of about 400 ms. Further reducing frequency causes the RTT to occasionally go even higher.

TCP is a bit different, because the OS is more aware of the open connection. What I've noticed is that TCP can suffer greatly on poor connections (regardless if we're talking wifi or 3G), because of its "packet loss = I'm using too much bandwidth" behaviour.

*In my case*, it's possible to build a fairly simple "reliable UDP" that's superior to TCP - for my game - by having the client send a packet every 200 ms and repeatedly send packets that haven't been acknowledged.

in particular this works a bit like the Q3 code, in that when you get packet with sequence number n, you can then discard any packets n - 1 or earlier without losing any data (because packet with seq number n will contain all previously unacked commands)

If packet n is lost, there's still a packet n + 1 arriving in 200 ms with that data.

This costs the occasional unnecessary resend (when an ack takes more than 200 ms to arrive), but latency is down to max ("network interruption time" + ping interval).

This would not work well if packets were fairly large, so that a resend of a packet would cause the next packet to fragment. There are many other implicit assumptions as well, so I wouldn't recommend this to anyone as a **general** solution.

Put my point is that UDP allows the flexibility to come up with a scheme that can be tailored to your particular game. If that outweighs the inconvenience of designing the UDP protocol will depend on the particulars of the game.

# Answer
> -1 votes
There seems to be quite a considerable amount of misinformation in the comments and answers above, including referencing papers that are no longer relevant.

**You should be utilizing both UDP and TCP** in your game and the reasoning is really quite simple:

**You should use TCP for reliable transmission of time insensitive actions** such as basic heartbeat and other blocking transactions (HTTP really). Some quick notes:

1. Beware of Nagle's Algorithm, where the network stack will attempt to buffer small TCP packets in an attempt to reduce the ratio of data to IP overhead. You can usually disable this functionality.
2. When network congestion occurs TCP will attempt to slow the connection down by temporarily reducing the window size and increasing it again back to normal over time. This does **not** actually affect UDP transmission anymore.

**UDP should be used for time sensitive data transmission** such as most active parts of an online game (movement, etc).

You could of course also just use UDP and build reliability around it to attempt to get the best of both worlds. But it will cost you time and complexity and in the end the best solutions best good use of prediction and user interaction transparent to network problems.

---
Tags: networking, udp, socket
---


title: Automatic shadow for isometric objects

text:
# Question
Title: Automatic shadow for isometric objects
I have like hunderd of isometric objects. One example:

I'm trying to find a way to automate creation of shadow they're casting. I ended up with following transformation:

```
   matrix.Shear(-0.25f, -0.25f, MatrixOrder.Append);
   matrix.Translate(0.5f * source.Width, 0.125f * source.Height, MatrixOrder.Append);

```

Whole algorithm:

```
  string sourceFileName = @"c:\in.png";
  string targetFileName = @"c:\out.png";
  using (var source = (Bitmap)Bitmap.FromFile(sourceFileName)) {
    using (Bitmap target = new Bitmap(source.Width * 2, source.Height, PixelFormat.Format32bppArgb)) {
      using (var g = Graphics.FromImage(target)) {
        GraphicsPath gp = new GraphicsPath();
        gp.AddPolygon(new Point[] { new Point(0, 0), new Point(source.Width, 0), new Point(0, source.Height) });
        var matrix = new Matrix();
        matrix.Reset();
        matrix.Shear(-0.25f, -0.25f, MatrixOrder.Append);
        matrix.Translate(0.5f * source.Width, 0.125f * source.Height, MatrixOrder.Append);
        gp.Transform(matrix);
        g.DrawImage(source, gp.PathPoints);
      }
      var grayscale = new Bitmap(target.Width, target.Height, PixelFormat.Format32bppArgb);
      for (var x = 0; x < target.Width; x++) {
        for (var y = 0; y < target.Height; y++) {
          var pixel = target.GetPixel(x, y);
          if (pixel.A != 0) {
            pixel = Color.FromArgb(255 / 3, Color.Black);
          }
          grayscale.SetPixel(x, y, pixel);
        }
      }
      for (var x = 0; x < source.Width / 2; x++) {
        for (var y = source.Height - 1; y >= 0; y--) {
          var pixel = source.GetPixel(x, y);
          if (pixel.A != 0) {
            break;
          } else {
            grayscale.SetPixel(x, y, Color.FromArgb(0, 0, 0, 0));
          }
        }
      }

      grayscale.Save(targetFileName, ImageFormat.Png);
    }
  }

```

Which produces something like:

It kind of works - but not 100% - the angle of shadow is changed according to proportion of the source object. Is there a way or algorithm that will work 100% or be closer to real ?

(Edited to explain more detaily).

# Answer
There is absolutely no way of making it perfect because you simply don't have enough information about depth. You have 2D representations of 3D objects.

Think about this. If it were a real object, there would be parts of it that the camera can't see, but still block the light and cast a shadow. Also, think about each pixel, there is no way to know how high off the ground the surface at that pixel is. I mean, WE can see that steps are leading up to a treehouse, but an algorithm does not have that kind of semantic information, it just sees a 2D sheet of colours and alphas.

I think what you have is the best approach you can hope for. Although, like ashes999 suggested, you can use photoshop to tweak your projection/angle/pivot.

Also, you could accumulate some jittered samples to get an antialiased shadow which would look nicer.

As for the angle being dependent on proportions, I am not sure what kind of linear algebra system you are using, but you could experiment with making the shear inversely proportional to sprite proportions to counteract the effect. I'll leave it up to you to experiment.
> 3 votes

---
Tags: c#, graphics, graphics-programming, isometric, graphic-effects
---


# Question
Title: Vertex Buffer Sharing between DirectX11 and Directx9
In my d3d9 engine i want to take benifit of compute shader of d3d11. So firstly I created a vertex buffer in d3d11 with D3D11\_BIND\_UNORDERED\_ACCESS and then tried to create the d3d9 vertex buffer with the Handle. like

```
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.ByteWidth = sizeof(stVertex) * 100;
bd.BindFlags =   D3D11_BIND_UNORDERED_ACCESS  | D3D11_BIND_VERTEX_BUFFER   ;
bd.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS | D3D11_RESOURCE_MISC_SHARED;
hr = dev->CreateBuffer(&bd, NULL, &pVBuffer);       // create the buffer
hr = CreateBufferUAV( dev, pVBuffer, &m_pBufOutUAV );

....
HANDLE sharedHandle = NULL;
IDXGIResource* pDXGIResource = NULL;
pVBuffer->QueryInterface(__uuidof(IDXGIResource), (LPVOID*) &pDXGIResource);
pDXGIResource->GetSharedHandle(&sharedHandle);

hr = g_pd3dDevice9->CreateVertexBuffer( 100*sizeof(stVertex), NULL ,
                                  VERTEX::FVF_Flags, D3DPOOL_DEFAULT,
                                  &g_pVertexBuffer9, &sharedHandle ); //ERROR :

```

which gives error :

> Direct3D9: (ERROR) :Opened and created resources don't match, unable to open the shared resource. Direct3D9: (ERROR) :Cannot create Vidmem or Driver managed vertex buffer. Will ***NOT*** failover to Sysmem. Direct3D9: (ERROR) :Failure trying to create Vertex Buffer

After that i tried to create vertex buffer in directx9 first and tries to share that in direct11 but still it gave error.

```
HANDLE sharedHandle9 = NULL;
    hr = g_pd3dDevice9->CreateVertexBuffer( 100*sizeof(VERTEX), NULL ,
                                      VERTEX::FVF_Flags, D3DPOOL_DEFAULT,
                                      &g_pVertexBuffer9, &sharedHandle9 );
ID3D11Resource*  pTempResource11 = NULL;
    hr = dev->OpenSharedResource( sharedHandle9 , __uuidof(ID3D11Buffer) ,(LPVOID*) &pTempResource11 ); //Error

```

> D3D11: ERROR: ID3D11Device::OpenSharedResource: Returning E\_INVALIDARG, meaning invalid parameters were passed. \[ STATE\_CREATION ERROR #381: DEVICE\_OPEN\_SHARED\_RESOURCE\_INVALIDARG\_RETURN \]

I am able to share textures but not buffers.please help me here.
thanks.

# Answer
Well, I'm surprised about the stuff you can learn when researching stuff for answering a question.

Short answer: you can't.

This stuff you probably already know, but I'll cover it in case other people find it useful.

At first I thought you can't share handles among Direct3D devices, let alone versions, but it turns out that you can actually do that! In fact, there are three things you can do:

## Share data, including vertex buffers across Direct3D 9 instances

You can even do this across processes! According to this article:

> Direct3D resources can now be shared between devices or processes. This applies to any Direct3D resource including textures, vertex buffers, index buffers, or surfaces (such as render targets, depth stencil buffers or off-screen plain surfaces). To be shared, you need to designate a resource for sharing at the time of creation, and locate the resource in the default pool (D3DPOOL\_DEFAULT). Once a resource is created for sharing, it can be shared across devices within a process, or shared across processes.

The key to do this, as you already know, is the last parameter of `CreateVertexBuffer`. Remember that this is part of DirectX9Ex, which is only available on Vista and up.

## Share a surface across different versions of Direct3D

You create a surface on one API, and render from another one.

This is not trivial, especially when one of the APIs is Direct3D 9, as it uses a completely different subsystem than DirectX 11 (DXGI 1.1). You also have to synchronize access to the surface, but in general, is very doable, according to this article.

## Share textures across Direct3D 11 instances, or even across Direct3D versions

So you create a buffer with `CreateBuffer` and then retrieve it with `OpenSharedResource`. However, unlike Direct3D 9, in Direct3D 11, you can only create a sharable buffer for 2D non-mipmapped textures, according to this article (emphasis mine):

> **D3D11\_RESOURCE\_MISC\_SHARED**
>
> Enables resource data sharing between two or more Direct3D devices. *The only resources that can be shared are 2D non-mipmapped textures*.

Also, in here:

> *The only resources that can be shared are 2D non-mipmapped textures.*

In fact, you can share a texture across Direct3D versions, with some restrictions. According to the same article:

> Textures being shared from D3D9 to D3D11 have the following restrictions.
>
> * Textures must be 2D
> * Only 1 mip level is allowed
> * Texture must have default usage
> * Texture must be write only
> * MSAA textures are not allowed
> * Bind flags must have `SHADER_RESOURCE` and `RENDER_TARGET` set
> * Only `R10G10B10A2_UNORM`, `R16G16B16A16_FLOAT` and `R8G8B8A8_UNORM` formats are allowed

So, unfortunately you're out of luck. You can't share a vertex buffer across Direct3D versions. In fact, you can't share anything different from 2D non-mipmapped textures when you're using Direct3D 11.
> 7 votes

---
Tags: directx, directx11, directx9, assets
---


# Question
Title: Resolving a collision between point and moving line
I am designing a 2d physics engine that uses *Verlet integration* for moving points (velocities mentioned below can be derived), *constraints* to represent moving line segments, and *continuous collision detection* to resolve collisions between moving points and static lines, and collisions between moving/static points and moving lines.

I already know how to calculate the Time of Impact for both types of collision events, and how to resolve moving point static line collisions. However, I can't figure out how to resolve moving/static point moving line collisions.

Here are the initial conditions in a point and moving line collision event. We have a line segment joined by two points, A and B. At this instant, point P is touching/colliding with line AB. These points have unit mass and some might have an initial velocity, unless point P is static. The line is massless and has no explicit rotational component, since points A and B could freely move around, extending or contracting the line as a result (which will be fixed later by the constraint solver). Collision is inelastic.

What are the final velocities of the points after collision?

# Answer
> 1 votes
Usually you can treat moving/moving intersections as though one of them is stationary and the other is moving with the sum of the two velocities.

Somewhere on the line segment is a collision point that you can determine. That point's velocity is an interpolation of A & B velocities. Now you can treat the line segment as static and sum P velocity to the collision Point velocity and treat it as if P was traveling at the summed velocity.

---
Tags: physics, collision-resolution
---


# Question
Title: What ways are there for making vector types available in scripting?
I use Google V8 engine to embed Javascript into my game for scripting. As interface to my native code, I already registered some C++ functions to the scripting context.

In the native code, I make intense use of the C++ library GLM which adds vector types and geometry functions. The naming is in a style that may be known from shader code, for example `vec3`, `uvec2`, `normalize()`, `length()`, and much more.

Now I would like to make these types available in scripting. That would be useful because of both, the geometry functions and the vector types. Especially, I want to use the vector types as parameters in the C++ functions I mapped to the Javascript context. At the moment I'm using arrays like `float[3]` instead of the vectors like `vec3`.

So I am looking for possible ways to bring GLM functionality into Javascript. This is what I can think of.

* Create the most important types by hand, either in a Javascript file or injected from C++ code using object templates. Unfortunately, I cannot do this for all of the many functions in GLM. But it would better than nothing.
* There might already be a GLM port of Javascript, which I haven't found on the internet.
* I could pick a different geometry library for use in Javascript. For bound C++ functions, I'd have to translate their types into GLM ones then.
* What can you think of...

Maybe there is a cool way to all the functionality of GLM over to Javascript. Are there things like C++ to Javascript source code converters? Or automatically binding a whole C++ namespace to scripting? I don't think that is possible. But Javascript is such a dynamic language, there must be a way to make the GLM types available for it.

What ways are there for making the vector types, and preferably also the useful geometry helper functions, available in scripting?

# Answer
In V8 you can wrap your own, custom C++ classes expose them to JavaScript and have V8 take care of destructing the instance once the corresponding JS object gets GC'd.

But you still have to write your methods in a style like this:

```
Handle<Value> Vector::add(const Arguments& args) {

    Vector *vector = WrappedClass::unwrap<Vector>(args.This());
    if (args.Length() == 2) {
        vector.x += args[0]->DoubleValue();
        vector.y += args[1]->DoubleValue();

    } else {
        // throw a exception or something
    }

    return args.This();

}

```

Now as you can see there's no trivial way to just take the C++ class and put it into JS. You either have to write some custom binding generator and generate the bindings pre-compile time, or you write it manually. You'll also have to handle cases where operator overloading happens, or where a method has multiple signatures.

Given all of this it would be not much more trouble to put the library through Emscripten and write bindings for that and then use the compiled JS code directly.

As for performance, I'm pretty sure that writing pure JS will probably be faster for 90% of the cases (except areas where you can do a lot of magic through raw pointers and memory access) because all those wrappers will introduce a lot of indirection.

Emscripten could be quite decent in terms of performance, but I assume it won't be trivial to set up.

So sadly, there's no easy way to expose all of the functionality, if you really just need a robust vector library for JS, you could take a look at Sylvester, but this of course won't give you the benefits of GLM's naming conventions. Also, I'd be careful and have a look at Sylvester's code base, just to make sure you know how much object creation / garbage collection you can expect from heavy use.

For reference you can check out two of my dead side projects in which I used V8 for scripting:
> 1 votes

# Answer
On JavaScript side you can use glMatrix. (Take a look on this presentation: http://media.tojicode.com/sfjs-vectors/#1 ). On C++ side you can use GLM as usaual. You can cast pointers to floats to GLM types. For example:

```
float fArray[3];
glm::vec3& v = *((glm::vec3*) fArray);

```
> 0 votes

---
Tags: c++, javascript, scripting, glm
---


# Question
Title: In XNA, what symbols are available for conditionally-compiling platform-specific code?
In XNA, what defines are set to allow me to determine if my code is running on a PC with Windows, Xbox, or Windows Phone?

Right now I am assuming it is these three:

* `WINDOWS_PHONE`
* `WINDOWS`
* `XBOX360`

Are these correct? Are there any additional symbols?

# Answer
According to the documentation, the available symbols are:

* `WINDOWS` for Windows.
* `XBOX` or `XBOX360` for the 360 and
* `WINDOWS_PHONE` for the phone.
> 2 votes

---
Tags: xna, windows, xbox360
---


# Question
Title: How to implement "identify item" feature in RPG
In many games there is an approach that you can't use item that hasn't been identified. And usualy you can't identify it by just using it. While this approach simplifies a lot of things it just doesn't feel right to me. It doesn't make sense that I can't equip an armor or sword because I don't know if it has any magical features.

I was thinking about some kind of "identification by use" system but I can't figure out a natural way to do it. What if I drink a potion that boosts my "Speech" skill for a period of time? Should my character instantaneously know that its skill have increased? Should it know the exact value? Or should I increase the skill behind the scenes but leave the displayed value intact and just give some subtle hint ("You suddenly (...)")?

What about weapons and armors? It wouldn't make sense to know anything about it just by equipping it. One approach would be that attacking a target could update weapon's min and max damage basing on damage dealt but then it greatly depends on target's defense and resistances (I'm not sure if that's a bad thing though).

Of course there are conventional ways like identification scrolls and I do have them but I was hoping for some alternative (not a replacement though, you probably can't know everything about every object only by using it).

Has anyone ever thought about it and can share some insight?

# Answer
Your hint at a "find the min and max progressively though use" is a great start!

Having an item's stats get rolled on pickup (or however you plan to generate stats for items), but separating that from what the player sees when inspecting an item could create very intriguing gameplay mechanics.

You could have a "learning" system, where from the get-go, the displayed weapon properties are blank. After dealing a blow to an enemy a random value D from the damage range is generated. This makes the displayed property of MinDamage and MaxDamage = D. After striking again, a new D is generated and compared to the MinDamage and MaxDamage. If D \> MaxDamage, then MaxDamage = D.

And so on. This would be fascinating to play with, especially if things that you don't perceive as a character (things like, borrowing from Diablo 3, Magic Find) are never displayed on an item unless an ID scroll is used. Through normal means, though, you would slowly start to find out more and more about a particular weapon/armor/trinket.

A feature like this would work better in a slower-paced hack-n-slash, where you can actively track your knowledge of an item between short fights. If you fought hundreds of mobs before checking, however, you will basically know the full extent of the obvious properties of an item.

I'm a junkie for stats and I love the idea of "learning" in a game. This is a neat idea.
> 4 votes

# Answer
First you should identify the purpose of the ID system. It servers a two core functions.

1. Paces the game. By forcing players to go back to town to ID things, or pick up ID items, gameplay is paced. Especially in dungeon crawler types, where the ID system is popular, without any forced break, gameplay quickly becomes monotonous. It also prevents breaking sprees to look at your gear. Instead you are encouraged to ID and evaluate it all at once.
2. Money sink. Many games, especially online games, need money sinks to help balance the economy.

Other than that, there is no big game mechanics reasons other than, "everyone else has it." If you don't think an ID system fits in your game, then don' put one. Simple as that.

You mentioned ID by use. You could have some sort of unlock or level system. As your character uses a weapon/armor more then your character could "learn" its secrets and unlocks its power. This basically gives items you find an experience/level system.
> 3 votes

---
Tags: game-design, rpg
---


# Question
Title: How can I use ParallaxBackground in AndEngine?
I'm new to game development with AndEngine. I want to add ParallaxBackground but I don't know how to change the background when the player moves. I'm using arrows for moving a player.

Now my question is where I write the code `parallaxBackground.setParallaxValue(5);`?

I have written this line in `onAreaTouched` method of arrow but it does not work.

**Code**

```
private Camera mCamera;
private static  int CAMERA_WIDTH = 800;
private static  int CAMERA_HEIGHT = 480;

private BitmapTextureAtlas bgTexture;
private ITextureRegion bgTextureRegion;

@Override
protected void onCreateResources() {

    BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
    bgTexture = new BitmapTextureAtlas(getTextureManager(),2160,480,TextureOptions.REPEATING_BILINEAR);
    bgTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bgTexture, this, "background.png", 0, 0);
    bgTexture.load();
}
@Override
protected Scene onCreateScene() {

    this.getEngine().registerUpdateHandler(new FPSLogger());

    Scene scene = new Scene();
    scene.setBackground(new Background(Color.BLACK));

    final ParallaxBackground parallaxBackground = new ParallaxBackground(0, 0, 0);
    final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();

    parallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.bgTextureRegion.getHeight(), this.bgTextureRegion, vertexBufferObjectManager)));
    scene.setBackground(parallaxBackground);

Robot robot = new Robot();

    // add Player
    final AnimatedSprite animatedRobotSprite = new AnimatedSprite(robot.centerX, robot.centerY, 122, 126, (ITiledTextureRegion) robotTextureRegion, getVertexBufferObjectManager());
    scene.attachChild(animatedRobotSprite);
    animatedRobotSprite.animate(new long[]{1250,50,50});

    // add right arrow button
    Sprite rightArrowSprite = new Sprite(0, CAMERA_HEIGHT-70, rightArrowTextureRegion, getVertexBufferObjectManager()){

        @Override
        public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) {

            switch (pSceneTouchEvent.getAction()) {

            case TouchEvent.ACTION_DOWN:
                moveRight = true;
                parallaxBackground.setParallaxValue(5);
                break;

            case TouchEvent.ACTION_MOVE:
                moveRight = true;
                break;

            case TouchEvent.ACTION_UP:
                moveRight = false;
                break;

            default:
                break;
            }
            return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
        }
    };
    scene.attachChild(rightArrowSprite);

    scene.registerTouchArea(rightArrowSprite);

    scene.setTouchAreaBindingOnActionDownEnabled(true);

    scene.setTouchAreaBindingOnActionMoveEnabled(true);

    scene.registerUpdateHandler(new IUpdateHandler() {

        @Override
        public void reset() {

        }

        @Override
        public void onUpdate(float pSecondsElapsed) {

            if ( moveRight ){
                animatedRobotSprite.setPosition(animatedRobotSprite.getX()+speedX, animatedRobotSprite.getY());

            }
        }
    });

    return scene;
}

```

# Answer
The Parallax layers themselves can be quite a bit of trouble- especially if you want them to move with the character rather than just being static or moving at a constant rate of speed.

My suggestion: One AndEngine user uploaded a custom ParallaxLayer if you're in the GLES2.0 branch that can be found here, I'd recommend using it as it supports scrolling at variable rates and overall seems like more of what you're looking for. Good luck with AndEngine- it's a fun way to make an Android game!
> 2 votes

---
Tags: android, opengl-es2, andengine
---


# Question
Title: Map logical coordinates to graphical for walking
I'm having a problem with mapping logical coordinates to graphical ones when my character is walking. I've been able to map them without the graphical walking in between, i.e it just "jumps" from one tile to the other.

The logical coordinates are represented such as \[0,0\], \[0,1\] etc. and a character can only be in one of these tiles at a time. I want my character to graphically move from one tile to the next at a given speed/pixels per rendering update until it hits the logical tile's graphical position.

If I didn't phrase myself good, please don't be afraid to tell me.

# Answer
Probably I should ask this as a comment, but I'm not yet allowed to. So I'll blatantly formulate this as a semi-answer.

It sounds like entity.getX() is returning an integer between \[0, maxTileNumberX\] representing the tile position. In the end you're trying to interpolate the movement between getX() and getX()+1 using integers only. Why not make xOffset a float between \[0,1\]? Then do the calculation

Math.round((entity.getX() + entity.getXOffset()) * tileSize)

Of course this means speed must also be a float and scaled appropriately. Is there a reason not to use float? If you want to decouple the logic and graphic, that would be the first natural step. Only the graphic layer needs integers, the logic should be allowed to operate with its own data types suitable for the problem.
> 2 votes

# Answer
Alright, I think it's time I posted my solution as an answer(thanks Byte56). It's not the prettiest but it works well enough for me.

I basically have a method for moving in the different directions. The goal variables are the tile we want to move to. In the next iteration of the game loop the entity's update method will take care of the goal variable.

```
/**
 * Move the entity right.
 */
public void moveRight() {
    if(goalY == y) {
        goalX = x+1;
        horizontalSpeed = speed;
        //  resetGoalY();
    }
}

```

I got a bug with this method that I will fix later on but I think it's good if you get the bigger picture of how my movement works. As long as goalX != x we will update the offset on each axis with the given speed. Note that the two different speeds can either be negative or positive depending on what direction we want to go. I then check if the offset equals the maximum offset (in my case, this is the tile size) and seeing as it can be either tilesize or -tilesize I will check with Math.abs which gives the absolute value of the values. If the values are equal it's time for the logic to move to that tile and I then reset the offsets.

```
/**
 * Update the entity's movement.
 */
private void updateMovement() {
    if(map.isTileWalkable(goalX, goalY)) {
        if(goalX != x) {
            xOffset += horizontalSpeed;
        }
        else if(goalY != y) {
            yOffset += verticalSpeed;
        }

        if(Math.abs(xOffset) == maxXOffset) {
            resetXOffset();
            x = goalX;
        }
        else if(Math.abs(yOffset) == maxYOffset) {
            resetYOffset();
            y = goalY;
        }
    }
}

```
> 0 votes

---
Tags: java, 2d, lwjgl, tilemap
---


title: jMonkeyEngine Pros and Cons

text:
# Question
Title: jMonkeyEngine Pros and Cons
I want to know some good reasons to use jMonkeyEngine for a Java 3d game development tool instead of just creating a game with LWJGL myself? I want to know a good reason I should choose this tool. Does anyone have a list of pros and cons for me to work with?

# Answer
> 3 votes
**Pros** (as from their own website http://jmonkeyengine.org/)

* Free, open source
* Multiple platform targets
* Modular design
* Great documentation
* Shader based architecture
* User friendly SDK

**Cons**

* If you're interested in the low level parts of creating a game you're better off starting with LWJGL yourself.
* Some engines make you work a certain way but I'm not sure if jMonkeyEngine does that.

If you're not familiar with OpenGL or game development I would advice you to start with jMonkeyEngine since that's more high level and you will be able to produce quality games a lot faster. LWJGL is not even an ounce object oriented which makes using it in java a bit of a pain in the beginning but it's great when you understand how everything works.

That's just my two cents but everyone has different opinions.

---
Tags: java, 3d, lwjgl, jmonkeyengine
---


# Question
Title: How do I get the areas enclosed by an arbitrary 2D shape?
In my game I want users to be able to draw arbitrary 2D shapes of any length around game objects. The shapes must be closed and drawn with a single stroke that does not overlap.

For example:

I want to detect the presence of any game object in the green areas above.

I know how to detect whether a point is within a given polygon, but how do I tell where the polygons (green areas) are from just the points in the line?

# Answer
First, define what is 'neighbour'. In your case, pixels 'A' and 'B' are connected if `abs(A.x - B.x) <= 1 && abs(A.y - B.y) <= 1`. This is the rule that Microsoft Paint uses when doing flood fill.

Your `Valid` and `Invalid-shape isn't closed` can be easily detected using a Flood fill. A flood fill marks a non-empty pixel green. It then continues the flood fill with its neighbours, eventually filling the full shape. To do this, pick a random pixel, then find an empty neighbour. Do a flood fill starting from this neighbour with a unique color. Re-iterate over all pixels to ensure you have filled all of the areas. (Picture 2)

Now find out which colors touch the edges of your picture. These colors should be erased, as they do not constitute a closed space. (Picture 3)

Now, you want to detect lines that do not contribute to a filled area. To do this, mark all black pixel neighbours of a filled pixel in BLUE. (Picture 4)

All lines which are still black do not contribute to the edges of an area. They are invalid. (Picture 5).

Detecting your 'Valid, within a single stroke' requires a small extra step. For every invalid pixel, start a flood fill. If, during your flood fill, you touch the edges of two different areas, this line actually connects two areas and it is therefore part of your valid image.

You need to decide whether this algorithm is good enough. For example, drawing a thick edge by going back a few pixels will be marked as 'invalid', as this extra 'blob of ink' does not connect two areas. You could improve this algorithm by adding a 'time' dimension: you give a list of pixels in the order in which they were drawn.

Finally, think about user experience. Drawing a 'V' shape will most likely result in \>2 pixel neighbours for a new pixel drawn in the tip of the V. Can you algorithm that detects overlapping edges cope with that?
> 3 votes

---
Tags: 2d, mathematics
---


title: Symmetry preserving path simplification

text:
# Question
Title: Symmetry preserving path simplification
I'm using the Douglas peucker (DP) algorithm to simplify some (2d) closed paths forming a shape. This works pretty good, but not so much for closed paths that have some symmetry. Take for example a pyramid like shape, with the slopes essentially being staircases. Depending where you define the start for DP it will (obviously) result in different simplified shapes.

Does anyone know of some sort of generic symmetry preserving simplification algorithm? In the case of (a top up) pyramid you could force this manually by having DP run from the end vertice of the top line to the first vertice of the bottom line, and another run from the end vertice of the bottom line to the first vertice of the top line. but this is of course very specific to the symmetry of this particular pyramid.

# Answer
Break your closed shape into open paths, some of which are related by known symmetry transformations. For example, depending on your needs and where control points are located, a circle (to be simplified into a polygon) can be divided into two halves or four quarters related by rotation or reflection, or a rhombus into its four sides.

Then you can compute the simplification of one of parts of the original curve and replace all its copies with transformed copies of the simplified curve.
> 1 votes

---
Tags: mathematics, graphics, algorithm, graphics-programming
---


# Question
Title: How to scale openGL textures by a ratio based on height/width (or alternative)?
I have been able to successfully allow my UI to extend over edges of my game on higher resolutions by using the Android Guide and by implementing this code on the GL10 object:

```
gl.glTranslatef(GTEngine.get_SCREEN_RATIO(), 0f, 0f);

```

Where the first parameter is the ratio calculated by dividing the width by the height.

My confusion arises in the ability to use :

```
gl.glScalef(n,n, 1f);

```

... to scale the image by using the same screen ratio in order to account for the "growth" or "shrinkage" that comes with different resolutions. Does anyone have a solution for this n variable? I cannot seem to make up some mathematically solution that works, and am worried that I may be forced to build a case by case logic (\>.\>)

# Answer
If I'm understanding you correctly you want an object to scale and appear the same size /ratio (relative) on whichever device you are using? (i.e., so it doesn't appear stretched in either the X or Y direction)?

If so, the way I worked around this was to decide the size I wanted my object to appear on my development device, so on my Nexus 10 which has a res of 2560 x 1504 (Ratio of 1.7) , my sprites are 102 x 100 in size.

Therefore, I said:

*102/2560 = 0.03984375f*

*100/1504 = 0.0664893617021277f*

And then, in my code just just did:

**(pseudo code** follows)

```
sprite width = (0.03984375 * current Viewport Width)
sprite height =(0.0664893617021277 * current Viewport Height)

```

I'm not using GLScalef to scale my objects though, I'm manipulating the vertices directly. But this results in objects of the same relative size and ratio on all screens which (I think) is what you're after?
> 1 votes

---
Tags: java, android, opengl-es
---


title: How to check for cube collisions?

text:
# Question
Title: How to check for cube collisions?
I want a method, which takes two "ObjectBox" objects (A "ObjectBox" has `.getX()` `.getY()` `.getZ()` `.getSizeX()` `.getSizeY()` `.getSizeZ()` methods) as a parameter and return true if the two Boxes are colliding and false if they aren't.

So it should be something like this:

```
public static boolean checkCollision(ObjectBox box1, ObjectBox box2){
return //TRUE IF COLLIDING - FALSE IF NOT COLLIDING
}

```

I tried figuring it out but it seemed pretty hard to me.

# Answer
This is called an AABB (Axis Aligned Bounding Box). The collision checks for these are pretty fast and simple. Basically you just check their relative positions and see if all three axes overlap:

```
public static boolean checkCollision(ObjectBox a, ObjectBox b){
{
   //check the X axis
   if(Math.abs(a.getX() - b.getX()) < a.getSizeX() + b.getSizeX())
   {
      //check the Y axis
      if(Math.abs(a.getY() - b.getY()) < a.getSizeY() + b.getSizeY())
      {
          //check the Z axis
          if(Math.abs(a.getZ() - b.getZ()) < a.getSizeZ() + b.getSizeZ())
          {
             return true;
          }
      }
   }

   return false;
}

```

Only if all three axes overlap there is a collision. For example, if the cubes were overlapping on the X and Z axes and not the Y, it means that the cubes are above or below each other and not colliding. You can optimize the code above slightly, if there's an axis you're more likely to be colliding on, put that check first so you don't need to check the others.

Keep in mind, the above code assumes that the position is the center of the cube and the size is getting the half extents of the cube. If your `getSize_` functions are returning the full dimension, you'll need to half them for the above to work properly.
> 10 votes

# Answer
You could also consider doing the checks as a method in one of the objects. It might end up making your program less complex. For example instead of

```
public static boolean checkCollision(ObjectBox box1, ObjectBox box2){
    return //TRUE IF COLLIDING - FALSE IF NOT COLLIDING
}

```

You would have something like

```
public boolean checkCollision(ObjectBox other){
    return //TRUE IF COLLIDING - FALSE IF NOT COLLIDING
}

```

Which would be a public method inside of your ObjectBox class. Then you just have to do some basic Math inside of the box assuming that the boxes are 2D ( a little more Math if they are 3D) and invoke the new method as follows:

```
ObjectBox obj1 = new ObjectBox(/*Assume some parameters*/);
ObjectBox obj2 = new ObjectBox(/*Assume some parameters*/);
//Now we can compare them without needing the static method.
if(obj1.checkCollision(obj2))
    //Do amazing things.

```

Edit: Byte56 has you covered on the collision checking.
> -3 votes

---
Tags: opengl, java, 3d, collision-detection
---


# Question
Title: Designing a four-directional movement control
I'm developing an RPG for iOS. Currently, I plan my controls to look like this:

So the user can interact with objects, people, etc. by tapping on the right side of the screen, and moves by swiping in the direction they want to go in on the left side of the screen. Right now, I'm having a problem with the movement controls. What I want is for there not to be a fixed d-pad; I want the user to be able to tap anywhere on the left side of the screen and swipe in the direction they want (within a range, demonstrated in the below image), and it seems easy enough to implement this.

However, I'm having a bit of a math problem. Since I'm developing for iOS, how I planned to implement this was to subclass UIView and have two properties, `startTouch` and `endTouch` that represented where the user began his/her swipe and where the user lifted his/her finger. Then, I could do a bit of math and discern which direction the swipe was in. But I'm having a bit of trouble doing the math, and that's what my question's about: **given two points, how can I figure out if the swipe was going up, down, left, or right**? Keep in mind that the user could tap anywhere on the screen and that tap is the center of the imaginary d-pad, like so:

# Answer
Take the resulting vector `Dir` from subtracting the start point from the end point. Now use `atan2(Dir.y, Dir.x)` to get the angle of the vector (angle between positive X axis). Use that angle to decide the direction of the swipe. Include your dead zones as desired.

You can easily utilize something like this answer. Where your direction could be:

```
enum direction {
    Left,
    DeadZoneDownLeft
    Down,
    DeadZoneDownRight,
    Right,
    DeadZoneUpRight,
    Up,
    DeadZoneUpLeft
}

```
> 2 votes

---
Tags: mathematics, ios, objective-c, controllers
---


# Question
Title: ASP.NET MVC & SQL Server vs. PHP & MySql
I'm going to develop a strategy browser-based game with ASP.NET MVC and SQL Server.

However, as I explored the web to get some ideas and patterns from existing games, I found out that none of them developed by .NET tools.

So, it made a question for me that what's the reason behind this...:

1) Is there any big draw back for microsoft technologies in this area?

2) Why all of games in this field are developed with PHP & (maybe1?) MySql?

3) Is there any performance issue with above mentioned microsoft technologies in this area?

Thanks in advance

# Answer
> 2 votes
1. There are some differences between ASP.NET and PHP, mostly they suit different programming styles. The both use a similar request/response pattern designed for generating old school web pages. They seem about equally useful.
2. I think the trends have more to do with market powers than technical differences, until a few years ago you couldn't get a good free software stack for ASP.NET, so hobbyists mostly went with PHP.
3. Both ASP.NET and PHP are geared towards treating each incoming request as a separate entity. If you want to share data between the processing of different requests you are more or less forced to do so through a database, and that can be a huge bottleneck.
4. What tool you actually should use? Well I'm glad you asked. Node.js provide easy to use http server functionality without making any assumptions on what threading structure you would like to use or how you want to share data internally. For a basic website the setup is a bit more complicated than PHP or ASP.NET, but for a game server you'll be rid of a lot of stupid constrictions. Send whatever data needs to persist in case of a crash to the database, keep everything else in process memory.

---
Tags: c#, browser-based-games, .net, strategy
---


# Question
Title: How to flip a quad (openGL es 2.0 Android / Java)
How would one go about 'flipping' a quad, either horizontally or vertically? (Just a single quad, not everything in view).

I know how to rotate a quad, this is my rotation method:

```
public void rotate(float x, float y, int angle){

    //Convert co-ordinates (Following section just converts my coordinates

    //Left hand
    xPlotLeft = (-MyGLRenderer.ratio)+((x)*MyGLRenderer.coordStepAmountWidth);
    //Top
    yPlotTop = +1-((y)*MyGLRenderer.coordStepAmountHeight);
    //Right hand
    xPlotRight = xPlotLeft+((quadWidth)*MyGLRenderer.coordStepAmountWidth);
    //Bottom
    yPlotBottom = yPlotTop-((quadHeight)*MyGLRenderer.coordStepAmountHeight);

    //Center of quad (Along the x)
    centreX = xPlotLeft + ((xPlotRight-xPlotLeft)/2);
    //Center of quad (Along the y)
    centreY = yPlotBottom + ((yPlotTop-yPlotBottom)/2);

    //Rotate the quad

    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

}

```

I'm unsure how to do something similar just to flip (or 'mirror') the quad.

# Answer
> 8 votes
Create a scale matrix with a scale of -1 on the axis you want to mirror.

# Answer
> 0 votes
The simplest way to flip it would be to remap texture coordinates so that they are the other way around. Alternatively, keep the texture coordinates as they are and do a switch on the vertex coordinates.

---
Tags: java, android, textures, opengl-es2
---


# Question
Title: Is it more efficient to render full size with AA, or scaled down with no AA?
Which is more resource-efficient (given a typical modern 3D game scene):

* Rendering it at 100% scale **with anti-aliasing**, or
* Rendering it larger and scaling it down to fit the screen, but **without AA**?

The idea is that anti-aliasing is a really expensive operation and avoiding it makes things faster. Is this the case?

I haven't had the opportunity to try it, since I work almost exclusively with 2D games.

# Answer
> 11 votes
The second option - drawing at a higher resolution than the target and downsampling to the target resolution - is known as supersampling and is considered a form of AA; if you read about this topic you'll see it referred to as SSAA.

It will almost certainly be slower than turning on other AA techniques built into modern games, such as MSAA (multisampled antialiasing, which is usually what people mean when they just say "AA" without any other qualifiers) or postprocessing effects like FXAA or MLAA. All these techniques were developed precisely to provide a faster alternative to SSAA.

For example, if you're doing 4xSSAA (let's say), you're drawing an image twice the width and height of the final image, so that you have 4 samples per pixel of the final image. Then, whenever you run a pixel shader on some object, you're running it 4 times for each final image pixel touched by that object. In contrast, with 4xMSAA you'll only run the pixel shader once for each final image pixel touched, and replicate that result to all 4 samples. This allows you to greatly reduce the amount of shader work while still getting the effects of antialiasing along geometry edges, which is where it matters most. This is typically *much* faster than SSAA. Modern GPUs also have compression schemes to reduce the memory bandwidth used for MSAA, which helps performance further.

And if you turn on a postprocessing AA method it'll be even faster (although the results aren't quite as good), as it is simply rendering the frame normally, at the target resolution, then going over it afterward with a shader that detects and repairs jaggies.

So, you can expect that the AA methods available in typical games these days are far faster than simply rendering at a higher resolution and downsampling.

---
Tags: 3d, performance, antialiasing, scale
---


# Question
Title: How to make money from creating a game for Windows?
I'm going to create a game. Well, a set of games, but they will accrue little by little. So, at the beginning there will be one game.

The game will be written in C# with WPF and WCF techs, including server-side game processing, statistics and so on.

And yeah, I just have quit my current job in one company, so I need to live on.

So, how to start making money on this wonderful development? It will make much pleasure for me, as soon as I like developing and actually playing those games (gomoku, sea battle, etc)?

I only see two ways — one of them is to find an investor and the other one is to complete at least one game with 100% server uptime and start distributing it.

But I need recommendations. I need help, actually — the explanation how exactly to do all of this things and to to not starve:) .

# Answer
> 17 votes
Most of the indie games that have made it big in the past few years have published extensive development blogs, engaged with the gaming community, and eventually released their games on Steam. Buzz for games like World of Goo, Braid, Super Meat Boy, VVVVVV, and others often took a year or more to build up. Many of them were made by 2-person teams consisting of a programmer and an artist. Polish and beauty are very important when you're trying to get noticed.

# Answer
> 9 votes
I am not sure the size of these games you are planning, but I have seen a lot of success with indie developers on the Steam store (Terraria is a great example of a game that earned $1 000 000 within one year of when development started). But if you are planning on a series of small games, maybe it would be best to make a website and use silverlight and let people play for free, and try to make money on advertising (similar to Addicting Games).

Though definitely a key to success with indie development is promoting it through social media. The game can be fantastic, but if no one ever hears about it then no one will play it. So while you are developing, start a blog or forum or something to build a community and when you have a demo/trial mode ready try to find indie game reviewers that will play it and blog about it on their websites.

# Answer
> 7 votes
Just to add to what many people have already said, "Buzz" is a key factor. The "hype-train" of a game can indeed make it very successful. Steam is an option, particularly if you want to reach the biggest user-base of gamers (as we all know Steam has the most users). However, and i can't stress this enough: **It is extremely difficult to get any indie game onto Steam unless it has a huge amount of "Buzz"**.

However there are quite a few specifically tailored alternatives: Desura, Indievania and IndieCity. So there's defiantly plenty of options, I believe Desura is probably your best bet to getting the biggest commercial audience without too much worry. I say "too much worry" because it's important to note that each service will have quality control. Steam is known to have very high standards albeit a bit obvious, whereas the alternatives suggested are **defiantly a lot more varied and open to all sorts of games**. Which is why i say it's your best bet.

There is also the legal side of things, and of course this depends on where you live but there is the matter of taxes, and it's also important not to forget that each of the services will take a specific cut of the sales (their cut varies from service to service). Do your research and find the best one for you.

Note: This answer is very much tailored to using indie-game hosting services that are already on the internet, and there are other alternatives such as Andrew Jackman stated in his answer, but for the majority of indie developers, depending on their background, using an established service is the most straight forward way.

(For example, I personally have no experience with Silverlight or using any form of web language, so personally for me, using a pre-defined service were all I have to worry about is making my games meet the terms of the services, is a lot easier.)

# Answer
> 2 votes
Recently it became a trend among indie studios to sell early development versions of games for much less than the expected final price, bundled with the guarantee that the early-buyers will get the final version as well as any new development versions for free. Examples are Moyang (Minecraft), Introversion (Prison Architect) or Squad (Kerbal Space Program).

This has several advantages.

1. it drastically shortens the time until the first revenue comes in
2. it provides early feedback from players and critics, telling them if further investment into the project makes sense
3. it generates hype

It reduces the total income per copy because many players will buy for the discounted price during development, but the added hype usually makes more than up for it in volume.

The downside is that they now have an existing playerbase during development which expects playable updates with visible progress at regular intervals. This makes the development schedule a lot less flexible and adds additional stress.

---
Tags: game-industry
---


# Question
Title: What advantages does bare OpenGL provide over frameworks/engines to small developers?
I've noticed a trend of indie developers steering away from frameworks and engines, and moving towards using bare OpenGL, or using it combined with SDL/SFML2. As an indie developer, I can't see what low-level OpenGL can offer over separate engines or frameworks.

Most decent engines and frameworks give the functionality that you need, and never get in your way. They might also open the option to deal with OpenGL directly. Some even offer the functionality to compile cross-platform!

I understand the aspiration to learn what is happening below the hood, but I can't see any upsides that OpenGL might offer to *indie developers* over engines or frameworks.

Could you explain the reasoning behind building games from scratch using OpenGL?

# Answer
This is largely an opinion based question/answer, so it's actually not necessarily ideal for this platform, but anyway:

Why no framework/engine as an indie? Here are my two cents:

* **Lack of budget:** This is probably the biggest point for most small/indie developers. Many frameworks or engines won't allow you to publish your product without either buying a more expensive version (assuming there's a cheap or free version available at all) and/or pay royalties, something you'll always have to consider for small projects. Sometimes you even have to pay once per platform as well.
* **Complexity:** Most engines or frameworks fall into one of two categories:
    + They're either very limited for one special genre (*RPG Maker* being a typical example).
    + Or the'yre simply too generic with lots of things you most likely won't use anyway (like *Unity*).
* **Proprietary code:** Most engines aren't open source and to get the actual source you'll have to pay even more (if even available). Without the actual source code porting to other platforms can be hard or even impossiblee (again, *RPG Maker* would be a perfect example).
* **Clunkyness:** This is my personal opinion, but at least to me this is often a rather huge letdown considering premade engines and frameworks, especially when you're building just a small game. Who wants to play a small break game that is like 200 KB in size but brings a 50 MB runtime with it?
* **Choice of language:** Some engines and frameworks don't provide libraries to use in your own code. Instead they provide a framework or runtime that will use its own scripting language or some set language (like Javascript or C#). If you're writing your own custom engine, you're free to use whatever language you chose.
* **Protection of your work:** If you're using a premade engine or framwork, chances are high others might have a far easier time to change or decompile your code or assets, something you might want to avoid (even if it's just to keep your highscore clean). Custom code and asset handling add a far bigger hurdle to take, especially when compiled into native code.
* **Branding:** This might be minor for many, but some engines and frameworks forces you to show their logo or maybe even ads, essentially taking your freedoms to choose who/what to promote. Of course, this is often dependent on the actual license, licensing fees, etc.
* **Incompatibility with licenses:** This is something many don't even consider when picking an engine, but depending on what you want to do, this might be a major factor. Even if you buy some engine, you might be restricted from disclosing any sources or related materials. Something like this might make modding impossible, even if you'd like users to be able to. Take Valve's *Source* engine (*Half-Life 2*, *Team Fortress 2*, etc.) as an example: They're allowing modders to use their engine for their own projects. If these games would be based on (for example) Unreal Engine, this wouldn't be possible, due to the limitations implied by the licensing terms.
> 23 votes

# Answer
> Most decent engines and frameworks give the functionality that you need, and never get in your way.

Do they? That rather depends on exactly what it is that you are doing, graphically speaking.

For many kinds of games, there are standard answers for graphical questions. The average 2D game for example can be handled just fine with the 2D prowess of, for example, XNA/MonoGame. It's just sprites, which can come in batches for terrain, can be rotated, and so forth.

But what if your game *used to be* the average 2D game, then you read about some cool technique, such as using a height map to build an imposter that has the appearance of depth relative to the screen. And you want to do that.

Now you're employing normal mapping and even possibly parallax mapping. All in the same context of "rendering sprites", but requiring more than a lot of pure 2D engines can handle. Specifically, it requires multitextured "sprite blitting", which is not something that many 2D engines can do.

What do you do if your engine can't adapt with you? So that means you have to do multiple passes, one for the color and one for the lighting via normal map. But that doesn't work, because you need the normal map's height field to employ parallax mapping to the color lookup. So... now what? You need the alpha to do transparency, so you can't steal the alpha. And the engine just doesn't support multitextures.

So you must pick one of the following:

1. Abandon the idea. This means that your game is functionally limited by your engine.
2. Hack the engine to have multitexture. Assuming you have access to the source code, you are now taking it on yourself to poke at someone else's code. This also means you need to *maintain* it and not break it with your stumbling around.
3. Do the best you can, within the limitations of the engine. So you can get parallax on the normal maps, but not on the colors. It may not be exactly what you wanted, but it's better than nothing.

Just as an example, take Geometry Wars. Most 2D engines would suck at these kinds of visuals, since most of them are built around drawing sprites, not lines. That's a game that needs a very specialized kind of renderer.

At the end of the day, you need to take responsibility for the elements of your game that are *important* to the needs of your game. If your game's visual look is primarily developed by the art style of the images and models you use, rather than specific effects, then using a pre-packaged solution is fine. But if your game's visual style is defined significantly by custom rendering code, odds are good that a standard engine could become a serious limitation if you decide to do things that are outside of the box.

Furthermore, there's a very practical issue: not all game engines are equally portable.

With the recent rise of mobile platforms, the marketplace for games is spread across numerous OS's and user-interface devices. Not all engines work on all devices. And if your engine doesn't work on a platform, you're certainly not going to take the time to *make* it work on one. After all, that's *why* you used an engine in the first place, right?

If it's important to you that your game function on a particular platform, then you again need to take responsibility for it. And the "easiest" way to ensure success with this is to *do it yourself.* To build an engine that can work across multiple platforms, perhaps employing simpler platform-specific frameworks where needed to handle some low-level details. That way, if it breaks, it's your code; you're the best person to be able to fix it.
> 9 votes

---
Tags: opengl, c++
---


# Question
Title: C++ SFML Box2D - Somewhat confused when it comes to syncing phyisical body with a render body
While testing Box2D with SFML I encountered something which confuses me: The relation between physical body centroids and SFML's sprite origin.

As an example I have a test class `GameObject` which is used to create a physical body and a render shape using Box2D and SFML:

```
class GameObject
{
private:
    b2Body* physicalBody;
    sf::ConvexShape renderShape;
public:
    static enum ObjectShape { Square, EqulateralTriangle };
    GameObject(b2World& world, const GameObject::ObjectShape shape = GameObject::Square, const sf::Color &color = sf::Color::White, float xPos = 0.f, float yPos = 0.f, float sizeInPixels = 30.f)
    {
        b2BodyDef bodyDef;
        bodyDef.type = b2_dynamicBody;
        bodyDef.position.Set(xPos / SCALE , yPos / SCALE);
        bodyDef.angle = -( b2_pi / 2.f );
        physicalBody = world.CreateBody(&bodyDef);

        b2PolygonShape bodyShape;
        float sizeInMKS = sizeInPixels / SCALE;
        switch (shape)
        {
        case EqulateralTriangle:
            {
                const int pointCount = 3;
                b2Vec2 points[pointCount] = { b2Vec2(sizeInMKS,0), b2Vec2(-sizeInMKS,sizeInMKS), b2Vec2(-sizeInMKS,-sizeInMKS) };
                bodyShape.Set(points, pointCount);
                b2FixtureDef fixture;
                fixture.shape = &bodyShape;
                fixture.density = 1.0f;
                fixture.friction = 0.3f;
                fixture.restitution = 0.5f;
                physicalBody->CreateFixture(&fixture);

                renderShape.setPointCount(3);
                renderShape.setPoint(0, sf::Vector2f((points[0].x * SCALE), (points[0].y * SCALE)));
                renderShape.setPoint(1, sf::Vector2f((points[1].x * SCALE), (points[1].y * SCALE)));
                renderShape.setPoint(2, sf::Vector2f((points[2].x * SCALE), (points[2].y * SCALE)));
                break;
            }
        case Square:
        default:
            {
                bodyShape.SetAsBox((sizeInPixels / 2.f) / SCALE, (sizeInPixels / 2.f) / SCALE);
                b2FixtureDef fixture;
                fixture.shape = &bodyShape;
                fixture.density = 1.0f;
                fixture.friction = 0.3f;
                fixture.restitution = 0.5f;
                physicalBody->CreateFixture(&fixture);

                renderShape.setPointCount(4);
                renderShape.setPoint(0, sf::Vector2f(0.f, 0.f));
                renderShape.setPoint(1, sf::Vector2f(sizeInPixels, 0.f));
                renderShape.setPoint(2, sf::Vector2f(sizeInPixels,sizeInPixels));
                renderShape.setPoint(3, sf::Vector2f(0.f, sizeInPixels));
                renderShape.setOrigin(sizeInPixels / 2.f, sizeInPixels / 2.f);
                break;
            }
        }
        renderShape.setFillColor(color);
        renderShape.setPosition((physicalBody->GetPosition().x * SCALE), (physicalBody->GetPosition().y * SCALE));
        renderShape.setRotation(physicalBody->GetAngle() * (180.0f/b2_pi));
    }
    void update()
    {
        renderShape.setPosition(physicalBody->GetPosition().x * SCALE, physicalBody->GetPosition().y * SCALE);
        renderShape.setRotation((physicalBody->GetAngle() * (180.0f/b2_pi)));
    }

    void render(sf::RenderWindow& renderWindow)
    {
        renderWindow.draw(renderShape);
    }
};

```

Now for the triangle after I call `bodyShape.Set()` the body centroid gets calculated(bodyShape.m\_centroid is equal to \[-0.33333, 0\]), however when I wish to combine it with a renderShape I MUSTN'T set the renderShape's origin to it's centroid otherwise the renderShape is offset from the body.

On the other hand when I create a square it's centroid seems to be 0 (bodyShape.m\_centroid is equal to \[0,0\]) and if I wish for the body and the renderShape to properly reflect one another then I MUST change the renderShape's origin to it's centroid.

Now what confuses me here is that this is completely opposite from what I thought I was supposed to do. Isn't Box2D's centroid effectively the body's center? And doesn't the body's position reflect the position of it's center? If that is the case then how does the physical body with a centroid which is not 0 sync with a render body whose origin is 0 and a physical body with a centroid of 0 not sync with a render body whose origin is 0?

I'm sorry if this is confusing to read but as english is not my native language I'm having a bit of a difficulty getting my question across. Basically what I'm asking is why a SFML square with it's origin being 0 doesn't reflect a Box2D square whose centroid is 0, properly? Shouldn't they fit? Same with the triangle. Why does a SFML triangle with it's origin 0 properly reflect a Box2D triangle whose centroid is \[-0.33333, 0\].

So am I missing something way obvious here?

# Answer
> 3 votes
The physical centroid is used by the physics engine as a center of mass. The center of mass is not the same as the position of a composition of shapes.

For instance, a body can have a transform position of (0, 0), and have it's shape's vertices for a polygon located around (10, 10). The shape vertices will be specified relative to the transform's location.

In short, use the transform's position of a body to get it's location.

The center of mass is used by the physics engine itself.

---
Tags: box2d, sfml, c++
---