# Question
Title: GetContactList stops reporting collisions on welded bodies
I have some strange problem with my game which uses Box2D as physics engine and I'm out of ideas on what I can do to solve it.

My game is a class assignment where I need to build a simple game where the main character moves in a 2D environment while square blocks comes from below him. Each time a collision occurs, that block is attached to the character using a weld joint, when three blocks of the same colors are together, they annihilate themselves(an effect similar to Bejeweled). I'm using a recursive function to iterate through all the attached blocks of a given block to see if there are enough blocks for them to be deleted.

I'm using GetContactList function to iterate through the list of contacts to see which blocks are adjacent to each other. The results are quite disappointing, the blocks only get annihilated in few cases. After a lot of debugging, I found the issue, but I still don't know how to solve.

My issue is: **after some time, GetContactList STOPS returning contacts (return NULL) to blocks that were already attached for some time**. I spent some time reading the Box2D manual as well as some tutorials and still didn't find any clue of what is happening.

Below there's some simplified version of the code that I wrote.

```
for(int a = 0; a < blocksList.size(); a++)
{
   blocksList[a].BuildConnections();
}

```

And on BuildConnections

```
b2ContactEdge* edge = body->GetContactList();
while(edge != NULL)
{
   if (long_check_to_see_if_there's_a_block_nearby)
   {
       // add itself to the list to be anihilated
       globalList.push_back(this);
       //if there's, call BuildConnections again on the adjacent block
       adjacentBody->GetUserData()->BuildConnections;
   }
   edge = edge->next;
}

```

I know that there's another issue related to circular inclusions, but I fairly sure that this problem isn't causing the problem with the collisions.

You can download my entire code from this page if you'd like http://code.google.com/p/fellz/source/list

# Answer
> 1 votes
I just solve the problem using a tip given by an user on Box2D forums, which I gonna reproduce here to help other people who might come into this problem as well.

*irresistible force* wrote:

> Joints have a collideConnected property which is usually set to false by default, so that any collisions between the two joined bodies are ignored. Maybe you just need to set this to true.

---
Tags: box2d
---


title: Moving AI in a multiplayer game

text:
# Question
Title: Moving AI in a multiplayer game
I've been programming a multiplayer game and its coming together very nicely. It uses both TCP and UDP (UDP for movement and TCP for just about everything else). What I was wondering was how I would go about sending multiple moving AI without much lag. At first I used TCP for everything and it was very slow when people moved. I'm currently using a butchered version of this http://corvstudios.com/tutorials/udpMultiplayer.php for my movement system and I'm wondering what the best method of sending AI movements is. By movements I mean the AI chooses left/right/up/down and the player can see this happening.

Thanks.

# Answer
> 1 votes
I'm not sure what you mean by "multiple moving AI". Do you have several gameobjects that have AI, and they are moving in the same time?

If so, then here's how I'd do it.

You can have the same AI system on both the server and the client, for example, a state machine. Every gameobject with AI can be described by several states, like "walking\_left *speed*". The AI system would provide various ways of changing these states, but that doesn't matter, because what you're interested in is synchronizing the movement between the server and the client.

What I did when I made my first multiplayer game, was foolishly have the server overwrite the positions of objects. Don't do this, because this results in choppy movement that is dependent on your network latency. Rather, you share those states, and make sure that both the server and the client know that a certain entity is walking at some direction (the direction vector can also specify the speed by its length). If everyone knows at which direction an entity is going, it's a simple matter of designing a movement system that make sure that in same time intervals, entities will be on the same position, and deploying that system on the server and the client side.

Someone at Valve made a post about making multiplayer systems: https://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking.

Also, I believe that using both UDP and TCP is not exactly a good idea, I forgot why, so you might want to investigate... Another useful link: http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/.

# Answer
> 1 votes
I don't think that sending information about ai movement every frame is a good idea. What you should send instead is just player actions/commands (not positions). Basically what you need is a simulation (the same) running on every client and just synchronize player actions. If you use random number generators, just initialize them on the clients with the same seed.

This article could be also helpfull to you: http://www.gamasutra.com/view/feature/3094/1500\_archers\_on\_a\_288\_network\_.php?print=1

---
Tags: java, networking
---


title: Marmalade SDK views navigation concepts

text:
# Question
Title: Marmalade SDK views navigation concepts
I want to develop a simple multi-Activity Android game using Marmalade SDK. I looked at the SDK samples and found that most of them are a single view (Android Activity) apps.

The Navigation model in Android is a stack-like model where views are pushed and popped.

I can't find whether Marmalade has a similar model or it uses a different approach.

would you please explain this to me and provide tutorials and samples to navigation in Marmalade if possible ?

Thanks

# Answer
> 0 votes
Marmalade compiles single code for multiple platforms. So you can't find Android Activities or iOS UIViewController in Marmalade code.

If you still wish to have access to Activity on Android e.g. implement SSO login with Facebook on Android then you should use EDK extension that provide direct access to Android and iOS

If you just develop game then you have to programs view system your self.

First time it took few hours to programs

Here are class declarations from my apps. I am not happy with them but it is real code that works for me.

```
class CButton;
class CScreen{
public:
enum{
    HIT_TOUCH,
    HIT_MOVE,
    HIT_RELEASE,
    HIT_BOOM,
    HIT_BOOMMOVE
};
CIwArray<CButton*> buttons;

CButton * touchButton;
int touchId, touchUniqueId;

CScreen();
virtual ~CScreen();
virtual void init(){}
virtual void terminate(){}
virtual void dispatch(int event);
virtual void touch(int id, int uniqueId, int x, int y);
virtual void release(int id, int uniqueId, int x, int y);
virtual void swipe(int id, int x, int y);
virtual void hit(int id, int power, int type, int x, int y, int old_x, int old_y);
virtual void hitFlash(int x1, int y1, int x2, int y2);
virtual void render();
};
class CButton{
public:
int eventId;
bool bvisible;
uint32 color;
CButton();
virtual ~CButton();
virtual bool testhit(int x, int y) = 0;
//virtual bool touch(int id, int unique, int x, int y);
//virtual bool release(int id, int unique, int x, int y);
virtual void render() = 0;
};

class CScreenGame: public CScreen{
public:
enum{
    EVENT_BACK,
    EVENT_PAUSE,
    EVENT_UNPAUSE,
    EVENT_HI
};
bool btouch;
int touchX, touchY;
class CGame * game;

char debugText[4096];

CButton * window;
CButton * buttonBack;
CButton * buttonPause;
CButton * buttonUnpause;
CButton * buttonNext;

CScreenGame();
~CScreenGame();
virtual void init();
virtual void terminate();
virtual void dispatch(int event);
virtual void touch(int id, int uniqueId, int x, int y);
virtual void swipe(int id, int x, int y);
virtual void hit(int id, int power, int type, int x, int y, int old_x, int old_y);
virtual void hitFlash(int x1, int y1, int x2, int y2);
void hit3D(int id, int power, int type, int x, int y, int old_x, int old_y);
virtual void render();
void transform(int x, int y, CIwVec3 & dir);
};

class CScreenMain: public CScreen{
public:
enum{
    EVENT_GAME,
    EVENT_CREDITS,
    EVENT_EXIT,
    EVENT_GIFT,
    EVENT_WEBSITE,
    EVENT_MORE_GAMES,
    EVENT_INTERESTIAL
};
CScreenMain();
virtual void dispatch(int event);
virtual void render();
};

class CScreenCredits: public CScreen{
public:
enum{
    EVENT_BACK
};
CScreenCredits();
virtual void dispatch(int event);
virtual void render();
};

```

