title: How are buttons made to be clicked?

text:
# Question
Title: How are buttons made to be clicked?
I just want to ask a general question. According to that answer, I'll continue thinking.

You know in games there are lots of clickable items. Play button, exit, combo-boxes, etc.

My question is: Are those buttons drawn in same canvas with background and all other things, or for every different thing there is another canvas object?

My question is a general sense. I'm not asking about a specific game, I'm asking how they are made generally.

I'm planning to start a game on Android, and I'm confused actually how to design buttons, and other object. Probably I'm going to use View/SurfaceView for now. I don't have much experience with OpenGL yet.

Thanks in advance.

# Answer
> 2 votes
If you are going to use the Android APIs (such as Canvas) for graphics and insist on not starting with OpenGL yet (a wise choice for a beginning programmer), you are only going to have one canvas object with multiple images drawn using drawBitmap(). In onTouchEvent() determine if the touch was inside the bounds of your object and, if so, call the necessary method. Good luck!

# Answer
> 2 votes
I think what you are talking about is a GUI Skin. There are a few ways to do this: A common way is for a designer to create all the textures, pack them into a texture atlas (using something like SpriteSheetPacker or TexturePacker) , and generate a text file (called a map) which gives you the coordinates of each frame present in the atlas, which is then used by your GUI system.

Here is an example of a Miyagi skin used with the atlas below (click for full size):

Another workflow when designing GUI skins involves working with 'look and feel' elements - This is when a base design is created, and all GUI controls (eg panels, buttons) you create will use this design. Think of the theme you are used to for Windows/Mac/Linux applications. Scroll through this site for a quick idea on what I mean, and see here for more info. (I don't have much experience with working with look'n'feel). Also read up on look and feel programs for working with WPF if you are interested.

Since you want to make an Android game, I'd also recommend using an existing API for graphics (or a game engine API). Look around for a good GUI API, it will make your life much easier when working on the user interface.

Good luck! :)

# Answer
> 0 votes
There are different techniques for simulating button click and the easiest three which I use are:

1. Have 2 different images - one for normal button and another for pressed button. Then you draw `pressed` image when TOUCH DOWN event is registered on the button and `normal` when TOUCH UP is registered on the button or if not clicked at all
2. Draw the button with displaced coordinates when pressed. If you have a button at x = 50, y = 50, when `pressed` draw it on `x+5, y+5` and when `normal` draw it on `x, y`. This is the simplest and generally looks good.
3. Scale down the image of the button a little bit when `pressed`. E.g. normal -\> scale = 1, pressed -\> scale 0.9 This looks good and provides a nice 3D effect when pressed.

---
Tags: android
---


# Question
Title: How can you easily determine the textureRect for tiled maps in SFML 2.0?
I'm working on creating a 2d map prototype, and I've come across the rendering bit of it. I have a tilesheet with tiles, each tile is 30x30 pixels, and there's a 1px border to delimitate them.

In SFML the usual method of drawing a part of a tilesheet is declaring an IntRect with the rectangle coordinates then calling the setTextureRectangle() method to a sprite.

In a small game it would work, but I have well over 45 tiles and adding more every day, I can't declare 45 intRects for every material, the map is not optimized yet, it would get even worse if I would have to call the setTextureRect() method, aside from declaring 45 rectangleInts.

How could I simplify this task? All I need is a very simple and flexible solution for extracting a region of the tilesheet.

Basically I have a Tile class. I create multiple instances of tiles (vectors) and each tile has a position and a material. I parse a map file and as I parse it I set the materials of the map according to the parsed map file, and all I need to do is render.

Basically I need to do something like this:

```
switch(tile.getMaterial())
{
   case GRASS:
       material_sprite.setTextureRect(something);
       window.draw(material_sprite);
       break;

   case WATER:
       material_sprite.setTextureRect(something);
       window.draw(material_sprite);
       break;

  // handle more cases
}

```

# Answer
> 1 votes
I was looking at the documentation. Far as I can tell, a sprite has a pointer to its texture, which in this case would be the tilesheet. I assume you declare this once somewhere, not per render, in which case all is well. I assume you would use one sprite as it sees you are suggesting, so that leaves only the IntRect's. As far as I can tell, though, you only need one IntRect per tile TYPE. For example, say you have two tiles, GRASS and WATER. So you would need two IntRect dictating where in the tilesheet the tile's texture is. I assume you would also declare this beforehand and not every render.

When rendering, then - and in whatever render function/thread/etc have you, the tilesheet and IntRects need to be in scope - you can declare a sprite - or just use one potentially declared before like the above - and set its texture as the tilesheet. (so perhaps having the sprite declared beforehand would be good). Then, by case, set the correct texture rect and position (you could have the grass tile, but you also need to draw it where the tile is on the screen), and draw it.

Note that I have not tested this myself. As far as I can tell, you do not need 45 IntRects per tile type, and I don't think this is to bad optimization wise, although this approach takes a toll on memory.

I don't think you would need more than one IntRect per tile, as your tilesheet should never change at runtime.

Edit after comment:

Your right, that would be a problem. I don't think there is a way around it unless you don't move the other tiles and make them independant of each other (leaving empty space). Although, assuming your tilesheet is perfect, you might be able to hold the IntRects in an array, which is created whilest looping. (you could then have an Enum which dictates which index is which).

