# Question
Title: How might I script the creation of CLR objects?
I am looking for a method to script the creation of entities (arrays of components) for delivery through my entity factory, i.e scripted creation of .net objects.

I have looked into Lua but it seems dynamically creating CLR objects is a somewhat impractical.

Is there another method I could use to achieve this? Is there a general pattern / approach to take towards scriptiing out functionality in this context?

My factory provides an abstracted EntityComponent\[\] per request, so the scripting platform would need to be aware of and be able to construct the component types defined within the c# namespace.

I want to be able to define the components of an entity and the components relevant properties in some declarative form within a script. To give some background information, I was let onto this when I found deserializing entity definitions from XML was going to be very awkward. Reflection within C# is an option but if it is not my **only** option I would very much seek to avoid it.

**EDIT:** Turns out I was very wrong about Lua! It is unbelievably easy to achieve what I was describing once you get the LuaInterface DLL up and running, importing types from your C# application into Lua is simple and effective.

# Answer
I've been writing a few blog posts about this recently. Specifically for entities data files, and the just published post for taking those data files and turning them into entities.

Essentially, you **write your own parser for a custom script language**. The parser reads components into "blueprint" form for your factory. Each entity will have a set of component blueprints that can be used to generate a unique entity. When you want your factory to create an entity of that type, it creates a component for each blueprint it has, then adds them all to an entity object.

It's not really likely you'll find something pre-built. Since there are so many ways to implement an entity component system, your solution will need to be specific to your implementation.
> 5 votes

# Answer
If you're using C# (it's in the tags) you might be able to take advantage of the Xml.Serialization in-built parser to serialise/deserialise your objects:

http://support.microsoft.com/kb/815813

In theory (probably a big in-theory) it's as simple as passing the object to a serializer and letting it do the hard work. Especially if your entities are just bags of components, which should just be a list of other objects to create. If you store Direct3D resources inside your components you might need to augment it a touch by customising the serialization of those parts. There's a fuller reference for the serialisation methods here.

Hope that helps.
> 2 votes

---
Tags: xna, c#, entity-system, scripting, lua
---