# Answer
> 1 votes
this is a post quite old but I got an answer for you. To easily work with Marmalade in the game field I would suggest you to use the brand new engine called IwGame (http://www.drmop.com/index.php/iwgame-engine/). I'm working for the porting of an Android game of mine and I started 2 months ago. It's really simple to learn and it's powerful. It's build on Marmalade so you can use all the knowledges you already learned but more, you can use a great engine to improve and speed development. For your specific question: IwGame use the "scene" method. Each Android activity could be translate in a scene. Each scene is easily build using the powerful XOML language and you can pass from a scene to another with few lines of code. For any more info, please ask.

Zapp

# Answer
> 1 votes
The question is quite old, but I think it's better to answer an unanswered question than just leave it.

`Android` doesn't need a loop to continuously render the views, it automatically invalidates the views at each frame. `Marmalade` doesn't follow this approach. You need a `game loop` in `Marmalade` which runs once every frame.

The approach I follow and which is also recommended by Marmalade is to use `UI files` for every view. `UI files` are like `XML layouts` in Android, where we can create our views statically. The UI file is called on runtime and set as current view using the following method -

```
 IwGetUIView()->SetModal(CIwUIElement* view);

```

If you see the structure of UI files, you can see that every view is a subclass of `CIwUIElement` (Same as `View` class in `Android`). `IwGetUIView()` returns the current root view or whatever it's called. This statement can be compared to `setContentView()` of Android.

Similarly you can call `RemoveElement()` method to remove the view. I instead just set it's visiblity to false, as it's less prone to error.

One thing you need to remember is you need to call `IwGetUIView()->Render();` and `IwGetUIView()->Update(int32 deltaMS);` in your app's `Render()` and `Update()` functions, which gets called at every frame.

---
Tags: android, marmalade
---


# Question
Title: Android development in Unreal with an existing project
I am currently using an Unreal 3 project that has been targeted for multiple devices. Originally, it was targeted for iOS and now I want to try and build it for Android. The project is capable of doing it and I am in the process of testing it.

I think I have everything I need in order to build it and launch it for an android device that I have set up and connected to my PC and is recognized by the Android SDK ABD. I am currently trying to build and launch the game through the Unreal Frontend but when I try, I am getting stuck at getting the Unreal Frontend to find my Android device as a platform to debug, like it would with a PC, Xbox360, or PS3.

Right now, I am just trying to launch the game to see if I can get it to simply run on an Android device, I'm going to worry about the packaging later.

So I have two questions:

Am I on the right track in looking at the Unreal Frontend to cook and launch the project on Android or should I look somewhere else?

How do I get Unreal to recognize my Android device as a platform to launch on? I would even settle for recognizing an emulator, but that seems even harder.

# Answer
> 1 votes
Following up to my own issue. Turns out it was the limitations that were put on me that were the downfall of this feature.

In order to make Unreal Frontend recognize an Android device, at least in this situation, the UDK must be installed along with the project.

I was working on the project without the UDK with no issues except for this one. Once it was installed, it worked out.

---
Tags: android, unreal
---


# Question
Title: Best practice for designing a risk-style board game
I'm just trying to figure out how to set up the code for a game like risk...

I would like it to be extensible, so that I can have multiple maps (ie- World, North America, Eurasia, Africa) so hardcoding in the map doesn't seem to make a whole lot of sense

I'm a bit confused on how/where items should be stored/accessed.

Here are the objects I see the game theoretically using: -Countries/Territories -Cities (Can be contained within territories) -Capitols -Connections -Continents -Map -Troops

At the moment, I feel like: -A map should have a list of continents and countries. The continents would be more of a 'logical' thing where the continents would just be lists of countries that are checked for bonuses at the start of turns -Countries should have a list of countries that they're connected to for the connections

What I can't figure out is: Where do I store the troops? Do I have an object for every single troop or do I just store the number of troops on a country object as an integer?

What about capitols and cities? Do those just have a reference to the country they reside in?

Is there anything I'm not seeing here that's going to screw me over in the long run with the way that I'm thinking about things now?

Any advice would be appreciated.

# Answer
> 3 votes
I would keep data tables (in a file most likely), then read at the start and stored into classes, using IDs, something like:

```
Continents:
ID, Display
-------------------
NA, North America
SA, South America
EU, Europe
AS, Asia
etc

Countries:
ID, Display, Continent ID, Capital City ID (see below for City list)
------------------
CA, Canada, NA, OT
US, United States, NA, WA
MX, Mexico, NA, MC
RS, Russia, EU, MO // Ha, EU or AS (I Googled it, they didn't even know!)
etc

Country Connection:
ID, Connected To
-------------------
CA, US
CA, RS
US, CA
US, MX
MX, US
etc

```

Technically, since MX is connected to US, therefore you don't need the 'redundant' entry saying US is connected to MX. But this style is easy for looking up connections based on the current country you are querying, and not have to check all entries etc. Also, as a bonus feature, this way lets you define 'one way' relationships for whatever reason. US can access MX, but maybe MX can't access US (terrain issues, country capabilities such as no navy presence, etc).

For cities, the ID should be unique across the entire world, no duplicates, so a four letter number / code would be recommended:

```
Cities:
ID, Country ID, Display
-----------------------
TO, CA, Toronto
OT, CA, Ottawa
DT, US, Detroit
NY, US, New York
MC, MX, Mexico City
MO, RS, Moscow
etc

```

If you want to track which cities connect to other cities (spanning country borders too):

```
City Connection:
TO, OT // Toronto connects to Ottawa
TO, DT // Toronto connects to Detroit
etc

```

Then to keep track of troops, track each player separately, using perhaps dynamic lists, such as (and update when new countries are lost / acquired):

```
Player Troops:
Player ID, Country ID, Qty
------------------
01, CA, 5 // Player 01 has 5 troops in Canada
01, US, 7 // Player 01 has 7 troops in the US
02, MX, 14 // Player 02 has 14 troops in Mexico
etc

```

If you want to track troops in cities rather than countries, use the city id instead. If there is only one style of troop, the above works. But if you have multiple troop styles (navy, land, air force) then give each style an ID, and update the above to something like:

```
01, NV, CA, 5 // Player 01 has 5 NAVY troops in Canada
01, AF, CA, 14 // Player 01 has 14 AIRFORCE troops in Canada
etc

```

You could even store each countries' borders as polygon lines in a table, for displaying, or checking if a country is clicked, or highlighting, etc.

\[EDIT\] Thinking over this I think I would create a 'troops' class, and a 'player' class that has an instance of a 'troop' object. The troop class would have no reference to any player. I was thinking too 'databasey' at the time!

# Answer
> 2 votes
Slydog's answer answers most of your questions, i guess. I would prefer to have this answer as a comment, as it may not contribute to what you are looking for here but I don't have the permissions to comment and I don't want that to stop me from giving my contribute to eventually help you.

Anyway, if you need a database with polygon information about countries borders, etc, there are a couple online. For example this: http://thematicmapping.org/downloads/world\_borders.php

---
Tags: architecture, maps, data-structure
---


# Question
Title: Triangle Line-Segment Intersection - detecting near misses
A ray is a very poor approximation of a player! I think approximating a player with a sphere traveling a straight line each game tick will solve my problems of the player intersecting edges of scenery because their line segment missed it yet their own model is not infinitely thin...

I have a 3D triangle and a line segment. I have the normal triangle-line-segment intersection code which I admit I have only a woolly grasp of.

To model movement and compute collisions of the player I have to determine if a line passes within sphere-radius of a triangle. But I can find no convenient line near-miss intersection code!

I have made a little test app with classic triangle-intersection code: https://gist.github.com/3751097

The simple test code:

```
# barycentric coords
w = vec3_sub(hit,a)
uu = vec3_dot(u,u)
uv = vec3_dot(u,v)
uw = vec3_dot(u,w)
vv = vec3_dot(v,v)
vw = vec3_dot(v,w)
invDenom = 1.0 / (uu * vv - uv * uv)
U = (vv * uw - uv * vw) * invDenom
V = (uu * vw - uv * uw) * invDenom
W = U+V
# basic in-triangle test
A, B, C = U>=0.0, V>=0.0, W<1.0
if A and B and C:
    return GREEN
# near miss?
if U>-0.1 and B and C:
    return BLUE
if A and V>-0.1 and C:
    return YELLOW
if A and B and W<1.1:
    return CYAN
# far miss
return BLACK

```

generates this:

Clearly the threshold on the barycentric coordinates for a near-miss need scaling somehow by something and multiplying by the `ray_radius`. Also the corners need special casing.

How can you determine if a line segment passes within some distance of a triangle?

# Answer
It sounds like what you really want to do is intersect the triangle with a volume representing the space the player swept out during the last timestep. If the player is represented by a sphere, this volume is a capsule (cylinder capped with spheres on the ends); if the player is an axis-aligned bounding box then the volume is a convex polyhedron; etc.

There are references to numerous intersection tests for all sorts of geometry at this page. You probably want to scroll down to the Dynamic section and look at the links for "Moving Sphere/Triangle". Their recommendation is to build an "inflated" triangle consisting of three spheres for the vertices, three cylinders for the edges, and a slab (convex polyhedron) for the interior; then do a raycast against their union (i.e. raycast against each of these shapes, return true if at least one of them hit). There is a link to some sample code.

Incidentally, this kind of shape is known as a Minkowski sum. Here's it's the sum of the triangle and the player-sphere. In general it's one shape "inflated" by another shape. This is a term you'll see often if you delve into the collision detection literature.
> 1 votes

# Answer
You can check against the individual triangle edges (segments) using an algorithm that provides you with the distance between two line segments.. it's probably not fast, but it works.. If you google for this algorithm, there are various (pseudocode) implementations to help you get started with your own. See here.
> 1 votes

---
Tags: 3d
---


# Question
Title: PHP Browser Game Question - Pretty General Language Suitability and Approach Question
I'm developing a browser game, using PHP, but I'm unsure if the way I'm going about doing it is to be encouraged anymore.

It's basically one of those MMOs where you level up various buildings and what have you, but, you then commit some abstract fighting entity that the game gives you, to an automated battle with another player (producing a textual, but hopefully amusing and varied combat report).

Basically, as soon as two players agree to fight, PHP functions on the "fight.php" page run queries against a huge MySQL database, looking up all sorts of complicated fight moves and outcomes. There are about three hundred thousand combinations of combat stance, attack, move and defensive stances, so obviously this is quite a resource hungry process, and, on the super cheapo hosted server I'm using for development, it rapidly runs out of memory.

The PHP script for the fight logic currently has about a thousand lines of code in it, and I'd say it's about half-finished as I try to add a bit of AI into the fight script.

Is there a better way to do something this massive than simply having some functions in a PHP file calling the MySQL Database?

I taught myself a modicum of PHP a while ago, and most of the stuff I read online (ages ago) about similar games was all PHP-based. but a) am I right to be using PHP at all, and b) am I missing some clever way of doing things that will somehow reduce server resource requirements?

I'd consider non PHP alternatives but, if PHP is suitable, I'd rather stick to that, so there's no overhead of learning something new. I think I'd bite that bullet if it's the best option for a better game, though.

# Answer
Although I'm not PHP fan, I don't think it's a problem of the language, 300,000 rows in a database is not that big (I worked with much more). Your problem is most likly in the code-\> algorithms you use..

As a side note..
1000 lines of code for just fight logic? How maintainable is that? It's ok that you know what's going on in there right now, but will you know it after half a year? ;)
> 5 votes

# Answer
Better? Probably, but at what cost? PHP has a truly fully-featured string API which will come in handy as soon as you do just about anything with text.

C# has native code and some added speed at the cost of having to use an awful API and the JIT compilation on first launch makes testing painful.

Python has a rather uncomfortable reference system so copying data is painful. But it's ~10x faster than PHP.

But never mind what I said about speed because your bottleneck will most probably be MySQL and the data you retrieve and you'll want to keep things simple. PHP is good for just that.

So instead of a language change I'd suggest you use LIMIT/OFFSET features of MySQL to limit the amount of memory that is used by the results at any time, disable some extensions that you don't use and do some throttling (storing server load info and reacting appropriately to high load situations).

---

By limiting memory usage with LIMIT/OFFSET I meant loading the first N results and checking if result count is N and if so, loading the next N results and repeating this until all results are processed.

This will require you to add an ORDER BY clause which in turn might benefit from having a indexed column to sort by, something (but not necessarily) like the primary key. In fact, any well-placed index will do. You can use the MySQL EXPLAIN feature to find out if/when/how an index is used and what generally happens during the execution of a certain query.
> 4 votes

# Answer
As the others already mentioned....300k of rows from a database and 1k lines of code shouldn't really be that huge of a problem for the memory.

Although if you load all 300k rows into memory at once (depending on how much data is in each row) that COULD pose a problem. Another possibility would be memory leaks especially as the phenomenon that you write about with the medium sized data and 1k lines of code sounds like a memory leak is happening inside your code. There are 2 things that I can see where it COULD come from (without knowing the code): Loading too much data, or having a memory leak in a loop. I'll go into a bit more details to these two things below (also how you could counter those):

a.) For getting data from the database be sure to only load the really relevant ones. Thus if only 1 of the 300k rows is really applicable load only that one and dont select all 300k rows (if you have quite a few coloumns with 5-100 bytes each it could already result in 10MB+ memory usage there).

b.) Be sure to eliminate unused variables or variables you need to reinitialise. Especially if you use loops. Depending on the PHP version it can happen that the variables if you overwrite them don't get cleared and instead a copy of the variable is created in memory while the old data still consists. (with earlier php versions this problem was even worse as variables created in functions weren't "unset" automatically). For example:

```
$arr=GetFightingDataALLRows()
foreach ($arr as $row)
{
   .....//do something
}

```

At least up to PHP 5.3 (not 100% about 5.4 as in most projects I still have to use 5.3) it was so that $row if you didnt use unset($row) at the end of the foreach-loop was not "unsetted", thus even though in the next iteration of the loop you got new data into $row a copy of the old data still existed in memory thus leading for example if you have 3MB of data you load that you have at least 6 MB memory usage. If you have a loop inside the loop where you also don't delete the variables manually by using "unset".....lets say the result for the memory usage is not pretty (if for example we iterate through all 300k rows and inside the iteration we have another loop creating another set of variables which use 1 MB each then in total you have a memory usage of 300k x meory usage per row x 2 plus 300000 x 1 MB). With PHP 5.3 this could happen very often and easily, thus I always suggest that you use unset at the end of a loop too unset every and all variables that you don't need outside the loop.
> 4 votes

# Answer
I would like to comment on game performance:

It is very-very unlikely that the code is not the culprit if you are running into issues with only two users during the combat phase. There games (should be designed) to host hundreds if not thousands of users. One user should never cause performance issues. Did you test it offline on your computer to see if it works?

Another area that puzzles me is why would you need DataBase rows for combat moves, you could and probably should include the combat moves and AI in the code itself inside php files.

If this project is one you wish to share with the public without spending a lot on resources (at least until the project grows in scale), I would recommend using Google App Engine for - reliable performance. It uses a DataStore system that treats each user individually and each request separately and handles it within a short amount of time from one of many servers. You the application owner - will only pay per user and the prices are reasonable.

I cannot comment on code efficiency since you did not share your code. There are ways to improve code more times than not and especially DataBase performance is an area where a lot of adjustments and improvements can be made to squeeze out better performance.
> 3 votes

# Answer
I think that as others have said, your issue does lie in your code. I think that it is likely in your interaction with the database. Since you've gone to the trouble of putting all your data in there, you should be able to use it. A database can be all about set theory and filtering of data.

I wouldn't build a system in the following way, but I'll infer one possible "easy to implement" optimization that you appear to be missing:

If Player\_1 chooses Attack\_Move\_X and Player\_2 chooses Defensive\_Move\_Y then you could simply ask your database to `SELECT The_Result WHERE Move1 = Attack_Move_X AND Move2 = Defensive_Move_Y` and it will spit out the result pronto. It appears from your description that you are loading many of the possible maneuvers into memory instead of letting your database do the filtering for which you could likely optimize it to do.

That said, as again others have pointed out, you should likely be handling combat in a different way. Maybe Attack\_Move\_X has a set of negative modifiers against your combat statistics, maybe Armor and Dexterity, while Defensive\_Move\_Y has a positive modifier to Dexterity and you simply do the modifier math, possibly after your randomization.

Since you asked about PHP specifically, my answer is to use whatever language you are comfortable with. Since this is a browser based game I'm not overly concerned about someone using it to steal my credit card information. However, if you are going to offer microtransactions then you need to be especially aware of PHP's Inherent Insecurity.
> 3 votes

---
Tags: mmo, browser-based-games, php, browser
---