As per declaring IntRects... the setTextureRect argument needs one, thus you need at least one. But somewhere, perhaps as defined/constant/magic numbers, but that is not very efficient either. Perhaps, though, you could... automate the process. Say, your tilesheet is x tiles by y tiles. You make an enumerated value for each tile. You can set IntRects either beforehand or at render (probably not to fast the latter way). Since you know how many tiles wide and high it is (given the texture and tilesize you can calculate this at runtime so changes don't break it), you can go from left to right, and upon grabbing the last tile, drop down a row, and so on. For each one, you fill an IntRect,, hopefully in an array of IntRects, with the coordinates of that texture.

Now, you would need an enum, with the tile values, like WATER, GRASS etc. Put them in the order the algorithm would fetch them - say, if it looks like this:

WATER, GRASS, SAND, ROCK, ICE, SOMETHING

then the enum is like:

```
enum TileType
{
    WATER,
    GRASS,
    SAND,
    ROCK,
    ICE,
    SOMETHING,
    NUM_TILES
};

```

Note that last one is optional, but it allows you to know how many tiles you have (assuming you don't modify it and it goes sequentially starting from 0), which might be useful.

Then, to access the according texture for a tile, you could go, say, intRects\[WATER\], and then it would access the water tile. Assuming you change the tilesheet, making sure to leave no enclosed holes, then you can simply change the order of enums. This is also where NUM\_TILES can come in handy, if you have an unfinished row for instance, so you can still collect it correctly. Assuming that works (this is speculation), I think this is decent from a maintenance. Worst part is adjusting the tilesheet, but once you have done that the worst is over, in theory.

---
Tags: c++, graphics, maps
---


title: How to protect Lua scripts in IOS game?

text:
# Question
Title: How to protect Lua scripts in IOS game?
I'm developing an iOS game and was considering putting level info and monster info in a Lua script for ease of use. However, since I'm using Game Center for multiplayer I'm concerned users will attempt to change these scripts to cheat. What measures can I take to protect my Lua scripts?

# Answer
One approach you can do is use the program `luac` to compile your scripts to bytecode. This provides an extra layer of obscurity. These compiled lua scripts can be loaded just like a normal text based script. Make sure you keep a text copy of the scripts that you compile however.

I believe luac is built when you build Lua from source. Also note that luac compiles scripts differently based on the platform it was built on, so don't, for example, use luac on windows to compile your scripts.

Read more about luac here http://www.lua.org/manual/4.0/luac.html

That provides one layer of security. You could add extra layers by say, archiving your lua scripts into another file format which would be opened and read by your program. I'm not very experienced with this however.
> 3 votes

# Answer
The same steps you would take to protect any data. Lua isn't special just because it's text. If you need the user to be unable to easily modify the data, employ some encryption. The more complex the encryption, the more difficult it will be for them to deprocess it.

However, as I understand iOS (which is admittedly not much), you probably don't have much to worry about from casual cheating. Users can't easily inspect an application's private data. So I wouldn't be concerned.
> 1 votes

# Answer
Your lua scripts are not autonomous, they are likely loaded by a bootstrapping mechanism and hardcoded along with your binary. You can run a simple md5 hash on the scripts and verify the hash matches before loading.

Having said that, to change the scripts an end user has to jailbreak the device to break the signing of your app, which means they are in theory also able to hijack the md5 checking code... as another answer said, it's a matter of how much effort you want to force your end users to go through to hack it and how much it forces your development to go through hoops.
> 0 votes

---
Tags: iphone, ios, lua, anti-cheat
---


title: Do games use threads?

text:
# Question
Title: Do games use threads?
I 'understand' that the concept of how a game runs i.e

```
while (game_loop = true)
 {
  //handle events
  // input/output/sound etc
 }

```

But it has come to my attention while programming in another HLL is do some games use threads for certain operations? For example take any Pokemon game ; during interaction a textbox appears to display information. Now I've been trying to simulate that sort of textbox and the only way I could have got it to be exactly the same is by using a loop and yes once a loop is started there is no way to handle window events unless they are handled again inside the loop itself.

I couldn't have used this loop inside a different thread other than the main one (due to a DirectX limitation) so the only option was to use it inside the main program thread. I was wondering if some games work like this ; do they only use the main program thread and handle events again if they're inside a loop?

Edit: I forgot to mention this is about console games not PC games!

Thanks Nubcake

# Answer
Up to these days threading in games can still be described as not very mature. It is mostly used for *island* calculations like sounds, physics, particle-systems, I/O, path-finding etc, stuff that can be easily *outsourced* from the main-thread without running into too many locking problems. Yet the main game entity update chain is very hard to distribute over multiple threads with current state of the art engine designs.

Unfortunetly there is still no language available on consoles (or in the general game development scene) that has the concept of threads in its very language design, like for instance Erlang has it. This is long overdue in my point of view.

The PS3 tried to adress that issue with its SPUs, but overall it's pretty much fair to say that it's concept didn't exactly succeed for the majority of the developers with some exeptions like for instance Mike Acton. Making properly use of the SPUs meant completely rewriting big parts of the engines for only one platform, making cross platform development even harder. Only some PS3 exclusive titles could really afford to go that route.

It's very interesting to see where it's going with the next gen consoles, since simply adding more cores only helps if we find better concepts of really making use of them, other than 1 big main game thread and some small low priority worker threads.
> 4 votes

# Answer
Of course many games use threads. It's impossible to make full use of modern hardware without them. The XBox360 has three cores, many phones have two or four cores, and PC's are typically shipping with four cores and up these days. Without threads, games would be stuck using only ~25%-50% of the hardware. Some platforms even require the use of threads to accomplish certain tasks.

That said, the problem you're referring to with the text box is a horrible place to consider using a thread. It's also a horrible place to use a loop. You want to look into event-driven programming for solving problems like these.

The basic idea is that you create some kind of object or other data and register it with a manager to note that there should be a texbox open. Your main loop can then update any open text boxes, such as redrawing them or updating their contents. When the text box no longer needs to be there, you simply destroy the object and deregister it from the manager. There's no need for a thread, the problem with loops can be entirely eliminated, and the model is pretty much necessary for doing more advanced games features.
> 4 votes

# Answer
For the type of text box you're talking about, you don't need to resort to a new thread.

It sounds like what you're talking about is putting a loop inside your main game loop that continues until the text box goes away, the problem with this course of action being that everything else in said game loop cannot progress until that loop finishes.

Your game loop is going to be set up to be one frame\* of time, so nothing that takes multiple frames should block it. Instead of putting a loop inside of the game loop what you will want to do is allow the logic to, instead of updating general game logic, update the textbox logic one frame and use the game loop as the textbox's loop. Through whatever methods you prefer, you'll want each run through the game loop while the text box is up to look something like

```
BeginGameLoop
     HandlePreLogicSystemStuff()  //Input and other stuff needed for the logic
     HandleTextBox()
     HandleEndOfFrameSystemStuff()  //Drawing and other output from frame
EndGameLoop

```

This could be as simple as putting an if block in there so if you're in text box mode you just update the text box logic and not the Move/Shoot/DanceParty logic you'd normally be running.

To answer your title question though: **Yes games can (but are not required to) use threads**. I wouldn't recommend it for solving this sort of problem though as deciding to start using threading opens a whole new can of worms and there are easier solutions available.

---

**Game loops can vary on whether they are simulated frames, drawn frames, or some other watchdog to decide when to call one or both of the previous, take this as a general statement for ease of conversation*
> 1 votes

# Answer
Game timing is one of the main concerns / mechanics to have in mind from the very start of designing a game, and there are several frameworks that handle them, but in most all cases, threads are used unless every object that you use has its own state and is updated based on time intervals, in which case that update function is the main thing that you're running as your game loops. Without a framework like one of those, you'd be stuck waiting for every action to finish before processing the next one, so you'd never be able to do things like show different graphical effects happening simultaneously, or have multiple objects with AI functions running at once.
> 0 votes

---
Tags: directx, multithreading
---


# Question
Title: I have created character human in blender. How to use it in Java/Android
Title says it all pretty much. I can't find anything online which explains it in details. I have created a character model in Blender and I want to use it in Android app. I want to make it move. What's my next step here?

# Answer
You can use libgdx. It's open source game engine. Here is example of importing 3D model from Blender
> 1 votes

# Answer
You need to load the model into your app. When you read the model file, you'll be able to load a list of coordinates for all the vertices that make up your model, and information such as which vertices connect to each other to form polygons (faces). Then when you perform your rendering in your app, you take the coordinates of your vertices and plot them in your 3D space. If your model has animations, the file will have information on what the vertex coordinates should be at each frame of the animation. You use this information to 'animate' your model.

How you do this is up to you. You could do it from scratch for example. Write your own model file parser to store all the vertex coordinates in your program for rendering. Or you can use a library, for example a premade .obj loader, along with more sophisticated graphics libraries that have support for animations.
> 0 votes

---
Tags: opengl, java, android, models, blender
---


# Question
Title: Techniques to prevent non-official clients in network gaming?
In multi-player network games, what techniques exist to try to ensure that users are connecting with the official client application, and not some hacked client app?

I realise there is probably no sure-fire way to do this, but rather I'm interested in techniques that can be employed to mitigate the problem.

I'm especially interested in any techniques that can be used for web based games, but I imagine most can be applied generally.

Thank you!

# Answer
That's interesting problem, but I think you are asking the wrong question here. Let me start from detecting hacked client approach:

If your client is executed on user's side, he can do whatever he wants with your code (until it's too complicated for him, but there will always be someone smarter in the line). Everything you can do like hard-coding encryption of messages between client and server, creating client certificates, or even making client to compute it's checksum, can and given enough time, will be decompiled and cracked. I have seen a software which came with a dongle, this dongle had part of the application's code, but to be able to execute it, dongle first checked crc of the app if it was not tempered.. of course after some time dongle was hacked too.. plus if you make a software update, you need to resend the dongle..

In addition to that, user can use your own client to cheat - by simulating mouse movement and clicks for example.

So the question should be - how to detect a bot player?

Here you have a few options - measuring time between clicks, measuring speed of mouse movements - does mouse move exactly from point A to point B numerous times and hit exactly the same coords? Do user movement is repeatable? If when resource which user was gathering was depleted, do user goes to other action or he waits in place for hours? At the end of the day you end up writing patterns recognition code.
> 13 votes

# Answer
> In multi-player network games, what techniques exist to try to ensure that users are connecting with the official client application, and not some hacked client app?

I don't think this is the right way to approach this or at least not the only thing you should be concerned with.

1. Make sure you only send client specific information to every client (e.g. a client doesn't need to know what a monster for example can drop, just send the information after killing it, and only to the specified clients)
2. Do most of the calculations on the server side (positioning etc.). The client is doing it's own calculations BUT can never send his own values only his actions. The server has to check if this action is valid and how it will effect the game.
3. 1 and 2 are usually combined with predictions. The client and server try to predict certain behaviors. The client for example moves the player but every x seconds or ms. receives a correction by the server
4. Charge users for their accounts not for the client, this way a user might get hold of a cracked version but can't play without an account.

With 2 you can make sure there are no money hacks, position hacks or wall hacks etc. but bots have always been a problem for many companies. Even big company names like blizzard have trouble with that. What you could do is limit the playable time per account, so that someone can't be online for more than 540 hours per month. I remember a bot which used color values of monsters + mouse input in order to farm XP. Another way would be to provide an additional program which checks for other running applications and memory access but this brings a handful of new problems.

Edit:

Very well written articles for beginners: http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/
> 9 votes

# Answer
There is no real foolproof way to guarantee that the "official client" is running; any such mechanism will rely on the validating code communicating back some kind of "secret" to the server, which can be reverse engineered, given enough time. This is basically what happens when an anti-hacking software tells the server that the client is OK.

Edit: to elaborate a bit on the above, consider the code that's validating the client side. It has two very difficult jobs: checking that the original code is being used (and nothing else is present which can interfere with the original code dynamically / at runtime(!)), and communicating this result back to the server, in such a way that this communication cannot be faked. While the first part is insanely difficult, the second part is downright impossible.

If you can update both the client and the server on a regular basis, then you can switch the secret out on a regular basis, with the hope of making it difficult for the crackers to keep up. In all likelihood however, unless you are changing the way the secret is encoded / implemented, it can be cracked very quickly again. So basically, it's an arms-race between you and whoever wants to crack it - who has more time and money to throw at the problem.

Having accepted that part, is there anything else we can do? In a perfect world, with infinite computing power and bandwidth, you could simply continuously transfer state between the client and the server, and have the server run a perfect simulation of what's happening on the client. This model could then be used to validate the actions that the client is claiming to be making. This will not detect whether a human or a bot is playing, but it will be able to validate whether the client is claiming a shot happening through a wall, or some other inconceivable action.

Having enough data on the server is also a first step in detecting irregular behaviour - aiming that's too quick for humans perhaps, etc. Obviously the perfect simulation situation is generally not feasible, but some kind of scaled-down, estimated model can be used in many situations.
> 4 votes

# Answer
You don't specify the type of game, so I will lean heavily toward RPG/MMO games. But a lot of this can and does apply to FPS, Strategy, and Action games. The way big multiplayer game companies like Blizzard deal with this issue in their games is:

1. Do all calculation and game actions server side, the client is just a dumb terminal and graphics engine. So if the players are using a different client, it really doesn't matter in game terms, they can't cheat the physics of the game.
2. Checks for obvious bot programs/clients by looking for obvious computer actions like perfect repetition of click events and mouse movements.
3. Checks for non-obvious bot programs/clients and alerts in-game moderators to the issue.

They then appear in game (if that's possible, for same games like Starcraft 2 it is not) or otherwise watch/talk to the player about their actions as a 'human check'. Or at least that's how it should be handled. Blizzard is pretty good about this but historically other MMO companies have not been.

Checking for non-obvious bots isn't easy, but a few basic rules to follow include

* Looking for players that, with only slight variation, are performing the same actions over and over again. This might be sitting at a resource node in an MMO and farming it when it respawns, or it might be running in circles between health/ammo packs in an FPS and never deviating from a specific path and always using the same gun. (Sub-optimal bots in FPSs are rare, but if your game has a ladder to climb where number of games is more important that the talent of the player like some modern FPSs have, bots become valuable again)
* Looking for players executing the same exact rush or strategy over and over in an RTS. There are certain build orders in Starcraft that can be nearly unbeatable when performed by a bot.
* Looking for players who have collected vast sums of resources and are now endlessly grinding out one item. This was a big problem in Ultima Online.

The problem is that the more popular your game is, and the more fruitful bots can be in reducing tedium in your game, the more likely people will be to both use and create these bots. And it is trivial to restrict mouse movement speed, add random humanistic variation to clicks, even have the bot make mistakes at a human rate, opening and closing parts of the menu, hitting the wrong button and then closing the window, switching between keyboard and mouse work like humans do to reduce hand fatigue. (you don't even realize you do it)

So the last step when someone or a bot is doing something repetitive for a very long time really has to be a human mod coming up to the player and talking to them. If they are there and respond with human answers, they are human. Typically the mods will ask the player to stop for a while, or follow them somewhere and perform some other actions, the hoops become more complex with time.

**Tanget**

Of course, eventually someone will create a bot that is indistinguishable from a real person, passing the Turing test. And there are a lot of bot writers out there who aim to do just that.

I, myself, had a passing fascination with the idea when I first started programming and created useless bots for Ultima Online which would stand in town and imitate NPCs. The commands were super simple so they were easy to make, just key strokes to step in different directions, and watching the chat log for its own name and piping the messages to ALICE over via a web version of the AI. I don't remember which and it probably doesn't exist anymore.

**/Tangent**

Point is, you need to decide where to draw the line. If you can't afford an army of moderators to talk to people your system identifies as bots, you are probably better off letting the community mark people as bots, and then when enough do over time, kick the player for about an hour. Not ban, just kick. The real problem for most players is that bots hog resources that other human players could be using. If mobs are scarce, as was the issue with Ragnarok Online, then bots that roam about and clear whole areas of enemies while scooping up items (or not) are common, and they ruin the game for other people. So you can skirt the cost of admin armies that way.

Finally, you can also live with bots as a reality of your game space and encourage their use. This requires designing your game around the eventual and common use of bots, trainers and helper programs. I want to say there was an MMO that did this about 10 years ago, but I can't remember which one it was. It spelled the end of the game, because MMOs are grind heavy and it meant that 95% of the players we away from their keyboards at any given time and destroyed the community. If you go this route, be careful.
> 4 votes

# Answer
*avoid having game-features from which a user can win by doing repetitive tasks*, especially in browser-like games. game-features which cause repetitive tasks not only cause other users angry because they don't have time to do them, but it also makes the game much easily botable (and much less fun!)

If a given game-feature can be botable, why is there that feature on the game anyway?? That feature is clearly calling the user to build a bot.

The game is meant to be played by giving the player a reasonable amount of entertainment, normally by a set of non-trivial choices. The ability do decide facing non-trivial choices separates a human from a bot. Ultimately, instead of searching for bots, search on your game where a bot could be implemented, and implement it you by yourself to be used by everyone. By doing that, you save time to a game-player by avoiding him of performing boring tasks, while you fight the bots from the root: if there are no botable game-features, how can there be bots?

My bottom line is: I would say that there is a threshold on the minimum amount of complexity a game needs to not be botable. Make your game above that threshold by adding non-trivial choices which will ultimately increase the user experience.

Anyway, maybe this paradigm no longer applies on the present days... but I still believe this is what makes a good game.
> 3 votes

# Answer
The existing answers are already good, but I wanted to point out that if your checks are expensive (ex: running the entire game server-side to make sure the client isn't cheating), then you can choose to only do it **some of the time**.

For example, you could only check actions in a particular region or by particular players (randomly changing after some time), or just have a queue of actions and randomly pick which ones to validate (and ignore the others). Maybe come up with a heuristic of who's likely to be cheating (basically look for people who are most successful) and validate their actions on the server.

Make sure the server doesn't give away when it's validating actions and when it's not. Always send your standard response until you're ready to take action (and don't give it away by taking longer to send a response when you're validating and when you're not).

This way you can get pretty good protection against cheating, using only the server power you can spare (although obviously the closer you are to validating every action, the better protection from cheating).
> 2 votes

# Answer
Well, I don't think there is an "the-Ultiamte-soltution". You may encode the Datapackages, and give the server that recieves the packages some rules. To example you could set that the biggest realistic/allowed move is +1 and not like a cheater/hacker that would set it to 5 or higher just to be faster. Just think about what could a hacker do to be better than other players and set rules for it.
> 1 votes

# Answer
The simplest way is to in essence make the client a dumb terminal. Everything is done on the server, and the client just sends commands to the server. This way the server is fully in control of everything.

This is probably not the most suitable case for you however, because the server has to perform more computations, and the user experience will be lackluster. So the more logic you leave up to the client to perform, the better the user experience, but the less security there is. So you'll have to find a middle ground that is acceptable for you.

Also, only send the client what it "should" know. For example, if an enemy player is behind a wall, don't send that information to a client, or a hacked client will be able to discern this information (read: wallhack).
> 0 votes

# Answer
**EDIT:** I misunderstood the question. I interpreted it as "prevent pirated/hacked key" instead of "hacked software that can send a message to generate 1 billion gold for the player."

Most games these days have a value tied to an account in a database since anything that a client can send to a server can be modified. This is probably the simplest and most effective method.

With the prevalence of high speed internet and P2P file transferring, companies have switched from cd-keys that are stored locally on the client to keys that are linked to an account on their servers. There are no more "official" or "non-official" client software since anyone can download the client. But you can only play if you have an account with access to play.

This also has a benefit to the company since they don't need to spend as much producing physical copies of the software.
> -1 votes

---
Tags: networking, multiplayer, security
---


title: Is there any map maker for javaME game?

text:
# Question
Title: Is there any map maker for javaME game?
For the past two weeks I was trying to make a map maker for my java ME 2D RPG game. I failed because i get errors using slick TWL and the forum for this is inactive.

So I just wondered is there anyone that knows slick TWL (Themable Widget Library)? Or maybe do you know a good MapMaker where i could upload my map elements build a map and get numbers to use them for building map with LayerManager class?

Already found one http://sourceforge.net/projects/tilemapeditor2d/. But the thing is my map elements are in different .png images. In one of those images there is 16 elements (trees water and etc) and those kind of images are 29. So it would be hard to build a map with LayerManager

Well I was thinking putting everything into one image and that way it would be simplier.

# Answer
Don't know of any tile map editors utilizing numbers for the tiles. However, you can parse a XML file into your map.

A popular 2D Tile map editor "Tiled" can be found here. This should also fix your multiple images problem. I'm not quite sure how "LayerManager" works in Slick, but if it renders the tiles based off numbers, you can use the solution above & convert the XML you read into numbers.

Also, I've never been a huge fan of everything inside one image (Not sprite sheets, I mean the entire map). It's normally a better idea that the game elements handle drawing themselves. When you put put everything in one image, it also forces you to manually import the various game objects coordinates, heights/widths, etc, for collision detection & whatever else you need. This is really bad practice & just makes it harder for you.

What is fine, is too have a non-interactive background image just there for detail / scenery (Normally you would see this in a side scroller, behind the tiles. A sky background could also be an example of this).
> 0 votes

---
Tags: java, mobile, slick
---


# Question
Title: Move penetrating OBB out of another OBB to resolve collision
I'm working on collision resolution for my game.

I just need a good way to get an object out of another object if it gets stuck. In this case a car.

Here is a typical scenario.

The red car is in the green object. How do I correctly get it out so the car can slide along the edge of the object as it should.

I tried:

```
if(buildings.size() > 0)
    {
        Entity e = buildings.get(0);
        Vector2D vel = new Vector2D();
        vel.x = vehicle.getVelocity().x;
        vel.y = vehicle.getVelocity().y;
        vel.normalize();
        while(vehicle.getRect().overlaps(e.getRect()))
        {
            vehicle.setCenter(vehicle.getCenterX() - vel.x * 0.1f, vehicle.getCenterY() - vel.y * 0.1f);
        }
        colided = true;
    }

```

But that does not work too well.

Is there some sort of vector I could calculate to use as the vector to move the car away from the object? Thanks

Here is my OBB2D class:

```
public class OBB2D
{

    // Corners of the box, where 0 is the lower left.
   private  Vector2D corner[] = new Vector2D[4];

   private Vector2D center = new Vector2D();
   private Vector2D extents = new Vector2D();

   private RectF boundingRect = new RectF();
   private float angle;

    //Two edges of the box extended away from corner[0].
   private  Vector2D axis[] = new Vector2D[2];

   private double origin[] = new double[2];

   public OBB2D(Vector2D center, float w, float h, float angle)
    {
       set(center,w,h,angle);
    }

   public OBB2D(float left, float top, float width, float height)
    {
       set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f);
   }

   public void set(Vector2D center,float w, float h,float angle)
   {
         Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle));
           Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle));

           X = X.multiply( w / 2);
           Y = Y.multiply( h / 2);

           corner[0] = center.subtract(X).subtract(Y);
           corner[1] = center.add(X).subtract(Y);
           corner[2] = center.add(X).add(Y);
           corner[3] = center.subtract(X).add(Y);

           computeAxes();
           extents.x = w / 2;
           extents.y = h / 2;
           computeDimensions(center,angle);
   }

   private void computeDimensions(Vector2D center,float angle)
   {
       this.center.x = center.x;
       this.center.y = center.y;
       this.angle = angle;

       boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x));
       boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y));
       boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x));
       boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y));
   }

   public void set(RectF rect)
   {
       set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f);
   }

    // Returns true if other overlaps one dimension of this.
    private boolean overlaps1Way(OBB2D other)
    {
        for (int a = 0; a < axis.length; ++a) {

            double t = other.corner[0].dot(axis[a]);

            // Find the extent of box 2 on axis a
            double tMin = t;
            double tMax = t;

            for (int c = 1; c < corner.length; ++c) {
                t = other.corner[c].dot(axis[a]);

                if (t < tMin) {
                    tMin = t;
                } else if (t > tMax) {
                    tMax = t;
                }
            }

            // We have to subtract off the origin

            // See if [tMin, tMax] intersects [0, 1]
            if ((tMin > 1 + origin[a]) || (tMax < origin[a])) {
                // There was no intersection along this dimension;
                // the boxes cannot possibly overlap.
                return false;
            }
        }

        // There was no dimension along which there is no intersection.
        // Therefore the boxes overlap.
        return true;
    }

    //Updates the axes after the corners move.  Assumes the
    //corners actually form a rectangle.
    private void computeAxes()
    {
        axis[0] = corner[1].subtract(corner[0]);
        axis[1] = corner[3].subtract(corner[0]);

        // Make the length of each axis 1/edge length so we know any
        // dot product must be less than 1 to fall within the edge.

        for (int a = 0; a < axis.length; ++a) {
            axis[a] = axis[a].divide((axis[a].length() * axis[a].length()));
            origin[a] = corner[0].dot(axis[a]);
        }
    }

    public void moveTo(Vector2D center)
    {
        Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f);

        Vector2D translation = center.subtract(centroid);

        for (int c = 0; c < 4; ++c)
        {
            corner[c] = corner[c].add(translation);
        }

        computeAxes();
        computeDimensions(center,angle);
    }

    // Returns true if the intersection of the boxes is non-empty.
    public boolean overlaps(OBB2D other)
    {
        if(right() < other.left())
        {
            return false;
        }

        if(bottom() < other.top())
        {
            return false;
        }

        if(left() > other.right())
        {
            return false;
        }

        if(top() > other.bottom())
        {
            return false;
        }

        if(other.getAngle() == 0.0f && getAngle() == 0.0f)
        {
            return true;
        }

        return overlaps1Way(other) && other.overlaps1Way(this);
    }

    public Vector2D getCenter()
    {
        return center;
    }

    public float getWidth()
    {
        return extents.x * 2;
    }

    public float getHeight()
    {
        return extents.y * 2;
    }

    public void setAngle(float angle)
    {
        set(center,getWidth(),getHeight(),angle);
    }

    public float getAngle()
    {
        return angle;
    }

    public void setSize(float w,float h)
    {
        set(center,w,h,angle);
    }

    public float left()
    {
        return boundingRect.left;
    }

    public float right()
    {
        return boundingRect.right;
    }

    public float bottom()
    {
        return boundingRect.bottom;
    }

    public float top()
    {
        return boundingRect.top;
    }

    public RectF getBoundingRect()
    {
        return boundingRect;
    }

    public boolean overlaps(float left, float top, float right, float bottom)
    {
        if(right() < left)
        {
            return false;
        }

        if(bottom() < top)
        {
            return false;
        }

        if(left() > right)
        {
            return false;
        }

        if(top() > bottom)
        {
            return false;
        }

        return true;
    }

};

```

# Answer
The quick and dirty answer to your question:

> Is there some sort of vector I could calculate to use as the vector to move the car away from the object?

is: **the normal of the face of the OBB that your car is colliding with, scaled by the distance that your car is penetrating the building.**

There is a longer answer though, and how exactly you resolve this collision depends on how detailed and physically accurate you want the resolution to be. I'll describe your options here, and what's required to make them work, but I'll also encourage you to read some articles written by Chris Hecker if you are really interested in the details of rigid body dynamics. Now, back to your problem...

Like, I said, the quick way to do this is to push the car out along the normal of the face it is colliding with. The calculation of this normal depends on how you store the geometric information of you boxes. The one I prefer to use is a half-vector scheme as follows:

```
class OBB {
    Vector3 half_x;
    Vector3 half_y;
    Vector3 position;
    float rotation;
};

```

Please note that I intend the above definition to be language-agnostic. The reason I prefer this scheme is it makes implementing the Separating Axis Theorem easier to calculate, as the half-vectors also act as your projection axes. In turn, the advantage of using SAT is that you can calculate the distance that your car has penetrated your building. This is given by:

```
penetration = (project(car vectors onto axis).length + project(building vectors onto axis).length)
              - project((car.position-building) onto axis).length*2

```

I kind of wish there is an easier way for me to write that equation, but it should be clear if you read the tutorial on SAT at the link I provided. (Maybe I can throw together an image that demonstrates better and upload it here...).

From there, you just have to scale the normal by the amount of penetration and move your car's position with the resulting vector, and your car is precisely touching the side of your building. Yay!

Furthermore, this could be considered an accurate representation of where the car would be had it "slid" along the wall. Technically, the normal of the wall the car is hitting enacts a force on the car *equal and opposite* to the velocity of the car projected onto that normal (thus cancelling out the portion of the car's velocity that would cause it to penetrate the wall), and the car would just travel parallel to the wall. So yay! The car is where we expect it to be! Except...

If you wanted to take your collisions a step further, and add friction to the car scraping along the wall of your building, then the quick resolution I just described doesn't really work well, because the car wouldn't have been able to travel that far along the wall with friction present. I'm not going to go too far into this case; it's probably more that you need.

However, for the sake of knowing, it involves back-tracking your simulation using some fancy math to determine exactly where the car is *the exact moment* it collides with the wall, adjusting its velocity from that point, applying the force of friction *and* the resisting force of the wall, and stepping the simulation from there.

This ended up being really long... so thanks for reading! I hope this helps :)
> 4 votes

---
Tags: java, collision-resolution
---


# Question
Title: Detecting pixels in a rotated Texture2D in XNA?
I know things similar to this have been posted, but I'm still trying to find a good solution... I'm drawing Texture2D objects on the ground in my game, and for Mouse-Over or targeting methods, I'm detecting whether or not the pixel in that Texture at the mouse position is Color.Transparent. This works perfectly when I do not rotate the texture, but I'd like to be able to rotate textures to add realism/variety. However, I either need to create a new Texture2D that is rotated at the correct angle so that I can detect its pixels, or I need to find some other method of detection... Any thoughts?

# Answer
You need to convert the mouse position to image coordinates by 'reverse' rotating the mouse vector. Technically, what you are doing is transforming the mouse position from screen coordinates to image coordinates.

1. get the position of the mouse relative to the position of the image
2. rotate this vector by the inverse of the angle the image was rotated
3. use this new vector to inspect the pixel

```
 protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    // TODO: Add your update logic here
    MouseState ms=Mouse.GetState();

    //convert mouse position to a vector
    Vector2 mPos = new Vector2(ms.X, ms.Y);

    //get mouse position relative to image position
    mPos = mPos - spritePos;

    //rotate the relative mouse vector in the opposite angle that we rotated the image
    Matrix rot = Matrix.CreateRotationZ(-spriteAngle);
    mPos = Vector2.Transform(mPos,rot);
    //add the image origin (if used in drawing)
    mPos += imageOrigin;
    //now the mouse position is Image coordinates
    //convert mouse position to a point for next stage
    Point mP=new Point((int)mPos.X,(int)mPos.Y);

    if(imageRect.Contains(mP)){// check if point is in the image rectangle
        //get the index of the pixel in the color array
        int index = mP.X +mP.Y * image.Width;

        if (imageData[index] == Color.Transparent)
        {
            //do stuff;
        }

    }
    base.Update(gameTime);
}

```
> 5 votes

---
Tags: xna, collision-detection, textures, rotation
---


# Question
Title: Has a multi player graphic adventure* ever been made?
By graphic adventure, I mean point & click LucasArts-type games.
Those games have a mostly linear structure in nature, and usually don't offer as many variants as other games types like action, rpg, strategy, which makes this genre difficult to implement a multi-player feature.
I'd like to know if there has been any attempts on doing such a thing, and if it would be viable, as players going offline or leaving a game in the middle would affect significantly the other players' game.

# Answer
Of course I can't say for sure since I haven't played all the games that there are in the world, but I seriously doubt that such a thing exists. I even doubt that it is viable. Here's why:

A large part of the fun in these adventure games comes from figuring things out from beginning to end. If another player partially does that for you (because you just joined the game, or because the game requires you to only solve a part of the puzzle) it kind of takes away the fun.

Adventure games are usually lengthy affairs, where you spend a lot of time in single chapters of the game. Having multiple players play this kind of game together would require them to play together for a very long time, which rarely works out even if you have buddies who want to play with you.

And last but not least: Adventure games are story-driven by design. I find it hard to imagine that these kinds of games would have a lot of replay value.

But of course, if you have some awesome idea to actually put this into practice, everyone's welcoming you. The gaming market is certainly not oversaturated with original ideas.
> 1 votes

# Answer
Graphic adventure games of the type you describe were never made multiplayer for one main reason: By the time computer networking was ubiquitous, the graphic adventure game genre was already dead. The few graphic adventures still being made were being made as niche games for a niche audience, they intentionally weren't breaking new design ground.

Yes, there are design challenges for making adventures work in a multiplayer context. But there are always design challenges no matter what you make; design challenges can be overcome. The reason there are no multiplayer adventure games is that the market had decided it didn't want adventure games long before multiplayer ever became a real option.
> 8 votes

# Answer
The only examples I can think of stretch your definition a bit.

Uru Live (Myst Online) is an undead MMO adventure game in the Myst series. It gives players their own instances of puzzle worlds, but some worlds require or benefit from players working together.

Zork: Grand Inquisitor has a co-op mode where one player controls the player character and the other player gets a "look here" cursor to help.
> 6 votes

# Answer
In SELEAG,we created a multiplayer engine for SCUMM based flash games: TIMEMESH. The idea was to create two teams of players which have to solve the same story but with slight variations. There are cross-bars in the adventure game. A cross-bar is a shared blocking between two teams playing a match. Until both teams have gone through 2 parallel challenges neither of them can progress in the adventure game.

They have a chat enabled to collaborate in solving this blocking points (which sometimes were minigames embedded in the main game).
> 3 votes

---
Tags: multiplayer, online, adventure-games
---


# Question
Title: Does SFML render graphics outside the window?
While working on a tile-based map I figured it would be a good idea if I would only render what the player sees on the game window, but then it occurred to me that SFML could already be optimized enough to know when it doesn't have to render those things.

Let's say I draw a 30x30 squared maps (A medium one) but the player only sees a bunch of them, not entirely. Would SFML automatically hide what the player doesn't see, or should I hide it myself?

# Answer
> 13 votes
Simple tile blitting engines will naturally cull objects outside the viewport, as they pretty much have to if using software rendering. Otherwise, the GPU will do the culling itself. Either way, the cost of the actual rendering of each tile is minimal. The speed problems are not the rendering in the graphics device, but rather the fact that your game and the high-level graphics API are doing a ton of work by simply *considering* rendering each tile.

That said, if you're interested in speed, culling objects on a one-by-one basis when they're outside the viewport is not going to give you much gain. You are far better off with an algorithmic approach that completely ignores entire swaths of objects that are off screen.

For a tile engine, this is as easy as calculating the bounding tiles of the viewport, and then only looping over those. Even if SFML does culling of objects, you will get a huge net gain in speed. You avoid looping over tiles that can't be seen. You avoid making draw calls for tiles that can't be seen. You avoid needing any culling code -- fast or not -- being run in the first place.

That said, a quick 10 second Google search indicates that the SFML lead developer does recommend that you do your own frustum (viewport, in 2D) culling: http://en.sfml-dev.org/forums/index.php?topic=7933.0

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


# Question
Title: How do I enlarge a SpriteFont without it becoming blurry?
How do I make spritefonts not blurry when I make them bigger? I have searched Google and haven't found any useful answer.

# Answer
> 4 votes
The problem with resizing spritefonts is that when you make the spritefont, a file is made with an image of the font *at the size you specify in the xml file*. Because of this, you are not going to get the scalability of vector fonts, meaning that when you make your fonts bigger they will be blurry. The only way around this is to create several sprite fonts of varying sizes that you can switch between when the quality starts to get too bad. Alternatively you can check out the Nuclex Framework which has support for vector fonts.

# Answer
> 2 votes
Bitmap fonts can be rendered less blurry by using bilinear filtering to sample the texture with alpha testing. In shaders alpha testing means that discarding any fragments where the alpha value is less than some constant, e.g 0.5.

See for example the middle image in the first page of this paper. With distance fields you could get even better looking results, but that requires different bitmap font data. With alpha testing you can already improve the rendering of normal bitmap fonts considerably.

# Answer
> 1 votes
If you want to make a single font bigger, just double click it on the Solution explorer search for

```
<Size>14</Size>

```

and change 14 for a bigger number such:

```
<Size>32</Size>

```

If you want to have multiple size fonts, you can follow ssb answer and use Nuclex. Another option, is making the font pretty large (72 pt seems a good size, you probably won't go bigger than this) and then just scaling down when you need smaller fonts. Never scaling up.

The trick here is that the loss when you scale down is more negligible that when you scale up. Still it's just a bitmap, and the quality won't be the best, but surely get the job done.

---
Tags: xna, xna-4.0, fonts
---


# Question
Title: Networking Client Server Packet logic (How they communicate)
I want to know what is the logic behind server client communication through packets for a **real time game**. for example the server sends x packets then the client receives x packets and processes them..

Basically what is the process to keep the client and server in sync and able to receive and send packets.

***more in depth example of what I want to know:***

*client*

**step 1** wait for a packet

**step 2** read x packets

**step 3** process x packets

**step 4** send x packets

and so on...

I need to know the very basic outline of the communication.

**Big questions are:**

**1)** do I send and read packets all at one time? i.e for loop though the incoming packets array list and read them all or one every server loop or what...

**2)** what order should I do things i.e first receive then read then process then send etc..

**3)** what I asked above a step by step of what the server / client should do..

Thanks!

# Answer
1) You have a poll loop which checks for incoming packets, if you receive a packet you usually have to check if you want to accept that packet, decrypt it since you usually have some kind of encryption in order to protect the data. Then you analyse what kind of information is stored in this packet and depending on the content proceed with it

2) You usually use non-blocking sockets. This means you are sending and receiving packets all the time. But in many cases an incoming packet triggers one are many outgoing packets (e.g. position update)

3) Depends on your game and architecture.

Read all articles on http://gafferongames.com/ These are the best written articles for bloody beginners from my point of view.
> 2 votes

# Answer
Client -\> Awaiting Gamestate

Server -\> sending Gamestate to Client

Server -\> Setting Position and Whatever ( depends how you divide the tasks for Client-Server-Model) -\> sending to Client Client -\> Sends Player movement to server

Server -\> Sends Playermovement to other players

another point: You cannot keep everything synchronous , games often use asynchronous communication models.
> 1 votes

---
Tags: networking, game-loop, client-server, process, packet
---


# Question
Title: Pygame Tile Based Character movement speed
Thanks for taking the time to read this. Right now I'm making a really basic tile based game. The map is a large amount of 16x16 tiles, and the character image is 16x16 as well. My character has its own class that is an extension of the sprite class, and the x and y position is saved in terms of the tile position.

To note I am fairly new to pygame.

My question is, I am planning to have character movement restricted to one tile at a time, and I'm not sure how to make it so that, even if the player hits the directional key dozens of time quickly, (WASD or arrow keys) it will only move from tile to tile at a certain speed. How could I implement this generally with pygame? (Similar to game movement of like Pokemon or NexusTk).

Edit: I should probably note that I want it so that the player can only end a movement in a tile. He couldn't stop moving halfway inbetween a tile for example.

Thanks for your time! Ryan

# Answer
Basically what you are probably looking for is a little timer which counts down the time until the next move is possible after a move was done. Like so (not tested, replace `w_key_pressed` etc by the proper input checks):

```
walk_cooldown = 0
WALK_DELAY = 1 # the time between 2 steps

clock = pygame.time.Clock()
while(true): # this is your MAIN LOOP, you can put some of this stuff into your player class
    delta = clock.tick() / 1000.0

    walk_cooldown -= delta

    if walk_cooldown <= 0:
        if(w_key_pressed):
            walk_down_one_tile()
            walk_cooldown = WALK_DELAY
        if(s_key_pressed):
            walk_down_one_tile()
            walk_cooldown = WALK_DELAY
        # ... the usual stuff, however you do it

```

Notice how `walk_cooldown` is set to `WALK_DELAY` when you move, and is being decreased by the time passed each frame. You can only move, when `walk_cooldown` is less than or equal to 0.
> 2 votes

---
Tags: movement, python, pygame
---


# Question
Title: What kind of math should I be expecting in advanced programming?
> **Possible Duplicate:**
> What math should all game programmers know?

And I don't mean just space shooters and such, because in non-3D environments it's obvious that not much beyond elementary math is needed to implement. Most of the programming in 2D games is mostly going to involve basic arithmetic, algorithms for enemy AI and dimensional worlds, rotation, and maybe some Algebra as well depending on how you want to design.

But I ask because I'm not really gifted with math at all. I get frustrated and worn out just by doing Pre-Algebra, so Algebra 2 and Calculus would likely be futile for me.

I guess I'm not so "right-brained" when it comes down to pure numbers and math formulas, but the bad part is that I'm no art-expert either.

What do you people here suppose I should do? Go along avoiding as much of the extremely difficult maths I can't fathom, or try to ease into more complex math as I excel at programming?

# Answer
Whatever you Math topics you want to learn about, I found http://www.khanacademy.org to be an awesome resource for learning such things.

The E-Learning videos presented on that site (by Sal Khan) are amazing, I learned a lot about advanced linear algebra (matrix projections and such stuff I needed for OpenGL programming) from him. Make sure to check it out - whatever topic you want explained very well.
> 1 votes

# Answer
I'd suggest you pick a development environment / framework which does most of the Maths for you. You don't need to be an expert on Matrix calculations when you know how to use matrices from a tutorial. XNA would be a good place to start.

When you know the basics it's enough to create most simple games, 2D and 3D. When you want something more and start optimizing performance etc. you might want to upgrade your math skill first.
> 0 votes

---
Tags: 3d, mathematics, software-engineering
---


# Question
Title: is wisdom of what happens 'behind scenes' (in compiler, external DLLs etc.) important?
I have been a computer-fanatic for almost a decade now. I've always loved and wondered how computers work, even from the purest, lowest hardware level to the very smallest pixel on the screen, and all the software around that.

That seems to be my problem though ... as I try to write code (I'm pretty fluent at C++) I always sit there enormous amounts of time in front of a text-editor wondering how every line, statement, datum, function, etc. will correspond to every Assembly and machine instruction performed to do absolutely everything necessary for the kernel to allocate memory to run my compiled program, and all of the other hardware being used as well.

For example ... I would write `cout << "Before memory changed" << endl;` and run the debugger to get the Assembly for this, and then try and reverse disassemble the Assembly to machine code based on my ISA, and then research every .dll, library file, linked library, linking process, linker source code of the program, the make file, the kernel I'm using's steps of processing this compilation, the hardware's part aside from the processor (e.g. video card, sound card, chipset, cache latency, byte-sized registers, calling convention use, DDR3 RAM and disk drive, filesystem functioning and so many other things).

Am I going about programming wrong? I mean I feel I should know everything that goes on underneath English syntax on a computer program.

But the problem is that the more I research every little thing the less I actually accomplish at all. I can never finish anything because of this mentality, yet I feel compelled to know everything... what should I do?

# Answer
In general, yes, you should indeed have a decent understanding of the hardware, the OS, how DLLs work, and other low-level details. As a C++ programmer, there will even be (rare) occasions where you need to inspect a stack, follow base pointers, and reconstruct a proper stack trace when the stack is so screwed that the debugger can't do it for you.

That said, in specific to what you've asked, you are definitely *massively* overdoing it in one sense. You don't need to worry about specific assembly output of code. In fact, I'll guarantee that your understanding of ideal assembly output is wrong, as modern CPUs are ridiculously complex and obtaining ideal efficiency has less to do with the specific assembly output of a line of code and more to do with whole-program transformations. Turn on the right level of optimization and you won't even be able to find or identify individual lines of code in the generated assembly in many cases. Humans are bad at anything besides micro-optimizations (short sequences of assembly) and macro-optimizations (algorithmic choices): everything in between is usually better done by the compiler than you, and even many micro-optimizations are better handled by the compiler.

It is useful to know what the compiler does. There are ways of writing code that lets the compiler do its job very well, and ways to write code that totally defeat the compiler's algorithms.

It is useful to know how the CPU (or GPU) work internally. There are many ways to write assembly that looks fast but which performs like crap. If you don't understand cache hierarchies, the way DRAM works, CPU instruction pipelines and data dependencies, GPU core block behavior, and GPU texture memory access patterns, then you are utterly incapable of making intelligent decisions about optimizing modern real-world programs. That said, know these in terms of whole algorithms, NOT individual lines of code.

Knowing the exact assembly output of C++ code is just not valuable. Knowing how to optimize code comes from knowing what lets the compiler work, knowing what general patterns to avoid or prefer for target hardware, and how to identify and fix *measured* performance problems.

And that's the last bit of optimization wisdom I have for you. PROFILE YOUR CODE. If you are making optimization decisions based on assembly output rather than actual metrics and performance data, you are not only wasting tons of your time, you are actively defeating yourself. To be blunt, optimization without profiled data verifying the optimization is pure incompetence. The majority of the time you do that, in my experience, you will be introducing performance pessimizations rather than optimizations. You might think you know what an individual line of code does all the way down to the hardware, but if you can't think about how the *entire algorithm* works, you lose. There are many cases where you can micro-optimize one small piece to the detriment of the whole. And you as a human being are not capable of understanding the whole down to the hardware level you are talking about, especially when you consider all the smarts in the hardware that "undermines" the assembles (out of order CPUs, DRAM row banks, cache layers, and a bazillion similar things). You MUST rely on profile data and larger metrics, not per-line performance tuning.

Again, I have very directly seen cases where optimizing one line really did make the whole algorithm slower. It was non-intuitive, had nothing to so with how the one lone executed, and everything to do with how that line defeated the ability for the compiler and CPU smarts to handle the larger body of code.

In reference to your problems with getting things done, that's a sign that you are failing as a game developer due to your preoccupation with performance. The performance of your game is utterly irrelevant compared to your performance as a game developer. Optimize for *speed of design and content iteration* first, and speed of engine execution second. The fastest game engine in the world that can't be used to make a real game in reasonable time periods is utterly worthless. Look for instance at how unpopular Carmack's engines have become (they haven't been licensed by more than a handful of companies since Quake 3, since they're barely useful for anything besides the one game they're made for) or how every major AAA developer used to have to spend so much time rewriting large parts of Unreal in order to make it work for non-FPS games (it's a lot better these days, but it was pretty bad back when Unreal 3 was new).
> 6 votes

# Answer
This seems a bit like obsessive / compulsive behaviour and I would try to avoid this as much as you can. If you want a future job optimizing performance on games etc. I'd say go for it.

It really depends on what you want with you future. Do you like designing stuff that's epicly optimized, or do you want to quickly produce lots of games etc.

I don't think your question has a really conclusive answer, but I'd like to point out most companies look at what your work output is. Working to slow could get an issue eventhough you know exactly what's going on beneath the hood.
> 2 votes

# Answer
I can say from my own experience: the more you know, the better. **But:**

I used to be a (more or less) successful programmer without knowing all the details about how stuff worked. I even wrote C++ without understanding *why* I had to write header files and source files, or even what they were used for. I just followed the rules, and it often worked.

But as I went on, I stumbled upon problems I was not able to resolve without understanding the problem itself. Now I can say I have a pretty good understanding of what the machine in front of me does and *why* it does it. This makes debugging etc. a lot easier and programming a lot faster.

I still don't know anything about assembler, I couldn't really interpret a line of it (yes, I know it moves memory around and not much more, but I can't read or write it). But that is not the point. I know basically what the languages I use (e.g. C++) will be compiled into, and how instructions are being translated. The hardest part was probably understanding memory management (pointers, references, etc.), but now I resolve most segfaults within seconds.

I hope this helps you to find your way through this huge amount of stuff you *could* learn, and you probably *will* learn while working with it. Best of luck!
> 1 votes

---
Tags: software-engineering
---


title: How to do pre-loading

text:
# Question
Title: How to do pre-loading
I have a question that is confusing me with making a game.

For my game launch i pre load everything for the main menu then i loop the game to display it.

But lets argue player wants to launch a new game or a specific level, then you preload the relevant sounds/graphics for that level right?

How ever, the player must already be running the game loop if they are at the main menu, so you can't load in the game loop or you will load every frame...but im pretty sure most big games don't preload every level when you first run the game from desktop because it would take a long time on some of these games....

How is it done :S

# Answer
> 5 votes
At the most basic level, you can simply put an `if` statement in your main loop, to make the loop do different things at different times.

This would probably take the form of a simple state machine. All you need to do is have a variable which tells the main loop whether it's in "loading" state or in "playing" state, and then have an `if ( state == loading ) { } else { }` block of code, with the loading code only happening in the 'loading' block, and the gameplay code only happening in the 'else' block.

# Answer
> 3 votes
"Big" games (commercial ones) usually do the loading in another thread. For every small beginner's game without a game engine involved I can give you this advice: **DON'T**.

Multi-threading is and will always be kind of a problem if you don't know what you're doing. So better don't. What this means for you: you have to load your resources and stop rendering in that time. So yes, basically you load your stuff in the main loop, but remember (e.g. in a boolean value) that you already loaded them and do not load them again in the text frame.

Notice, that with this approach, the main loop will "hang" while you load your resources. People may get confused when the game does not react, so you should make sure to display a loading screen (e.g. the text "loading" somewhere visible) and render it the frame before you do the loading. Look at the in-game loading screen of any Source engine game (Portal, Black Mesa Mod, ...) for an example.

Of course, if you are hardcore, you could try your hand at loading something in the background while displaying a status bar, or loading the resources step by step (one each frame) and drawing the new status in between - but this is rather complicated and not really suited for first-time game developers.

---
Tags: preload
---


title: General approach to isometrics

text:
# Question
Title: General approach to isometrics
I am currently discovering the world of isometrics, now I found out there are two approaches to creating the tilemap;

1. Just create 2:1 ratio tile-images and draw those.
2. Creating squares and transforming them to the 2:1 ratio. What is the general approach on developing an isometric game?

Now I was wondering a few things;

* How do more known games like AOE1/2 do this?
* What are the pros/cons of both methods?
* Which method is preferred to be used in this day and age?

**Edit added more general question**

# Answer
> 1 votes
I never did this, so I might be wrong with all of this. But I have a pretty good understanding of graphics programming, so here are my thoughts:

* When AOE 1/2 were written, memory and disk space were valuable. A 2:1 tile-image is bigger than a square which is transformed.
* If you draw squares and transform them, you do not have pixel-perfect control over you final image.
* ... but it is easier to create tilable 2D sprites as squares.
* transforming a square to an isometric tile is not necessarily trivial

I for myself would do the first approach (2:1 tiles), because it is easier to implement...

---
Tags: isometric, tilemap
---


title: Task Core dividing

text:
# Question
Title: Task Core dividing
How can I divide the tasks for diffrent cores?

E.g. 4 Cores func1() -\> core1

func2() -\> core2

func3() -\> core3

func4() -\> core4

Is there special libary for this? Or do I have to use the old fashioned way of integrating the functions in the main loop ?

( I'm using C++ on Windows)

# Answer
> 2 votes
Even if there might be ways to select specific cores for parallel tasks, it's considered bad practice. Number of cores vary from machine to machine, and it's better to let the OS decide where to put the load. You should just create a few Windows threads and let the scheduler manage.

---
Tags: c++, directx, windows
---


# Question
Title: Problem when texturing triangles using glVertexPointer()
I'm having a problem for displaying a single quad, here is how i do :

```
//note: this code is only for 2 triangles, while on picture there is 4 triangles
float tex_coord[] =
{
   0.0, 0.0, //3
   0.0, 1.0, //2
   1.0, 1.0, //0
   1.0, 1.0, //0
   1.0, 0.0, //1
   0.0, 0.0  //3
};

int indexes[] =
{
    3, 2, 0, 0, 1, 3
}

 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
 glEnableClientState(GL_VERTEX_ARRAY);
   glVertexPointer(3, GL_FLOAT, 0, vertexes);
   glTexCoordPointer(2, GL_FLOAT, 0, tex_coord);
   glDrawElements(GL_TRIANGLES, 2, GL_UNSIGNED_INT, indices);
 glDisableClientState(GL_VERTEX_ARRAY);
 glDisableClientState(GL_TEXTURE_COORD_ARRAY);

```

The result :

# Answer
> 2 votes
In your code you need 4 texture coords; one for each position in vertices.

tex\_coord\[2\] & text\_coord\[3\] are the same, even though they are for different vertices.

Change text\_coord\[2\] to 1.0,0 ; should fix the problem.

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


title: DirectX 9.0c Lights?

text:
# Question
Title: DirectX 9.0c Lights?
I'm still learning DirectX from a book. It says that a graphiccards can only handle 15 lights. I'm just a bit confused , there are a lot of games using more lights, or are this just some alpha blending tricks or what ever?

# Answer
Your title mentions DirectX 9, which is almost a decade old and a lot has happened in the graphics space since then.

I assume your book is referring to a limit on lights in the fixed function pipeline (FFP). I always thought there was a maximum of 8 lights in DirectX9 class FFP. But remember that this was 8 'active' lights, you could have many more lights but they did not have any effect until they were made active.

Current versions of Directx (and Opengl) have removed the FFP so they don't implicitly support *any* lights. All the lighting is done in the shader.

However modern shader programming, pretty much allow for unlimited number of lights.

Back in the day, a lot of lights would be simulated by things like "light mapping" (basically baking in the lighting into textures).
> 3 votes

---
Tags: c++, directx
---


title: How to select a random node

text:
# Question
Title: How to select a random node
I need to know if it is possible to select a random node or select a node itself because I'm doing a zombie AI and I need him to randomly move, and I wanted to know if it's possible to do it and how.

# Answer
1. Assign a number to each possible destination node.
2. Pick a random number.
3. Select the node with the number you randomly selected.
> 6 votes

# Answer
In addition to @Trevor Powell answer i would say that if you are using a simple graph for your A\* pathfinding (such as a grid or something), you can easily generate a random X and Y coordinate and get the node located at this point.

It could avoid assigning an id to each node.
> 0 votes

# Answer
Use recursion

1) Choose a random child in a node

2) Repeat until no child nodes or early escape

```
node randomnode(node currentnode)
{
    int n = random number between (and including) 0 and the number of child nodes + 1
    if (n == number of child nodes + 1)
    {
        return currentnode //early escape.
    }
    else
    {
        return randomnode(currentnode[n])
    }
}

```
> 0 votes

# Answer
While the previous answers are all technically correct to the question you posted, I think you're asking the wrong question.

Simply picking a random point and moving there will NOT give you good-looking zombie behavior. It's going to look and feel like a computer algorithm rather than giving the impression of "artificial intelligence." The zombie will have a tendency to make radical turns and spin on a dime to walk backwards or the like rather than aimlessly shambling like a "natural" creature (ignoring the unnaturalness of zombies, of course).

You are much better off using a wander steering behavior mixed with a random tendency to stop for a while and drool/moan/etc, or even a random speed or the like. (By random here I mean something weighted towards reasonable values, not a simple "random(min,max)" call, as again the latter will look like a computer algorithm and not feel natural.)

You can use the steering algorithms on that same site (linked because the home link on the Wander page is apparently broken) to continue making the zombies look more natural. Use obstacle avoidance rather than A\* to move around objects. Maybe even use some small flocking influence to make zombies congregate or move apart from each other. The seek or pursue behaviors on the site are also great options for making zombies chase the player or other food sources. Arrival is a decent choice if you want the zombie to run the last point it saw the player but to slow down and return to normal behavior after getting there (assuming it doesn't see the player again and pick up the chase).
> 0 votes

---
Tags: c#, path-finding, random
---


# Question
Title: How does Against The Wall create an infinite wall?
There is a game called *Against The Wall*, developed by Michael P. Consoli. It's a fantastic game, as I've always been stumped at how the game creates an infinitely spanning wall.

In the game, you can fall forever, and the wall will keep spanning. I can fall as long as I like, and still be able to climb back to where I was before. The game is developed in Unity.

How can a game do this without crashing, or creating some kind of memory overload?

# Answer
There's no need for the wall to actually be infinite in the implementation itself. Games are 99% smoke and mirrors. The game could easily be despawning bits of wall that are too far away and recreating them on demand.

Doing so with the right algorithmic approach would make the wall generation "stable" (that is, if you fall enough and then climb back up, it'll be the same wall layout and not a new random layout). There would be some kind of limit to that based purely on the limits of integer sizes, but this limit can be large enough that it is effectively infinite in practice. If the world eventually wraps (no idea if it does) you can even avoid ever showing the player any "edge" to the world.

The game also possibly moves the wall rather than the player. If the player moved, then eventually the player would move to some coordinate where floating point inaccuracies and imprecision would cause severe errors. Keeping the player at position 0,0,0 and them moving the wall avoids that, as the walls are despawned from memory before they get too far away from the origin.
> 8 votes

---
Tags: unity
---


# Question
Title: What features should a good DirectX game engine contain?
What features should a good DirectX game engine contain?

I've been reading certain books, but I want to make sure. My own engine contains

* Networking
* Rendering
* Sound
* GUI
* Data management
* Logbook functions

# Answer
There is no rule for what a "good game engine" should contain. If you create your own engine, you decide what it is there for and what is required. Take the Unity engine for example (it is a really well designed and feature-rich universal 3D game engine). It does most everything you will need to make any kind of game:

* Any kind of Graphics
* Networking
* User Input
* 2D / 3D Audio
* Asset Management and Distribution

You can do almost any game with it. Then look at the Source Engine by Valve. The type of game you can create with it is kind of limited. I don't know if it is entirely impossible, but that engine is not intended for anything except FPS games.

You see, you have to decide what you game engine should do and what it has to include. You probably have a reason for making your own engine (apart from the learning effort), so stick to that goal. You want a universal game engine? Try to look at other (commerial and FOSS) engines and see what they do for the developer. You want something special (e.g. an engine for 2D turn-based roguelike games)? Cut down on the feature list and don't do stuff you don't need.
> 4 votes

# Answer
Write Games, Not Engines. You cannot make an engine in isolation, because questions like "what features should the engine have" are utterly incapable of being answered without knowing what specific game you're trying to make. Worse, even if you write some generic system, it is almost absolutely buggy, incomplete, and unusable if you have no real-world game use cases that it has been developed for.

Once you accept that, I'd say that Game Engine Architecture is one of the better books on the subject of building game engines. Not that a single book can really cover it all, but it's a very good attempt at doing so. It's course material for several high-end game engine development courses I know of.
> 4 votes

---
Tags: directx
---


# Question
Title: OpenGL ES 2. How do I Create a Basic Fading Streak Effect?
For the iPad app I am writing using OpenGL ES 2 I have a single quad - shaded using GLSL - that is dragged around the screen. Very basic. This works fine. But is rather boring.

I want to increase the coolness a bit in the following way: when the user drags the quad it leaves a streak behind that fades over time. Continuous dragging would be a bit like a streaking comet across the night sky.

What is the simplest way to implement this?

Thanks.

# Answer
If you want the quad itself to be "streaked" across the background, the simplest way is to just store N (say, 10) previous positions for the quad. Each frame, pop the first item from the front of the list. Each frame that the user is dragging the image, push a new position onto the end of the list. During rendering, simply render the quad a number of times for each item in the list. Start with a low opacity (say, 10%) and increase it by +10% for each step in the list. Render the real quad at full opacity. This is the effect you see in games like the 2D Castlevania titles.

If you want the quad to blur the background that it's being dragged over, you should look into motion blur. Render the whole scene to a texture with an FBO. Store a vector representing movement, and scale it down each frame. Use the vector and the quad's current position to calculate a blur shape (take the four corner of the quad, add the vector, find the convex hull of the original 4 vertices and the resulting 4 vertices; you can also use some smarts with the vector's direction to simplify finding the convex hull considerably). Use the vector in a loop in your post-processing fragment shader to calculate the texels to sample from the source scene texture from the FBO when rendering the blur shape. Note that this approach won't look super great when the user makes sharp changes in the direction he's dragging in, unless you store multiple vectors and use a somewhat more complex series of blur shape calculations (you'd want to avoid overlapping regions).
> 1 votes

---
Tags: ios, glsl, opengl-es2
---


# Question
Title: What is the best Broadphase Interface for moving spheres?
As of now I am working on optimizing the performance of the physics and collision, and as of now I am having some slowdowns on my other computers from my main.

I have well over 3000 btSphereShape Rigidbodies and 2/3 of them do not move at all, but I am noticing(by the profile below) that collision is taking a bit of time to maneuver.

```
    Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 10.09      0.65     0.65                             SphereTriangleDetector::collide(btVector3 const&, btVector3&, btVector3&, float&, float&, float)
  7.61      1.14     0.49                             btSphereTriangleCollisionAlgorithm::processCollision(btCollisionObject*, btCollisionObject*, btDispatcherInfo const&, btManifoldResult*)
  5.59      1.50     0.36                             btConvexTriangleCallback::processTriangle(btVector3*, int, int)
  5.43      1.85     0.35                             btQuantizedBvh::reportAabbOverlappingNodex(btNodeOverlapCallback*, btVector3 const&, btVector3 const&) const
  4.97      2.17     0.32                             btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback*, btVector3 const&, btVector3 const&) const::MyNodeOverlapCallback::processNode(int, int)
  4.19      2.44     0.27                             btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btRigidBody&, btRigidBody&, btSolverConstraint const&)
  4.04      2.70     0.26                             btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btRigidBody&, btRigidBody&, btSolverConstraint const&)
  3.73      2.94     0.24                             Ogre::OctreeSceneManager::walkOctree(Ogre::OctreeCamera*, Ogre::RenderQueue*, Ogre::Octree*, Ogre::VisibleObjectsBoundsInfo*, bool, bool)
  3.42      3.16     0.22                             btTriangleShape::getVertex(int, btVector3&) const
  2.48      3.32     0.16                             Ogre::Frustum::isVisible(Ogre::AxisAlignedBox const&, Ogre::FrustumPlane*) const
  2.33      3.47     0.15  1246357     0.00     0.00  Gorilla::Layer::setVisible(bool)
  2.33      3.62     0.15                             SphereTriangleDetector::getClosestPoints(btDiscreteCollisionDetectorInterface::ClosestPointInput const&, btDiscreteCollisionDetectorInterface::Result&, btIDebugDraw*, bool)
  1.86      3.74     0.12                             btCollisionDispatcher::findAlgorithm(btCollisionObject*, btCollisionObject*, btPersistentManifold*)
  1.86      3.86     0.12                             btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint&, btCollisionObject*, btCollisionObject*, btManifoldPoint&, btContactSolverInfo const&, btVector3&, float&, float&, btVector3&, btVector3&)
  1.71      3.97     0.11                             btTriangleShape::getEdge(int, btVector3&, btVector3&) const
  1.55      4.07     0.10                             _Unwind_SjLj_Register
  1.55      4.17     0.10                             _Unwind_SjLj_Unregister
  1.55      4.27     0.10                             Ogre::D3D9HardwareVertexBuffer::updateBufferResources(char const*, Ogre::D3D9HardwareVertexBuffer::BufferResources*)
  1.40      4.36     0.09                             btManifoldResult::addContactPoint(btVector3 const&, btVector3 const&, float)
  1.40      4.45     0.09                             btSequentialImpulseConstraintSolver::setupFrictionConstraint(btSolverConstraint&, btVector3 const&, btRigidBody*, btRigidBody*, btManifoldPoint&, btVector3 const&, btVector3 const&, btCollisionObject*, btCollisionObject*, float, float, float)
  1.24      4.53     0.08                             btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold*, btContactSolverInfo const&)
  1.09      4.60     0.07   408760     0.00     0.00  Living::MapHide()
  1.09      4.67     0.07                             btSphereTriangleCollisionAlgorithm::~btSphereTriangleCollisionAlgorithm()
  1.09      4.74     0.07                             inflate_fast

```

EDIT: Updated to show current Profile. I have only listed the functions using over 1% time from the many functions that are being used. Another thing is that each monster has a certain area that they stay in and are only active when a player is in said area. I was wondering if maybe there is a way to deactivate the non-active monsters from bullet(reactivating once in the area again) or maybe theres a different broadphase interface that I should use.

The current BPI is btDbvtBroadphase.

EDIT: Here is the Profile on the other computer(the top one is my main)

```
    Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 12.18      1.19     1.19                             SphereTriangleDetector::collide(btVector3 const&, btVector3&, btVector3&, float&, float&, float)
  6.76      1.85     0.66                             btSphereTriangleCollisionAlgorithm::processCollision(btCollisionObject*, btCollisionObject*, btDispatcherInfo const&, btManifoldResult*)
  5.83      2.42     0.57                             btQuantizedBvh::reportAabbOverlappingNodex(btNodeOverlapCallback*, btVector3 const&, btVector3 const&) const
  5.12      2.92     0.50                             btConvexTriangleCallback::processTriangle(btVector3*, int, int)
  4.61      3.37     0.45                             btTriangleShape::getVertex(int, btVector3&) const
  4.09      3.77     0.40                             _Unwind_SjLj_Register
  3.48      4.11     0.34                             btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback*, btVector3 const&, btVector3 const&) const::MyNodeOverlapCallback::processNode(int, int)
  2.46      4.35     0.24                             btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btRigidBody&, btRigidBody&, btSolverConstraint const&)
  2.15      4.56     0.21                             _Unwind_SjLj_Unregister
  2.15      4.77     0.21                             SphereTriangleDetector::getClosestPoints(btDiscreteCollisionDetectorInterface::ClosestPointInput const&, btDiscreteCollisionDetectorInterface::Result&, btIDebugDraw*, bool)
  1.84      4.95     0.18                             btTriangleShape::getEdge(int, btVector3&, btVector3&) const
  1.64      5.11     0.16                             btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btRigidBody&, btRigidBody&, btSolverConstraint const&)
  1.54      5.26     0.15                             btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint&, btCollisionObject*, btCollisionObject*, btManifoldPoint&, btContactSolverInfo const&, btVector3&, float&, float&, btVector3&, btVector3&)
  1.43      5.40     0.14                             Ogre::D3D9HardwareVertexBuffer::updateBufferResources(char const*, Ogre::D3D9HardwareVertexBuffer::BufferResources*)
  1.33      5.53     0.13                             btManifoldResult::addContactPoint(btVector3 const&, btVector3 const&, float)
  1.13      5.64     0.11                             btRigidBody::predictIntegratedTransform(float, btTransform&)
  1.13      5.75     0.11                             btTriangleIndexVertexArray::getLockedReadOnlyVertexIndexBase(unsigned char const**, int&, PHY_ScalarType&, int&, unsigned char const**, int&, int&, PHY_ScalarType&, int) const
  1.02      5.85     0.10                             btSphereTriangleCollisionAlgorithm::CreateFunc::CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo&, btCollisionObject*, btCollisionObject*)
  1.02      5.95     0.10                             btSphereTriangleCollisionAlgorithm::btSphereTriangleCollisionAlgorithm(btPersistentManifold*, btCollisionAlgorithmConstructionInfo const&, btCollisionObject*, btCollisionObject*, bool)

```

Edited same as other Profile.

# Answer
> 2 votes
The broadphase is not the bottleneck, it seems narrowphase sphere versus triangle.

Is this a profile using full optimizations? What platform?

It could be the trianglemesh is not optimized for collision, but for rendering? Too many small triangles slows down a lot.

You can also dump the Bullet timings using CProfileManager::dumpAll() right after stepSimulation, to get more details. We could add a faster sphere trangle collider, file a request to http://bullet.googlecode.com

Deactivation would help too, you could create sphere rigid bodies in deactivated )sleeping) state.

---
Tags: c++, ogre, bullet-physics
---


# Question
Title: What is the best way to check if there is overlap between player and static, non-collidable items in bullet physic engine
I'd like to add non collidable objects (eg: power ups, items, ...) in a game world using `Bullet Physics Engine` and to know if there is collision between player and them.

Some info : there is a lot of items (\> 1000), all are box shapes and they don't overlap.

Here is things i have tried :

```
btDbvt* bvtItems = new btDbvt(); //btDbvt is a hierachical AABB tree, used by Bullet
foreach(var item ...)
{
    btDbvtVolume volume = ... //compute item AABB;
    bvtItems->insert(volume, (void*)someExtraData);
}

```

Then, to find collisions between items and player :

```
playerRigidBody->getAabb(min, max);
btDbvtVolume playervolume = ... //compute player AABB
bvtItems->collideTV(bvtItems->m_root, playervolume, *someCollisionHandler);

```

This works fairly well (and its very fast), however, there is a problem : it only check items AABB against player AABB. That loss of precision is acceptable for items but not for player which is not a box. It would actually need another check to make sure player really collide with item but i don't know how to do this in Bullet. It would have been nice to have a function like this :

`playerRigidBody->checkCollisionWithAABB();`

---

After doing trying that, I discovered that a `btGhostObject` exist and seems to have been made for that.

I changed my code like this :

```
foreach(var item...)
{
    btCollisionObject* ghostObject = new btGhostObject();
    ghostObject->setCollisionShape(boxShape);
    ghostObject->setCollisionFlags(ghostObject->getCollisionFlags()
                                   | btCollisionObject::CF_NO_CONTACT_RESPONSE);
    startTransform.setOrigin(...); //item position
    ghostObject->setWorldTransform(startTransform);
    dynamicsWorld->addCollisionObject(ghostObject, btBroadphaseProxy::SensorTrigger,
                   btBroadphaseProxy:: CharacterFilter);
}

```

It also works ok, but there is a *huge* fps drop (almost ten times slower) which is not acceptable. Maybe there is something missing (forget set a flag) and `Bullet` is doing extra job for nothing or maybe all that `ghostObjects` are polluting broad phase and `ghostObject` is not the right thing for that.

Any help would be appreciated.

# Answer
You could use world-\>contactTest(player, callback);

This will use the same dynamic aaabb tree (if you use btDbvtBroadphase) and uses an exact contact computation. It is probably fastest and easiest. World can be btCollisionWorld or btDiscreteDynamicsWorld.

If you use ghosts: You don't need to add a ghost for each item, just a single ghost around the player.
> 5 votes

# Answer
Create a normal static or kinematic rigid body and set collision flag NO\_CONTACT\_RESPONSE. This way the object participates in physics calculations and records collisions, but does not give any impulses to other objects.

You can then check for collisions with these instructions.
> 2 votes

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


# Question
Title: What is a good tool for producing animated sprites?
Has anyone come across a software package that allows you to build animations in a similar way to how you can in Flash (i.e. using techniques such as tweens & bones & easings, etc) and then have the result exported as a sprite sheet?

# Answer
> 17 votes
You can use Flash, a 3D Tool or even Photoshops animation feature. Then render the frames to images and combine them to a sprite-sheet.

ImageMagick has a great tool for that purpose called *montage*. Here's a blog post explaining how to use it to create a sprite sheet.

# Answer
> 6 votes
While those techniques work well for vector graphics, they don't translate well to pixel art. Sprites don't tend to handle rotation or scaling without distortion, so hand editing is essential.

Two products worth looking into for spriting are Cosmigo's ProMotion and GraphicsGale. Onion skinning and other features are available. But if you want clean pixel art, automation isn't going to do the job.

edit: Okay, my brain is tired. A cup of coffee later and I realize what you're looking for. You could try out SynFig, which looks like it might be adaptable to your needs :)

# Answer
> 2 votes
The way we make our animated sprites is by rendering out frames from a 3D modeling program.

# Answer
> 2 votes
I've been using Texture Packer to create sprites for my iPhone game. It's similar to Zwoptex but has a free version. I'm porting a game originally developed in Flash, so I'm simply exporting each frame of the MovieClip to png and then importing those images in Texture Packer.

# Answer
> 2 votes
I use Gamedev Animation Studio for create animation. It can export animated images into C# classes which i instantly include into my project

# Answer
> 1 votes
I'm pretty Sure you can use Flash and go file \> export movie\> png sequence. Then combine the pngs using Photoshop to make your sprite sheet. Also check out the animation features of fireworks.

# Answer
> 1 votes
ToonBoom studio is a flash like animation tool and can export sprite sheets.

# Answer
> 1 votes
Use gimp and its plugin called sprite sheet

---
Tags: tools, sprites, animation
---