# Question
Title: What platform is best for Android and iPhone development?
I've been developing non-mobile apps for linux; mainly stuff like interpreters, compilers, database engines and business apps.

I've been told that if I wanted to learn how to develop iPhone/iPad applications, I should buy a Mac since Apple has all it's development tools for iPhone/iPad on Mac.

Now, what about Android phones / tablets? Are the development tools better on Mac or PC?

I need to buy a new laptop, and I would like to factor in mobile development in my choice of PC or Mac.

# Answer
> 10 votes
For iPhone / iPad development, you are going to need a Mac. See Tetrad's comment for relevant "Can I use a Hackintosh" discussion.

For android development the development tool is the same, it is the Eclipse IDE, and it is available across all three primary OS choices.

You can find the relevant information about it here: http://developer.android.com/sdk/index.html

and you will find eclipse here: http://www.eclipse.org/

--

Personally, I haven't noticed any major operating differences using Eclipse between any of my systems (Linux Laptop, Windows Desktop, Mac Laptop) outside of menus being placed in a few different places on the Mac.

# Answer
> 10 votes
If you really want to have your options open, just buy a Mac. You could always bootcamp it into Windows if you really need to be on the PC side of things. That way you get a proper native iPhone dev environment, and a really good Android environment (since, like was already said, it's very Unix-like). And the option to switch over later if you really need to.

Of course this costs the most amount of money.

# Answer
> 4 votes
If you intend to create games, which is a fair assumption IMO given this website's main theme ;) , there are also multiplatform engines both for android and iphone, like unity3d, although you still need a Mac because Xcode is used in the compilation and code signing.

So, the easy way to develop in both plattforms is buying a mac, cause the Android SDK, and specially the Android NDK (Native Development Kit) fits an unix-like environment like Mac very well

# Answer
> 3 votes
While it's true that Apples SDK only support Macs for iphone-development, i know of atleast one alternative that works on Windows. Airplay SDK: http://www.airplaysdk.com/

It's a cross plattform SDK and that comes with it's own advantages and disadvantages.

# Answer
> 1 votes
Corona Sdk and Unity 3d both support iOS and Android. You still have to run on OSX for iOS development, but supposedly you don't need to re-write your code for each platform.

Corona runs on windows, so you can try it out now without spending a lot of money.

http://www.anscamobile.com/corona/

http://unity3d.com/

# Answer
> 1 votes
As an alternative to buying a mac, you could also consider http://www.macincloud.com/

Not tried myself, so I can't vouch for it, but the idea of renting a mac for developing iPhone apps seems reasonable.

I once had plans to develop mobile apps and bought a mac mini. Unfortunately, I haven't had time for that, and my mac mini is collecting dust. I don't want to upset apple-fans, but if you already have a Windows PC as your main machine, buying a mac solely for the purpose of developing apps is only worth it if you are committed to developing apps.

# Answer
> -1 votes
I strongly urge you to check out Unity 3D. Buy a MacBook and an iPhone Unity license and you'll be happy.

# Answer
> -1 votes
I recommend u cocos2dx, corona or marmalade.

In cocos2dx if you know c++ it is easy to learn, developing in c++ you can deploy it directly to ios with a MAC and to Android using ndk, you can also use Lua for scripts. http://www.cocos2d-x.org/ I use this.

Corona and Marmalade are also cross platforms too.

Marmalade I think it is difficult to learn, the configuration and all of that, because it also uses c++. http://www.madewithmarmalade.com/

And Corona I don't really know how easy or hard is to use, but it is cross platform too :) http://www.coronalabs.com/products/corona-sdk/

# Answer
> -3 votes
Use Adobe Air. It's the best way to develop real multi-platform games!

---
Tags: iphone, android, mobile
---


title: Low dexterity game development

text:
# Question
Title: Low dexterity game development
I am tasked with developing a game for kids with low dexterity (as a college project). I am stuck trying to find examples of similar games to generate ideas about game play and overall function. The general idea is that these kids wont be using a fully featured controller, it will be more basic, for example just a joystick.

Can anyone point me in the direction where I might find some resources (specifically game play ideas) to aid the in the development of low dexterity games?

# Answer
> 2 votes
You could look at almost any game from the 80s - admittedly most had at least 2 controls, eg. a joystick and a jump or fire button, but that's still fairly minimal.

Another idea is the concept of the "one button game" where you control everything literally just by using one button. There is often still a timing aspect though, so whether it meets your dexterity requirements or not, I don't know.

# Answer
> 2 votes
A turn based game is an obvious option. That could be anything from Chess to an X-Com clone. That lets you avoid issues with reaction time, and gives you more flexibility with the control system design.

I'd also suggest getting a better definition of what your players are capable of with their reduced dexterity - games that are too easy often aren't much fun. I'd also ask them what computer games they already like playing, and if possible watch / video them playing a game.

# Answer
> 2 votes
What you're talking about is accessibility, and a great resource for that is http://www.oneswitch.org.uk/. Another resource is the Able Gamers group at http://www.ablegamers.com/, which focuses on this kind of thing.

It's really important that you don't confuse cognitive and physical ability. Accessible doesn't mean "dumbed down" by a long shot.

# Answer
> 0 votes
For ideas look at Alice project. It is a 3D programming environment for introductory teaching for programming/computing. Ideas implemented in this environment may give you an insight for the project you are working on.

# Answer
> 0 votes
Just a joystick sounds interesting.

Dragon's Lair used just a joystick, but required fast player response times. Making the response time a user preference is one option.

I think it would be beneficial to look at games that are friendly to your design goals, rather than examples of, because I don't think there are a lot of examples.

For a single joystick, the hurdle to overcome would be selection and the thing to design for would be very sluggish user response. (i.e. a very forgivable UI.) One example of selection could be auto-selection/snapping of game objects (and using a radial menu) and pausing over non-game-object selections (with a verification radial popup - top/bottom). The latter could be used wherever the former is inappropriate.

If you had something like this, then many games could potentially be used for gameplay examples: Sid Meier's Civilization 5, Puzzle Quest, The Walking Dead, Phoenix Wright Ace Attorney, ...

# Answer
> 0 votes
Look at DoubleFine's previous and future productions. Point-and-click games sounds like a perfect solution to this issue.

---
Tags: game-design, game-mechanics
---


# Question
Title: Online Identification for Desktop Games?
What methods are there for providing means of authentification for multiplayer?

A few thoughts:

* I don't want to be restricted to a single publishing platform such as Steam.
* Something like OpenID would be great, but OpenID itself seems to be limited to the world wide web.
* It shouldn't be anything cryptic, so if you know the email or the user name of your friend you should be able to find him with that.
* People shouldn't be required to create a additional account just for this one game.
* OCS could be used for something like this but afaik it's not supported by any big vendor. So it would be somewhat useless.
* Things like querying what the players friends are are optional.

# Answer
If you can embed a browser in some form, one that supports cookies or similar, then the likes of OpenID, OAuth, Facebook Connect, etc., are open to you.

If not, then it's a bit more complicated. Generally you will have to maintain your own server and store accounts on there, and authenticate players by requiring them to enter the password for the account.

Ultimately this type of authentication just authenticates that you *either* know the password *or* have access to a certain email address associated with the account. As such, you can authenticate someone by sending them a random number to their email account and requiring them to enter the random number into your app. The benefit is that you don't have to store anything except which random numbers you sent to which addresses - the downside is that it's a hassle for users compared to even a password system.

Another type of authentication is to authenticate that it's the same machine playing the game as before. Browser cookies basically work this way - the server tells the browser to write a small file to disk and send it with every request to that site in future, so that the browser knows it's the same user each time. You can do something similar by giving each player a cookie which the app saves on their machine and sends to your server each time they log in. The cookie needs to be encrypted to ensure that people can't generate fake cookies, and you need to be careful that it doesn't get deleted or the account is effectively lost.

In general, authentication is a hard problem, which is why most places still resort to a simple username/email and password system.
> 7 votes

# Answer
1. If you don't want to require the player to create an account, you must support an account they already have.
2. There won't be a single system where all players already have an account.

*Therefore* you must support multiple systems. Look at what Stack Overflow does. They allow logging in with one of 12 existing accounts, *or* you can create an account on their site directly.

One of the developers I worked with decided that on their own site they'd have you log in with their own account, but if you come from Kongregate, then you can use your existing Kongregate account, and if you come from Steam, then you can use your existing Steam account. That way players aren't forced to create another account, but if they're coming from a place that already has one, then they can use it. Otherwise, they do have to create a new account.

I think if you want to satisfy all of your requirements you have to allow multiple types of login.
> 2 votes

# Answer
You can easily use OpenID, there are a great number of libraries available. However users might have to create an account there just for your application. Integrating facebook/google/yahoo authentication is also easy, but I find requiring an account in a service I don't use/like, just to use an application extremely obnoxious.

If you want to implement something yourself it is as easy as distributing a key with your application. Since that key is unique, random and only known by one user you can use it to log the user in, optionally requiring a password. You should store the key so that it is recoverable, like in the distributors cloud, on the receipt, or have the option of mailing it to the user.

You can also require a machine-based authentication (like steam) where you generate a unique key from the machine your app is running on, register it together with the application-key to your server and mail the user a confirmation key he has to type into his app once. The machine can now safely authenticate without requiring a password from the user. The process has to be repeated every time the hardware changes though.

Now that the user is logged in, you can store additional details about him, that you get from the platform he is using (steam, windows live, ...) or a contact form in your application, or data from the receipt, etc.

If you give the users the ability to name themselves you should make the username unique, to allow search and friend requests. If you don't want real uniqueness, you can go the blizzard way and use GenericUser#1234.
> 1 votes

# Answer
Chances are you will need to roll your own if you don't like the idea of embedding a small webbrowser directly in the game or opening up one. You will need to setup your own server (but you would probably need to do that anyway).

For rolling your own have a look at how web pages normally handle authentication.

Your not going to get away with having them not create an account (otherwise what are they logging into), you can however make it very quick and painless. If there is no account with that username, ask if they want to register it and then just do it without asking a bunch of things like emails and so on (Reddit does that). If you want to ensure they can recover their password then make the email optional.

Your not going to find a 3rd party login system that won't require to visit to their stuff to authorize things. Since the alternative would require the username/password to be entered in every single 3rd party program, it would be trivial for a malicious developer to capture that information (of course that's possible anyway since they could fake something like a Google login prompt).