# Question
Title: Sharing the XNA executable of my game on dropbox
I'm currently making a game and I have my artist living in a different city as me. We share a dropbox folder so that I can see her art, and I thought it should be easy to copy the debug bin folder into the dropbox so that she can see it. This doesn't work (I can't even run it), so what could I do?

EDIT:

I run the executable in the dropbox folder, and immediately I get the "game.exe" has stopped working. So obviously I have XNA installed, but my game can't run in this folder.

# Answer
> 5 votes
Just to clarify, your artist will need to install the XNA framework as well. Additionally, if your game requires other stuff to be installed (like OpenAL if you use MonoGame), your artist will need that too.

Also, if you're using the XNA content pipeline, this won't work, because the file formats are all in `.xnb` and similar processed formats; you need to use straight-up assets instead.

**Edit:** Beyond that, you will need at *least* the following:

* Release-built .EXE (it's faster than debug)
* XNA and other DLLs that are dumped out in `bin\Release`
* `Content` directory and all subdirectories/files
* Anything else your game needs at runtime (eg. level files or whatever you use)

# Answer
> 4 votes
Select a folder (preferrably empty) where you will publish the contents, and then send it whole to your friend.

Make sure your project is using Reach in its Properties, otherwise it most certainly won't install properly and you'll have to put up with your friend's complaints. :)

---
Tags: xna
---


# Question
Title: Complex Models using bounding boxes in xna 4
I'm new to XNA, and have just started looking into collision detection. I've managed to get a bounding sphere around my first person camera object and i want to check the collision between that and the walls of my cube. e.g.

this is a cube i have built in Maya and it is 1 combined mesh. What i want to do i check my bounding sphere against the inside of the walls. and also allow the myself to enter in and out of the holes in the sides and th top. My first thought would be using each vertex to test against collision but i have no idea how to do this, since this is the first time attempting. Can anyone point me in the right direction?

# Answer
For this model, I think I might be tempted to create a compound bounding structure where there is one box that encompasses the whole model (level1 box), then 6 individual boxes for each major wall/side (level2 box), then lastly, a box for the passage way from outside to inside(level3 box) attached to its respective level2 box. Since your model is pretty simple & symmetrical, determining min, max for each box doesn't seem too hard.

The logic flow would be something like:

```
if(intersects level1 box)
{
  foreach (level2 box l2b)
   {
     if(intersects l2b)
      if(!intersects l2b.level3Box)
      {
         //collision occurred
      }
   }
}

```

Alternatively, have a look at the ship sample on the app hub site (requires premium membership), it creates an octtree for the model and uses it to narrow down which model triangles to test the camera against.
> 1 votes

---
Tags: collision-detection, xna-4.0
---


# Question
Title: Game loosely based on a copyrighted story
I want to make a game based on a copyrighted book. It's not about recreating it strictly with all details, but rather about building something new around the general idea (possibly incorporating some concepts from other books by the same author).

I don't want any copyright infrigement or plagiarism problems. How far can I move with "borrowing" concepts from the original story? Will it be fine to:

* set the action in the same universe? (possibly changing character names etc)
* use the same general concept (rather unique one), but with my own plot?
* let the player choose one of many story threads, one of which will be the original one?

# Answer
> 3 votes
The safest way to avoid ANY "copyright infringement or plagiarism problems" is to NOT base your game on any other person's creative work.

By "problems" I'm including the hassle of responding to an allegation that your work infringes theirs---even if, according to the laws of what ever country your working in---it doesn't. A helpful rule of thumb is: if the original work is at all recognizable in yours, someone will probably think you're infringing and may make an issue of it. Reproducing the **original story thread**, or setting your action in the **original author's universe** is pretty likely to raise a red flag.

**"General Concept"** is a pretty vague term. If general enough ie. "a protagonist and his or her rag-tag gang of accomplices fight against an evil galactic empire/wizard/high-school principle for freedom and justice using magic spells/mutant powers/zany pranks" then you're probably within your rights to try a new variation on an old theme. Obviously this entails creating your own story.

If you have any serious plans to share your game with the public (commercially or otherwise) the only responsible thing to do is seek permission from the copyright holder. Anything else is likely to attract some form of copyright "problem".

---
Tags: legal, copyright
---


# Question
Title: Unity: Assigning a key to perform an action in the inspector
I am trying to write a simple piece of code in `JavaScript` where a button toggles the activation of a shield, by dragging a prefab with `Resources.load("ActivateShieldPreFab")` and destroying it again (Haven't implemented that yet).

I wish to assign this button through the inspector, so I have created a string variable which appears as intended in the inspector. Though it doesn't seem to register the inspector input, even though I changed the value through the inspector.

> It only provides the error: "Input Key named: is unknown" When the button name is assigned within the code, there is no issues.

Code as follows:

```
var ShieldOn = false;
var stringbutton : String;

function Start(){
}

function Update () {
    if(Input.GetKey(stringbutton) && ShieldOn != true)
    {
        Instantiate(Resources.load("ActivateShieldPreFab"), Vector3 (0, 0, 0), Quaternion.identity);
        ShieldOn = true;
    }
}

```

# Answer
For at least one object in your scene, the variable `stringbutton` isn't assigned. The error "Input Key named: is unknown" shows that it's not displaying a key's name (otherwise the error would be more like "Input Key named: **up** is unknown").

For every instance of whatever object has that script on it, you need to ensure it has a legitimate value in the inspector. The value additionally must match the name of a key as expected by the Input Manager (see Input.GetKey()'s documentation for further details) or you'll just get different errors. If you have instances that don't need to check that button, either remove that script from the object or check that `stringbutton` has a value before checking `Input.GetKey()`.
> 2 votes

# Answer
You're using the wrong pattern.

If you want to change the key, you should use `Input.GetButton`. http://unity3d.com/support/documentation/ScriptReference/Input.GetButton.html

Give the key a name, and then you can assign the key you want to use from the input manager. End users can then also assign that key from the launcher (assuming a standalone build).
> 2 votes

# Answer
Hm, you've probably solved this by now, but I'll post this here in case anybody else gets stuck with this.

You just needed your var to be:

```
var button : KeyCode;

```

This will expose a drop down for which key you want in the editor. The rest of your code is correct, so this would be right:

```
if(Input.GetKey(button) && ShieldOn != true)

```
> 2 votes

# Answer
Okay thanks for the help everybody but I think I found the solution myself, though I am not hundred percent sure of what I did to resolve it.

After playing around with it for some time, I decided to put it away and return to it later. When I returned, I cleared the entire scene, and began my scene on a fresh, making sure no other GameObjects where using the script for activating the shield.

I did a little change within the code, though I am pretty sure that didn't change the outcome:

```
var ShieldOn = false;
var stringbutton : String;
var prefab : GameObject;

function Start(){
}

function Update () {
    if(Input.GetKey(stringbutton) && ShieldOn != true)
    {
        Instantiate(prefab, Vector3 (0, 0, 0), Quaternion.identity);
        ShieldOn = true;
    }
}

```

As you can see, I didn't do any changes with the GetKey or GetButton, but it still works as intended, and now you can assign which button you wish to use through the inspector.
> 0 votes

---
Tags: unity, unityscript
---


title: How to draw a Bezier line with shaders?

text:
# Question
Title: How to draw a Bezier line with shaders?
I found a shader code to draw a filled Quadratic Bezier in

https://developer.nvidia.com/gpugems/GPUGems3/gpugems3\_ch25.html

How can I use something similar to draw a Bezier line that follows the same path?

# Answer
> 7 votes
The HLSL code in the linked article gives you a signed distance to the curve, which is used for antialiasing. Since the value is signed instead of clamped, it can be used on both sides of the curve. Absolute value of the signed distance gives the distance to the curve.

Changing

```
float alpha = 0.5 - sd;

```

to

```
float alpha = 1.0 - abs(sd);

```

gives you alpha = 1 when the pixel is exactly on the curve and alpha between \[0,1\] when the pixel is within 1 pixel radius of the curve.

You can set the thickness of the curve with:

```
float alpha = thickness - abs(sd);

```

Beware that the polygon must be large enough to cover the thick curve.

---
Tags: shaders
---


# Question
Title: Calculating a RPG character's wages based off their attributes?
I am programming a Mafia RPG where you can hire people with attributes. The attributes are the same for everyone, and are ranked from 1 to 10 (although this might change to 1 to 20)

I want to keep the attributes simple, no more than 6 skills.

The attributes could be anything, but lets say there are examples.

> Driving: 1/10
>
> Stealth: 1/10
>
> Robbery: 1/10
>
> Brains: 1/10
>
> Toughness: 1/10
>
> Greed: 1/10

Greed is meant to be a modifier, the higher the number the more greedier they are. I'd like to use this for wages

The problem I have is, I am not sure how I should calculate a goons wages.

I don't just want to randomly pick a number; its needs to be reflective of the person's attributes.

At first I thought if they all go up to 10 or 20, I could use an average, with greed being a multiplier. But this does not feel right.

The other idea I have is bands; so that if each attribute score is between X and Y the goon could get Z wages (which are then totalled up) with greed being a modifier; but this feels very dry.

Ideally, I would like the wages to be reflective of their attribute, and most importantly reflect how greedy they are but at the same time not make the wages unrealistic or spiral into very high figures.

I'm thinking the wages should be from $100 /wk up to $5,000 or $10,000 /wk but would welcome suggestions.

What would be the best way to calculate a RPG character's wages based off their attributes?

Many thanks

# Answer
> 8 votes
As Petr stated, it is difficult for us to provide you with a good wage structure when we know so little about how this needs to suit your game. However, I can provide an example formula that suits this statement:

> I'm thinking the wages should be from $100 /wk up to $5,000 or $10,000 /wk but would welcome suggestions.

Potential Wage formula: Wages\_per\_week = (Driving# + Stealth# + Robbery# + Brains# + Toughness#) * Greed# * 20

With this formula, a goon with stats of all 1's would cost $100 a week. However, if he had the max greed of 10 he would cost $1000 a week. This would make Greed act as a sort of multiplier to the total of the other stats. A goon with all 10's would cost $10,000 a week, though would cost only $1,000 a week with a greed of 1.

I don't know for sure if this is the kind of formula you're looking for. This formula can be exploited for some beneficial game mechanics. For example, you could have the player visit different locations in the city to buy randomly generated goons. Then, you could have some areas that usually spawn unskilled goons with low greed, with a rare skilled goon popping up there for a cheap price. Conversely, you could have areas that spawn expensive greedy goons that are usually quite skilled. Perhaps you could even have the player spend money to gain access to areas with better goons.

If this formula isn't quite what you wanted, I suggest you use a formula that can be best utilized to improve your gameplay mechanics. I hope that helps.

# Answer
> 2 votes
This is a question of game balance. The price of a resource should always be relative to its worth for the player.

Does your game system make generalists more important who are good at everything, or does it favor specialists who excel at just one stat?

When your game is designed towards generalism, that means all stats are important for a character, the wage should be calculated from the average of all stats.

When your game is designed towards specialization and most characters will only be used in specific roles where only one stat matters, then only the highest stat is important to determine their worth for the player. So the highest stat should be most important for estimating their monetary value. Other high stats could also make the character more expensive because they open up the strategical option for alternative uses for the character, but not as much as the highest one.

When one extremely low stat is a weakness regardless of the role the character is used for, then very weak stats could give a discount. Example: The opponent can send a bomb to anyone of your characters, which will injure him unless he has enough *Brains* to defuse it. That would mean low *Brains* are a disadvantage for every character, regardless of its role, and should give a discount.

About the role of Greed in your system: How about making it not just affect the wage, but also makes the character more susceptible to bribery from opponents? On the other hand, a high greed could also be an advantage in certain situations. It could, for example, make the character more effective at extorting money or increase its motivation when you pay him a bonus.

# Answer
> 0 votes
I guess that's the question which is really up to you to decide. There is no really "best way" to calculate something, unless we are talking about some common sense, but that is that you should have naturally as a game designer.

How wages will vary is depends on other game design aspects or goals which we don't know.

So as a conclusion: it's really up to you. Try to implement some strategy, and if you feel that it's not working as you want, you can ask again with more specific limitations and goals. As a start point you can use approach like this (pseudocode):

```
// sum of attributes points, devided by number of attributes
var level = SUM(stat) / stat_count;

var wage = pow(level, 2) * 100;

```

And you have:

> level 1: 1 * 100 = $100
>
> level 2: 2^2 * 100 = $400
>
> level 10: 10^2 * 100 = $10 000

# Answer
> 0 votes
How about take a weighted average of each stat based on how much that stat affects the value of the goon, as well as how much the stat affects the goon's ability to negotiate wages.

For example, let's say that more brains affects a goon's negotiating skill more than most stats, so we give it a 1.5 weight. Greed affects desire to ask for more, so 1.4 weight.

Stealth is handy, sure, but if you're stealthy you probably haven't spent as much time developing social skills and haggling, so we weigh it 0.8.

High robbery means you don't need the money as much, but on the other hand you're still looking for work so you obviously need someone to tell you what to do so we'll tell you to take less 0.9 modifier.

You get the idea. Anyway, take the multipliers and make a weighted average. If you want to get fancy, make them expect more after they've done a few jobs. Why not make their stats improve as they perform those roles too.

---
Tags: rpg
---


title: How to do FoV similiar to Nethack?

text:
# Question
Title: How to do FoV similiar to Nethack?
I am currently writing a little roguelike and wondered how Nethack/other games do the FoV of the player. I had a look at Nethacks source code, but since it's C it's pretty hard to read.

For people who don't know how it looks in nethack:

I couldn't find good resources on how to achieve this result.
Of note is that my maps are a little more complex with regards to shape and objects that block sight.

So how would I actually implement that? Map is just an array of ints.

I figure I should have flags on each cell saying if it's been discovered or not, but how to I simulate the FoV?

# Answer
This is a very similar question to one posted just today: Cast ray to select block in voxel game

Basically, you could implement the Bressenham's Line Algorithm and cast rays from the player's location to all the possible tiles. If the ray intersects a wall, then given tile is not visible.
> 3 votes

# Answer
I wrote an article recently on how to do field-of-view calculations. That article shows an implementation for a slightly different type of map then the one you would have in a Nethack map but the basic math should still apply.

Basically I ray-cast from the observer to via the edges of obstacles to the extents of the visible area and then calculate and area that would be obscured from the observer.

The article can be found here; http://www.codeproject.com/Articles/545808/Visual-concealment-for-games-using-Javascript

And there's an **JsFiddle** over here if you want to play around with it.
> 0 votes

---
Tags: c#, algorithm, roguelikes
---


# Question
Title: Box2D - Do these simple objects need to be in the simulation?
I would like to get input from the community regarding how best to represent *simple objects* in a Box2D based simulation.

**Some background:**
Without going into too much detail, think of a top down game with a character and some 'food'. You can *picture* PacMan™ even. Suppose I will simulate the character and the walls to be Box2D so the guy cannot leave the maze and I get collision feed back etc.

**My question:**
Should the 'food' be part of the Box2D simulation?

**My thoughts:**

*The food doesn't need to be in the simulation because..*
It doesn't move.
As soon as the character collides with the food it is removed from the game.
It should not apply any force to the guy, or anything, ever.
Nor should anything ever need to apply force to it.
It's extra computation that isn't necessary.

*The food could be in the simulation because..*
I am already using Box2D.
Box2D can handle the collision events for me.
Again, *Box2D can handle the collision events* for me; I don't really want to check for collisions myself.
Box2D should let the food 'sleep' so it won't be much extra computation, correct?

What do you guys think? Do the benefits outweigh the costs here? Are there other pros/cons I'm missing?

I look forward to getting feedback.

# Answer
> 2 votes
It all depends on the complexity of your simulation. The more objects you have the more time it will take to solve the collisions.

You can set your food filters to collide only with your player and your food bodies type to static.

Then when you collide simply disable the collision resolution and add your food objects to the "end of lived" list.

You might have many objects like that so this process will be simple to setup and repeat.

---

If your simulation starts slowing down or if you want to increase performance, all you have to do is to use a position and check the distance of all food objects with your players. This is a very small operation and will be faster than letting box2d handle it.

Your food objects can even be reduced to an array of recyclable vec2. They will take much less space in memory and in processing time.

---

It also depends on the structure of your game. If you can simply add an new system and components to your entities you might find it simpler to use your own system for the food. have a look at Component Based Entity Systems

---

Concerning javascript I would go with my own solution as the garbage collector and other mechanisms in js tend to create some inconsistent results with larger amounts of bodies.

# Answer
> 6 votes
**I think you should include food in the simulation.**

If you do you will already have efficient checks for collisions with player body which you will need to make yourself otherwise. If you do not iclude it in the simulation you might need to implement a sweep and prune algorithm yourself (or maybe some space partition or similar) that box2d will already be doing for you.

***What you need is to use sensors which detect collisions without having a "response".***

Who knows, one day you might want to let different types of physics apply to the food as well? Magnets, explosions etc might need to apply forces/impulses and then you already have a lot of the structure in place.

# Answer
> 5 votes
My thought is that you could use it - Say as a static body and assign it to an impact group that has no effect on other bodies. But like you say, box2d will do collision for you so it would make it a lot easier to implement pacman eating the food. And also like you say, it would be asleep so it wouldn't cost too much more in computation.

Why make it more difficult - you should probably use the engine as it does a lot of the heavy lifting and doing so shouldn't add too much (if anything) to the processor use.

---
Tags: box2d, jbox2d
---


title: Optimizing an XNA 2D game

text:
# Question
Title: Optimizing an XNA 2D game
Does it make sense to implement the logic to skip rendering objects outside the viewport or should I not care about it and let the Framework do it?

# Answer
> 81 votes
Culling is a performance optimisation. So it doesn't make sense to just do it just for the sake of it. You have to have a reason.

---

The GPU (not the XNA Framework) culls triangles and pixels at blindingly fast speed. Every triangle you submit must be transformed (via your vertex shader). Then it culls the ones that land off screen. Then it fills the remaining triangles, culling pixels that are off-screen. The remaining pixels are then drawn to the back buffer (via your pixel shader).

(When I say "then" - it actually does all this in a massively parallel pipeline.)

So it's very rare and unusual that you might have to cull individual triangles. To hit vertex limits you have to be drawing an absurdly large number of triangles. To hit fill-rate, texture-fetch or pixel-shading limits, you generally need to have a high depth-complexity (in which case viewport/frustum culling will not help).

---

So there's usually little or no cost to having geometry off-screen.

The cost - particularly in the context of drawing "objects" (usually 3D objects) - is actually **in submitting those objects to the GPU in the first place**. Submit too many objects and you hit your batch limit (you get a few thousand batches per frame).

I recommend reading this answer and this linked slide deck for an in depth description of batches.

Because of this, if you implement frustum culling, you can reduce the number of batches you submit to the GPU. If you're batch limited - this can get you under the limit.

---

Now - your question is about 2D XNA - so presumably you are using `SpriteBatch`. **This is a bit different.**

It is no mistake that it is called "Sprite *Batch*". What it is doing is taking the sprites you draw and doing the best it can to submit those sprites to the GPU in *as few batches as possible* by batching them together.

But SpriteBatch will be forced to start a new batch if:

* You draw more sprites than it can fit into a single batch (2048 sprites in XNA 4)
* You change texture (this is why there is a sort-by-texture option)

So culling is a suitable optimisation if you are running into the first one. If you are sending such a huge number of sprites that you end up with too many batches (you're probably using up bandwidth as well - but I'm pretty sure you'll hit the batch limit first). This will generally only happen if you have a truly enormous world - so you can generally get away with very simplistic, fast-but-inaccurate culling in this case.

Now - If you are drawing with enough texture-swaps to take you over the batch limit, *and* lots of them are actually off-screen ***and*** culling them would get you under the batch limit. Then yes - culling is an optimisation that will work.

**However** \- a better optimisation to pursue in this case is to use **texture atlases** (aka: sprite sheets). This allows you to reduce the number of texture-swaps and therefore batches - *regardless* of what is on screen or off. (This is the main reason you can specify a source rectangle for your sprites.)

---

(As always: this is advice on performance optimisation. So you should measure and understand your game's own performance, and what limits you are hitting, before spending effort on adding optimisations.)

# Answer
> 13 votes
According to the a post on the forums at MSDN, XNA framework does not do frustum culling:

> XNA framework will not do any frustum culling for you - it could not becuase it has no clue where anything will actually end up. All the transformations are done on the GPU and could be a custom shader.

http://xboxforums.create.msdn.com/forums/p/22763/121897.aspx

This post goes on to say, that if you have a lot of objects in your scene, it might be worth rolling your own.

# Answer
> 1 votes
I've been developing procedural voxel terrain engines for a few years now in XNA. In most frames, the engines are transforming literally hundreds of thousands of quads. In my profiling, i've found that frustum and occlusion culling make performance boosts.

XNA HiDef profile (not Reach) has an OcclusionQuery class that is used to perform Occlusion Culling. Occlusion Culling removes those quads from a viewport that are hidden from view by other quads.

Something else that you should consider is theading both the generation and tesselation separately.

So yes, when you approach a very large number of quads in each frame that are being transformed, you need to think carefully at how you can apply culling and threading techniques to maintain the frame rate, by reducing the traffic to the gpu shaders.

---
Tags: xna, 2d, optimization, xna-4.0
---


# Question
Title: What are the main requirements to port a game to Linux
Steam for Linux is out today and I was surprised to see many games already being sold, which made me wonder what are going to be the difficulties for all those games to be ported to Linux. I broke this though into 3 questions:

1. Is it a matter of basically make the game run in OpenGL?
2. Are there any engines that build to Linux?
3. Did Valve have any hand on the development of some framework/toolset/OpenGL to make porting easier?

# Answer
> 5 votes
Generally speaking, it depends on how the game is programmed.

In the case of Source-engine games, they used a multi-tier software architecture, and moved everything platform-specific into /tier0 in their code. When they need to port something, at least by the original engine design, they just swap out /tier0 files for platform-specific ones, and reimplement the Source engine executable for, say, Linux, re-binding things like audio (ALSA/etc. vs. DirectSound), graphics (OpenGL vs. Direct3D), video playback (who knows), window generation (X/GLUT/whatever vs. Win32/64), and I/O (XInput/whatever vs. DirectInput) to their system-specific counterparts. It was designed like that from the very beginning, though a lot of system-specific stuff has crept into higher tiers of the engine due to bad maintenance over the years. Most of what they did to "port" the Source titles to Linux was just refactoring out the Windows-specific stuff, and reimplementing the core executable.

In terms of "Are there engines that build to Linux?": Of course. With the changes made for this big release, the Source engine now runs on Linux. There are literally hundreds of others, of varying quality or availability.

As for your third question, porting happens by the developers. If you don't design your software with platform-nonspecificity in mind, then it just makes it harder. Nothing is truly impossible to port, disregarding hardware capabilities and computing speed. There's no such comprehensive "tool" for porting games to other platforms, though, since they all work differently under the hood.

# Answer
> 4 votes
I'll share our experience of porting a certain game to Linux (and Mac).

* System-specific APIs - window creation, rendering, audio, networking, input, non-trivial filesystem access etc. The other answers go into details. I'll just say that portable libraries (SFML, SDL, but also things like boost) help a lot.
* Driver bugs - happen on Linux a bit more often than Windows. Or maybe that's a thing of the past, I'm not up to date.
* Storing user data - generally in $HOME on Linux. Perhaps not an issue if you're using Steam?
* Paths to resources - UTF characters, slashes/backslashes, spaces and non-alphanumeric characters can all cause problems. You'll need to check all your paths, especially those generated programmatically.
* System fonts - your game might be using some default resources provided by the operating system; in particular, fonts could be pitfall.
* Quirks of "portable" code interoperations - I think it's pretty obvious that even though every single function you use is portable, it doesn't mean that your whole game will be using those functions in a portable way. For instance, on Mac our SFML code crashed because we tried to preload a font before creating the game window.
* Compiler differences - you might stumble into some if you were using Visual Studio for Windows. g++ and Clang can be used on both platforms, and behave similarly. Applies in a limited fashion to Java and C# code as well.
* Build-system - actually building a proper Linux binary, depending on appropriate shared libraries and providing your own where needed, can actually be a bit tiresome. Again, Steam might help you a lot here.

One more thing - if you were to develop future games which you would intend to port, I would suggest developing them on two platforms at once. Setting up a continuous integration server which run compilation + smoke tests on Linux builds every time our source code was updated (most of us worked on Windows) saved us a ton of time while working on our game.

# Answer
> 2 votes
It's not just graphics (though that might be the hardest part). Consider also audio, input devices and other OS APIs (no Windows registry, etc.)

Additionally, if you are using any third-party library, the library must also be available for Linux.

Different Linux distributions may use different versions of the same library (or provide different libraries for the same purpose). Note that, officially, Steam only runs on Ubuntu so this issue is avoided.

There are multiple engines that can run on Linux. Among the open-source ones are Irrlicht and Ogre. Other compatible engines include Unity 3D 4.0 and (now) the Source engine.

Apparently, Valve used a layer to translate Direct3D calls to OpenGL. However, it required more effort than that. I can't find any information saying what they're using for Audio, Input and I/O.

# Answer
> 1 votes
To answer your 2nd sub-question: A great engine that not only builds on Linux, Windows, OS X and other platforms, but also abstracts away from all the OS-specific build tasks is Unity 3D.

It gives you SDK which allows you to build your project for any of those platforms.

---
Tags: linux, steam, valve
---


title: Can anyone recommend an AI sandbox?

text:
# Question
Title: Can anyone recommend an AI sandbox?
I'm passionate person, who has been around AI from a long time \[1\] but never going in deep enough. Now it's time!

I've been really looking for some way to concentrate on AI coding but couldn't succeeded to find an AI environment I can focus on. I just want to use an AI sandbox environment which would let me have tools like:

* visibility information
* character controller
* able to easily define a level, with obstacles of course
* physics
* collider management
* triggers management
* don't need to be a shiny, eye candy graphical render : this is about pathfinding, tactical reasoning, etc..

I have tried :

* Unreal Dev Kit : while the new release announce is about C++ coding, this is about external tools and will be released in 2013
* Cry Engine : really interesting as AI is presents here but coding with it appears to be an hell: did I got it wrong ?
* Half Life source, C4, Torque, Dx Studio : either quite old, not very useful or costly these imply to dig in documentation (when provided) to code everything, graphics included.
* Unity 3D : the most promising platform. While you also need to create your own environment, there are lot of examples. The disadvantage is, in addition to spend time to have this env. working, is the languages choice : C#, Javascript or Boo. C# is not that hard, but this implies you'll allways have to convert papers (I love those from Lars Linden) books codes, or anything you can have in Aigamedev are most often in C++. This is extra work. I've look at "Simple Path", the very good Arong Greenberg work but no source provided and AngryAnt work.
* AI Sandbox : this seems to be exactly what as AI coder I want to use. I saw some preview but from 2009 we still don't know what it will be about precisely, will it be opensource or free (I strongly doubt), will I be able to buy it? will it really provide me tools I need to focus on AI ?

That being said, what is the best environment to be able to focus on AI coding only, is it even possible?

# Answer
The only piece of software that is right for you is the one that you write.

Don't bother searching for this among the options that the market is offering, this are production tools, not research tools, they are geared for production not for experiments, also they are subject to several license terms and optional payment options.

If I was you i would approach this in terms of languages rather than tools, use Python if you want a modern scripting language with more than decent performances without caring too much about the language internal mechanism and design, use C++ if you want ( unlikely ) and if you are ready to take care of all the design aspects and performances issues.

Considering the fact that Python is a really easy language to grasp, at least for a beginner, and considering the fact you can easily find many AI algorithms just searching online, by the time that you will get into the logic of anyone of this engines you are likely to get something up and running coded by you. And the big plus is you don't have to care about legal issues, you can use your code as you want instead of being forced to deal with more than one license and deal for everything you are going to do with this engines.

In the end just searching around you can find a really good amount of Python libraries that are surely more flexible, in every way, when compared to this engines.
> 2 votes

# Answer
An option if you're not looking for an eventual release are the Quake 3 based open source games, like OpenArena or Alien Arena. You could use any of the pre-built levels and have the other bots in the distribution as examples. I have no idea whether these really do meet your requirements or not, but I know that you can make bots in them, they are free, and they're not on your list, so I'm just tossing them out there.
> 1 votes

# Answer
Regarding Unity3D, if you're ok with working in a Windows environment, you can compile C++ examples to Dlls (try to use C++/CLI, or make a .NET wrapper to the unmanaged dll using Pinvokes) and import them in the references of the project. More on this here:

http://answers.unity3d.com/questions/8798/interop-with-other-c-assemblies.html

http://answers.unity3d.com/questions/42719/how-should-i-add-references-to-additional-mono-ass.html

http://forum.unity3d.com/threads/32267-How-to-use-custom-compiled-c-dlls-or-assemblies
> 0 votes

---
Tags: ai
---


# Question
Title: How do I debug two android devices simultaneously in Eclipse?
I have a multiplayer game which should be tested on two devices at the same time, if possible, with debugging.

Can eclipse do this? If so, how?

# Answer
Yes, you need to select each device in the **DDMS** perspective to get the **LogCat** output from the relevant device because that window is on a per device basis, but other than that there's nothing preventing you from debugging multiple instances at once.
> 6 votes

---
Tags: android, debugging
---


title: XNA Help - Slerping the KoolAid

text:
# Question
Title: XNA Help - Slerping the KoolAid
I'm having some SLERP issues and was hoping one of you guys' could help me with your expertise...

(The following code is the Update method of a component whose responsibility is to rotates it's actor towards a given target using SLERP over the course of multiple frames...)

The problem I'm having is that the following causes the actor to rotate on some arbitrary axis when it is facing any direction other than the negative Z axis (works just fine when pointed down negative Z)...

```
public override void Update(GameTime gameTime)
    {
        if (this.Status == AnimationStatus.Running)
        {
            TransformComponent transformComponent = this.Owner.GetComponent<TransformComponent>();

            Vector3 position = transformComponent.Transform.Translation;

            Vector3 forwardVector = Vector3.Normalize(transformComponent.Transform.Forward);

            float dot = (float)Math.Round(
                Vector3.Dot(
                    forwardVector,
                    Vector3.Normalize(_targetVector)),
                4);

            if (dot == 1)
            {
                this.Status = AnimationStatus.Finished;

                return;
            }

            _targetVector.Normalize();

            Vector3 rotationAxis =
                Vector3.Normalize(
                    Vector3.Cross(
                        _targetVector,
                        forwardVector));

            float rotationAngle = MathUtilities.GetSignedAngle(
                forwardVector,
                _targetVector);

            _slerpAmount += (float)gameTime.ElapsedGameTime.Milliseconds / 20000f;

            Quaternion qStart = Quaternion.CreateFromRotationMatrix(transformComponent.Transform);

            Quaternion qEnd = Quaternion.CreateFromAxisAngle(rotationAxis, rotationAngle);

            Quaternion qSlerp = Quaternion.Slerp(
                qStart,
                qStart * qEnd,
                _slerpAmount);

            Matrix rotation = Matrix.CreateFromQuaternion(qSlerp);

            rotation.Translation = position;

            PhysicsComponent physicsComponent = this.Owner.GetComponent<PhysicsComponent>();

            physicsComponent.KinematicMove(rotation);
        }
    }

```

...and if anyone's curious, here's the GetSignedAngle() method...

```
public static float GetSignedAngle(
        Vector3 a,
        Vector3 b)
    {
        a.Normalize();

        b.Normalize();

        float theta = (float)Math.Acos(
            Vector3.Dot(
                a,
                b));

        Vector3 normal = Vector3.Normalize(
            Vector3.Cross(
                b,
                a));

        Vector3 v3 = Vector3.Normalize(
            Vector3.Cross(
                a,
                normal));

        if (Vector3.Dot(
            v3,
            b) > 0)
        {
            theta *= -1;
        }

        return theta;
    }

```

....the really odd thing (and proof that SLERP isn't working as I'd expect it to), is that if I replace the code that performs the SLERP...

```
_slerpAmount += (float)gameTime.ElapsedGameTime.Milliseconds / 20000f;

            Quaternion qStart = Quaternion.CreateFromRotationMatrix(transformComponent.Transform);

            Quaternion qEnd = Quaternion.CreateFromAxisAngle(rotationAxis, rotationAngle);

            Quaternion qSlerp = Quaternion.Slerp(
                qStart,
                qStart * qEnd,
                _slerpAmount);

            Matrix rotation = Matrix.CreateFromQuaternion(qSlerp);

```

...with a regular old rotation transformation like so...

```
Matrix rotation = transformComponent.Transform *
              Matrix.CreateFromAxisAngle(
                rotationAxis, rotationAngle);

```

..then the object is rotated correctly (hoever it is instant and so I lose the rotation "animation").

If anyone has any ideas as to how this could be happening or just a suggestion on how I can make this code better please let me know.

EDIT: So I've resolved the issue but I'm not 100% sure why using matrices resolves the issue as I thought concatenating quaternions worked the same way. Here's the updated Slerpage...

Quaternion qStart = Quaternion.CreateFromRotationMatrix(transformComponent.Transform);

Quaternion qEnd = Quaternion.CreateFromRotationMatrix( transformComponent.Transform * Matrix.CreateFromAxisAngle( rotationAxis, rotationAngle));

Quaternion qSlerp = Quaternion.Slerp( qStart, qEnd, \_slerpAmount);

Matrix rotation = Matrix.CreateFromQuaternion(qSlerp);

...so as you can see I'm just converting the rotation axis and angle into a matrix first, transforming the original matrix by the rotation then creating a quaternion. But as Steve pointed out below, this is essentially the same thing I was doing with the quaternions?!?! Does anyone have any insight into this? Thanks again!

Thanks!

# Answer
> 0 votes
your axis and angle represent only the rotation change necessary to go from where you are to where you want to be.

`qStart` represents where you are.

Your `qEnd` isn't the goal orientation but only the rotation change necessary to get there.

try:

```
Quaternion qStart = Quaternion.CreateFromRotationMatrix(transformComponent.Transform);

Quaternion qChange = Quaternion.CreateFromAxisAngle(rotationAxis, rotationAngle);

Quaternion qEnd = qChange * qStart;//or your favorite method of concatenation

```

EDIT sorry, I looked again at your code and saw that you are effectively doing that in the slerp statement already. But it would be worth changing the order that you combine them. In Xna, matrices combine left to right but quaternions combine right to left.

---
Tags: xna, animation, rotation
---


# Question
Title: XNA drawing textures on random positions
I'm trying to reproduce this tutorial, but each time I try to implement it into my code, I always get a lot of errors. Now I finally managed to code something like this, the game runs, but nothing happens at all, my screen remains black without any texture drawn on it, and I just can't figure out what am I doing wrong here.
Here's my background class:

```
public class background
{
    public Vector2 position;
    public Texture2D texture;
    private List<Star> stars;
    private Random _Random;

    private int MaxX;
    private int MaxY;
    private int _Intensity;

    public background(ContentManager content, int Intensity)
    {
        this.texture = content.Load<Texture2D>("star2");
        _Intensity = Intensity;
        this.MaxX = 1280;
        this.MaxY = 720;
        stars = new List<Star>();
        _Random = new Random(DateTime.Now.Millisecond);

        for (int i = 0; i < Intensity; i++)
        {
            int StarColorR = _Random.Next(25, 100);
            int StarColorG = _Random.Next(10, 100);
            int StarColorB = _Random.Next(90, 150);
            int StarColorA = _Random.Next(10, 50);

            stars.Add(new Star(new Vector2(_Random.Next(MaxX / -2 - 1280, MaxX / 2 + 720), _Random.Next(MaxY / -2 - 1280, MaxY / 2 + 720)),
                new Color(StarColorR / 3, StarColorG / 3, StarColorB / 3, StarColorA / 3)));

        }
    }

    public void Update(GameTime gameTime)
    {

    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Begin();
        foreach (Star s in stars)
        {
            spriteBatch.Draw(texture, s.Position, s.Color);
        }
        spriteBatch.End();
    }

}

```

And the stars class:

```
class Star
{
    public Vector2 Position;
    public Color Color;
    public Star(Vector2 Position, Color Color)
    {
        this.Position = Position;
        this.Color = Color;
    }
}

```

As you can see I'm not using the exact same Star class as it is in the original code. First, I'm just trying to achieve the stars to appear on the game screen in random positions.

# Answer
> 2 votes
The code works as is when plugged in properly so...You must not have initialized background.

1. Did you initialize the Background class in your Game1 class?
2. Did you call Background's Draw method from the Game1 class?

*Bonus* 3. Your MaxX and MaxY fields tell me that your screen is 1280 X 720. Did you establish this in the Game1 class? (i.e. graphics.PreferredBackBufferWidth = 1280;)

*Secret Bonus* 4. You are telling your stars to form between -640 and 1360 for both X and Y values. Something more desirable might be:

```
 new Vector2(_Random.Next(0, MaxX), _Random.Next(0,MaxY))

```

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


title: Opengl lighting not working

text:
# Question
Title: Opengl lighting not working
I have rendered a spinning model in LWJGL. I have calculated normals and enabled lighting. Now I make a light:

```
float lightpos[] = {0, 0, 0, 0};
FloatBuffer lightposb = BufferUtils.createFloatBuffer(8);
lightposb.put(lightpos);
glLight(GL_LIGHT0, GL_POSITION, lightposb);
float light[] = {10, 10, 10, 1};
FloatBuffer lightb = BufferUtils.createFloatBuffer(8);
lightb.put(light);
glLight(GL_LIGHT0, GL_SPECULAR, lightb);
glLight(GL_LIGHT0, GL_DIFFUSE, lightb);
glLight(GL_LIGHT0, GL_AMBIENT, lightb);

```

The model, instead of being lit up, is a dark gray. Also, no color appears on the model, even though I set its color to cyan:

```
    float color[] = {0,1,1,1};
    FloatBuffer colorb = BufferUtils.createFloatBuffer(8);
    colorb.put(color);
    glMaterial(GL_FRONT, GL_AMBIENT, colorb);

```

UPDATE: Even though I have calculated normals and set them with glNormal3f, the model still appears to be shaded flat.

UPDATE: I HAVE done glEnable(GL\_LIGHTING) and glEnable(GL\_LIGHT0); that is NOT the problem.

UPDATE: I reversed the order of the light code and the model code and now the model flashes white, then goes dark grey and stays there.

# Answer
> 0 votes
I have solved the problem by adding code from this example: http://forum.codecall.net/topic/66017-simple-lwjgl-lighting/

# Answer
> 1 votes
What Sid said.

What you are missing is:

```
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

```

# Answer
> 1 votes
In order to use both color and lighting you must activate openGL color materials using:

```
glEnable(GL_COLOR_MATERIAL);

```

Hope that helps.

# Answer
> 0 votes
The model showing up as grey is a bi-product of lighting being enabled but no light actually being cast on the object aside from ambient.

Without seeing the where your object is being rendered it is possible that you are rendering within the object itself.

It is also possible that you missed enabling color materials.

Also as a general helper with lighting you might want to look through this to see if you missed anything.

---
Tags: opengl, lighting, lwjgl
---


# Question
Title: Build a Cube/Prism from other varied Cubes/Prisms
I'm wondering, are there any algorithms or theories in existence (that aren't patented/proprietary/protected) that would take a series of 3d rectangular prisms (or cubes but a cube is a prism) and stacks them in such a way as they form another cube or fit together in the best possible format?

I'm working on logistics software at work and this might be an interesting feature.

I'd also accept good articles that discuss the theory of this, if an algorithm isn't already available for me to look at and study.

# Answer
Essentially you are asking for a derivation of the **Cube Packing Problem**, which is just a special case of a **Packing Problem**. This class of problems is known to be **NP-Hard** (*non polynomial time solvable and at least as hard as the hardest NP-Complete problem*).

There are heuristics to try and solve this that aren't guaranteed to return the optimal solution. You're going to have to refer to papers though to dig deeper.

This paper may help you get started(*behind a pay wall*)

**A heuristic algorithm for cube packing with time schedule** *\- Wei Li, WenQi Huang, DongChen Jiang, XiangLong Liu*
> 2 votes

---
Tags: mathematics, algorithm, ai, geometry
---


# Question
Title: Can you suggest ways to store and track lots of objects in a turn based strategy game?
I know just enough about programming to be dangerous, so please be gentle. I've created and released few simple apps for android and do some powershell scripting at work, but that's about the extent of my programming experience. I'll be using c# and XNA if that makes a difference.

If I need to keep track of ten thousand to several hundred thousand of the same object with a handful of variables each, what's a good way to handle that in a turn based strategy game? The game will need to loop through each object on each turn to check a few things.

# Answer
> 3 votes
First create any solution you want and profile. I won't be surprised if your 100k objects will work OK using any container (unless of course you're doing mobile development for windows phone).

If it wont work, I see 2 mayor sources of optimization:

1. Do you really need to loop through every object in every turn? Can you possibly limit your loop to the objects currently on-screen? If yes, you'll benefit a lot from some spatial-aware container, i.e. the container that can quickly give you the objects within a boundary box (there're several methods how to implement such container, all have pros and cons).
2. If you do need to access that many objects every turn, your objects have ~20 variables each, each turn you only need to access ~2 variables of that 20 - you could benefit from optimizing your memory layout, see this article. It's for C++ but the idea is mostly language-agnostic: regardless on the programming language, you still have the CPU with 3 levels of on-die cache that can only access system RAM by 64 bytes blocks.

---
Tags: xna, c#, turn-based-strategy
---


# Question
Title: Whats the physics behind the doodle jump game?
I'd like to know how we can achieve the doodle jump type physics using **andengine**.

I mean the character is **not colliding** with the ground blocks when he **moves upwards** but will **collide when he came downwards** and will make a jump from their.

Can it be achieved using the collision filter? If yes how? Is it possible to enable and disable collision filter for particular bodies dynamically?

# Answer
> 6 votes
I'm not familiar with AndEngine, but the obvious general approach is to turn off collisions between the character and platforms whenever the character's vertical velocity is positive (i.e. the character is moving upwards).

If your platforms (or character) have a non-negligible thickness, you may need to deal with the situation where the character partially overlaps a platform at the top of their jump. There are (at least) two ways to handle that situation: either ignore collisions with platforms which the character already overlaps (which causes them to just fall back down if they didn't jump high enough to fully clear the platform) or detect such overlaps and move the character up until they're standing on the platform, perhaps accompanied by a special grabbing and climbing animation.

Note that, if your platforms are not always perfectly horizontal, you'll need to take some extra care. First, when the character is running uphill along a platform, you obviously don't want them to sink into it; this may require separate treatment of running/standing characters as opposed to jumping ones. Also, simply checking the vertical component of the character's velocity is not always correct for highly tilted platforms; what you really need to test is the vector dot product between the character's velocity and the platform's (upward-pointing) surface normal. You may also want to set a slope cutoff above which platforms are simply treated as walls, and cannot be jumped through.

(As an alternative to a simple cutoff, you could do something like taking the platform's upward-pointing surface normal, rotating it around the vertical axis to face the character, and then taking the dot product of the character's velocity with the rotated normal. If I didn't mess up the math, that should restrict the range of directions from which the character can pass through the platform as it gets more and more vertical, like this:
Here, the thick black freehand line is the platform, and the cones show the directions from which the character can pass through three different points on the platform.)

# Answer
> 3 votes
Ilmari Karonen's answer would suffice if you're coding the collision and physics yourself. Otherwise I assume you wanted to use AndEngine's Box2D wrapper for physics since you mentioned "collision filter".

In that case, you probably want to refer to this tutorial on one side platforms. General idea is to use BeginContact and EndContact callbacks to disable/enable contact based on whether object is moving up or down. It's not exactly as simple as it sounds due to some quirks in Box2D.

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


# Question
Title: Does it make sense to use Lua scripting in a game developed in Python?
Well for C++ written games using Lua scripts for easy changing ai, quets etc is very reasonable and it's common. However now I'm going to write a game in pure python and I don't know if I should use Lua. Python itself is very high level script language. However, there are things to consider why I could use lua scripts:

1. Lua is commonly used for game scripting and other people who will work with me know Lua and don't know python
2. Python module to embed lua code into python uses very fast JIT compiler so the lua code actually would be much faster than python code (big plus for AI)
3. It would separate the game engine itself (Python) from the scripted logic (Lua)

Do python games use Lua? Is it a resonable thing or I should just stick to pure python? I need some advice because I have no idea.

# Answer
> Do python games use Lua?

Generally? No.

> Is it a resonable thing or I should just stick to pure python?

Define "reasonable"?

Python has been used in many game development scenarios. While Lua may be well known among some game mod circles (like WoW GUIs, Garry's Mod, and so forth), Python was the language of choice for Civilization IV modding. So it's not like the language is unknown among game modders in general.

If the people working with you don't know Lua, then a larger question is this: why aren't you writing the engine in *Lua* to begin with? I mean, if Lua code is going to be faster than Python code due to JIT, why would you not want the entire codebase to be in Lua?

It's strange that you've gather together this group of Lua programmers to make a game... in Python.

If you're doing it that way because Python has access to modules that Lua doesn't, then I would suggest using your Python-\>Lua bridge to give Lua access to those modules and let your Lua scripts do most of the heavy lifting. You'll be able to use the rest of your team as more than just game scripters. And Lua already has plenty of mechanisms for encapsulating scripts, so there's no trouble with sandboxing AIs from the rest of the engine.

That is, write a thin wrapper around your needed Python modules, expose it to Lua, and transfer most of the engine into Lua script. From there, use your Lua scripts to execute potentially user-scripts as needed.

However, if you don't want to do that (presumably because *you* don't want to code in Lua), then you can stick with your original plan. There's nothing wrong with it per-se; it's just odd to have a script-based engine call a faster script-based scripting system. Generally speaking, it's the core engine stuff that needs performance the most; the AI scripts don't need it as much.
> 7 votes

# Answer
I think it makes perfect sense. If Lua can benefit from (PyPy?) python JIT, even better. Lua is much easier for beginners, which means more community mods. It also makes it very easy to separate it from main code, as you said.

I see no reason for not doing it.
> 1 votes

---
Tags: architecture, python, scripting, lua
---


title: How compatible is OpenAL?

text:
# Question
Title: How compatible is OpenAL?
I'm making a game that needs sounds and LWJGL uses OpenAL.

I was wondering out of 1.0, 1.1, C 1.0 and C 1.1 which would be the best to pick? I don't know what the C is but it's there in LWJGL :).

My point is what is the difference between these versions? And also how compatible are both are these as far as system requirements go?

# Answer
Even 1.1 is from 2008. So they are all pretty outdated. You should use the latest though. The wiki page says there's a version 2.0.7.0 from 3 years ago that's even newer that what you mentioned. You can also read about the supported platforms there and maybe figure a way to make the 2.0 version work with LWJGL.
> 2 votes

---
Tags: java, lwjgl, sound, openal
---


# Question
Title: How should I manage the AI using lua scripts?
My game is in C++ and I want to make AI being managed by lua scripts, but I have no idea how should the scripts look like and the integration in C++.

Should the script be like

```
   if (whatever_happening) do_something
   if (....) .....
   etc

```

And in every frame in C++ I should call for every enemy:

```
   foreach(enemy)
   enemy.handleAi(luascript.file)

```

Or it is wrong and I should handle it different?

# Answer
A good approach is to design the behaviors in C++, and put the desicion parts in Lua scripts. The benefit is you can modify AI decisions without compiling your game; and with some good design, you may be able to modify AI desicions at runtime (opening up a debug window in game and change the variables to affect the decisions).

A behavior can be related to the position, the animations, and other status changing values. For example: Jump. This behavior changes the position, the velocity, and the animation of the AI, and also change the "IsInAir" and "IsJumping" flag.

A decision can be a branch of several behaviors. Here is the place you can use a state machine or behavior tree to implement the decision making system.
> 8 votes

# Answer
This is a pretty general question with many different approaches. I'll just mention two major differences in coding AI logic into Lua.

As a prerequisite you will still need to expose C/C++ low level functions so that lua can make function calls to affect game systems or query for game information.

Movement, pathfinding, inventory, etc, etc

## Script as low level decision logic

Basically you can use script for the very core decisions. How an AI may select a target, or how an AI chooses which weapon to use, etc. Think of lua functions or individual scripts as very small amounts of AI behavior.

This would mean C/C++ would call a function on the lua side, passing in values where the decision logic comes up with the result and passes the result back to the caller.

This type of approach works very well when the overall structure of what makes up an AI is in code and can be constructed either through hard coding or from a data source.

Structures like **Finite State Machines** with states in lua, or **Behavior Trees** where individual tree nodes are coded in lua fit perfectly in this model.

## Script as high level decision logic

A completely different approach is to allow the lua script to completely control the AI. In this sense you could have a **"think"** lua function that is called every tick which represents the AI logic. The **"think"** function would need to be ticked either per frame or whenever is appropriate for the game you're making.

For example if lua is controlling animation playback it would probably need to be ticked per frame to have control over animation handling.

This approach isn't structured except for the known function that C/C++ calls into for the specific AI. All AI structure and logic can be written in any form you want in script with the AI storing any persistent knowledge as global variables in lua.

---

*These are just two very different high level approaches to using scripting. Of course not taking into consideration memory or performance of the AI.*
> 4 votes

# Answer
It depends. If `determining_happening` is expensive and well-defined, it may be beneficial to keep that calculation in C++. E.g. in C++

```
for (auto& enemy : enemies) {
  if enemy.collide(player) enemy.callLua(collisionScript)
}

```
> 1 votes

---
Tags: c++, ai, lua
---


# Question
Title: Implementing a multilanguage AI contest platform
This is a followup to this question. To sum: I'm implementing an AI contest site, where each user may submit several AI implementations for different games. Think about Google AI Challenge but instead of just having a big event once a year, I would like it more on a league fashion, with all virtual players playing with each other every some close period of time.

I want to support as many programming languages as possible. I've seen that contest sites (like codeforces) ask you to submit a source code and interact through **stdin** and **stdout**. The first question is: what is the best way of supporting multiple languages?

As I see it, I can either ask people to upload some binary/script, and interact either through **stdin**/**stdout**, or sockets, or the file system; or ask people to submit source code, and wrap it with whatever is necessary for the interaction. I would like to skip the need to compile the code by myself (in the server, I mean), but I am willing to do it if its the "best" choice. I need to comunicate virtual players with each other, or even better, with some intermediary arbiter.

The second question is regarding security. If I'm going to be running user code in my server, I want to ensure strict security conditions, like no file system access, no networking, etc. Otherwise it would be a safe heaven for hackers.

I will be implementing the engine/arbiter in .NET. I would like to support at least C#, C++, Java and Python for the user's implementations. I'm willing to write interfaces for each of these languages to simplify the user interaction with the system.

Thanks in advance.

# Answer
> 2 votes
I think the socket approach is the most flexible. I suggest you have a close look at the arimaa bot interface. It seems to me those guys faced roughly the same problem you have.

# Answer
> 0 votes
There is simple and free tool that helps creating satellite assemblies to compiled applications.

http://tbs-apps.com/lsacreator/

---
Tags: c#, ai, multiplayer, .net
---


# Question
Title: When should I load assets for optimal performance?
I'm writing a game using LWJGL and Java, and was wondering if there were best practices for when to load resources.

I have seen examples that load all resources when initializing the game (XNA), ones that load the new resources needed for each level while referencing the already loaded assets again.

# Answer
It depends on how many resources you have and how they perform with your game. I recommend to start with a simple solution, which means loading all the assets at the beginning, so you can use them anytime. Once the game performs slowly because of the memory problems consider writing some kind of manager, which will load assets in a smarter way.

What I recommend is to ready all your assets through a "dummy" manager, which will at the beginning just load all the resources and provide them. But your code will treat it as a black box providing assets. If you need to make changes, then you just change the manager and not game code. Once the game gets slower, you can add simple tricks to your manager. For example, it can watch what assets are requested per level and pre-load them for this level and drop those that are not used, which would be the first optimization I would do in your case.
> 4 votes

---
Tags: java, performance, lwjgl, asset-management
---


title: Plotting entities on a radar

text:
# Question
Title: Plotting entities on a radar
I'm trying to build a radar system like the one in the original X-Wing games. The way it works is that there are two circular radar systems, one for behind the ship, and one for infront.

So, I've written a class to represent the radar, it has a vector representing the direction the radar is facing, and a 3D position of where the radar is. Both of these things will change in realtime as the ship moves and so the radar will need updating each frame.

Now I'm trying to figure out how to transform the position of another ship onto the radar. What I need is a final 2D X/Y coordinate between -1,-1 and 1, 1 for plotting on the 2D radar screen.

Given two vectors (the direction of the ship - which the radar is facing - and the direction to the ship we are plotting), how can I calculate a 2D X-Y position on the radar? Obviously I also have access to the up and right vectors of the ship too.

My instinct says that this should be relatively straightforward, but my math skills suck.

# Answer
> 1 votes
As is typical, about 10 minutes after posting this question I realized that "planes" are actually a thing and this is pretty easy...

To find the position on the X axis, I can do this:

1. Project the ship position onto the XZ plane
2. Get the direction to the ship (e.g. (ship\_pos - radar\_pos).normalize())
3. Calculate the angle between the radar's forward direction and this direction
4. X = (angle\_in\_degrees / 90.0) * plane\_classification (where plane\_classification is -1 if the point is to the left of the YZ plane, 0 if it's on the plane, and 1 if it's to the right of it)

You can then work out the Y-axis position by reversing the planes in steps 1 and 4.

# Answer
> 3 votes
Well, There is probably many ways to do this. But this is how i would do it:

1 : Get the dot product of the ship. this way we can determin if the ship is actualy infront of the player. also saving this value beacuse we are going to transform it into radians.

2 : if the ship is in front of the player, get the length of the vector. ( from player to ship )

3 : now just rotate an at vector around the up vector with the dot radians. normalize that vector and scale it by the distance. You will need to just determin if it´s on the left or right side.

So that in code would be something like this:

```
float3 v1 = playerPos - shipPos;
float dotRad = dot(normalize(v1),playerAt);
float angel = acos(dotRad);
float radians = angel * ( 180.0f / 3.14f );
float length2 = dot(v1,v1);
float3 rotVec = RotateVector( playerCopyAt, playerUp, radians );
rotVec = normalize( rotVec ) * sqrt( length2 );

rotVec.x / radarWidth;
rotVec.y / radarHeight;
rotVec.xy * 2.0f - 1.0f

```

Some thing like that, just wrote this from my mind so i havent actualy tested the code, but the idea will probably do.

otherwise i think this side will help you pretty well: http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm

---
Tags: 3d, mathematics
---


# Question
Title: Integer vs String for "type" data in data-driven games
I've been developing a few mobile games, in which those games fetch their data from a server-database.

I'm used to storing "type" values as an integer identifier, and an enum in the client to identify the data coming from the server.

I'm under the impression that games like MMOs or PC games that get patches model their data to identify "types" as integers.

As an example: On the database table:

Monsters Table: MonsterId(int), Name(string), MonsterType(int)

On the client-sided code:

```
typedef enum {
    MonsterTypeGround = 1,
    MonsterTypeAquatic = 2,
    MonsterTypeAmphibious = 3,
    MonsterTypeAerial = 4
}MonsterType;

```

Is there an objectively correct answer on what to use (int vs string) for these types of data?

Do I have the correct impression that MMO's usually use integers for this, or it highly depends on the developers as well?

# Answer
> 5 votes
It depends on the developer. But I'd say ints are more common.

It's generally far more efficient to use an int for both network communication and storage. You need to be careful to ensure int IDs are "stable" - that you don't insert or remove an enum value, except adding news ones at the end of the list. Otherwise your data breaks.

For data source, using strings is fine and has value. I'd just generally expect a tool to convert any XML/text data files into efficient binary data during build. It's easier to inspect and debug text file. That does *not* means that text/strings are good for editing; always put effort into good tools for game/level designers. Developers, not designers/artists, are the only ones who should ever have to open any data files for raw inspection/editing.

Also, beware encoding too muxh in code-specified ints. That defeats the purpose of data-driven design. For things like your simple example, if all the monster type affects is movement and combat, you can easily make that data-driven. You van use flags to denote the surface/tile types a monster can move on and more data to define those surface types (e.g. a mountain is "outdoor large impassable, value 3" and all flying monsters have bit 3 set for movement (or a list of string identifiers, of course). Same goes for combat immunities and the like. Only put in code what *needs* to be controlled by game logic.

# Answer
> 0 votes
You can use whatever sort of data can be correctly interpreted by the receiving end. Ideally you use the format that strikes a good balance between being small in size (to reduce bandwidth, memory use, etc) and being easy to use (so your code isn't overcomplicated by it).

If you know that both sides have a list of all the possible values, then you can just send a number and they can look up the correct value based on that number.

But if there is a near-infinite number of different values that could be held, it's not feasible to put them in a list and send a number to look them up with. There, you might send a string - names are an example of this.

---
Tags: mmo, databases, data-driven
---


# Question
Title: How precise should timers in update loops be?
What is the suggestion of "enough precision" in a timer for a fixed game update loop? Currently I'm testing with this code, but it sometimes misses 1-2 updates @ 50hz. While at 30hz it seems to work perfect. 60hz again is even worse than 50hz. Is this because I have too low resolution on the timer? Is there something I'm missing?

# Answer
> 3 votes
There is a wrong assumption behind this question which leads to a solution that is not well prepared for real world requirements.

**Don't ever count on a consistently stable frame time X, unless you are on a Real Time Operating System**. The usual gaming platforms don't fall under this category. On all other systems the frame time is not deterministic (even if your update loop were deterministic, which it isn't either), it depends on variables that the game cannot control, the OS scheduler for one thing, other processes can kick in, energy saving settings and lots of other things.

Having that out of our way, the first and most important conclusion is: **The game has to deal with a varying frame time**. It might be 16 ms in one frame, and 27 ms in the next. The update loop simply has to deal with it. That rules out the fixed `dt` value in your code example.

So what is the solution?

Basically there is only one relyable and reasonable source of game time, the refresh rate of the graphics device. It does not make sense to update the game state with a higher frequency than the graphics card can render it. In fact that would introduce new problems without any reasonable gain.

However, it makes sense to update some subsystems with a higher frequency, as a physics engine for instance needs a stable simulation time. Most physics engines handle this theirselves by adding sub-steps/sub-loops, for instances bullets btDynamicsWorld::stepSimulation(btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep) needs only be called once in your game loop and handles the necessary substeps itsself. The first parameter `timeStep` is the real dt since the last frame. The third parameter `fixedTimeStep` is the fixed simulation time, so it will step the simulation by adding substeps of `fixedTimeStep` until it hits the real frame time (`timeStep`) and even interpolates the physics state to the exact frame time. So that dirty work is off your shoulder unless you implement your own physics system.

So at the end it is much simpler and does not need any timers at all, except vsync to wait for the graphics cards swapping. Other than that, just measure the time since the last swap, that is the frame time to be passed to the game's subsystems.

# Answer
> 2 votes
The precision should be precise enough to meet your requirements. Your requirements may allow for some missed updates now and then. Your requirements may allow only high-end hardware.

It's up to you to find the balance between resource usage and precision. The precision will vary from genre to another, from one game to game and even from one game mode to the next.

In this case, if you don't have any other problems with setting the precision at 30Hz, then set it at 30Hz.

# Answer
> 2 votes
I see several issues with your code:

* First, your update loop never sleeps, it just busy-waits until enough time has passed. While this *shouldn't* actually cause any problems in your example (other than possibly overheating your CPU), it would be a problem if you wanted to do anything useful in some other thread at the same time. Also, it's just plain silly. A much better solution is to calculate the time at which the next update should happen and, if that time has not yet passed, sleep until it has.
* Second, you seem to be relying on `Thread.Sleep()` being accurate, and on `Thread.Abort()` immediately stopping the thread no matter what. These are both bad assumptions. Instead, if you want the thread to stop exactly after a given amount of time, let the thread itself figure out when to do that (since it's already timing itself) and call `Thread.Join()` to wait until the thread exits. (In fact, for this simple example, you don't really need to spawn a separate thread at all, since all your main thread does is sleep anyway.)
* Also, you're storing your timestep as a whole number of millisecond. This is a problem because you cannot, for example, accurately represent 1/60 of a second that way. Indeed, with integer arithmetic, `1000 / 60 = 16`, while `1000 / 16 = 62`, so, even if it worked otherwise exactly as intended, your update loop would run 62 times per second, not 60.

A simple solution here is to store the timestep (and the target time for the next update) as a floating point value. That's still not exact, but it's *much* more accurate than an integer value. Alternatively, you don't really need to store the timestep at all if you simply calculate the target time by multiplying the number of updates executed so far by 1000 and dividing it by the desired update frequency per second.

The following code snippets demonstrate these two approaches. This one uses a floating-point timestep (demo on ideone):

```
double dt = 1000.0 / 60;
double targetTime = 0;
int i = 1;

while (targetTime + dt/2 < 1000)
{
    long currentTime = sw.ElapsedMilliseconds;
    if (currentTime < targetTime)
    {
        Thread.Sleep((int) (targetTime - currentTime));
    }
    else if (currentTime > targetTime + 100)
    {
        targetTime = currentTime;  // we're too late, give up
    }

    Console.WriteLine("Update " + i + " at t=" + sw.ElapsedMilliseconds + " (target=" + targetTime + ")");
    i++;
    targetTime += dt;
}

```

while this one recalculates the target time directly from the desired frequency and the number of updates using integer arithmetic (demo on ideone):

```
int freq = 60;
int maxSlip = 100;  // give up if we're more than 0.1s late

for (int i = 0; i < 1*freq; i++)
{
    long currentTime = sw.ElapsedMilliseconds;
    long targetTime = (1000 * i) / freq;
    if (currentTime < targetTime)
    {
        Thread.Sleep((int)(targetTime - currentTime));
    }
    else if (currentTime > targetTime + maxSlip)
    {
        i = (int)( (double)currentTime / freq + 0.5 );  // we're too late, give up
    }

    Console.WriteLine("Update " + i + " at t=" + sw.ElapsedMilliseconds + " (target=" + targetTime + ")");
}

```

One detail worth pointing out is the `+ dt/2` in the terminating condition of the first snippet, which ensures that we stop as soon as the target time is *approximately* 1000 (or as close to it as we can get using increments of `dt`), even if floating point roundoff might cause it to actually be something like 999.99999999.

Also note that neither of the demo programs actually spawns a separate thread. If you do want to do that (e.g. to carry out something else while the loop runs), you can just replace the direct call to `FixedLoop()` with:

```
Thread t = new Thread(FixedLoop);
t.Start();
t.Join();  // wait for the thread to end

```

---
Tags: game-loop, fixed-timestep, vsync
---


# Question
Title: Multiplayer game communication framework for mac/ios
(Cross post from stackoverflow)

I am creating a multiplayer 2D game for Mac and iOS devices. I'll be using cocso2d for graphics/game engine, however I am largely blank on what to use for multiplayer communication. Please note that I cannot use central severs e.g. SmartFox, RedDwarf, etc since I want the players to "host" games for others and be able to play it on their LAN, VPN or my own servers.

Any pointers? I checked lidgren but it's for .NET only and hence not an option for me.

EDIT: just in case it wasn't clear, the messaging has to be real time hence it's probably going to be over UDP

# Answer
I've used ReplicaNet http://www.replicanet.com with three different iOS devices connected to the same game. You need to know how to have bindings to C++ but the source compiled without needing many changes for what I wanted. It seems to be the best performing library for mobile devices out there at the moment. It is also well worth talking to the ReplicaNet guys about an indie license if you're short of cash.
> 1 votes

# Answer
You don't want to be hosting any games from an iOS device, so you are probably looking for something to run on OSX.

I'm not sure how lidgren works or if it is Mono compatible, but the Mono project has done an excellent job of bringing .NET to OSX and Linux. I highly recommend you look into it, especially if your library of choice is .NET.

The server architecture and platform don't dictate what the client must use, so having a Mono/.NET lidgren server and an iOS (Objective-C) client should be just fine; however, there is MonoTouch which brings .NET and C# to iOS, so you *could* use that if you felt like it.
> 0 votes

# Answer
You can also use check out AppWarp for building multiplayer games using MonoTouch/MonoDroid. It has a server but doesn't require you to host or deploy. Its on the cloud. Here is a pointer to a blog post describing how to get started on it. http://blogs.shephertz.com/2013/02/15/build-cross-platform-realtime-games-and-apps-using-mono/
> 0 votes

---
Tags: architecture, multiplayer, networking, ios
---


title: World-map navigation and path-finding

text:
# Question
Title: World-map navigation and path-finding
I'm designing a 2d RPG where you navigate on a overhead map. The terrain is mostly open with big parts of inaccessible terrain such as mountains and rivers. The player navigates short distances at a time by clicking/tapping where to go on the map.

I'm looking for a pathfinding algorithm for the navigation. Avoiding obstacles isn't the most important issue. I can see the game stopping the player when hitting an obstacle and leave it to the player to take another path. Although having it would be a bonus, e.g. when crossing bridges etc. it would be easier for the player if he just has to click on the other side and don't have to worry about bumping into walls.

The more important issue is the roads on the map, and I can see it being rather tedious for the player to constantly have to correct the path for staying on the road. As there are incentives to stay on the road such as walking faster and encountering less enemies - I want to make it easy for the player to stay on the roads. So navigation should gravitate to using roads, before going off-road. I also think the game will be more aesthetically pleasing if the navigation gravitates to using roads on the map.

Pathfinding is a new topic for me so I'm unsure where to begin. What is a good way to represent the terrain and roads? Should I use waypoints for the roads and what is a good algorithm for finding a good path that gravitates to using roads?

Thanks

# Answer
> 5 votes
I would recommend to start reading about A\* algorithm. It's one of the most commonly used pathfinding algorithms. For example, Wikipedia has a pretty good article on the topic. Here is an animated gif demonstrating the process:

---
Tags: game-design, path-finding
---


# Question
Title: Is it better to import photoshop files or illustrator files into flash?
I was wondering what would be better to import into flash for when I animate. My intention is to animate my characters and objects and then export as a png sequence and make a sprite sheet then take into cocos2d.

Illustrator like flash is vector based but I will have to turn it into pixels anyway to play on a screen.

So I was just wondering what would be better or easier or does it not matter either way?

Additional information: I have all the adobe software above at CS5. I am slightly more comfortable working in Illustrator. My intention was to make the graphics in illustrator so that I could easily resize my graphics for multiple devices, sometimes I may have to rasterize my illustrator file and add final touches in photoshop.

As I'm sure you can tell i'm pretty new to flash and iphone development so any help or advice would be greatly appreciated, sorry for all the questions.

# Answer
If you are comfortable with illustrator then i would recommend attempting to use the drawing tools within flash - they are less refined but if you get used to them it will become easier to then animate in flash

Flash is also vector based and you should be able to copy and paste paths/shapes etc.. from illustrator and back to flash

If you need to do any Photoshop tweaks to the animation I would say it would be easier to export the animation as pngs from flash then edit the pngs - if it's the same process per frame then make an action to make your life easier
> 0 votes

# Answer
It doesn't matter all that much. Since you're feeling more comfortable using Illustrator, I'd chose Illustrator over Photoshop.

If you use Illustrator, you're pretty much resolution independent (unless you use pixel-graphics within Illustrator). This has the benefit, that you can scale/deform your artwork without quality-loss up to the moment where you export it into a sprite-sheet.

I think you should chose the tools based on two factors:

* Will this tool allow me to create the art-style I'm aiming for (eg. using Illustrator for retro-style pixel-art would be a bad choice)
* Do I know the tool well, can I be productive enough using it. It doesn't make sense to use a tool that hinders your productivity too much (unless you absolutely want to learn to use it for future projects)
> 0 votes

---
Tags: 2d, graphics, iphone, flash
---


# Question
Title: Networked Physics - Interpolation Causes Physics Engine to Explode
A major issue I am encountering right now is that my physics engine (BEPU) and my network interpolation are conflicting with each other.

The player is a physics object, and so the physics engine updates it every update on the client. When the client receives an authoritative position from the server, it replays the player's commands since the position was sent, and sets a "serverPos" variable in the player controller to that value.

Unfortunately, if a player should be on the other side of a bump in the terrain, the interpolation code will move the player into the terrain, which will cause loop of the player getting pushed back, the interpolation algorithm trying to push the player back in, and so forth until the engine literally explodes and gives me an NaN error.

My interpolation algorithm is extremely simple; each update, I keep track of how far the player has moved, add that to the interpolation target, and subtract away the distance interpolated from the last frame:

```
Vector3 serverPos;
Vector3 interpolationDistance;

void interpolate()
{
   serverPos += Position - lastPosition - interpolationDistance; // interpolated distance should not be factored into the target, as it will cause an infinite chain

   Vector3 preInterp = Position;

   Position = Vector3.Smoothstep(Position, serverPos, 0.3f);

   interpolationDistance = Position - preInterp;
}

```

Any advice on how to deal with this is greatly appreciated.

# Answer
The problem is who owns the master copy of the data. I saw a similar problem on trial versions of Halo.

Your server updates the master position, and your interpolator believes it. The problem is your collider believes it owns the master copy of the data. That should be updated by the server as well as the interpolator, but when a master copy comes across the wire you should respect the server's version of events.
> 1 votes

---
Tags: xna, collision-detection, physics, networking, interpolation
---


# Question
Title: Why does glGetString returns a NULL string
I am trying my hands at GLFW library. I have written a basic program to get OpenGL renderer and vendor string. Here is the code

```
 #include <GL/glew.h>
#include <GL/glfw.h>
#include <cstdio>
#include <cstdlib>
#include <string>

using namespace std;

void shutDown(int returnCode) {
    printf("There was an error in running the code with error %d\n",returnCode);
    GLenum res = glGetError();
    const GLubyte *errString = gluErrorString(res);
    printf("Error is %s\n", errString);
    glfwTerminate();
    exit(returnCode);
}

int main() {
    // start GL context and O/S window using GLFW helper library
    if (glfwInit() != GL_TRUE)
        shutDown(1);
    if (glfwOpenWindow(0, 0, 0, 0, 0, 0, 0, 0, GLFW_WINDOW) != GL_TRUE)
        shutDown(2);
    // start GLEW extension handler
    glewInit();

    // get version info
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf("Renderer: %s\n", renderer);
    printf("OpenGL version supported %s\n", version);

    // close GL context and any other GLFW resources
    glfwTerminate();
    return 0;
}

```

I googled this error and found out that we have to initialize the OpenGL context before calling `glGetString()`. Although I have initialized OpenGL context using `glfwInit()` but still the function returns a NULL string. Any ideas?

**Edit** I have updated the code with error checking mechanisms. This code on running outputs the following

```
There was an error in running the code with error 2
Error is no error

```

# Answer
> 4 votes
`glfwInit()` isn't actually creating a valid context. `glfwOpenWindow` should do that, but I suspect you're passing invalid parameters. You should check the return of `glfwOpenWindow` (and `glfwInit()`) to ensure that it's successfully creating a context. This thread also mentions creating a context manually, supposedly without window creation.

---
Tags: opengl, glfw
---


title: LWJGL MouseY Coordinates are flipped

text:
# Question
Title: LWJGL MouseY Coordinates are flipped
So I'm very new to using OpenGL and LWJGL, although I am proficient in Java itself. One of the first things I read in the documentation of the Display class was that it maps the origin to the bottom left as opposed to how most other programs map it to the top left.

I was ready to take this into account until I discovered that the OpenGL libraries in LWJGL still map everything to the top left. It would also appear that the two spaces (window coordinates and game/OpenGL space) do not correspond to each other. ie. if I set a quads position to 10 x 10 via a mouse click in the lower left corner of the screen, it will move to what looks more like (windowWidth - 100, windowHeight - 100) or (100,100) using a standard top left origin.

I am attempting to write a 2D game using quads to draw my sprites, and I was wondering if there was a way to get the screen and game space to correspond.

Any help would be greatly appreciated, Thanks! Peter

Just in case it helps, here's how I'm creating a window and initializing OpenGL Display

```
Display.setResizable(true);
Display.setDisplayMode(new DisplayMode(WIDTH,HEIGHT));
Display.setVSyncEnabled(VSYNC);
Display.setFullscreen(FULLSCREEN);

Display.create();

```

OpenGL

```
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,Display.getWidth(),Display.getHeight(),0,1,-1);

    glMatrixMode(GL_MODELVIEW);

    glClearColor(0,0,0,1);

    glDisable(GL_DEPTH_TEST);

    glEnable(GL_BLEND);
    glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

```

# Answer
I think your problem may lie here:

```
glOrtho(0,Display.getWidth(),Display.getHeight(),0,1,-1);

```

In OpenGL, coordinates go from -1 on the left of the viewport to 1 on the right, and -1 on the bottom to 1 on the top, with (0,0) in the center of the screen (and the Z axis going back to front). This is the same regardless of the shape of your viewport, and it is completely up to you to make some sense of these coordinates.

So usually you want to change this coordinate system to something that makes more sense. That is what the projection matrix is usually used for. One way to change your coordinate system is to use an orthographic projection matrix. `glOrtho()` offers a way to create one.

The first two parameters define where the left and right borders should go to. In your case, *left* is set to 0, and *right* is set to the display width (make sure this is what you want. If you're in a windowed application, you want to set this to the client area of your window, not the entire display width).

The next two parameters define where the bottom and top borders should go to. In your case, *bottom* is set to the display height, and *top* is set to 0. This effectively makes your origin to be set at the top left of the screen. If you want your origin to be set at the bottom left, you can invert these two parameters.

The final two parameters define where the near and far borders should go to. This is the same as before, but with the Z-axis.

Here's a nice tutorial that explains the coordinate systems in OpenGL.
> 5 votes

# Answer
Panda Pajama said it all, if you want to make it so you are using coords from the top down and not the bottom up change glOrtho to:

```
glOrtho(0, Display.getWidth(), Display.getHeight(), 0, -1, 1);

```

and to sort the mouse Y pos out you just do:

```
mousey = Display.getHeight() - Mouse.getY();

```

You should defo read up on all the gl functions you have in your post there so you have a clear picture of whats going on when you start drawing things to the screen, it will save you alot of trouble later on.
> 1 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: I would like to build a 2D multiplayer game. Do I need a game engine or not?
I plan to build a very basic 2D game in html5: it's purely a map divided in 2D equal square tiles. A player can click on a tile to see the message "behind" a tile. Once open, other players can't open it anymore.

So there are no teams, no physics, no complexe player moves just the need to be massively multiplayer and cross platform (it needs to be playable on computer but also mobile so touch is needed for example).

I have read this nice comparison between game engines http://buildnewgames.com/game-engine-comparison/ but I wonder: do I really need a game engine or can i make without a game engine, just using javascript and all the necessary technologies(canvas, node, socket.io...) ? In what does it make my work easier/faster ?

thanks for your help, Mathieu

# Answer
You never *need* an engine. An engine is just the parts of a game that are not specific to any one game and can be reused for multiple games.

Note however that a game engine provides several pieces of game-related functionality that you will not get from generic application development libraries such as socket.io, node, etc. For this reason it's often wise to use an engine, or at least a game-specific library or two. (An engine is really just a very comprehensive library for game development.)

In your case your game is so simple that it's hard to see that you'll need much game specific code and a game engine may be overkill for your purposes. But for the general case of "2D multiplayer game" it is almost always wise to start with an engine or game libraries.
> 1 votes

# Answer
If your goal is a finished product, rather than a learning exercise, don't reinvent the wheel.

If somebody's already written a library that does what you need (and is making it available under a license you can work with), use the library. Games, the better ones at least, are among the most sophisticated software there is. Moreover, if you don't use an engine, you often spend too much time writing your own "engine" and not enough time making the "game" part of your game.

HAVING SAID THAT, the exception would be when you're making something very simple. What you're describing, if I understand you correctly, sounds extremely simple. In fact, it sounds more like a website than a piece of software. (Have you considered making this as a simple website? Boom. Massively-multiplayer requirement solved.)

Game engines have a steep learning curve. Often the first couple of weeks with a new engine aren't really spent "programming," they're spent just figuring out how the engine organizes things. This can be frustrating. Sometimes you'll find yourself struggling to accomplish something with the game engine that would be easy if the engine weren't in your way. But still, for most games, the benefit of working with an engine outweighs the downside of spending a few weeks figuring it out.
> 0 votes

---
Tags: multiplayer, html5
---