# Question
Title: How to implement a physical with perspective effect on Android?
I'm working on a project that looks like PaperToss. Instead of tossing a page, you toss a coin. Suppose that I have a coin put in three-dimensional that have coordinates at A(x,y,z). I throw that point ahead, after 1/100 second, that coin move from A(x,y,z) to A'(x',y',z'). By this way, I have two problems need to solve.

1. Where will be the coin at time t?
2. How can I display this on a screen?

For 2., I thought about using Orthographic projection & Perspective projection. I'm told that OpenGL can help me, but I don't know how.

How can I solve 1. and 2.?

# Answer
> 1 votes
1. You are probably looking for motion equations. However, I would advice you to use a 3D physics engine.
2. Well, if you want to draw a 3D world in a 2D canvas (aka, the device's screen), then the way to go is OpenGL, that aims exactly that.

---
Tags: opengl, android, physics, physics-engine
---


title: Collision Detection for a 2D RPG

text:
# Question
Title: Collision Detection for a 2D RPG
First of all, I have done some research on this topic before asking, and I'm asking this question as a mean to get some opinions on this topic, so I don't make a decision only on my own, but taking into account other people's experience as well.

I'm starting a 2D online RPG project. I am using SFML for graphics and input and I'm creating a basic game structure and all for the game, creating modules for each part of the game.

Well, let me get to the point I just wanted to give you guys some context.

I want to decide on how I'm going to work with collision detection. Well I'm kinda going to work on maps with a tile map divided in layers (as usual) and add an extra 2 layers - not exactly in the map - for objects. So I'll have collisions between objects and agents (players - npcs - monsters - spells etc) and agents and tiles. The seconds one can be easily solved the first one need a little bit of work.

I considered both creating a basic collision test engine using polygons and a quadtree to diminish tests since I'm going to be working with big maps with lots of objects - creating both a physical and graphical world representation. And I also considered using a physics engine like Box2D for collision tests.

I think the first approach would take more work on my part but the second one would have the overhead of using a whole physics engine for just collision detection and no physics.

What do you guys think ?

# Answer
For an RPG with tiled map, i think the best would be to use some really simple collision test with rectangular boxes. And then, when two rect intersect, for instance, the player and a blocking tile, you can do some pixel perfect collision on the intersection area to see if at least one pixel (or any other pixel tolerance) overlap.

Some old school RPG use a dedicated layer to determine if a tile is blocking or not on a map, it's just a simple bit array (0 non blocking and 1 blocking). For the dynamic entities, in some cases, you may want to use another shape like circle to be a bit more precise. Collision detection would be the same for tile than for entities, tile would be rect and entities would be any other simple shape.

Using a physics engine only for collision detection in an RPG would be a bit overkill to me.
> 3 votes

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


# Question
Title: What is the correct way to implement hit detection with non-rectangular sprites?
What is the correct way to implement hit or touch detection for non-rectangular sprites in Cocos2d?

I am working on a jigsaw puzzle, so our sprites have some strange forms (jigsaw puzzle bricks). As of now, we have implemented the "detection" this way:

```
- (void)selectSpriteForTouch:(CGPoint)touchLocation {
    CCSprite * newSprite = nil;

    // Loop array of sprites
    for (CCSprite *sprite in movableSprites) {

        // Check if sprite is hit.
        // TODO: Swap if with something better.
        if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
            newSprite = sprite;
            break;
        }
    }
    if (newSprite != selSprite) {
        // Move along, nothing to see here
        // Not the problem
    }
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    [self selectSpriteForTouch:touchLocation];
    return TRUE;
}

```

I know that the problem is in the keyword "`sprite.boundingBox`". Is there a better way of implementing this, or is it a limitation when using sprites based on .png's? If so, how should I proceed?

# Answer
> 5 votes
I actually found a simple solution!

Changed the character objects to not only include info and sprite, but also a CGPath. Then implemented a method, to loop all character objects, and check for

```
CGPathContainsPoint( params ...)

```

instead for

```
CGRectContainsPoint( params ...)

```

Tutorial I used: http://www.youtube.com/watch?v=HxHZwzaadNQ \- "The magic of CGPath"

# Answer
> 3 votes
I'm unfamiliar with objective C, so I can't give any specific code. But the general way to accomplish things like this is by doing a per pixel collision check. Basically it works just like how you have it based on the rectangle, but before firing the touch event, you have to loop through all the pixels that were touched and make sure at least one of them wasn't transparent. That should help you get closer to the answer, hopefully someone else can give you some actual code samples on the subject.

---
Tags: ios, cocos2d, xcode
---


# Question
Title: Can applications using old versions of Opengl still run on newer cards?
OpenGl 3.0 and up has a quite big difference from the older versions like OpenGl 2.x and opengl 1.x in terms of implementation, does that mean applications which are written with the old versions of opengl won't run on computers having video cards supporting Opengl 3.x and up?

Sorry, if this is not the right place to ask this.

Thanks.

# Answer
> 2 votes
In short: OpenGL 1.x will still be supported.

It's theoretically possible for someone to write an OpenGL implementation that only supports 3.x and up, but supporting the older stuff gives you such a wide range of existing applications that it would be silly not to support it.

Some parts of the OpenGL 1.x pipeline may be implemented in a non-optimal (i.e. slow) manner, but things will still work. ATI drivers made picking horribly slow at some point, prompting changes in Blender, for instance.

On the OpenGL ES side things are a bit more complicated. I'm not aware of any instances of it, but ES 2.0 and onwards are so much different from ES 1.x that it's possible that some devices have no ES 1.x support. In most cases, ES2+ hardware emulated ES 1.x in software (generating shaders on the fly and fun things like that).

# Answer
> 3 votes
Currently no driver has removed support for earlier versions of OpenGL. On top of that, most also implement the compatibility extension, which means you can mix old stuff with OpenGL 3.2+ contexts (the exception is Mac OSX, where only core profile for OpenGL 3.2 is available - you can still use old stuff, but not together with new stuff).

---
Tags: opengl
---


title: Test your Mobile App's Code

text:
# Question
Title: Test your Mobile App's Code
I am new to game development in HTML5, and I would like to know how I can test my code out to see what I made with an IDE or something. Thanks!

# Answer
You should be able to load HTML5 in a web browser or an appropriate emulator or it's targeted toward a specific device
> 0 votes

---
Tags: html5, ide
---


# Question
Title: (Quaternion based) Trouble moving foward based on model rotation
Using quaternions, I'm having trouble moving my model in its facing direction. Currently the model moves can move in all cardinal directions with no problems. The problem comes when I rotate the move as it still travelling in the direction of world space. Meaning, if I'm moving forward, backward or any other direction while rotating the model, the model acts like its a figure skater spinning while traveling in the same direction.

How do I update the direction of travel proper with the facing direction of the model?

**Rotates model on Y-axis:**

```
        Yaw = pController.ThumbSticks.Right.X * MathHelper.ToRadians(speedAngleMAX);
        AddRotation = Quaternion.CreateFromYawPitchRoll(yaw, 0, 0);
        ModelLoad.MRotation *= AddRotation;
        MOrientation = Matrix.CreateFromQuaternion(ModelLoad.MRotation);

```

**Moves model forward:**

```
        // Move Forward
        if (pController.IsButtonDown(Buttons.LeftThumbstickUp))
        {
            SpeedX = (float)(Math.Sin(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
            SpeedZ = (float)(Math.Cos(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
            // Update model position
            ModelLoad._modelPos += Vector3.Forward * SpeedZ;
            ModelLoad._modelPos += Vector3.Left * SpeedX;
        }

```

# Answer
The problem stems from these lines:

```
        ModelLoad._modelPos += Vector3.Forward * SpeedZ;
        ModelLoad._modelPos += Vector3.Left * SpeedX;

```

Both `Vector3.Forward` and `Vector3.Left` are in *world space*, while you'd rather have the controller change the direction in the (rotated) *object space* of the model.

The easiest solution (warning: Don't know XNA that good to know if it is the *fastest* solution as well) would be to calculate the displacement as above, then rotate it with the quaternion (or in 2D space, complex number) describing the model orientation, then adding that to change the model position:

```
Vector3 Displacement = Vector3.Forward * SpeedZ + Vector3.Left * SpeedX;
ModelLoad._modelPos += Vector3.Transform(Displacement, ModelLoad.MRotation);

```

As a side note, your current calculations for SpeedX and SpeedY don't take into account varying frame rates. If the execution of them is bound to display frame rate, it's better to use "time since last frame" as a multiplier for both to ensure the same speed regardless of processing power and current frame rate.

See also this question for a possibly related problem (and solution thereof): Moving a rotated model in XNA
> 1 votes

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


# Question
Title: Bullet pattern isn't behaving as expected
I have a boss that's supposed to continuously shoot five streams of bullets, each at a different angle. It starts off just fine, but doesn't seem to want to use its entire array of bullets. No matter how large I set the length of bulletList, the boss simply stops shooting after a couple of seconds, then pick up again shortly. Here's what I'm using to generate the pattern:

```
Vector3 direction = new Vector3(0.5f, -1, 0);

for (int r = 0; r < boss.gun.bulletList.Length; r++)
{
   if (!boss.gun.bulletList[r].isActive)
   {
      boss.gun.bulletList[r].direction = direction;
      boss.gun.bulletList[r].speed = boss.gun.BulletSpeedAdjustment;
      boss.gun.bulletList[r].position = boss.position;
      boss.gun.bulletList[r].isActive = true;
      break;
   }

}
direction = new Vector3(-0.5f, -1, 0);
//Repeat with four similar for loops, to place a bullet in each direction

```

It doesn't seem to matter if the bulletList length is 1000 or 100000. What could be the issue here?

EDIT: This is the code that removes a bullet, when it goes out of bounds. It is inside Bullet.Update()

```
if (position.X > 950 ||
position.X < -950 ||
position.Y > 570 ||
position.Y < -570)
isActive = false;

```

This is the code that removes a bullet on contact with the player ship:

```
for (int i = 0; i < boss.gun.bulletList.Length; i++)
{
   if (boss.gun.bulletList[i].isActive)
   {
      boss.gun.bulletList[i].Update(timeDelta);

      if (!ship.invincible)
      {
         bulletSphere.Center = boss.gun.bulletList[i].position;
         if (bulletSphere.Intersects(shipSphere))
         {
             boss.gun.bulletList[i].isActive = false;
             ship.health -= boss.gun.damage;
         }
      }
    }
}

```

And just for safe measure, here's the code that draws the bullets:

```
for (int j = 0; j < boss.gun.bulletList.Length; j++)
{
   if (boss.gun.bulletList[j].isActive)
   {
      Matrix bulletTransform = Matrix.CreateTranslation(boss.gun.bulletList[j].position);
      DrawModel(boss.gun.bulletModel, bulletTransform, boss.gun.bulletTransforms);
   }
}

```

**EDIT: It would appear that a large number of bullets are getting "stuck" on the boss. That is, they draw at boss.position, and never move.**

# Answer
> 3 votes
You must make sure that your bullet are inactive at some point again. Or else your loop won't work. If all bullets are "active" the forloop won't shoot any bullets.

Coupled with break; it will just jump out of your for loop. ( I guess this is meant for the interval ? )

( But then again, I have the feeling you are leaving out some crucial code )

I suggest using a Stack or ObjectPool that just pops the top element and returns an inactive bullet. Once a bullet goes inactive ( after being activated) it's pushed back on the stack. This way you don't need to loop trough your bullet list to see if any of the bullets are inactive. You just check if something is in the stack. It's much faster.

C# has its own stack class. But creating one for your own needs isn't hard.

As an addition you could wrap your bullet patterns into a class which holds the direction for each bullet, the interval time( perhaps per bullet), speed(perhaps per bullet) etc. And when it's time to shoot the next bullet you simply request the next bullet settings from your "BulletPattern" class. This might prevent you writing giant pieces of codes just for one object. If you wrap the data you can also reuse/share them for/with other entities and such.

---
Tags: xna
---


# Question
Title: How to make an Image still when at position at Slick 2D?
I wanted to have a build functions. When I press for example 2, the image will appear with my character.

The question is, how do I stop it from following my character

```
//build

//I created many comments cuz this part would be confusing!

//buildInit if its initiated it would draw
if(buildInit==false || buildInit==true)
{
    //contol ro make it on
    if(input.isKeyDown(Input.KEY_B))
    {//buildInit is to enable the build inventory (The player can choose)
        buildInit=true;
        //What buildings

    }
        if(buildInit==true)
    {

        if(input.isKeyDown(Input.KEY_1))
        {
            supply=true;
        }

    }

    //Put it down!!!
    if(supply==true)
    {
                //this would stop it from following and stop there FOREVER
        if(input.isKeyDown(Input.KEY_SPACE))
        {
            stopCarry=true;
        }
    }

}
//TO stop carry
if(stopCarry==true)
{
       //I don't know how to do this part. I tried to do many ways but I couldn't get //it!

}

```

The Booleans are here

```
//building
boolean buildInit = false;
//
boolean supply = false;
boolean stopCarry = false;

```

Image: \` //build if(buildInit==true) { Build.draw(100,20); }

```
  if(supply==true)
  {//shiftX is my character also shiftY
      SupplyImg.draw(shiftX, shiftY);
  }
  if(stopCarry==true)
  {//stayX and stayY is the place for the building to stay. I don't know how to do this

      SupplyImg.draw(stayX, stayY);
  }

```

\`

The cord as you see, the map is moving, not my character!

```
float probePositionX = 0; //this is the pos for the maps
float probePositionY = 0;
float shiftX = probePositionX + 700;//this is the pos for my character
float shiftY = probePositionY + 400;

```

For stayX and stayY, I don't know the code for the building to stop following

These are experiments:

```
    float stayX = probePositionX + shiftX;
float stayY = probePositionY + shiftY;

```

I don't know which one should I write the code. And how do I make the Image stop following me? My opinion is shiftX and shiftY. I will add you to my credits in my game.

# Answer
> 1 votes
TLDR Version: Don't store position value and states of objects directly in the game / state class. Create classes for game objects and only store, update and render those objects. When you press you build key, simply remove the building material from the player and create a new game object on the respective position.

Long Version:

Ok, from looking at your code I think you have to learn a bit more about object oriented design and how to apply it for problems as yours. Maybe I drift a bit offtopic concerning your question. If so sorry about that, but I think you should get the idea, how this can help you.

In your code, you have a variable that tracks, if you are building something. Now imagine, you want to have 10 other building options, then you would need 10 variables to track the state. Try to grasp the concept of classes and objects.

So maybe start reading the concepts of OOP or read the Wikipedia article to get used to the subject.

So, back to your question. First of all I would think of what classes you will have in your game. Assuming from your question I would start by implementing a class GameObject. This class holds some basic information, that are used for all game objects. I put a vector in the class, that represents the position of the object, and an image, that is the graphical representation of that object.

```
public abstract class GameObject{
    public Vector2f position;
    public Image image;

    public GameObject(Image image){
        this.position = new Vector2f();
        this.image = image;
    }

    public void render(Graphics g, float xOffset, float yOffset)
    {
        if(this.image == null) return;
        g.drawImage(this.image, this.position.x + xOffset, this.position.y + yOffset);
    }

    public abstract void update(int d);
}

```

Maybe you noticed that the class is marked abstract. This means, that this class is not meant to be instanciated, but other classes need to extend from it. It already implements a basic render methodThe method update is defined here in the base class without any implementation.

So now lets look on how to implement another game object. One thing you will need is the player class and this could look something like this:

```
public class PlayerObject extends GameObject {
    public final static int STATE_NONE = -1;
    public final static int STATE_BUILDING_ROCK = 0;
    public final static int STATE_BUILDING_WOOD = 1;

    public final static int INDEX_ROCK = 0;
    public final static int INDEX_WOOD = 1;

    public final static float MOVE_SPEED = 0.1f;

    public int state;
    public Vector2f velocity;

    public Image[] objectImages;

    //Because we want to display objects, that can be built, we need to provide the sprites /
    //images of the objects.
    public PlayerObject(Image image, Image[] objectImages){
        super(image);
        this.velocity = new Vector2f();
    }

    @Override
    public void render(Graphics g, float xOffset, float yOffset)
         //First of all we call the render method of the base class
         //This calls the code defined in the GameObject.render method.
         super.render(g, xOffset, yOffset);

         //Now in the player implementation of the render method, we want to
         //know, if the player holds an object, that also should be rendered
         if(this.state == STATE_BUILDING_ROCK){
             g.drawImage(this.objectImages[INDEX_ROCK], this.position.x + xOffset, this.position.y + yOffset);
         }
         else if(this.state == STATE_BUILDING_WOOD){
             g.drawImage(this.objectImages[INDEX_WOOD], this.position.x + xOffset, this.position.y + yOffset);
         }
    }

    @Override
    public void update(int d){
        this.position.x += this.velocity.x * MOVE_SPEED;
        this.position.y += this.velocity.y * MOVE_SPEED;
    }
}

```

If you look at the code, you can see that two things were implemented. The update method changes the position of the GameObject according to the defined velocity. And the render method first simply calls the render method of the base class and then checks, if it has to draw the building material.

Some comments to this. The entities do not manage their state themselves (besides the position), but you would handle all game objects in the game loop and depending on the state you would change the fields of the entity, for example like this:

```
if(container.getInput().isKeyPressed(Input.KEY_2)){
    player.state = PlayerObject.STATE_BUILDING_ROCK;
}

```

With this, you would have the display functionality capsuled in the GameObject and extend that functionality in the PlayerObject class by updating the players position and rendering the building materials, if the player is currently in a building state.

Now to the second part, building the object and leaving it there. To accomplish this, I would create another class StaticObject or something like that.

```
public class StaticGameObject extends GameObject{
    public StaticGameObject(Image i){
        super(i);
    }
    @Override
    public void update(int d){
        //Does not do anything in update
    }
}

```

To make things a bit more interesting, we add the logic to spawn a static game object to the player object (this is maybe not the best solution, but it should do the work). So we add this code to the PlayerObject class:

```
public StaticObject build()
{
    Image i = null;
    if(this.state == STATE_BUILDING_ROCK){
        i = materials[INDEX_ROCK];
    }
    else if(this.state == STATE_BUILDING_WOOD){
        i = materials[INDEX_GRASS];
    }
    //If no image has been found for the material, the thing is not built.
    if(i == null) return null;
    StaticObject obj = new StaticObject(i);
    obj.position.set(this.position);
    //Reset the state
    this.state = MODE_NONE;
    return obj;
}

```

Now, when the player presses a key to build the object, you have to do 2 things. First set the players state back to MODE\_NONE, because he completed the action. As second, you create a StaticObject with the building material and add it to your GameObject list. This object is now independent from your player and stays at its place, even if you move around.

A short abstract, how (parts) of my Game or GameState class would look like, using the examples from above:

```
public class TestGame extends BasicGame
{
    private Image playerImage;
    private Image[] materials;
    private PlayerObject player;
    private List<GameObject> objects;

    public TestGame(){
        super("Test Game");
        objects = new ArrayList<GameObject>();
    }

    [...]
    public void init(GameContainer container){
        playerImage = new Image("PlayerImage.png");
        materials = new Image[2];
        materials[0] = new Image("Rock.png");
        materials[1] = new Image("Wood.png");

        player = new PlayerObject(playerImage, materials);
        player.position.set(100, 100);
        objects.add(player);
        [...]
    }

    public void update(GameContainer container, int d){
        //First do input handling and update the player objects state, if needed
        Input i = container.getInput();
        if(i.isKeyPressed(Input.KEY_1)){
            player.state = PlayerObject.STATE_BUILDING_ROCK;
        }
        if(i.isKeyPressed(Input.KEY_2)){
            player.state = PlayerObject.STATE_BUILDING_WOOD;
        }

        if(i.isKeyPressed(Input.KEY_ENTER) )
        {
            //If the build key is pressed, we try to build with the player
            GameObject obj = player.build();
            //If an object could have been built, it is added to the global game object list
            if(obj != null){
                objects.add(obj);
            }
        }
        //Now update all objects
        for(GameObject object : objects){
            object.update(d);
        }
    }

    public void render(Graphics g, GameContainer container, int d){
        for(GameObject object : objects){
            //The x and y offset parameters are used, when the map scrolls
            object.render(d, 0, 0);
        }
    }
}

```

Keep in mind, it is not the ultimately best solution and I scribbled it down without any IDE, so no warranties that the code actually works ;)

Sooo, I hope it isn't too much. As you can see, we try to capsule functionality to the respective actors. Also, like this you can implement very easily computer controlled characters, that also can use the same build mechanics (just instead of receiving its state from the keyboard input, an AI component would change the state). And also, you can add 10 objects, and you don't have to create all the boolean and position variables for all of them, but only an GameObject per object.

---
Tags: 2d, java, slick
---


# Question
Title: Importing 3d model with multiple skeletons
I have created an animated butterfly in 3ds Max and try to export it in ".fbx" format to use in XNA, however as soon as I compile, i get the following Errors:

**Warning 1 Multiple skeletons were found in the file. The first skeleton, named "Left.Wing" has been moved to be a child of the scene root. The other, "Right.Wing", will be ignored. Fragment identifier "Right.Wing".**

**Error 2 Vertex is bound to bone "Right.Wing", but this bone is not present in the skeleton.**

Which is confusing since I have the bone Right.Wing . . and I use it to animate the butterfly

I have seen a few possible solution for Blender but none for 3Ds max it would be really helpful if someone could help me out with this

# Answer
Though I don't use 3DSMax or XNA, I would assume this issue is caused by the left and right wing not sharing a common parent. All the bones should be connected to a common root bone, since most applications (it seems XNA is included) don't support multiple skeletons per model.

Place a bone down the center of your butterfly and make the left and right wing children of that bone.

```
  left       right
    -----|-----
         |
         |
         | root

```

It doesn't need to have any function, but it would make sense to bind the body vertices to it and use it to move the body as part of your flapping motion.
> 3 votes

---
Tags: xna-4.0, 3dsmax, xna-content-pipeline
---


# Question
Title: Unity: parallel vectors and cross product, how to compare vectors
I read this post explaining a method to understand if the angle between 2 given vectors and the normal to the plane described by them, is clockwise or anticlockwise:

```
public static AngleDir GetAngleDirection(Vector3 beginDir, Vector3 endDir, Vector3 upDir)
{
    Vector3 cross = Vector3.Cross(beginDir, endDir);

    float dot = Vector3.Dot(cross, upDir);

    if (dot > 0.0f)
        return AngleDir.CLOCK;
    else if (dot < 0.0f)
        return AngleDir.ANTICLOCK;
    return AngleDir.PARALLEL;
}

```

After having used it a little bit, I think it's wrong. If I supply the same vector as input (beginDir equal to endDir), the cross product is zero, but the dot product is a little bit more than zero.

I think that to fix that I can simply check if the cross product is zero, means that the 2 vectors are parallel, but my code doesn't work.

I tried the following solution:

```
Vector3 cross = Vector3.Cross(beginDir, endDir);
if (cross == Vector.zero)
    return AngleDir.PARALLEL;

```

And it doesn't work because comparison between Vector.zero and cross is always different from zero (even if cross is actually \[0.0f, 0.0f, 0.0f\]).

I tried also this:

```
Vector3 cross = Vector3.Cross(beginDir, endDir);
if (cross.magnitude == 0.0f)
    return AngleDir.PARALLEL;

```

it also fails because magnitude is slightly more than zero.

So my question is: given 2 Vector3 in Unity, how to compare them?

I need the elegant equivalent version of this:

```
if (beginDir.x == endDir.x && beginDir.y == endDir.y && beginDir.z == endDir.z)
    return true;

```

# Answer
When working with floating point values it's usually not a good idea to use the comparison operator, as even slight inaccuracies will result in inequality. That's why a comparison of floats usually incorporates some sort of "epsilon".. a margin of error.

Example:

```
if(Math.abs(floatA - floatB) <= epsilon){
    // equal
}

```

Epsilon is the desired accuracy.. it's usually a really small number (`1E-5` in C++ I believe).

So your check for equality could look like this:

```
if(Mathf.abs(cross.magnitude) <= Mathf.Epsilon){
    // equal
}

```
> 3 votes

---
Tags: unity, vector, angles
---


title: Dirt compression from vehicle tires

text:
# Question
Title: Dirt compression from vehicle tires
So I kinda have this working but its not correct because it just averages, so I wanted to know if anyone here has any ideas.

I'm trying to simulate loose dirt compression under the tires of a vehicle to reduce the potential bumpiness of 'chunky' terrain. Currently how I do this is that I have a bounding box shape around my tires, set a little lower so they intersect with the terrain.

Each frame, I (currently) average all of the heights of each point in the terrain that are within the box bounds of that tire, and then set them all to that average. Clearly this won't work in most cases because, for example, if i'm on a hill, the terrain will deform way too much.

One way I thought was to have a max and min amount the points could raise and lower but that still doesn't seem to work properly and sometimes looks more like steps than smooth dirt.

I wanna say that there is probably a bit more to this that what i'm currently doing but I am not sure where to look. Could anyone here shed some light on this subject? Would I benefit any by maybe looking up some smoothing algorith or something similar?

# Answer
> 5 votes
This is a much harder problem than it seems on the surface. Consider what a wheel actually does on a big hill made of dirt. It pulls dirt from the front of the tire to the back and sprays it out. The same is happening on the flat land.

The compression itself is also complex, in that once-compressed land doesn't compress the same amount on future passes. You can simulate the compression easier than you are trying to do. Just lower each vertex and mark it as 'compressed' when the tire touches it, then don't lower it again if it is already compressed. This would work on hills and flats just fine, would look a bit like snow tracks.

The hard part is the spray, which increases with the incline of the hill and needs to take from the front of the tire and move to the back. This would be cumulative and could be combined with the compression itself. However, the specifics of it are probably not going to be easy to do. If you were performing this often enough you could probably get close just by taking height from the vertex/ices from the front of the tire and distributing the height over the vertices behind the tire, more closer to the tire, less in an expanding trapezoid coming out from the tire. Don't do it from below the tire, just in-front to behind, let compression handle the under-side.

You can probably ignore this effect for most flat land, and only apply it to inclines above a certain threshold, defined by what looks right and performs well. If this calculation is too great to perform often enough, you'll end up with stepping like you were seeing in your own model, only probably a little less pronounced.

Combine this with a proper reduction in velocity to match the 'fluidity' of the dirt displacement and you've got a simulation that should be able to produce stuck cars with trenching/digging tires and piles of dirt. Could be really cool looking. I'd use this sparingly, on patches of dirt and not make entire maps out of the stuff.

---
Tags: terrain, vehicle
---


# Question
Title: Will C++ remain viable for game engines in somewhat distant future?
C++11 has opened ways, which were only dreamt by the C++ programmers. It has been three years since I have been learning C++, and I am going well. Now I want to get into video games. Every core of the game code I saw, was monstrously written in C++. My question is - If I get into serious game engine dev, and perfecting it would take, maybe say 10 years, would we still be writing game engines in C++ ?(newer standard)

Or, will John Carmack, write id tech 7 in c++?

note - I am strictly talking about game engines.

# Answer
Short answer: yes, game engines will probably be still written in C++ at least for the next 10 years or so.

Long answer: big parts of engine code still include C. Members of the C++ standards committee have been trying (or at least dreaming of it) to close down the pointer arithmetics part of the language in favor of "safe" C++ (the STL/Boost crap that is the complete opposite of what game developers need). \[proof\] As soon as any big push is made in that direction, I assume that the developers will promptly disconnect from the latest standard (if they haven't done that already).

Protip: the language doesn't matter for a good programmer. If you're interested in being one of them, I'd suggest you to try working with lots of different languages and focus on generic concepts that can be applied everywhere.
> 7 votes

# Answer
> Will we still be writing game engines in C++ \[in ten years from now\]?

No one can tell.

Ten years is quite a long time when speaking about programming languages. In the beginning games were written in assembly, then there was a major shift towards C, then a major shift towards C++. There's arguably quite a big shift towards more "modern" languages (such as C#, Java, Javascript...) now that the mobile & web games market is taking so much space, even if C++ remains strong in the PC & console world.

Is this situation going to last long, like in until-2022-long? **Really, you shouldn't bet on it**.

My belief is that one of the main technical reason why we still stick to C++ is memory management: with consoles being so limited memory-wise, you can't afford to leave the memory control to a virtual machine. So if next-gen consoles come with a massive amount of memory, C++ as we know it might very well disappear.

But it's even disputed if the next-gen is still a relevant concept. Maybe the living-room convergence people have been talking about for years will finally happen, and there won't be a market big enough to keep the AAA game industry as it stands now. Maybe cloud gaming will become the norm and games will be running on huge server farms that won't require such a fine-grained control of the machine.

> Or, will John Carmack, write id Tech 7 in C++?

Still, no one can tell. Just look at the previous id Techs:

It's not even clear when will id Tech 6 come to life, and what it will do exactly, how could one predict which programming language an hypothetical id Tech 7 would be written with?

That said, as others answered, my feeling is that C++ is here to stay for a while, but I might be wrong. I suggest you read Scott Meyer's Effective C++, Third Edition, if you didn't already. The author explains how C++ contains already 3 different paradigms in one language (procedural, OOP, template-based): one could imagine **a fourth paradigm becoming popular in the games industry in the near future**, learning about it would be like learning a whole new language.

Now what you need to do is not to focus too much on the programming language. Of course becoming a C++ guru now gives you a good chance to get a job in the mainstream games industry. **But what you have to master is software engineering, this will certainly stay viable for quite a long time.**
> 3 votes

# Answer
"It depends". If you're aiming to work at id or Blizzard then your best bet is C++, but if you're going to work in a small studio then it can be anything, HTML5/CSS3/JavaScript, Flash, C#, Java, etc. simply because most small titles don't need the power of C++ and these other languages allow for faster and easier development a lot of the time.

You're going to be writing "serious" game engines no matter the language of choice. It's a matter of the sector you want to be working in. All i can tell you is that setting your mind on only one language is bad. It's like only driving SUVs, while there are dozens of other types of cars that all have a steering wheel and a gear box.

So will C++ stay viable for game engines? Yes. Will it be the best language to use? It depends on the studio, the target platform and the type of game they'll be making.
> 1 votes

# Answer
C++ is probably the most stable language in the moment:

* It just got modernized with the C++11 specification.
* C#, which is the largest rival at the moment seems to be crumbling with Microsoft switching back to C++ as primary language and abandoning XNA.
* D is still far away from being any serious competition.
> 0 votes

# Answer
In case of AAA or AAAA game engines, I think that C++ will be majorly used for (Virtually) eternally...If you want to go into any big studio, go for C++, they wont switch(at least, in case of game engines).

Indie games have a different story-- C++ will be there, ( Unity, Panda3d are actually writern in C++ :) but the focus will be on beginner freindly languages.
> -2 votes

# Answer
C++ isnt going away any time soon. C#, Java. . . all these managed languages can be used in actual game, but they will always run on an engine in native language. . for example, rust, c, c++.
> -2 votes

---
Tags: c++
---


title: OpenGLES how to make a 3D object iOS

text:
# Question
Title: OpenGLES how to make a 3D object iOS
I am a newbie in OpenGLES, so pardon me if I cannot state the question properly.

1. Is it possible to create a 3D box with the following imports only: OpenGLES, QuartzCore, GLKit
2. I have created a 2D object, (squares, triangles, polygons) but I want to make them into 3D without using cocos3D or blender or other frameworks or api (if its possibe). But how?

# Answer
> 1 votes
Creating a 2D object is the same as creating a 3D object. You just need more vertices you would go from 4 vertices in a square to 8 to create a cube. Also, the same happens to indices, vertex color and normals.

If you want to properly set up a 3D shape (a cube) with proper texture, you need to calculate the texture coordinates. The reason you don't do this yourself is because is inefficient. You need to use blender to get the proper coordinates for vertices, normals, colors and textures.

Using blender usually takes about 20 seconds to create a cube with textures or to create a 3D human character. If you do the first manually it would take you about two days to complete. More over, if you do a 3D human character manually it might result impossible due to the number of coordinates multiplied by 4 because of the vertices/normals/color/texture.

My suggestion is to use blender, you should watch a youtube tutorial. Then you would be ready to go in less that 30 minutes.

---
Tags: ios, opengl-es, objective-c, opengl-es2
---


# Question
Title: My Maya texture does not render at all in Open GL!
I uploaded my layered Maya (Maya 2012) Textures via objLoader into my opengl project. I also uploaded 3D textured model. I am able to render a model but not even one texture is showing. Before pasting any code here, i thought maybe there is some common mistake that we beginners are doing, regarding this issue!?

# Answer
Displaying vertex and colors from and imported model is always a snap but showing a texture has many factors involved with it. You might not solve this problem in one day, but there is hope.

I'm going to suggest you UV map your texture properly, avoid using any layers or what not. Maybe your application doesn't support multitexture. So, UV mapping is the simplest way to do things. Then try it out to see if it works.

I'm certain your model loader supports UV mapping.
> 1 votes

---
Tags: opengl, textures
---


title: List of 3D libraries based on WebGL

text:
# Question
Title: List of 3D libraries based on WebGL
Is there a up-to-date list of WebGL libraries or articals with comparison? Until now I heard only three.js and GLGE.

# Answer
> 6 votes
Khronos, the guys who are the "keepers" of OpenGL and WebGL have a preeeeeety loooooong list of WebGL stuff found on the web: http://www.khronos.org/webgl/wiki/User\_Contributions
And, the list is actively updated, although, there might be some outdated stuff hiding in-between.

And, I bet, that a little in depth browsing through http://www.khronos.org/webgl/wiki/Main\_Page would give you more than enough information to get you started.

But, if you're looking for direct comparison chart, that's a problem. Because 3D graphics is such a broad term, and WebGL is nowhere near production use, all the libraries out there are basicly experiments.

There are no set guidelines what a WebGL library should boast, therefore, it's hard to compare them.

# Answer
> 2 votes
I have been looking into this question, and creating a comparison of my own. As a starter I used this post.

http://weblog.benjaminsommer.com/blog/2012/05/13/comparison-of-webgl-framework-apis/

While this is not a comparison of the complete list of WebGL frameworks, it is more then I have found available. If anyone else has similar links I hope they share!

# Answer
> 1 votes
My own super-lightweight barebones.js can do basic matrix and vector math, load and draw fonts, textures and animated meshes. It has a super-basic 2D UI framework too.

I actually have quite a lot of stuff I made for my last Ludum Dare entry \- a 3D online multiplayer space combat game - to fold back into barebones.js including performance improvements, fps counters and so on.

Finally I've got some newer mesh collision code, auto-normals code and other goodies under development for my latest hobby game; I'll fold them into barebones.js when they work too.

All in all its super lightweight and is super-easy to initialise your canvas properly, give you simple glu equivs like look-at, unproject, perspective etc as well as quaternions and that kind of stuff. And then it gets out of your way and lets you make your game!

I'd be happy to fix and improve if others use it too. Long live hobby coding!

---
Tags: 3d, javascript, webgl
---


# Question
Title: Rotate sphere in Javascript / three.js while moving along x/z plane
I have a sphere/ball in three.js which I want to "roll" around on the x/z plane. For the z axis I could simply do this no matter what the current x and y rotation is:

```
sphere.roll_z = function(distance) {
      sphere.position.z += distance;
      sphere.rotation.x += distance > 0 ? 0.05 : -0.05;
    }

```

But how can I roll it along the x axis? And how could I *properly* do the roll\_z? I've found a lot about quaternion and matrices, but I can't figure out how to use them properly to achieve my (rather simple) goal.

I'm aware that I have to update multiple rotations and that I have to calculate how far to rotate the sphere to match the distance, but the "how" is the question. It's probably just lack of mathematical skills which I should train, but a working example/short explanation would help a lot to start with.

Here is an example of how the rotation goes wrong (WASD movement): http://js.blockheaven.net/simple.html

# Answer
After searching arround for hours, digging through three.js code and commits I found out which code snippets do what I was intending to do and how to make them run with the current three.js version (documentation and all stackexchange answers are outdated).

```
// Rotate an object around an arbitrary axis in world space
var rotWorldMatrix;
function rotateAroundWorldAxis(object, axis, radians) {
  rotWorldMatrix = new THREE.Matrix4();
  rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
  rotWorldMatrix.multiplySelf(object.matrix);
  object.matrix = rotWorldMatrix;
  object.rotation.setEulerFromRotationMatrix(object.matrix);
}

```

Original by Cory Gross found at: https://stackoverflow.com/questions/11060734/how-to-rotate-a-3d-object-on-axis-three-js?rq=1 (but getRotationFromMatrix is outdated).

This method rotates the object based on world axes aka rolling a ball on the floor while the camera is fixed. To use this, it needs to know which axe (x, y, z) of the object it should rotate:

```
var xAxis = new THREE.Vector3(1, 0, 0);
var yAxis = new THREE.Vector3(0, 1, 0);
var zAxis = new THREE.Vector3(0, 0, 1);

```

Now, because I want to move it by a certain distance of pixels, to calculate the angle to rotate it:

```
var angle = distance / (2 * Math.PI * object.boundRadius) * Math.PI;

```

And there is my roll\_z function:

```
sphere.roll_z = function(distance) {
  this.position.z += distance;

  var xAxis = new THREE.Vector3(1, 0, 0);
  var angle = distance / (2 * Math.PI * this.boundRadius) * Math.PI;
  rotateAroundWorldAxis(this, xAxis, angle);
}

```

Hope this might help others trying to achieve the same thing from going crazy like I was.
> 2 votes

# Answer
Lets say `d` vector contains the distance you want to roll on `x` and `z` axis as `d.x` and `d.y` respectively.

Let `R` be the radius of the sphere (which you haven't mentioned).

Now for a distance of `2*pi*R`, your sphere makes a full rotation of `2*pi` radians (360 degrees)

So for a distance of `d`, it will rotate `d/R` radians.

Rotation for x and z axis will happen in exactly the same way.

```
sphere.roll_x = function(distance) {
  sphere.rotation.z += distance.x / R;   //Rotation around z axis
  sphere.position.x += distance.x;
}

sphere.roll_z = function(distance) {
  sphere.rotation.x += distance.z / R;   //Rotation around x axis
  sphere.position.z += distance.z;
}

```

First do rotation, then translate it.
> 0 votes

---
Tags: 3d, mathematics, javascript, rotation, webgl
---


title: Game Server on Windows Azure

text:
# Question
Title: Game Server on Windows Azure
What do you guys think of using Windows Azure for deploying a custom built game server. It's being built in C#, and I want to get a few things down before stretching too far into the project.

I like the idea of being scalable, but I also know that I will never get to the scale of anything to the scale of WOW, or something quite as big. It will just be an interesting journey to test something like this.

So, will Windows Azure work for that, or is there any other services that can provide something like that?

# Answer
> So, will Windows Azure work for that

Yes, Windows Azure will work.

> or is there any other services that can provide something like that?

If you want to develop and run a .NET game server, you'll need something that will run the .NET framework (as well as any other libraries you end up using in your project). Any server host that offers Windows Servers will suffice.

The two big options for Windows Server hosting are Windows Azure and Amazon EC2. There are others out there as well, some being a tad more reliable than others.

How do you choose your host? Personal preference. Finances. Methods of access. Reliability. Reputation. None of us can answer that for you.

If you have the ability to install the software you need (.NET, any dependency libraries, Visual Studio, SQL Server, whatever else you require to build and run your game server), and you can access the system in a way that works for you (ssh vs. rdp vs. telnet vs. vnc vs. http) then the rest is fairly subjective.

Windows Azure has a 90-day free trial. Give it a shot. If it works, keep it. If not, check out the others.
> 1 votes

# Answer
You can also consider the google computing engine.

But before you commit to a service, you should analyse pricings. You pay for traffic / processing time / space, so this may not be a viable solution ...

\[**UPDATE**\]

Maybe Google Compute is not the best alternative for Azure (I guess is more related to heavy computation than with hosting web apps ...); I found this presentation regarding different cloud services, and you have two more options:

* Amazon EC2, which can run Windows
* AppHarbor, which hosts .NET applications (C#, ASP.NET, ...)
> 2 votes

---
Tags: c#, mmo, server, windows
---


title: Tiny Wings - Placing items

text:
# Question
Title: Tiny Wings - Placing items
I'm currently developing a Flash game like 'Tiny Wings'. I have a lot of work done, but i'm currently working on placing the items ( coins and obstacles ) on the terrain.

My player it is moving on a auto-generated terrain (based on Emanuele Feronato's tutorials) so every time the player's x position is greater than (screenWidth + x) another hill is generated and so on.

I'm currently having problems placing the items in a correct angle and put 5 or more items together on a hill.

Could you please help me with this?

Thanks, Regards.

PS: This is the URL to the Emanuele Feronato post and the code to make the hills http://www.emanueleferonato.com/2011/10/04/create-a-terrain-like-the-one-in-tiny-wings-with-flash-and-box2d-%E2%80%93-adding-more-bumps/

# Answer
Just find the hill-element that's at the position where you want to place your item and rotate it to match the orientation of the hill-element. You can get the angle of the element by doing something like this (please note that the angle will be in radians):

```
segment = vertexB - vertexA
angle = atan2(segment.y, segment.x)

```

Personally, I would just store the vertices (vectors) that make out the slope of the terrain in a separate data-structure, because reading them out from the box2d bodies can be cumbersome. To find `vertexA` and `vertexB` given a desired item-position `itemX`, you would iterate through the hill-vertices (assuming they are ordered from left to right) and stop whenever `vertices[currentIndex].x` is bigger than `itemX`. Then `vertexB` will be `vertices[currentIndex]` and `vertexA` will be `vertices[currentIndex - 1]`.
> 2 votes

# Answer
@bummzack is correct; use trigonometry. also worth noting is the 2d perpendicular vector to a segment is

```
(-segment.y, segment.x) or (segment.y, -segment.x)

```

notice the dot product with the segment in both cases is zero (because cos(90) = 0)
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: Unity3d - setting gameobject position by percentage of view
I am having trouble finding a way to set a gameobject's position with regards to the screen size. I am building a 2d game that I will be putting on iPhone, iPad, and Android. I need to be able to set the object's position to a percent of the view.

# Answer
The solution ended up being pretty simple. What I had to do is use the conversion of ViewportToWorldPoint.

```
Camera.main.ViewportToWorldPoint(Vector3(.05, .90, 3));

```

The decimals are percentages of the screen. and the Z is distance from the camera.
> 2 votes

---
Tags: unity, javascript
---


# Question
Title: Simulating a sine wave/oscillating pattern for enemies
I'm creating a simple top down shooter, right now I have an enemy which simply follows the player. I'd like to change things up and have the enemies move towards the player but in a wave like motion. I have looked at some similar questions like this but they don't take into account for the Y changing. How can I simulate a wave like pattern for my enemies whilst they are homing into their target.

Edit:

Sample code

In my update method I have the following:

```
            Vector2 trackingPos = position - target;
            trackingPos.Normalize();
            position -= trackingPos * elaspedTime  * speed;

```

# Answer
Here is the solution I would try

```
Vector2 dir = target - position; // direction
dir.Normalize();
Vector2 perp( -dir.y, dir.x ); // perpendicular

float waveAmp = 0.05f; // adjust if needed
float waveAngle = elapsedTime * 3.14f * 2; // adjust if needed
Vector2 wave = perp * sin(waveAngle) * waveAmp;

Vector2 vel = dir * speed;
position += vel * elaspedTime + wave;

```
> 2 votes

# Answer
Assuming you have your logic for homing actually working, I would just have an offset variable (float) that you update over time for how much oscillation you want (for a simple test case I would simply do something like `sin( elapsedTime )` until you figure out exactly what you want. Then just add a vector with a length of that offset value and a direction that's perpendicular to your enemy's forward vector (assuming forward is pointing towards its target) and put it there.
> 3 votes

# Answer
Here's what I would use:

```
//Change 800 to whatever number you like - that's how much it bows out
position.X = position_x_origin - (800 * (float)Math.Sin(((float)gameTime.TotalGameTime.TotalSeconds - timeSpawned)
   * MathHelper.Pi / 2));
//This causes the change in Y
Velocity = Vector3.Down * speed;

```
> 0 votes

# Answer
You should take a look at Bézier curves, they're easy to implement and offer lots of possibilities.

Bézier curves on Wikipedia
> -2 votes

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


# Question
Title: Diamond-square terrain generation problem
I've implemented a diamond-square algorithm according to this article: http://www.lighthouse3d.com/opengl/terrain/index.php?mpd2

The problem is that I get these steep cliffs all over the map. It happens on the edges, when the terrain is recursively subdivided:

Here is the source:

```
void DiamondSquare(unsigned x1,unsigned y1,unsigned x2,unsigned y2,float range)
    {
    int c1 = (int)x2 - (int)x1;
    int c2 = (int)y2 - (int)y1;
    unsigned hx = (x2 - x1)/2;
    unsigned hy = (y2 - y1)/2;
    if((c1 <= 1) || (c2 <= 1))
            return;

// Diamond stage
float a = m_heightmap[x1][y1];
float b = m_heightmap[x2][y1];
float c = m_heightmap[x1][y2];
float d = m_heightmap[x2][y2];
float e = (a+b+c+d) / 4 + GetRnd() * range;

m_heightmap[x1 + hx][y1 + hy] = e;

// Square stage
float f = (a + c + e + e) / 4 + GetRnd() * range;
m_heightmap[x1][y1+hy] = f;
float g = (a + b + e + e) / 4 + GetRnd() * range;
m_heightmap[x1+hx][y1] = g;
float h = (b + d + e + e) / 4 + GetRnd() * range;
m_heightmap[x2][y1+hy] = h;
float i = (c + d + e + e) / 4 + GetRnd() * range;
m_heightmap[x1+hx][y2] = i;

DiamondSquare(x1, y1, x1+hx, y1+hy, range / 2.0);   // Upper left
DiamondSquare(x1+hx, y1, x2, y1+hy, range / 2.0);   // Upper right
DiamondSquare(x1, y1+hy, x1+hx, y2, range / 2.0);   // Lower left
DiamondSquare(x1+hx, y1+hy, x2, y2, range / 2.0);       // Lower right

```

}

Parameters: (x1,y1),(x2,y2) - coordinates that define a region on a heightmap (default (0,0)(128,128)). range - basically max. height. (default 32)

Help would be greatly appreciated.

# Answer
In each subdivision level, the "square" step relies on the results of the "diamond step". But it also factors in the diamond-step produced in the adjacent cell, which you aren't accounting for. I'd rewrite the DiamondSquare function to iterate Breadth-first, instead of depth-first as you currently have it.

Your first issue is that since you re-calculate the square edges twice, it ignores the contribution of the adjacent centerpoint. For example, in the article you reference,

```
P = (J + G + K + E)/4 + RAND(d)

```

but your code effectively does

```
P = (J + G + J + E)/4 + RAND(d)

```

i.e. it factors in the **current** centerpoint twice, not the adjecent centerpoint. This is why you need to go breadth-first, so that you have the previous centerpoints calculated.

Here's my code and the output: .

```
void DiamondSquare(unsigned x1, unsigned y1, unsigned x2, unsigned y2, float range, unsigned level) {
    if (level < 1) return;

    // diamonds
    for (unsigned i = x1 + level; i < x2; i += level)
        for (unsigned j = y1 + level; j < y2; j += level) {
            float a = m_heightmap[i - level][j - level];
            float b = m_heightmap[i][j - level];
            float c = m_heightmap[i - level][j];
            float d = m_heightmap[i][j];
            float e = m_heightmap[i - level / 2][j - level / 2] = (a + b + c + d) / 4 + GetRnd() * range;
        }

    // squares
    for (unsigned i = x1 + 2 * level; i < x2; i += level)
        for (unsigned j = y1 + 2 * level; j < y2; j += level) {
            float a = m_heightmap[i - level][j - level];
            float b = m_heightmap[i][j - level];
            float c = m_heightmap[i - level][j];
            float d = m_heightmap[i][j];
            float e = m_heightmap[i - level / 2][j - level / 2];

            float f = m_heightmap[i - level][j - level / 2] = (a + c + e + m_heightmap[i - 3 * level / 2][j - level / 2]) / 4 + GetRnd() * range;
            float g = m_heightmap[i - level / 2][j - level] = (a + b + e + m_heightmap[i - level / 2][j - 3 * level / 2]) / 4 + GetRnd() * range;
        }

    DiamondSquare(x1, y1, x2, y2, range / 2, level / 2);
}

```
> 12 votes

# Answer
One possibility is that you are taking a shortcut with your implementation that the algorithm on your linked page does not.

For the square stage, you are calculating the height of the points with

```
float f = (a + c + e + e) / 4 + GetRnd() * range;
m_heightmap[x1][y1+hy] = f;

```

which the page's algorithm indicates to use if you are wrapping your map. This gives the appearance that you are using the "next square over"'s height value to calculate this one's. In the simplest, first case, the central point (with height 'e') is used on both the left and right sides to calculate f.

However, the algorithm you reference has you use the actual values of the other squares/diamonds to help you calculate the value of the height of this square point. In their algorithm, the second level point is calculated with the following formula:

```
N = (K + A + J + F)/4 + RAND(d)

```

Notice the lack of duplication of a value in there?

I think you might want to try to go for using the non-wrapping versions of the formulae given, those will recurse better, I think.

```
F = (A + C + E)/3 + ...
    instead of
F = (A + C + E + E)/4 + ...

```
> 3 votes

---
Tags: algorithm, procedural-generation, terrain
---


# Question
Title: Best Way To Develop Robust Cross-Platform Application?
> **Possible Duplicate:**
> Any tips for creating cross-platform games?

Windows C programmer here (going back to 1992 and Windows95 back when it was called Windows93). Can function in C++, but mostly still a C programmer.

Looking to build a cross-platform casual game. Very numbers heavy with only a few artistic embellishments and animations, so perhaps a development environment for business apps might be the best option. Or an easy-to-use 2D game dev platform.

Target platforms: Windows, Mac, MS Tablet, iPhone, iPad, Android.

I currently develop on Windows with Visual Studio 2012, but we could spend up to $50K on hardware/software/middleware if necessary. Not very competent getting open-source software working. Would rather pay the money and jump right into app development.

Recommendations?

# Answer
> 0 votes
If you are looking to do something with C or C++, I would personally recommend using OpenGL with GLFW (and toss in GLEW if you plan on using OpenGL 2 or higher functions). GLFW and GLEW work well with Visual Studio 2012 and other compilers.

However, if you aren't interested in creating your own engine with OpenGL, and are willing to use c#, you could use XNA with MonoDevelop, which should work on all or most of your target platforms.

# Answer
> 0 votes
Cocos2d-x lets you stick with C++ and Visual Studio for development but gets you running on Windows, Mac, iPhone, iPad, and Android with little fuss. MS tablet is trickier since you'll probably use C# and XNA for that.

---
Tags: windows, cross-platform, macos
---


title: Setting Krypton Light to Screen Pixels

text:
# Question
Title: Setting Krypton Light to Screen Pixels
So a few days back, I started playing around with Krypton XNA for 2D lighting in my game.

I noticed in general, that spawning a light at (0,0) with Krypton causes the light to appear in, pretty much, the centre of the game screen. Is there any way to change this so a Krypton light's "starting point" at \[0,0\] would spawn at the top left of the screen, and thus follow the standard screen co-ordinates for position?

I ask because currently I'm busy working on my game where my spawn point is \[512,512\]. With hard code, the closest I've got to the light being "central" to this point is the vector position \[12,-20\], which makes no sense and is impossible to craft, mathematically, if I want the light to move with the camera (the position \[480,512\] maps roughly to \[10,-20\]).

So, is there any way to "normalise" the krypton lights to use standard screen co-ordinates?

If you guys can, play around with the demo from the site and please see if you can find anything out about it. Documentation on the engine is rather scarce, so it's difficult to find anything relevant to my "pixel-perfect" need. It might just also be something in the code with regards to the matrices that I'm not fully understanding.

Any help would be useful.

Thanks.

# Answer
I am the creator of Krypton

SpriteBatch uses pixels as it's default unit. Krypton does not have a default unit. Imagine "1px" vs "1" vs "1km". Krypton's units would simply be "1".

You'll need to either adjust Krypton's matrix to compensate for the variation by enabling "SpriteBatch" mode on Krypton, or by adjusting SpriteBatch's matrix, which can be accomplished via an overload to the Begin call.

There has been some confusion about how to do this easily, and my attempts to make the framework *easily* usable with SpriteBatch have thus far been less than satisfactory. I will be making some improvements within the next month or two, as I will need this feature for a game I am currently working on.
> 1 votes

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


# Question
Title: 2D Physics Engine to Handle Shapes Composed of Multiple Densities XNA
The game I'm working on involves shapes that might be composed of multiple materials in a variety of ways. Let's just take for example a wooden rod with and sizable tip of iron or say a block composed of a couple triangles of stone and aluminum and small nugget of gold. The shapes and compositions will change from time to time, so I was wondering what engine I should use and how I might implement this feature?

I've looked at Farseer 3, but I'm still trying to decipher the library by reading the source and the samples and wasn't sure if I was barking up the wrong tree.

Thanks!

# Answer
> 1 votes
Farseer's physics operates on "**Bodies**" made up of one or more "**Fixtures**". Bodies are rigid, and the fixtures of a single body cannot move relative to each other.

**Bodies** have a position, angular velocity, linear velocity, torque, mass, centre-of-mass, etc. And, of course, a list of child fixtures.

**Fixtures** have a shape (eg: a polygon made up of points, or a circle), a coefficient of restitution, a coefficient of friction, **and a mass** (although you usually specify a density, and Farseer will work out the mass from the shape's area).

So, yes, Farseer should be able to handle exactly what you want. Just make up a body from multiple fixtures.

(You could also, as an optimisation, have a single fixture, and set the mass/center-of-mass/etc properties on the body by hand. If you need to separate your fixtures at some point - you can modify bodies on-the-fly - or you can use multiple bodies and attach them together with joints.)

---
Tags: xna, c#, physics, farseer-physics-engine
---


# Question
Title: Having troubles with LibNoise.XNA and generating tileable maps
Following up on my previous post, I found a wonderful port of LibNoise for XNA. I've been working with it for about 8 hours straight and I'm tearing my hair out - I just can not get maps to tile, I can't figure out **how** to do this.

Here's my attempt:

```
            Perlin perlin = new Perlin(1.2, 1.95, 0.56, 12, 2353, QualityMode.Medium);
        RiggedMultifractal rigged = new RiggedMultifractal();

        Add add = new Add(perlin, rigged);

        // Initialize the noise map
        int mapSize = 64;
        this.m_noiseMap = new Noise2D(mapSize, perlin);
        //this.m_noiseMap.GeneratePlanar(0, 1, -1, 1);

        // Generate the textures

        this.m_noiseMap.GeneratePlanar(-1,1,-1,1);
        this.m_textures[0] = this.m_noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale);

        this.m_noiseMap.GeneratePlanar(mapSize, mapSize * 2, mapSize, mapSize * 2);
        this.m_textures[1] = this.m_noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale);

        this.m_noiseMap.GeneratePlanar(-1, 1, -1, 1);
        this.m_textures[2] = this.m_noiseMap.GetTexture(this.graphics.GraphicsDevice, Gradient.Grayscale);

```

The first and third ones generate fine, they create a perlin noise map - however the middle one, which I wanted to be a continuation of the first (As per my original post), is just a bunch of static.

How exactly do I get this to generate maps that connect to each other, by entering in the mapsize * tile, using the same seed, settings, etc.?

# Answer
Here's how I've been handling it.

1: use the same generator. This is not really optional. You need the same noise function if you want to generate seamless noise between textures, chunks, etc. The seed and other variables should NOT be modified outside of the initial startup.

2: Continue on with incrementing the X/Y/Z in relation to your first texture.

For example... lets say you are creating 2 64x64 pixel textures side by side. Your first texture is going to look something along the lines of...

```
for(int y = 0; y < 64; y++)
    for(int x = 0; x < 64; x++)
        noiseArray[y * 64 + x] = generator.GetValue(x, y, 0);

```

Now... we have that generated but what happens for our second texture? Simple! Just continue boosting x and y.

```
noiseArray[y * 64 + x] = generator.GetValue(x, y + 64, 0);
//this texture is to be placed at y++ from first one

```

Now.. that's all well and good but especially if you need large maps, this may not be your best approach. Personally I'd consider each texture as taking up 1 coord. Therefor each pixel, block or however you want to think of it inside that texture is going to be 1/Dimensions.X or 1/Dimensions.Y

Simply alter your noise function (or output returned from it) so that it will accept these much smaller increments.

Hope that helps.

Here's a very, very basic bit of code I whipped up for a noisemap test in XNA.

```
    Texture2D One, Two;
    Point Dimensions = new Point(500, 500);
void GenerateHeightmaps()
    {
        generator = new GeneralTerrain(new Random().Next(int.MaxValue / 2));
        One = GenerateTexture(new Vector3(0, 0, 0));
        Two = GenerateTexture(new Vector3(0, 1, 0));
    }
    Texture2D GenerateTexture(Vector3 worldLocation)
    {
        Color[] noise = new Color[Dimensions.X * Dimensions.Y];
        for (float x = 0; x < Dimensions.X; x++)
            for (float y = 0; y < Dimensions.Y; y++)
            {

                int cval = GenerateHeight(worldLocation,
                    new Vector2(x, y));
                noise[(int)(y + x * Dimensions.Y)] = new Color(cval, cval, cval);
            }
        Texture2D text = new Texture2D(GraphicsDevice, Dimensions.X, Dimensions.Y);
        text.SetData(noise);
        return text;
    }
    int GenerateHeight(Vector3 worldLocation, Vector2 blockLocation)
    {
        Point loc = new Point((int)(blockLocation.X + worldLocation.X * Dimensions.Y),
            (int)(blockLocation.Y + worldLocation.Y * Dimensions.Y));
        return generator.GetData(loc.X, loc.Y);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw(One, Vector2.Zero, Color.White);
        spriteBatch.Draw(Two, new Vector2(Dimensions.Y + 1, 0), Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }

```

And the Simple GeneralTerrain class to configure the generator

```
public class GeneralTerrain
{
    Perlin generator;
    public GeneralTerrain(int seed)
    {
        generator = new Perlin();
        generator.Seed = seed;
        generator.NoiseQuality = NoiseQuality.Standard;
        generator.OctaveCount = 5;
        generator.Frequency = .01;
    }
    public int GetData(double x, double y)
    {
        return (int)(generator.GetValue(x, y, 0) * 128 + 100);
    }
}

```
> 2 votes

---
Tags: xna, c#, maps, random, perlin-noise
---


# Question
Title: Mesa library vs Hardware accelerated OpenGL for my executable - it's just a linking problem?
Supposing that i have my program that is targeting a specific OpenGL version, let's say the 3.0, now i want to produce an executable that will support the software rendering with Mesa and another executable that will support the Hardware accelerated context, i can use the same source code for both without expecting any issues ?

In another words, the instrunctions in this libraries are the same for my linking purpose ?

# Answer
> 1 votes
Mesa and other libraries that implement the opengl API are dynamically linked, so yes, your application doesn't need to know what the actual library is.

---
Tags: opengl, mesa
---