A few important key points if you setup your own: * Firstly make sure everything is done over encryption (SSL/TLS). This will stop man in the middle attacks. You will need to use a signed certificate. Either use the main certificate authorities (StartSSL does them for free). Alternatively if you don't want to bother with the certificate authorities you can self sign and ship the public side of your certificate as part of the game executable. If you don't use a cert then someone can do things like setting up a fake DNS on large lans and steal logins by acting as a proxy between the player and your servers.

* Make sure passwords are encrypted hashes in the database, not in some plain text form. If you don't do this you risk the chance of getting hacked and having everyones passwords stolen. Even if you force everyone to reset their passwords there is a good chance many (most) of them are stupid enough to have used password for multiple places. For example their email that is often used to send them new passwords for just about every other account they login with. This would be a massive PR nightmare.
* Use randomly generated salt, unique for each login stored with the account. This stops people from reversing the hashes by using precomputed databases.
* Use multiple rounds of encryption. Even with salt it's possible to break a few accounts in a time frame.
* Try not to build as much of this as possible, chances are you will mess it up in a big way. Look at bcrypt/scrypt for decent password hashing functions that include multiple rounds designed to scale difficulty with modern hardware. If possible find a complete password storage library that has been prewritten for your language/platform. Things that have more use have more testing and are often designed by a team of people much smarter than you are. Assume your own programming is horrible and will get hacked, then program in a way to ensure if that does happen it's not a major disaster. You can't afford to cut corners here just because something is hard, or you think that a particular problem is unlikely to occur, or because your user base isn't going to be that big and you can fix it later if it grows.
* Make sure your random numbers are generated in a cryptographically secure way. The default random function in your programming language isn't likely to be.
* Generate a random token that is sent to the player, that authenticates them. If you wan't to offer a 'remember password' function it might be better to just store the token rather than the password. That way if someone has access to the players computer they can't steal their password just the token that can be reset. You will need to keep track of all active tokens and there may be multiple per player. Time out the tokens eventually.

It's a good idea to make a very minimal login server that runs on a separate server from your other components. Since this is where all the security is if your main game server/website is hacked in your login database won't be compromised. Make sure you log everything.

If you don't want your own host, you can look at Google App Engine and similar solutions. It's even free for small usage cases.

It might be worth looking at how XMPP handles authentication. Of course the whole standard is somewhat over engineered for a whole game. But it does do chat as well. XMPP itself could serve as a authentication system but it would be kind of a hacky use of it. I'm not sure if Google would allow that kind of use with GTalk since they probably don't like 3rd party programs asking for password. You could operate your own XMPP server and get chat, authentication and encryption, but you would need a XMPP client built into your game.

OAuth isn't too bad, it only would require the user to use the webinterface one time to authorize the program to be linked and it works with Google/Facebook and probably quite a few others and it does mean you no longer have to bother with running your own server.

BrowserID is another new alternative. But it's also a browser based system.
> 1 votes

---
Tags: networking, authentication
---


title: What are hosting demands for webgame?

text:
# Question
Title: What are hosting demands for webgame?
What are demands on hosting for multiplayer strategy game like **Empire, Travian**?

(memory for application, memory for database)

1. in flash
2. in .net
3. in php ?

**EDIT:**
Comments says there is no response for this question .., but I wrote **concrete examples**. So some tips, which could be near to reallity would be helpful for me.
For example:
Empire is in flash it could need about xxx GB memory for the application + about xxx MB/GB memory form database. (for one world)
Travian (it is probably in php) it could need xxx GB for engine and xxx MB/GB for database.(For one world).

# Answer
> 2 votes
This question is making my head hurt, but I'll try to help you out.

I do not know what limitations either of the games you mention have. I'm hoping you can take this info and fill in the blanks.

---

First we can look at database size. We need to take the maximum size of the gaming world and make it persistent in a database.

If the game board is made up of cells that have a biome/type, that could be an enumerated type or a short int/cell. If the board is 1 000 X 1 000 cells, that's one million short int's. If there is a capacity associated, that could be another int/cell. Keep adding until you think you've gotten all the information per cell accounted for.

Next we count towns. Towns usually have buildings in them, we can again make that an enumeration, so we'll call that another short int/building space. If each town has a 10 X 10 building space, that's 100 short int's per town + the town name + an int identifying the owning player. Again, if there are other important pieces of data, such as a capacity per building or a building time, that's more space yet. How many towns will there be on the board? 1 every ~10 cells? That's 10 million short int's just for the building types. Again, keep adding until your game is a game.

How many players will there be? and what information will you keep per player? (You can see this is starting to become wildly speculative based on how you program it) From memory I remember Travian kept user logins separate from the game data so a user could be active in more than one game at a time, however there was a lot of in-game player information to keep track of. Guild membership, messages to and from other players, army information, science progress? etc.

Assuming we're using MySQL for the database we can check out the size requirements here

Crunch the numbers and see what they come out as... 20MB? we can afford more than that, let's make the board bigger. 500GB? way too big, let's remove a couple extraneous bits of information per cell...

---

Next we can look at the bandwidth use. This has a lot more to do with the way you program your game, and so will be *more* speculative than the above size estimate. You need to estimate how many players you will have, how often they will be making web requests, and how much data you will be transmitting per request. Are you giving them the ability to see the whole board at once? Then you'll be transmitting all of the board data each request, so you probably don't want to do that. You want to give the user exactly the information that will show up on their screen at any moment and no more. Use the above estimation methods to total the data that will be required to set up one screen-shot from your game, and consider that the minimum of what you will have to transfer per request.

Assuming that you go to the effort of transmitting the data in some sort of binary format, you can probably estimate the byte-sizes with the SQL sizes above. If you transmit the information in JSON or XML, you can start counting one byte per digit in each of the numbers.

Again, tot the numbers and see where we're at. 1 MB per month? no problem. 1 MB per second? maybe we should start restricting user's request rates...

---

I think I'll stop here and hope you get the picture. It should be evident that without some kind of design information (preferably source code and database schematics) we can't really say what size restrictions a game will meet. I hope you can also see that depending on game design and coding, these things can be scaled to meet any reasonable size restrictions we put on them.

In the end, I would say that size is really so low on the worry-list that it's basically a non-issue. Go make a game and once it works and is coded to a good standard, *then* you can check to see how much it'll cost to host and scale it accordingly.

# Answer
> 2 votes
If you are developing your game with Flash, you could easily get away using player.io (server-side components are developed with .net). A cheaper (and far more advanced) option is to use a cloud solution like Windows Azure or Amazon EC2. Any of these services will bill you exactly by the resources you use, i.e they are scalable. Note that these options won't work on 3D games or otherwise any games where there are permanent connections between the client and server.

In that case, you'll need dedicated hardware where the requirements depend on the game itself and how many users you plan on having connected at the same time.

Rough estimates of requirements for the OpenSimulator server software can be found here.

---
Tags: game-industry, web
---


# Question
Title: What article discusses weightmaps for ai control?
A while back, I read an article on using weightmaps to control ai movement, particularly in an RTS environment. I can't find the article again, so perhaps someone here read it? I'm not asking for a list, there's a specific article I'm looking for, and so far I haven't found the magic query on google to find it.

# Answer
I suspect you actually mean influence maps, which have some sort of 'weight' at each point on the grid. My mind-reading skills are not great so I can't tell exactly which article you read but maybe one of these will help: The Mechanics of Influence Mapping, Influence Maps, Influence Maps I, etc.
> 3 votes

---
Tags: ai, tilemap, articles
---


# Question
Title: How would a sprite spawn more sprites under themself every second?
I am making a snake game and am having trouble to make the snake go longer, at the moment when I run the program, I just have the snake head eating apples. But I want the snake head(30x30) to spawn body parts(20x20) under himself every second. After I can do that, the snake head has to draw 4 body parts and the computer must "delete" the oldest body part before a new one spawns. It is a 2d game, and the snake can curve instead of 90 degree turns. I hope you will all understand.

# Answer
Without knowing the structure of the program I'd suggest making a `Queue<BodyPart>` to track the current body parts. Each second dequeue the tail or the snake, spawn the part at the head's location and add it to the queue, and then move the head. To draw the snake you just iterate over the queue and draw the body parts it contains.
> 0 votes

---
Tags: c#, xna, movement, snake
---


# Question
Title: Input into a switch statement to change position of a character.
I'm trying to make a simulation of Travelling sales man problem. So I got random circles spawning and each circle.

I want to make it so I can switch between the circles. Currently the player spawns to the first circle created which is in position (cir\[0\].x, cir\[0\].y). However, I'm trying to make an input so you can type in for example 12 and the position of the queen would now be (cir\[12\].x, cir\[12\].y). But, this seems to not work.

```
int number;
cin>>number;

if(number<NUMCIRC)
{
    switch(number)
    {
    case number:
        queenX = cir[number].x;
        queenY= cir[number].y;
        break;

    default: break;

    }
}

```

I was wondering as surely if I input the number and then press enter it should jump to the number. Assuming it's smaller than NUMCIRC, which is the number of circles that I have spawned.

# Answer
> 6 votes
Your `switch` statement is completely superfluous because you're not switching between anything. The point of an array is you can select a value by its numerical index. I'm not entirely sure how the `switch` statement will execute with a variable `case`. Regardless, you can achieve the desired result with the following code.

```
int number;
cin>>number;

if(number<NUMCIRC)
{
    queenX = cir[number].x;
    queenY = cir[number].y;
}

```

---
Tags: c++
---


title: Scene management for 3D editor

text:
# Question
Title: Scene management for 3D editor
I need a scene graph/management method for a 3D editor (brute force rendering is not really a possibility), where lots of data (geometry) are constantly being modified, it also would need to work great for picking (casting rays from the camera to select objects). Octrees seem to be a great solution, but i'm not quite sure.

# Answer
Think only just one part of the data will be edited at the time, so that makes it easier. Do all just as normal and pick out the one that is editted to use a differend rendering method such as wireframe, coloured or whatever you need.

Brute force is actually never a good possibility unless you have only one checkersboard or such.

Two optimazations can be a vertex and texture cache. Collect objects that share the same vertex data and texture data. Then render all of those in one time. This saves a lot of gpu time as you only set the texture data once and then render 10 objects for instance. This is in addition too octree and frustum culling. Firstly check the distance from the camera, if further then the farplane, do not bother doing anything. Use bounding spheres, that's the cheapest way to determine if something is in view or not, then check the axis aligned bounding box (aabb). For higher precision you could do a boundingbox check.

EDIT: For ray picking I would create a new class. As I go through all objects on the next render I only pass in that ray instance so it can be filled. This means I have in the object class a method for a ray picking check where the ray class is being passed to. It will cost almost nothing.

Regards,
> 1 votes

# Answer
OcTree (or portals) + Batching + LODs + Culling.

You might want to have several rendering modes, one at top quality and some with reduced quality but improved performance (simplified lighting and shading, lower resolution textures, no particles, etc).
> 1 votes

---
Tags: optimization, scene-graph, map-editor
---


# Question
Title: Multiplayer (Database, Users,etc) for game
I'm am looking to add multiplayer into my game (2D Platformer in XNA C#) My worlds are quite large (Up to 30 Million tiles max, Average 20 million maybe. 2000x10000). You could say the game is quite like Terraria.

I have been using Player.IO, It has everything I could need, Except for the fact that I will easily run out of bandwidth with such large worlds.

So I have been experimenting with the Lidgren Networking Library, Its okay, But not having to port forward for users would be nice, But Minecraft and terraria still get away with it.

So if I have serverside Code figured out (Lidgren). Now I just Need unique usernames, and possibly a Database for them (as player.io has PlayerObjects), a way to make a server list would also be a plus.

Almost something such as The way minecraft does it would be fine, Players have accounts, but they also have to make a server.

So how should I go about adding,

* Unique Usernames (Login and registration)
* Database for players acheivements and stats
* A way to easily intergrate it with a server ran by players (Unless the service includes this)

By the way, We are Indie, So if we can do users through SQl and a site it would be cheap, or a cheaper multiplayer service would be cool

# Answer
1. Let your central server (CS) do only 'lightweight' things:

* Manage the authentication,
    * Store the achievements.
    * Store some basic stats of the available player-owned servers.
2. Let player-owned servers (POS) store the tiles and manage the game states.
3. The game client (GC) should only communicate with the CS when logging in, and when the player is looking at the POS list.
4. POS's should regularly communicate with the CS, to:

* Send a notification when a player fulfilled the requirements of getting a new achievement,
    * Send pings every x seconds, so that the CS can create and update a POS list.
    * Send some other data of the game state (number of players logged in, etc.) to show some statistics in the POS list lobby.

This is similar to what Minecraft does. The main advantage is that you can support millions of players with relatively cheap back-end, yet force players to have a valid account (making piracy a bit more difficult).
> 3 votes

---
Tags: xna, networking, client-server, databases, sql
---


# Question
Title: Writing a basic shader for large input files
I started writing a shader for my iOS app and instead of starting from scratch i used this tutorial here: http://www.raywenderlich.com/3664/opengl-es-2-0-for-iphone-tutorial

I wrote an import function, first to import wavefront .obj models. My problem is that with I can't handle larger inputs (with a simple cube it was working). I realized that the indices array is an array of GLubyte values, which is unsigned char, so as a result i cant have more than 256 indexes. I modified it to GLuint, but then only get a blank screen.

What else needs to me modified?

p.s.: the source can be downloaded from here: http://d1xzuxjlafny7l.cloudfront.net/downloads/HelloOpenGL.zip

# Answer
> 1 votes
glDrawElements accepts only GL\_UNSIGNED\_BYTE and GL\_UNSIGNED\_SHORT. Using GL\_UNSIGNED\_INT should give you an error. Are you checking errors with glGetError function?

---
Tags: opengl-es, ios
---


# Question
Title: Stop map from scrolling but let player still move?
I have a basic method of scrolling around on a map (moving the map instead of the player), but at when the player gets to a certain proximity to the edge, how do you stop the map from scrolling, but still allow the player to move around until it is away from that proximity? I'm not looking for any code. Just a suggestion so that I can implement it myself. I can see it visually (creating 4 boxed intersecting boundaries for the player to enter), but not sure how to come about stopping and resuming the scrolling of the map.

# Answer
Define your viewport (position and size of the viewport). If you have this, you can define your borders. When your viewport position defines the upper left corner of your screen its pretty easy to restrict the screen position.

First of all you set the screen position to be centered on the player:

```
viewport.x = player.x - viewport.width / 2
viewport.y = player.y - viewport.height / 2

```

Then you have to make sure, that the viewport doesn't goes over the map.

```
if(viewport.x < 0) viewport.x = 0
if(viewport.y < 0) viewport.y = 0
if(viewport.x > map.width - viewport.width) viewport.x = map.width - viewport.width
if(viewport.y > map.height - viewport.height) viewport.y = map.height - viewport.height

```

Basically this should be what you are looking for... You have to keep some things in mind, for example you can leave out the upper bounds check, if the screen size in that dimension is bigger than the map size ( viewport.width \> map.width ). Also, if you have your map width in tiles instead of pixel, you would have to multiply the map sizes with the tile size.

If your screen position marks the middle of the screen, you would need to change some of the calculations a bit, but the basic idea is the same.
> 1 votes

# Answer
You shouldn't do scrolling like that, it is very counter intuitive. Just create a `Camera` object, that has a position, and then render everything according to the camera's position. Move the camera around, don't change the entity positions, as that can alter your logic and mess everything up.

```
//If the camera is really far to the right, everything is rendered far to the left.
render(e.sprite, e.position.x - camera.position.x, e.position.y - camera.position.y)

```
> 6 votes

---
Tags: java, side-scroller
---


# Question
Title: How to get smooth transition within slick?
When a player clicks start, my app immediately switches to the first level. My question is how do I incorporate a smooth transition within Slick?

# Answer
> 5 votes
I'm not sure this kind of functionality is engine-specific. If you have a way of setting a global alpha, then you could do it just fine.

Interpolate the scene alpha and the menu alpha through time, for example, for one second...

```
timeStarted = currentTime() //Time in milliseconds since the program started, probably 0 if this is the actual start of the program.
scene.alpha = 0 //The scene is transparent at start.
menu.alpha = 1 //We render only the menu.
renderMenu = true //After the menu alpha reaches 0, we can stop rendering it.
transitionTime = 1000 //How long does the transition last?

do:
    timePassed = currentTime() - timeStarted

    if timePassed > transitionTime:
        renderMenu = false //Transition over, no point in rendering a transparent menu.
        scene.alpha = 1 //We can render the scene fully now.
    else:
        scene.alpha = timePassed/transitionTime //From 0 to 1.
        menu.alpha = 1 - timePassed/transitionTime //From 1 to 0.

    if renderMenu:
        menu.render() //It's important to just render it, not actually search for GUI events.

    scene.render()

```

**Edit:**

We have two objects, `scene` and `menu` here... The scene is the actual game, while the menu is, well, your start GUI. `alpha` denotes how translucent (transparent is the wrong word for this) a picture will render. If it was 0, you wouldn't see the picture (it would be transparent). If it was 1, the picture would be opaque, which means that you can't see whats behind the picture. `renderMenu` is simply a flag that tells your game whether to render the menu (eg "start" and "highscore" buttons) or not.

What we do here is increase the alpha of the game, and decrease the alpha of the menu, making it slowly fade away. If you set `transitionTime` to `10000`, the transition would last 10 seconds. It is also important to understand that this isn't Java, but pseudocode. You probably have different names for these things in your code.

I hope I cleared things up.

# Answer
> 2 votes
You can apply transition effects when changing a game state, just use the overloaded method:

See Javadoc: enterState

On this javadoc page you can see, what transitions are available: JavaDoc: Transition

I have just tried it out in my current prototype and its pretty easy to do. Example of how I made a transition from my main menu state to the gameplay state (the main menu looks pretty ugly and isn't a menu at all, thats because I haven't implemented it yet ;) but I think it should suffice as example.

http://youtu.be/pYHbV\_xyBoM

The code I used to produce this simple transition from the menu to white and then to the game state looks like this:

```
@Override
public void update(GameContainer gc, StateBasedGame sbg, int d)
        throws SlickException {
    [...]
    if(App.keys.menuEnter.pressed(i))
    {

        sbg.enterState(2, new FadeOutTransition(Color.white, 1000), new FadeInTransition(Color.white, 1000) );
    }
    [...]
}

```

If you look at the method signature of enterState you see, that the overload will take the state id, a fade out and a fade in transition. I simply took two of the transitions and looked at the constructor of them. There you already see, what options are possible (color and duration in the case of the fade in/out).

Just try out the classes, look at the methods and constructors and try to find out how they work, if to few documentation is provided.

*Edit:* Make sure that your update and render methods work, even if init hasn't run yet. I think the transitions may cause the render method to be called before init.

---
Tags: java, slick
---


# Question
Title: I need to sell an almost-complete MMORPG project. How can I do that?
I need your help. We have to sell MMORPG at an advanced stage. The game has a unique engine, written on the need for the game, graphics, sound, map editor, web site etc.

As it happens in the play mmorpg we can develop the characters, monsters. We can fight with other characters or to establish cooperation in solving the challenges. We can fight using own monsters, or throwing their own cards with spells.

Unfortunately we have no idea how to promote the game. Ended fund and I think the whole team surrendered. How can I find a buyer? Where can I find him? Thank you for your help.

# Answer
I see two questions here: How can I secure funding for finishing my game? and How do I handle promotion of my game?

## Getting Started

I believe this is the perfect situation to apply the Minecraft Model to. Setup a site for your game. Get registration working. Start selling subscriptions cheap, $1-3 a month, or even sell lifetime memberships for $10-25.

As Bummzack says, get it on kickstater.

Engage in the MMO community, engage in the game dev community, engage in the hobby homebrew community. Get on social media. Allow the few early adopters and people who love your videos and screenshots to fund the early needs like the server. Iterate forever.

## Next Steps

It doesn't matter how bad it looks to start with, you only need to get a few people to buy it to start. Just keep making it better and fun. Always fun.

Expand the options for players, always tying back to the core game play. Make everything support that one unique aspect of your game. If your game is a world based on living cards, make everything the player does either need cards they already have or give them new cards. If the point of your game is monster collection, make everything need attributes of monsters to work.

If you want to add item crafting to the game, make it require iron cards/monsters and fire cards/monsters to be able to craft those items. Focus on the economy of your game. In Minecraft, that economy is blocks that were mined. Everything in the game needs those mined blocks.

If you keep giving the players new ways, weekly or at worst monthly, to make use of the items they already have, then you will keep them coming back for years. And they will tell their friends and you will keep getting new sales or subs and therefore new players.

## Downside

The major problem with this is your game has to be really fun and engaging to be successful with this model. It works because you build a community around something that a few really interested people love. Minecraft initially appealed only to a certain type of lego-centric player, however they kept adding features to the game that appealed to other types of gamers and eventually broke out and grew exponentially. For me, it was the addition of mine-cart roller-coasters that got me to buy it.

If your game can't grab people by the throat and not let go. If it isn't fun and totally engaging for hours on hours, this model won't work.
> 15 votes

---
Tags: mmo, marketing, sales
---


# Question
Title: What is the best way to implement dialogs in an xna game?
I want to implement some startup dialogs, for selecting game parameters, etc. The obvious (and I suppose naive) choice is to just use windows forms (I'm not really planning on porting this game to anything other than windows). But implementing this seems to be a real pain, i.e. can't use ShowDialog, and if I use Show() I have the question of how to return the result to the main loop.

I was wondering if there's an established way to implement dialogs (radio buttons, combo boxes, text boxes, etc) in XNA (maybe some libraries) or is it just a case of reinventing the wheel each time?

Just looking for some general advice on this issue before I spend too much time thrashing around trying different things.

# Answer
From my personal experience with XNA, it's a pain. I think the way they expect us to do it, is to write our own GUI controls from the ground up. Buttons and checkboxes aren't so bad, but when you want lists, or text fields, it can eat up a lot of your development time.

I would highly recommend using a 3rd party GUI library. @ClassicThunder has developed one such library that you can check out on CodePlex, although I can't personally vouch for it. In my game, I was completely sick of developing my own GUI library, so I took off in a completely different direction. I've started to use Awesomium, a web-GUI. With Awesomium, you can create your entire interface using HTML, JavaScript, CSS, and any other fancy web package like JQuery. @MindWorX and I have co-authored an open-source Awesomium component for XNA that you can find on BitBicket.

Whatever you decide, I would not recommend making your own GUI package unless you are certain you will only need really basic controls. Use someone else's package.
> 8 votes

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


title: Book on designing game architecture?

text:
# Question
Title: Book on designing game architecture?
I would like to make nice games with good architecture that are easy to support and extend. But when i write code it all gets messy and hardcoded, so when I want to add a feature it becomes a huge pain. Is there any book that teaches me how to design my game upfront, so I will know what classes I will want, how to do certain features etc.

# Answer
> 5 votes
I would recommend Game Coding Complete.

It has a large focus on the design of each part of the game, and how they work together. Most books that deal with programming games try to dumb everything down into small demos that break or become messy when you try to extend them. Instead, this book spends the time to break each part up into extendable pieces of a framework.

It's authors have experience working on large projects with many people, and the book reflects that.

I know exactly what you mean when you say " it all gets messy and hardcoded, so when I want to add a feature it becomes a huge pain." Reading this book really helped me solve this problem.

I believe that the book recently released it's fourth edition. Here is the amazon link http://www.amazon.com/Game-Coding-Complete-Fourth-Edition/dp/1133776574/ref=dp\_ob\_title\_bk.

To see what I mean you can use Amazon's preview to read the first part of Chapter 2 "What's in a Game?" This chapter describe the architecture that the rest of the book implements.

# Answer
> 3 votes
It seems like what you're looking for is a more informed outlook on software architecture and software design in general, which are more along the lines of software engineering topics than game development topics. My suggestion is to dig through the architectures of several other existing games, and see how they are structured; in addition, pick up a copy of Head-First Design Patterns, and that might help. The above comment about Dave Eberly's Game Engine Design book is also spot-on.

---
Tags: architecture
---


# Question
Title: Cocos2D game engine javascript is too slow on mobile
i developed a game using `cocos2D javascript` that works fine on web browsers but when i run it on mobile ( `iPhone 4s` , `android nexus`) the FPS was dropped to 20 - 22 on `iPhone` (max) how to optimize it to increase the FPS to 30 on mobile .

# Answer
> 3 votes
Generally slow downs are an inevitable part of using a mobile browser. There just isn't as much grunt on a phone, and mobile browsers are not yet as natively accelerated as their desktop counterparts. This is changing though (iOS 6 for example has made great leaps).

For now though, generally you need to profile and optimize your code. Try to use some isolated testing to understand what's causing the lag. Some general tips:

1. Drawing is slow. Try to draw less things.
2. Consider preredering complex graphics.
3. Don't create objects. I recommend using gamecore.js object pooling.
4. Test your effects and sprite rendering: generally rotation, alpha and scaling are going to slow you down a lot.
5. Buffer input events and only handle them once per cycle.
6. Buffer audio objects.
7. Slow down your physics cycling (if you're running a simulation)
8. Consider using a game engine like playcraft.
9. Look at using appMobi or Ludei for native acceleration wrapping.

---
Tags: javascript, html5, cocos2d, mobile
---


# Question
Title: Weird error with opengl in Android using Libgdx : "EGL_BAD_ATTRIBUTE"
I am having a weird error when uploading my game in the phones.

**E/Adreno200-EGL(5128): qeglDrvAPI\_eglGetConfigAttrib:484\>: EGL\_BAD\_ATTRIBUTE**

I am uploading the textures with AssetManager.

I am using OpenGL 1.0.

It begans to upload the textures, but when it is about to finish uploading them, it finishes unexpectedly without any message in logcat.

Any ideas what is happening?

When I updated my xperia ray to ics it began having this problem

And when it loads, and I navigate through screens I get this in logcat

\<**qgl2DrvAPI\_glClear:33\>: GL\_INVALID\_VALUE**

**This is my line using the clear**

* this.gl.glClear(GL10.GL\_COLOR\_BUFFER\_BIT | GL10.GL\_DEPTH\_BUFFER\_BIT);

The type of gl is GL10

Although the first error occurs when it is loading :/

Here is my logcat output

# Answer
According to the official OpenGL documentation,

> `glClear` generates `GL_INVALID_VALUE` if any bit other than the four defined bits is set in mask.

So, i would double check your `glClear` sentence. Can you post a few of your code so we can check it?

---

**EDIT:** I believe you have more than one error in your code. First, looks like OpenGL ES is complaining about this `glClear` and it is causing a `GL_INVALID_VALUE` gl error. Then, regarding other error, having a look at the OpenGL ES documentation of eglGetConfigAttrib, you can see that

> `EGL_BAD_ATTRIBUTE` is generated if *attribute* is not a valid frame buffer configuration attribute.

Can you post again the line where you use `eglGetConfigAttrib`? I would double check that *`attribute`* parameter and its value.
> 2 votes

---
Tags: opengl, android, libgdx
---


title: Rotating To Face a Point

text:
# Question
Title: Rotating To Face a Point
I am trying to rotate a line to point to the mouse's world coordinates (rather where the mouse lies on the plane where y=0).

I am running into a couple of problems though:

* Whilst it follows the mouse the line doesn't always lie directly beneath the cursor, which is what I would expect to see. It seems to be perfect when the position is at the origin and less accurate the further away from the origin I get.
* The rotation doesn't go from 0 - 360, rather 0 - 180. I think the solution here is to use a dot product but the first problem is preventing me from fixing this problem.

Here's where I calculate the angle by which to rotate:

Calculating mouse position

```
 Vector3 near, far, dir;
 unproject(*mouse_, near, far);
 dir = near - far;
 normalize(dir);

 float t = -near.y / dir.y;
 Vector3 point = near + (t * dir); //where the mouse lies on the plane y=0

```

I'm almost certain the above is correct as when I draw a point at `point` the rendered point is directly beneath the cursor on the plane y=0

Calculating angle between the line and the point.

```
 rotation_.y = angleBetween(position_ - dir_, position_ - point);
 rotation_.y = radToDeg(rotation_.y);

```

`position_` is where I want the line to start from. Which is the player's position at the moment.
`dir_` is the direction of the line, set to and never changed `Vector3(0.0f, 0.0f, 5.0f);`

```
 float angleBetween(const Vector3& a, const Vector3& b) {
     float cosTheta = dot(a, b) / (length(a) * length(b));

     return acos(cosTheta);
 }

```

Here's how I am drawing the line:

```
 glPushMatrix();
 glTranslatef(position_.x, position_.y, position_.z);
 glRotatef(rotation_.x, 1.0f, 0.0f, 0.0f);
 glRotatef(rotation_.y, 0.0f, 1.0f, 0.0f);
 glRotatef(rotation_.z, 0.0f, 0.0f, 1.0f);

 glDisable(GL_LIGHTING);
 glLineWidth(3.0f);
 glColor3f(0.0f, 1.0f, 1.0f);
 glBegin(GL_LINES);

 glVertex3f(0.0f, 0.0f, 0.0f);
 glVertex3fv(end_.toArray().data()); //toArray() returns and std::array of the vector

 glEnd();
 glPopMatrix();

```

And just in case it matters, for the camera I do:

```
void Camera::transform() {
    gluLookAt(position_.x, position_.y, position_.z,
              target_.x, target_.y, target_.z,
              0.0f, 1.0f, 0.0f);
}

```

`target_` is also the player's position.

I hope this is enough information.

# Answer
> 2 votes
Regarding this bit of code:

```
rotation_.y = angleBetween(position_ - dir_, position_ - point);
rotation_.y = radToDeg(rotation_.y);

```

First of all, if `dir_` is truly a direction vector, it shouldn't be subtracted from the position, so you'd just call `angleBetween(dir_, point - position_);`. (I reversed the subtraction in the second argument so that it's calculating the vector *from* `position_` *to* `point`, which I think is what you wanted.)

Second, the way you want to calculate the angle between these vectors is probably something like `atan2(b.x, b.z) - atan2(a.x, a.z)` rather than the method you used. As you noted, the acos(dot product) method will always pick the shortest distance around the circle and give a positive angle; the atan2 method should give a correctly-signed result so that you'll rotate either clockwise or anticlockwise as appropriate. Also, this will automatically project things into the XZ plane, which is appropriate since you're always going to be rotating around the Y axis. (The dot product version of `angleBetween` will give an angle around whatever axis is perpendicular to the two vectors, which won't be the Y axis if either vector has a nonzero Y component.)

---
Tags: c++, opengl, rotation, mouse
---


# Question
Title: What would be a good game making engine supporting Vector images?
I want to create a simple platforming game, in which you are a square in a wonderful world. I would like this game to be able to be played in browsers. Basically I am searching for something similar to "Flixel", but with the following features:

* Support Vector Graphics
* Allow zooming/rotating objects without producing huge amounts of lag as soon as you are using more objects. (Because I want to rotate the map around the player) So in other words, preferably zoom the viewport/camera instead of the objects themselves.

Does an engine like that exist?

# Answer
> 2 votes
Well, Flash is vector based (and their vector renderer is really fast). Since you tagged your question with flash, I guess you're looking for something that's more of a game-engine?

Flixel and Flashpunk are both bitmap based engines. The only other engine that's commonly used would be the Pushbutton engine. Sadly the development on this engine has stopped.

In my opinion the feature-set of flash alone is plenty enough to start developing games. No need for a specialized game-engine. Also there are lots of 3rd party libraries available that can add some missing feature to the existing flash API. Have a look at this question.

**Update:** If you'd rather venture into developing games with JavaScript/HTML5, RaphaelJS or PaperJS might be for you. These are "just" libraries to render vector-graphics, not game-engines though.

# Answer
> 1 votes
Why would you want to make the game with vector images? Once your screen gets filled with a lot them, it's going to slow down considerably.

That being said, have you tried with the Citrus Engine? http://citrusengine.com I'm not sure if it covers yous specific needs, but it's specifically made for platform games

Cheers!

edit: I forgot to mention that is open source now! :)

---
Tags: camera, html5, flash, vector-art
---


# Question
Title: What's the newest trend / method for terrain rendering?
The last time I checked in on terrain rendering, ROAM was the new hotness. Yes, that was a long time ago. I liked ROAM a lot, though, because it was extremely simple to program, and gave pretty decent results. I imagine that the technology has improved quite a bit now. What are the most popular methods for terrain rendering these days?

# Answer
> 17 votes
You should definitely check out the Halo Wars GDC presentation, "The Terrain of Next-Gen." It discusses using full vector field displacement instead of simple height field displacement.

For something a little less revolutionary, maybe check into geometry clipmaps. There's a good article in GPU Gems 2 here.

# Answer
> 11 votes
For one, the geometry pipeline needs to be as simple as possible and just push geometry to the GPU with quite basic LOD management on it.

I did a presentation at Siggraph 2007 titled Terrain Rendering in Frostbite using Procedural Shader Splatting which goes into some detail of how we handle both the geometry LOD and the general texture and shading of the terrain. We use a combination of semi-procedural shaders in multiple layers. This is also covered in some more detail in the course notes for the talk (pdf).

# Answer
> 5 votes
Well, actually the **newest** trend is to use raytracing into a sparse voxel octree for the terrain in combination with rasterization of triangle meshes for all the rest. id software currently works on this technology to implement it in their upcoming engine.

# Answer
> 2 votes
Just as a friendly warning, any Googling on the subject will no doubt get you 100 000 hits on ROAM and related technologies (ROAM, Geo mip-mapping etc.). Keep well away from them, they are very CPU-bound.

I have read here and there that 'brute force' can actually work; and have personal experience of it working better than any ROAM technologies that I implemented. Simply dividing the landscape and culling out portions of it worked brilliantly; as a proof-of-concept solution.

Simple systems are always the best **first** implementation. If you don't have an in-house landscape engine make a simple one, continue with the rest of the game and come back to other ideas later. Landscapes are fun to implement (because you get such varied results for very simple changes) and a typical developer will get distracted by this puzzle for far too long.

Once you have your game laid out; Neverender is right on the mark.

# Answer
> 2 votes
As an alternative to geometry clipmapping, chunked LOD is a commonly used technique that efficiently feeds the graphics pipeline and is not patented like geometry clipmapping. It is probably used in most modern virtual globes.

There are more modern techniques that fully utilize today's GPUs by sending only height and color textures to the GPU and building the terrain geometry via shaders (see Bruneton and Neyret 2008), but be warned that while this is fast, it also means you don't have terrain geometry on the CPU for physics and simulation. There's also a modern technique that dynamically switches between rasterization and ray casting depending on what is most efficient (see Dick ea 2010).

---
Tags: terrain-rendering, 3d
---


# Question
Title: Started game development no idea of computer graphics. Should I learn tools or concepts?
I am in 6th semester of my Computer science bachelor degree program, Working as Intern in a start up company. I started game development using AndEngine, things are going good because I have good hold on OOP and Java.

But I don't have any experience in OpenGL programming and neither studied a course of computer graphics. I want to develop 3D games and there are tools available like Unity3d etc.

My question is should I master tools or take online lectures of computer graphics to get started on basics. I want to continue game development as my profession. So what should I do? start learning from scratch or Learn already built tools and just dive into development?

I see successful designers with no background of academic study, just did a photoshop course and now they are in the softwarehouse and making websites, sprites etc.

# Answer
> 12 votes
The simple answer is: you'll have to learn both concepts and tools. First, you should learn the very basics of game mechanics and game design. Then you'll be able to decide, which direction would you like to go next. Keep in mind, that tools won't do any good without knowledge of the concept.

To use your example: if a graphic designer doesn't realize, that the sprites he has to make are going to be rotated randomly in the game, then he might screw up the shading. If he doesn't know that the sprites need to have transparency, he might end up creating them with colored backrounds, or just simply save them in BMP or JPEG.

So the question is really: how much time should I spend learning concepts and tools, versus creating something marketable. And there's no good answer for that. It depends on your goals and a million other circumstances. If you want to produce new apps every 3 months, then learn about Unity or some other similar tool. If you want to get a bit deeper, then learn and use XNA. If you want to write your own engine, then learn C++ and DirectX or OpenGL.

My personal recommendation is to spend 1/3 of your time on learning about a concept, 1/3 of your time designing and planning, and 1/3 of your time implementing. These numbers aren't based on any scientific research however. Once you really get into it though, you'll feel which areas you need (or like) to spend more time on.

# Answer
> 7 votes
If I were you, I would question myself about 'What do I enjoy doing for a game?'. Do you want to be a graphics programmer or a game programmer? Do you enjoy fixing those odd pixel in the screen that doesn't fit with the rest of the screen or do you enjoy building the game and don't want to be really bothered by the graphics implementation?

If you're more into graphics, learn a high-level graphics API first, like Ogre3D, Irrlicht, Horde3D, etc. Once you grasp high-level concepts, take your time and dive into details.

If you're looking to game development, learn to use game engines like Unity3D, Unreal3D, etc. They've done the hardwork of getting the engine implementation right and you can concentrate on the building the game itself.

# Answer
> 3 votes
Vite Falcon touches one of the most important aspects of any sort of skill development. What are you most interested in? What makes you stay up way too late just to learn a bit more or just to solve a problem stopping you from progressing? If you feel that passionate about an area, then you have the most important basis to learn more.

Other than that I think Marton gives you good advice in his first part - you need both. I've been teaching 3D graphics, graphics design, digital imaging, programming and many other things. There is always that tough question - what should come first, the theory or the practice? Should one first learn why things should be done in a certain way, and then learn how to do it, or should it be the other way around? And I have yet to find one answer that fits all. I guess it very much depends on you and what you prefer yourself. Some want to get a good theoretical base before they start doing anything practical where as others just want to jump in and start making things. If anything, I personally would emphasis the practical part, since no matter how good your theoretical skills are, you won't do anything better than what you can achieve through the tools you use. The other way around, however, is not necessarily true. As you yourself pointed out there are quite a few successful designers without any academical skills.

Best of luck on your path into a very challenging and rewarding world. ///JmD

---
Tags: opengl, android, unity, software-engineering, tools
---


title: Real Time Motion Retargeting

text:
# Question
Title: Real Time Motion Retargeting
Using Kinect I've extracted coordinates(x,y,z) of user, I'm in search of method which can help me out transferring motion of Skeleton to any 3D model(AVATAR) using OpenNI and OpenGL.

# Answer
If you're OK with commercial software, it looks like this is the kind of things Natural Motion is selling with morpheme.
> 0 votes

---
Tags: skeletal-animation
---


title: How to code a simple torch light?

text:
# Question
Title: How to code a simple torch light?
How would you code a simple "8 bit fire torch" (just one, nothing else to worry about on screen), without using any sprites?

For instance, how would you "animate" a torch that looks like this one:

# Answer
> 16 votes
You could try the old school fire effect.

Let's say you store an 8-bit temperature value for each of your pixels. At each update:

1. Feed the bottom line with random "hot" pixels (e.g. 200-256).
2. For the others lines, all the way up:

* Each pixel gets a new temperature from the pixel below
    * Times a random decay factor
3. Pick your pixel colors from an 8-bit palette with:

* 256 = hot, white pixels
    * 0 = cold, black pixels
    * Shades of yellow, orange and red in between

See this blog post for a Javascript implementation. And this for a Processing demo.

Some variants:

* Make the middle values hotter on the bottom line (e.g. with a Gauss curve)
* Get a mean of the pixels below instead of just one of them
* Play around with this pixel lookup, try to balance it with some "wind" factor, etc.

---
Tags: animation, particles
---


# Question
Title: Creating a Custom Map Editor using XNA and Windows Forms
I'm looking to create my own level editor for a game I'm making, and I came across the following post:

Tutorial or Example of creating custom sprite tool/map editor for XNA?

In the example posted by Blau, I am unsure what needs to be replaced in this line, and with what:

```
XnaControlGame.CreateAndShow<MainDialog, VoxelEditorGame>( );

```

If anyone could help at all, that would be great!

# Answer
MainDialog is the type of your windows main form, that needs to implement `IXnaFormContainer`

```
//Form1 is the standard winform when a new WindowsForms application is created
public partial Form1 : Form, IXnaFormContainer{

//YourControl is some control placed on your form. I'm guessing a Panel will work
public Control XnaControl { get{return this.YourControl} }

//Game1 is your XNA game class
private XnaControlGame _game;
public XnaControlGame Game { get{return _game;} set{_game=value;} }
}

```

In the next step you need to alter your `Game1` class

```
public class Game1 : XnaControlGame{  //instead of Microsoft.Xna.Framework.Game
  public Game1 ( IntPtr handle, System.Windows.Forms.Form parentForm, System.Windows.Forms.Control surfaceControl) : base(handle, parentForm, surfaceControl){
    ...
  }
}

```

In the static void main

```
static void Main(string[] args){
  XnaControlGame.CreateAndShow<Form1, Game1>( );
}

```
> 3 votes

# Answer
This might not be what you want, but you're using an unofficial workaround to do this. I would honestly reccomend doing it the offical way with a UserControl, then you can even design inside the WinForms designer!

http://create.msdn.com/en-US/education/catalog/sample/winforms\_series\_1
> 4 votes

---
Tags: xna
---


# Question
Title: Convert point to its barymetric coordinates
I'm making a 2.5D game engine (in JavaScript) and I'm trying to get it to detect whether a block is under the cursor. This would be a simple task were it restricted to *single-level* isometric coordinates, but instead it's supposed to support isometric worlds, trimetric worlds and well, any projection angle really, in addition to it being multi-level (tiles can be stacked on each other up to an arbitrary limit). Almost all the conditions are arbitrary, but I've managed to narrow the problem to this, for now:

I need to know whether a point is inside a hexagon:

What I've set up so far is a bit hackish, I'm checking whether the point is inside the bounding rectangle first to drop out the most obvious cases. Next, I'm checking whether it's inside the rectangle formed by the points ACDF, another easy check. Now the hard part is that I need to check whether the point is inside the triangles. That's pretty straightforward if you have the barycentric coordinates, but I seem to have lost all the knowledge of how to obtain them.

Do take into account that while the inner rectangle is always a rectangle, the triangles might not be equal-sided. Bonus points if there's an optimization to be made because the bottom (or top, respectively) of the triangle is flat.

# Answer
> 2 votes
Wikipedia has an excellent article explaining exactly how to get the barycentric coordinates at 2.1 Converting to barycentric coordinates

From Wikipedia:

> Explicitly, the formulae for the barycentric co-ordinates of are:

So in your top triangle A.x would correspond to x1, A.y to y1 and so forth. Plugging in the values in the formulae will yield the lamdas which are your barycentric coordinates. If they are all positive then the point is obviously inside the triangle.

Possible optimization due to the bottom of the triangle being flat (by that I assume it doesn't rotate or can be evaluated in local coordinates) is that one lambda can easily be evaluated by comparing only the y-values like:

lambda1 = y1 - y

# Answer
> 2 votes
If your goal is only to do point-in-hex tests (and you don't actually need the barycentric coordinates themselves), then your problem becomes much easier; you can simply look at the equations of your line segments and find the intercepts with the horizontal span containing your test point, then check whether it falls between the two ends.

For instance, if the coordinates of your points A, B, C are (Ax, Ay), (Bx, By) and (Cx, Cy) with (Ay=Cy and Ax \< Cx and By \< Ay, akin to your illustration - note that I'm pointing positive Y in the down direction!) then the line segment through A and B is defined by `x=Bx+(Ax-Bx)*(y-By)/(Ay-By)` (you'll never divide by 0 here because we explicitly said that By \< Ay, and you can confirm that plugging in y=Ay and y=By gives the correct values of x); likewise, the line segment through C and B is defined by `x=Bx+(Cx-Bx)*(y-By)/(Cy-By)`. Once you have those two lines, you can just test to make sure the x position of your test point is between the two segments' values at its y:

```
bool TestPointInHex(point pt, point A, point B, point C, point D, point E, point F) {
  if ( (pt.y < B.y) || (pt.y > E.y) || (pt.x < A.x) || (pt.x > C.x) )
    return false;
  if ( (pt.y >= A.y) && (pt.y <= F.y) )
    return true;
  if ( pt.y < A.y ) {
    float leftX = B.x + (A.x-B.x)*(pt.y-B.y)/(A.y-B.y);
    float rightX = B.x + (C.x-B.x)*(pt.y-B.y)/(C.y-B.y);
    return ( (pt.x >= leftX) && (pt.x <= rightX) );
  } else { // pt.y > F.y
    float leftX = E.x + (F.x-E.x)*(pt.y-E.y)/(F.y-E.y);
    float rightX = E.x + (D.x-E.x)*(pt.y-E.y)/(D.y-E.y);
    return ( (pt.x >= leftX) && (pt.x <= rightX) );
  }
}

```

# Answer
> 1 votes
Thanks to @mikael-hogstrom 's answer, here's a function I created for the purpose:

```
/**
 * Checks whether point `p` is inside triangle `abc` based on barycentric
 * coordinates.
 *
 * @param {Number} px x of p
 * @param {Number} py y of p
 * @param {Number} ax x of a
 * @param {Number} ay y of a
 * @param {Number} bx x of b
 * @param {Number} by y of b
 * @param {Number} cx x of c
 * @param {Number} cy y of c
 *
 * @return {Boolean} A boolean indicating whether p is inside abc
*/
function isPointInsideTriangle (px, py, ax, ay, bx, by, cx, cy) {
        var v0x = bx - ax
        var v0y = by - ay
        var v1x = cx - ax
        var v1y = cy - ay
        var v2x = px - ax
        var v2y = py - ay

        var d00 = v0x * v0x + v0y * v0y
        var d01 = v0x * v1x + v0y * v1y
        var d11 = v1x * v1x + v1y * v1y
        var d20 = v2x * v0x + v2y * v0y
        var d21 = v2x * v1x + v2y * v1y

        var denom = d00 * d11 - d01 * d01

        var v = (d11 * d20 - d01 * d21) / denom
        var w = (d00 * d21 - d01 * d20) / denom
        var u = 1.0 - v - w

        return u >= 0 && v >= 0 && u + v < 1
}

```

I think I'll just optimize it later if necessary. :)

Here's a silly test page to try it in action: http://labs.avd.io/bary.html

Thanks to everyone for the help!

---
Tags: mathematics, coordinates, barycentric-coordinates
---


# Question
Title: How are lights rendered as geometry in deferred shading?
1. So my problem is that: At the last stage of implementing this I had problem with this sentence, " the lights in the scene are rendered as geometry". What does this mean?
2. Why do I store depth info for the model in an earlier stage?
3. What is texture projection ?

I had try to read many tutorials, but every time I end up coming here because I find what I need.

# Answer
1. "The lights in the scene are rendered as geometry" means that you draw a polygon mesh that encloses the light's region of influence. For example, if it's a point light you draw a sphere of the light's radius. For a spotlight you draw a cone, etc.

The reason to do this is you are trying to select exactly those pixels on the screen that the light will have an effect on. You *could* simply render each light as a full-screen quad, hitting every pixel on screen; you must do this for a directional light, since it has no finite region of influence, but for point and spot lights this would be very inefficient, because in many cases, the light will only affect a few pixels, so you waste a lot of time processing pixels that have no effect from the light.

By drawing a mesh in the shape of the light's region of influence, you put the GPU to work to pick out just the pixels you need to draw.

2. To evaluate the lighting equations for a pixel, you need to know where that pixel is in space. It's possible to store the world-space position in a floating-point G-buffer, but that's wasteful. The world-space position of a pixel can be reconstructed from its screen-space XY position and the depth buffer, using a little math. The depth requires much less space than the full position. You store depth so you can reconstruct position later.

3. Texture projection is a method of generating UVs for a texture map that make it look like the texture is being projected onto the geometry, such as by a film projector. In the context of deferred shading, texture projection can be used to project full-screen buffers (G-buffer, depth buffer) from the camera onto the light source geometry, generating UVs that match the screen-space XY coordinates, so that each pixel drawn will sample exactly the same pixel in the full-screen buffers. However, the `VPOS` pixel shader semantic (in D3D9 HLSL) can be used to get the screen-space position of the pixel directly. Texture projection is also used when applying a spotlight shadow map.
> 5 votes

---
Tags: xna, deferred-rendering
---


# Question
Title: Ray Picking: how can I find which copy of model to pick, if they share the same vertices, but each one is translated before being drawn?
I have a scene, in which I am drawing few different objects - each one has the same vertices and each one is translated to proper place before being drawn.

While using libgdx (but I think that this question should be generic enough to work with other libraries), I try to do ray picking, casting ray and trying to find intersections of given ray with triangles, from meshes of each object. My problem is, that because they all share the same set of vertices, how should I find which one exactly was pointed by user?

As I have no experience in this, I was thinking about translating the vertices for each object and getting rid of glTranslate(x, y, z) called before each one, but in that situation I won't be able to use one copy of mesh to work with all objects.

May I ask for a few hints / links to articles how this should be done?

# Answer
Are you using bounding volumes for your objects?

If yes then you could do something like this:

```
boundingVolumes = GetBVIntersection(ray)
foreach boundingVolume in boundingVolues
    (the model associated with the boundingVolume).Transform = boundingVolume.Transform
    triangles = GetTriangleIntersection(ray, model)

```
> 3 votes

# Answer
Translate the ray to be in the origin of the model (inverse transformation used to render the models) and then test the ray.

Keep the closest point of each hit (if any) and return the point/instance with the smallest distance.

No need to transform every point of the models or to move the transformation off the GPU.
> 1 votes

---
Tags: opengl, java, 3d, android, libgdx
---


# Question
Title: How to bounce a 2d point particle off of a circular edge
In a prototype I'm building, a particle can spawn anywhere within a larger, confining circle. Important to note is that the particle will not spawn in the origin of the larger circle, but anywhere within it.

This particle will essentially be given a random x and y velocity and set on it's way.

When the particle hits the edge of the confining circle, I want it to bounce back inwards appropriately.

Unfortunately I'm extremely new to vector math, and have never really directly dealt with it before.

Given that I'm treating the particle as a point, and I don't care about any loss of force or friction, what should I ultimately do to the particle's x and y velocities after the bounce?

I will know the particle's x and y velocity, it's x and y coordinate when it hits the outer circle, the radius of the outer circle, and the x and y coordinates of the origin of the outer circle (since its origin will likely not be 0,0).

My brief research on vector math tells me I need to find the normal velocity at the point where the particle hits the outer circle and then negate that, but unfortunately I'm not sure how to do that exactly.

# Answer
What you want to do can also be thought of as reflecting the particle's velocity off the plane tangent to the circle at the point of contact. If you know the equation for doing that, then all you need to know is the circle's normal at the point of contact. To get that, all you need to do is normalize the vector from the center of the circle to the point in question.

---

A property of circles is that the vector from any point on the circle to the center of the circle is orthogonal to the tangent line of the circle at that point. (In other words, the magenta lines are always at a right angle to each other.) And the easiest way to describe a plane is a normal vector (a vector orthogonal to every vector in that plane), which is easy enough to compute and turn into a unit-length vector.

At this point you can think of the problem as reflecting the velocity vector **v** across the plane with normal **n** (unit-length). The formula comes from taking the length of the projection of the vector **v** onto the line **n**, which is the dot product **n** · **v**. So the part of **v** that is perpendicular to the plane (the perpendicular component) is (**n** · **v**) **n**. The "rest" of it is the parallel component: **v** \- (**n** · **v**) **n**. If we sum those two components, we get back to the original vector:

> **v** = \[**v** − (**n** · **v**) **n**\] + \[(**n** · **v**) **n**\]

The reflection is the that same expression, but with the perpendicular component negated:

> **r** = \[**v** − (**n** · **v**) **n**\] − \[(**n** · **v**) **n**\]

And simplified:

> **r** = **v** − \[2 (**n** · **v**) **n**\]
> 11 votes

---
Tags: physics, vector, particles
---


title: Special relativity shader in GLSL

text:
# Question
Title: Special relativity shader in GLSL
I'm trying to implement a GLSL shader which helps understanding special relativity Lorentz Transformation.

Let's take two axis-aligned inertial observer `O` and `O'` . The observer `O'` is in motion w.r.t observer `O` with velocity `v=(v_x,0,0)`.

When described in terms of `O'` coordinates, an event `P' = (x',y',z',ct')` has transformed coordinates `(x,y,z,ct)= L (x',y',z',ct')`

where L is a 4x4 matrix called Lorentz transformation which helps us writing the coordinates of event P' in `O` coordinates.

(for details look http://en.wikipedia.org/wiki/Lorentz\_transformation#Boost\_in\_the\_x-direction)

I've wrote down a first preliminary vertex shader that apply the Lorentz transformation given the velocity to every vertex, but I can't get the transformation to work correctly.

```
vec3 beta= vec3(0.5,0.0,0.0);
float b2 = (beta.x*beta.x + beta.y*beta.y + beta.z*beta.z )+1E-12;
float g=1.0/(sqrt(abs(1.0-b2))+1E-12); // Lorentz factor (boost)
float q=(g-1.0)/b2;

//http://en.wikipedia.org/wiki/Lorentz_transformation#Matrix_forms
vec3 tmpVertex = (gl_ModelViewMatrix*gl_Vertex).xyz;
float w = gl_Vertex.w;

mat4  lorentzTransformation =
        mat4(
            1.0+beta.x*beta.x*q ,   beta.x*beta.y*q ,   beta.x*beta.z*q , beta.x*g ,
            beta.y*beta.x*q , 1.0+beta.y*beta.y*q ,   beta.y*beta.z*q , beta.y*g ,
            beta.z*beta.x*q ,   beta.z*beta.y*q , 1.0+beta.z*beta.z*q , beta.z*g ,
            beta.x*g , beta.y*g , beta.z*g , g
            );
vec4 vertex2 = (lorentzTransformation)*vec4(tmpVertex,1.0);

gl_Position = gl_ProjectionMatrix*(vec4(vertex2.xyz,1.0) );

```

This shader should apply to every vertex and perform the non-linear Lorentz transformation, but the transformation it performs is clearly different from what I'd expect (in this case a length-contraction on x-axis).

Has somebody already worked on special relativity shader for 3D videogame?

# Answer
To implement Lorentz contraction, your best bet is probably just to explicitly scale the object by 1/gamma along the direction of motion.

The trouble is that the Lorentz transformation displaces vertices in the time direction as well as in space, so by itself it will not give you what a moving object looks like at a specific moment in time. To do that, you would have to first transform the whole object then take a "slice" through it parallel to the space axes, like in this diagram:

To calculate this for real, you'd effectively have to raytrace in 4D, intersecting the world-line of the vertex with the 3D hyperplane of the current moment of time in the observer's reference frame. I believe the result of doing this is the same as simply scaling by 1/gamma.

(For extra credit, take into account the fact that an observer wouldn't actually see the whole object at a single moment in time: they'd see it using light rays. So you'd need to intersect the world-line of the vertex with the past light cone of the observer. This actually changes the results significantly: an object moving away from you will look shortened, but an object moving toward you will appear elongated and an object moving sidways will be *rotated* \- see Penrose-Terrell rotation for more.)
> 4 votes

---
Tags: shaders, glsl, vertex, transformation
---


# Question
Title: What's the name of the rendering problem I describe here?
I don't remember how is it called that rendering problem that you have when you get fast movements (a sprite moves fast for example from right to left) and you have half of the image in a position and half in another for a given frame (for example the top left of the sprite moves correctly but the bottom half of the same sprite is lagging back).

In particular I'm using SFML2 but this is kinda a Library-Agnostic question.

And what are the most common methods to fix it?

# Answer
You are probably referring to tearing. You should enable VSync and/or use multiple buffering.
> 8 votes

---
Tags: c++, rendering
---


title: Convert map of USA to isometric format

text:
# Question
Title: Convert map of USA to isometric format
How can I convert the map of the US to isometric format. How do you ensure that the angles that you are making are perfect? I mean in isometric maps even slight errors can cause difficulty.

Also any idea how do I ensure that the map is readable (understandable) in Isometric format?

I want to know how to draw the lines of the states to ensure that they are correct.

# Answer
> 7 votes
A possible solution is to use a heightmap of the usa, for example:

OpenTTD Heightmaps

However this may be a little big anyway you could then read this image pixel by pixel creating a tile with that relative height for that shade of color.. so say White (highest) and black is 0 (Lowest / Sea level) producing an accurate height listing of usa.

since you now have a array of heights you have no issues on the angle of isometric tiles

**EDIT**

It is important to remember the HeightMap above is not seen in your game but read by your game to generate the tiles. (In this case this heightmap would need to be rotated by the angle of your tiles (i.e. like 45 degs)

When creating isometric tiles all the tiles ideally are the same angle rotated.

The Red/Blue line that intersect in center of the tile is the "Plane" the maps 0 height reference so in this case your sea level could be at this height. as the shade gets lighter you could increase height however this will make the terrain impassible as there no way up. To rectify this you would use a slope tile which is a block which is designed to look like the slope and can not be facing directly towards the viewport.

Here is an example of all I describe but you have to use your imagination to see that even tho it looks like blocks once textures are on it will look more realistic.

**UPDATE**

I was digging around and noticed Age of Empires 2 using a similar method to above (increasing the y coord of the tile) but also uses shading to darken inclines works well i think.

Hope this helps

---
Tags: isometric
---


# Question
Title: Shaking objects near correct position (with video)
All right, so I'm testing two box objects. One is standing fixed in a position and another at the beginning of the program goes to the first one. And at the end the latter should stand completely over the first (so the center of both is equal).

Here's my method in the Object class:

**Old code**

```
void Object::moveTo(Point _p) { // _p is always the center of the other object we want to go to

    // adjust speed, don't worry it's not important here, I guess
    if (current_speed == 0)
        current_speed = speed/16;
    else if (current_speed >= speed)
        current_speed = speed;
    else
        current_speed *= 2;

    // we want to calculate the new center of the
    // our object (the one that run this method)
    Point center;
    // distance(x) calculate the distance between the center point of the object and
    // the x point passed
    if (distance(_p) <= current_speed) {
        // we don't want shaking things!
        center = Point(_p.x, _p.y);
    } else {
        // move diagonally
        center.x = getCenter().x + current_speed*std::cos(angle(_p)); // angle calculates the angle between the center of the object and the _p point
        center.y = getCenter().y + current_speed*std::sin(angle(_p));
    }
    // since we draw sprites by the top left corner we need to convert
    // the center point to the correct top left point
    center = toPosition(center);
    sprite.setPosition(center);
}

```

**New code**

Notice that the origin of the sprite is set to be in the center so `setPosition` will correctly set the center and that `getCenter()` returns `sprite.getPosition()` which is the center point.

```
void Object::moveTo(Point _p) {
    Point center;
    //std::cout << distance(_p) << std::endl;
    if (distance(_p) <= speed) {
        center = Point(_p.x, _p.y);
    } else {
        center.x = getCenter().x + speed*std::cos(angle(_p));
        center.y = getCenter().y + speed*std::sin(angle(_p));
    }
    sprite.setPosition(center);
}

```

This is what happens: http://youtu.be/Ngra3FXFe0A.

The distance keeps going from 15.xxx to 16.xxx and I don't know why.

**Testing surprise**

* Doing `distance(_p) <= 10` instead doesn't make it shake. With 9, 8... or minor it shakes.
* Defining a minor `speed` the object gets nearer the correct position before start shaking.
* Setting the white cube to follow the player (yellow sprite) it moves like a jagger: http://youtu.be/9FjRfHHprEQ
* Here's a recent video: the 3 little squares points (its the specific top left corner) to: blue = box center, red = player center, green = top left corner of the box. As you can see they are correctly calculated (this test was made with speed of 1, while the others were made with a greater speed): http://youtu.be/iFAWGssk7NI

**Distance function:**

```
float Object::distance(Point _p) {
    return sqrt((pow((getCenter().x - _p.x), 2) + pow((getCenter().y - _p.y), 2)));
}

```

**Angle function**

```
float Object::angle(Point _p) {
    //  (180 / PI = 57.3065)
    return 57.3065f * atan2(getCenter().y - _p.y, getCenter().x - _p.x);
}

```

Why is that?

# Answer
Do you know guys what the problem was? This: `57.3065f`. This makes the `angle()` function returns degrees. And this was bad because `std::sin` and `std::cos` expects radians to be passed.
> 0 votes

# Answer
It's clear that the simple 'new' code posted doesn't have a significant problem - the angle calculation looks correct, and as soon as the object would get within range, the position will be set to \_p.x, \_p.y, which is exactly where it needs to be. The only reason this would ever jitter is one of the following:

1. current\_speed hits zero when distance(\_p) is non-zero (perhaps due to floating point error), meaning the sprite moves a full amount again - this seems the most likely problem in the 'old' code, but you don't show how you calculate current\_speed, and it's not even in the 'new' code;
2. distance(\_p) changes even when \_p and the sprite's position are constant;
3. \_p is not constant, and something is periodically changing it, even when the object appears to be still;
4. the following sprite's position is not constant, despite being set to equal \_p - perhaps something else moves the sprite;

One way you can reduce the jitter is to remove the "move or don't move" test and instead scale the movement amount proportional to the distance to the target. You don't need an angle at all - just calculate the movement vector (your current argument to atan2() in angle()) and if the length of the vector is more than your speed, scale it down to that size. Otherwise, leave it as it is. Then add that vector to your sprite's position to apply the movement. It's impossible to overshoot that way because the length of the movement is never bigger than the distance to the target.

But don't do this until you find the problem in your code that is causing the issue, otherwise you'll just be hiding a bug rather than fixing it!
> 1 votes

# Answer
In this part:

```
    center.x = getCenter().x + speed*std::cos(angle(_p)); // angle calculates the angle between the center of the object and the _p point
    center.y = getCenter().y + speed*std::sin(angle(_p));

```

I think you want `current_speed` instead of `speed`.
> 0 votes

---
Tags: c++, sprites, movement
---


# Question
Title: Javascript and PHP for real-time multiplayer?
I'm wondering if combining Javascript clientside with PHP/mysql serverside is a good idea for HTML5 real-time multiplayer (small scale) browser games?

My technical knowledge is very limited, and even though I plan on learn node.js in the future, the learning curve is rather huge right now.

Since I'm already familiar with PHP I feel I would get it functioning much faster.

The scale I'm thinking is 2-8 players at the time. And trying to keep the client to server message count as low as possible.

The values I intend to store/handle are:

* Player name and ID.
* X and Y position.
* Health.
* Equipped items (maximum 8 slots, probably less).
* Actions (walk, attack, use etc but only 1 action/player at a time).
* Bullet X,Y coordinates and trajectory.
* Guild/Clan name.
* And some basic chat/mailing function.

My guess is even though it's not the best solution, but aslong as I keep the logic small, that this is completely doable. Am I right?

# Answer
> 12 votes
For a real-time game, you want to minimize latency. Here's two tips for achieving it, with notes about PHP and Node:

1. Use WebSockets. They allow fast two-way communication between the server and the client. Using node.js here has the advantage that you can use the same JavaScript API on both ends of the pipe. There's also the wonderful socket.io module for node.js that provides fallback technologies to lesser browsers that don't support WebSockets. Googling a bit, it seems you can also use WebSockets from PHP if you really want to.
2. Don't involve database in time critical data such as coordinates of fast moving objects. This means keeping them in memory, which is not particularly well suited for the traditional PHP use model of having it fire once for each request to apache (or whatever web server), but you can launch your PHP server app also as standalone. I'd guess Node, with its V8 core, is going to be faster than PHP though. Whether that's an issue depends on how demanding your game is and how powerful the server is.

I myself find node.js very easy to pick up and since you are going to need to code quite a bit of JavaScript anyway, I'd recommend you try it. At least take a quick look at the socket.io tutorials to see how trivial it is to set up a real-time communication channel.

# Answer
> 1 votes
Along with Tapio's answer I would like to suggest to only (if possible) send user input (clicks and keyboard input) to the server, and having both server and client emulate the game. Every N ticks the client would ask the server for a sync, and the server will reply with all the information the client needs to render the game such as health, items, etc. This is to make sure the client doesn't get desynchronized too much.

Of course both the server and the client will need to have the exact same implementation of the game so this might be a bit more work. If you have perfect implementations on both client and server, the client will need to sync less often.

This will reduce client/server messaging and this reduce latency. This would also help prevent cheating.

Assuming you are creating this game in JavaScript, it might be worthwhile to write the back-end in JavaScript as well, using NodeJS. This way you could reuse the JavaScript implementation of your game for both the server and the client.

# Answer
> 0 votes
I recommend learning Nodejs. If you already now Javascript, it won't be so difficult. I made a TRON Multiplayer game quickly with Nodejs, and it was my first day using it. (Oh, and the client was an HTML5 canvas; I was only sending key input, as mentioned in the other comments.)

Take a look at a module called nowjs. Good luck!

---
Tags: javascript, networking, html5, client-server, php
---


# Question
Title: How do I configure the clipping region when drawing with XNA's SpriteBatch?
I have a `SpriteBatch` that is set to draw to a `RenderTarget2D` that is 500 pixels larger in both height and width. Whenever I draw to a point outside of the physical screen dimensions, it will not draw the object.

I am performing some 3D transforms on the texture so I need the areas outside the screen to be drawn. I have tried setting culling to `None` and this had no effect.

# Answer
> 1 votes
Modify the `Viewport` on your `GraphicsDevice` before drawing to your `RenderTarget2D`.

```
GraphicsDevice.SetRenderTarget(myRenderTarget2D);
GraphicsDevice.Viewport.Width += 500; //or a more sensible calculation
GraphicsDevice.ViewPort.Height += 500;
GraphicsDevice.Clear(Color.Transparent);
//Spritebatch operations

```

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.graphicsdevice.viewport

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport\_members

---
Tags: xna, spritebatch
---


title: Current library situation

text:
# Question
Title: Current library situation
Allright so I've been doing some searches, here what I got:

* SDL: It is a standard, very mature but very old. (I got posts of late 2009 where they were still waiting for the 1.3 to come up...we are still waiting 3 years later). Also it seems abandoned and old style (it's around from the '98). And also it's made in C (for this there's no downside nor upside. Someone prefers C over C++ nowadays for some reason and C can run on C++ but not viceversa).
* SFML: It's a new born in the libraries. It's not very mature and lack of a lot of documentation. It was buggy till 1.6 but now the 2.0 is quitely good (it's the one I've tried). It has a lot of things built in (even the possibility to easily use OpenGL). It's in C++ and has the OOP paradigm.
* Allegro: I haven't heard much about it. It gives me the idea of a toy, but it's not an opinion I count on. It is C based (like SFML) but doesn't have that large community (like SFML).

I'm considering only cross platform libraries. Now I'd like to make few questions about this situation:

1. Is SDL falling apart?
2. Why isn't SDL being update to the so awaited 1.3 (which will, they say, support iPhone and phones) in 3 years?
3. Is SFML gonna take SDL place?
4. Why people say that SFML is more abstract then SDL? It seems pretty much the same to me. You have likely all the configurations you want on both.
5. Allegro had a troubled story. It was only for DOS, then it was ported for other platforms etc... Is it really cross platform?
6. How stable is Allegro?

Thanks.

# Answer
If I had to choose from that list, I'd definitely gun from SFML as it has a simple API and allows you to implement much of it yourself, a great learning experience. I'd like to just chime in and say SFML is simpler and sticks to what it needs to do. A base framework for rendering things.

I think you should also consider the new contender MonoGame (http://monogame.codeplex.com/) OpenGL and written on .NET, it runs on Mono pretty much everywhere =) It has a beautiful API based off of XNA and does a lot of the work for you such as game loops and the really redundant stuff we all end up writing ourselves, anyway.
> 6 votes

# Answer
I currently use Allegro 4.x, it has some flaws that I had to manually work around, but since then they've released 5.x that overhauled the entire API and fixed all the problems I was having to fix.

Allegro 4.x is very stable (as in, no longer being developed) because the entire community suggests that if you are just starting with it that you start with 5.x which fixes all the problems with 4.x and is still cross-platform.
> 3 votes

# Answer
Allegro 5 is quite adept - I like it personally. The initialization code is simple to use, and easy to stuff away in a class or an Init() function. Really, if you write a wrapper function or class, you won't even have to directly call anything from any of these libraries.

Are you interested in game graphics or game development? Because if you want to make games, you should just pick one of these libraries and run with it. I'd only sweat these small steps if you're particularly interested in learning the nitty gritty of graphics development.
> 3 votes

---
Tags: c++, sdl, sfml, allegro
---


# Question
Title: What is the proper term for "permanent world"?
How to name the fact that for a MMO game there's one big session, the same things are happening for all the players, you log out and after two days log in to the same place as the same person ?

I'd like to mention that not all MMO games are constructed this way, for example majority of MMOFPS games are based on lobby/separated severs system, so prefix "MMO" isn't necessarily equal to "onesessionism".

I myself can't think of any better expression than "permanent world".

# Answer
It's "persistent world".

Also note that there is phasing, the world is usually divided into many zones all ran on different servers. Also, this isn't really gamedev related at all.
> 13 votes

# Answer
I've also come across terms like **open world** and the opposite

> lobby/separated severs system

as **matchmaking**.
> 0 votes

---
Tags: mmo, first-person-shooter, terminology
---


# Question
Title: Predicting physics/trajectory for pool/billiards games
I'm thinking of making a quick proof of concept of a billiard-style game mechanic, where the player has perfect information of what is about to happen. Here's a good example:

I'm only mildly familiar with physics in both Unity and Flixel-Box2D, and I can't really off the top of my head imagine how to do this.

Should I even use physics at all, or should I just use basic math?

# Answer
> 5 votes
To generate those lines you need to run the complete simulation of the whole shot every frame, as if you'd just hit the cue ball. This requires keeping two copies of the table state - one for display and one for simulation. For each frame of the simulation you just store the position of each ball, and at the end use that data to draw lines with. This simulation wants to happen quickly enough to maintain an interactive frame rate, although you can work round spikes in compute time with a thread.

The physics for a basic 2D simulation aren't too complicated if you don't care too much about accurately simulating a real pool table. It gets significantly harder to simulate it well when you take in to account jump shots and swerve shots as the balls can then move along curves instead of straight lines. The shot where you break the pack is also difficult to simulate correctly as there are going to be lots of touching, or almost-touching balls, which may trip up a physics simulation.

I'd suggest trying out a few physics libraries to see which one gives you the best results. Setting up a box full of spheres and hitting one of them should be fairly simple in any decent physics engine.

---
Tags: physics, mathematics, billiards
---