title: Trophies programming design pattern

text:
# Question
Title: Trophies programming design pattern
What design pattern is best for implementing trophies in a game? I am not a games developer, but is it easy for each player's action to check and update conditions that satisfy 50-100 trophies at any time aside from everything that goes on in the game engine? How is it best done?

# Answer
I think the best way to design something like this is first to inspire yourself from the best, Assassins Creed 2 is a good example.

You find a trophy for each chapter and one for completing the game on each difficulty. These are generally 'Complete Chapter x' or 'Defeat Boss xyz'. I would prefer having really exmplcit names eg 'Complete Chapter x', as you don't want the player to check his trophies every time he finishes a chapter because he thinks he got someting cool.

You also should have trophies that will push the player to play how YOU want him to.

For exploration you will have a collectible trophy, for fighting you will have a 'Kill x Guards' etc. These can help to force the player to explore more, and even learn to play better.

The biggest difficulty in my sense is Hidden Trophies. The name needs to imply what needs to be done but without spoiling any of the game. You don't want for example 'Kill the Traitor' when you only have one Ally in the game. These should also be some of the hardest trophies where people could rarely get them without specifically trying for it.

There can often be half of the total trophies that are secrets.

Of course, 'Lolphies' are also good and will inspire or reward a certain type of play.

Trophies are very game-dependant though and require a lot of thought!
> 4 votes

# Answer
Basically you want at least 3 types of data structures:

Counters: This happened. A gun was fired. An enemy was killed. This polygon was touched.

Conditions: If Counter X \> 500. If Counter Y = 0.

Trophy: If condition A is met, this condition is visible. If condition Y is met, this condition is invisible.

In your game code you sprinkle counters firing where appropriate and forget about it.

Some other class either in response to an event of the counter firing or periodically will check the list of conditions and see if they've been met. After, again either in response to an event or periodically trophy's will check if all their conditions are met. If so it gets rewarded.

Your UI can iterate all trophies and display the visible conditions. If no conditions are visible, then the trophy is hidden.

Everything is separate and during the update loop all you need to do is increase a number and maybe flag the data as changed, anything else can be deferred to when there's more time / even a separate thread.
> 3 votes

# Answer
If you are asking for a technical way: I'm a very, very noob game developer, but this is how I implemented my AchievmentManager (I think it's the observer pattern):

```
Class BaseAchievement{

public abstract boolean checkAchieved(Game game);

public abstract String getName();

//etc. etc.

}

```

Manager:

```
Class AchievementManager
{
public void notifyScoreUpdated(Game game){
   for(ScoreListener s : scoreListeners)
   {
         boolean achieved = s.checkAchieved(game);
         if(achieved) unlockAchievement(s.getName());
   }
}

public void notifyPlayerMoved(Game game){
   for(MoveListener m : moveListeners)
   {
         boolean achieved = m.checkAchieved(game);
         if(achieved) unlockAchievement(m.getName());
   }
}

public void unlockAchievement(String name){
    //bla bla bla
}

}

```
> -1 votes

---
Tags: architecture, software-engineering, design-patterns
---


title: Tiling Physics using Farseer

text:
# Question
Title: Tiling Physics using Farseer
I'm having a problem with the Farseer Physics Engine, where in a tiled environment, my object will at times interact with corners of others objects, even if they align perfectly.

I've read about people suggesting that you calculate and create one larger object, using Marching Squares or something similar. This is not an option however, as I'd like each tile to have different physical qualities, like different friction and restitution.

My question is, what exactly is causing it, is it float precision issues or something else? And is there a way to fix it, without breaking the whole physics engine?

# Answer
Farseer uses an iterative solver, so when your wheel starts colliding with another rectangle at high velocity, from time to time you'll see bumps since it's a "perfect align" to us, not to a physics simulation, with iterations things like these will never be "pixel-perfect".

You will have to convert rectangles to Edge/Loop shapes and then model different physical qualities with hacks like creating artificial tile bounds and then changing properties when character enters a bounding box, but not every physical quality can be emulated that way.

Sooner or later you'll end up writing your own tile-based physics instead of Farseer. If your game doesn't have lots of complex physics puzzles, it will be simpler to abandon Farseer completely and roll your own tile-based physics.
> 5 votes

# Answer
you can optimize your collisions shapes, this scene can be done with only four rectangles.

you can join correlative boxes to make one bigger.

this video shows it http://www.youtube.com/watch?v=eyhGckHgkkE

when it is adding boxes you can see a light blue rectangle with the optimized shape.
> 0 votes

# Answer
Hmm... I suspect it might have something to do with your circle and not the tiles beneath it. Try making the ground using a single hull and see if you get the same results. If not, it's the tiles like you suspect. If so, your circle isn't as round as you might think it is.
> 0 votes

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


title: How does an Input Pipeline work?

text:
# Question
Title: How does an Input Pipeline work?
I found this article on implementing an input pipeline for Android, but I don't really understand how it works. I also don't completely understand the programming concept of a pipeline or a pool either. Could someone explain these concepts and how they work as this input pipeline?

# Answer
I haven't looked at the code in depth but the basic idea is that input events are asynchronous in Android, meaning they could happen at any time. You don't want to interrupt your main loop code to process input events because it could slow down your game and might alter your game state in unexpected ways.

The traditional approach used in the Lunar Lander sample is to have a synchronized block around the main loop and around each of your input handlers to ensure that they'd never happen at the same time. This might be a valid approach for a small game but as your game gets more complicated you'll find that it's not very efficient and it might not work correctly.

The article suggests a better approach of storing the input events in a queue, and processing them at a known point in your main loop. Input handlers simply push the event (after wrapping them in an InputObject that describe them) to the end of the queue, and they are later processed in the processInput method in the game thread.

The author of the article actually uses two queues, an input queue and an input object pool. The input object pool in the main activity is used because we don't want to keep creating new input objects every time we get an input event. This is bad because input events happen frequently and creating a lot of object will cause the garbage collector to run often, which makes your game choppy and unresponsive. The better approach is to create a pool of object once (basically a queue) and take objects from the queue when you need them and return them to the queue when you're done. That's what the queue in the main activity is for. The other queue is an input queue in the game thread which actually contains the input events received and which is processed game loop using the processInput method.

The pool queue will always have a fixed number of objects (specified by the INPUT\_QUEUE\_SIZE constant which can be 30 for example) which are allocated in the createInputObjectPool method when the activity is created, while the input queue will have a variable number of input events which are fed by the activity and returned back to the pool queue once they are processed using the returnToPool method. These queues are ArrayBlockingQueues which are normal queues (first in first out) implemented using an array (as opposed to linked list for example) that would block, in circumstances where a normal queue would overflow and underflow, until the queue is ready for the operation.
> 5 votes

---
Tags: android, input, pipeline
---


# Question
Title: Graphical Android game: Bad performance in some situations
I am developing a simple graphical game for Android (Java and OpenGL ES). There is no high-end graphics involved, basically a few (less than 10) sprites and some (about 10) dynamically drawn primitives. The performance of the game is quite fine, I get about 50-60 FPS on my HTC Desire.

However, there is one specific performance issue. In my game I can fire a characters' gun, which then fires a laser beam that moves over the screen following its velocity vector. This beam is dynmically drawn. The thing is: when I fire the gut the first time, the laser beam is moving very unsteady (its "hopping" over the screen). But, after this first time, when I then fire the gun for how often I like, the laser beam is moving very smooth over the screen.

I first thought this might be an issue with Android's garbage collector. But I double-checked my code. Not one single new object is created within the main game loop, I solely use pre-created objects (i.e. class instances). I also doubt the problem is related to the dynamic drawing of my primitives (laser beam), because as said its working fine and very smooth for every gun shot after the first one. It is solely this first shot where I encounter this performance issue.

So my question is, does this behaviour sound familiar to anyone of you guys? I would appreciate any idea very much.

# Answer
Try limiting your delta time (time between updates) to 0.1 or something similar - I've read about a bug where sometimes on Android the time is incorrectly reported and could cause an issue similar to the one you're having.
> 1 votes

# Answer
Are you sure that it is not garbage collection happening? You can check the logs in DDMS to see when garbage collection happens. If it's the first time then it's indicative of some object being allocated (or falling out of scope) or textures being allocated.

If you don't see any garbage collection happening then the next step is to profile the function to see exactly which line it hangs on and then figure out what's happening or edit the question so that we can offer suggestions.

While not specifically helpful for your problem but useful for game development on Android in general, you might also like to have a look at the Android Traceview program that lets you profile which calls are taking a long time so that you can optimise them.
> 0 votes

---
Tags: android, graphics, opengl-es, performance, graphic-effects
---


# Question
Title: What kind of digitizing tablet did developers use back in the day?
I have had trouble getting the money together to buy a digitizing tablet, and it would cheer me up to know what kind of digitizing tablet the artists were using to create classic games like Super Mario World and Sonic The Hedgehog. Part of me feels that maybe there is a way to make games without 2000+ pressure sensitivity levels. Does anyone know which models were widely used by console developers at the height of 2d gaming, and what their specs were?

# Answer
> 8 votes
I doubt they did. The majority of the true old school art (80's to early 90's) was done with a plain old mouse and pixel-pushing (raster) software like Deluxe Paint (now known as Cosmigo Pro-Motion).

As for when tablets did become really widespread and usable in the sense you know them today (perhaps mid 90's onward), Wacom was pretty much a big name throughout.

You can be sure that even the lowest end of what you buy *new* today will be better (and better supported in terms of drivers) than what they used back then. If I were to buy a new tablet now, I wouldn't go for anything too fancy, I reckon a Wacom Intuos 4 would be fine, IIRC there's a b5 size one that has what most artists need.

# Answer
> 2 votes
In addition to Nick, Wacom is the only brand that can be suggested with eyes closed & they have low price models.

I own 2 Wacom tablets, one I bought 3-4 or more years ago. The point is it still acts like brand new. Unless you break the pen (which can be bought separately), the touch surface shows no sign of age.

A few months back I bought another Wacom Bamboo. I suggest you to go for this one, as it's not expensive. I have heard a lot of high profile artist that still use their old Wacom tablet, cause it still works so well and they don't want to shift to something else for no reason.

Intuos are high-end artist models. See the feature list. If you don't need any of these, then simply go for the Bamboo series. It wont disappoint you. Paying a little more now will come back to you as a rare service in the long run.

---
Tags: art, hardware
---


# Question
Title: Is there a 2d animation authoring GUI for creating C++ games?
I'm moving from Flash to C++, and am wondering if there are any tools out there that would let me author animation much like Flash does.

Basically I want a GUI that lets me layout sprites and specify keyframes + easing for position, size, rotation, etc., then later be able to load and play these animations from my own code.

I've found a couple promising projects for UI interface animation, but I suspect since they're built for UI they're not optimized for game playback.

I've also found a bunch of animation libraries, but nothing that also provides a GUI for creating the animations.

Being able to animate textures would also be a plus.

# Answer
Torque 2D is the only such I've heard of for C++ development, and I am not sure it offers anything like Flash's level of control in terms of timeline animation. Other paid solutions may offer similar. But in general, you'll find that C++ doesn't do a magical all-in-one the way Flash does, i.e. executable and resources all nicely packaged up into one file from the same single development environment. Once you move into the world of C++, building custom tools is going to become a necessary part of developing your games.

As for ease of coding, its not going to be as simple to integrate with the resources, although Allegro, Torque2D, HGE and others may at least provide the sort of 2D game-related foundations you're looking for in terms of their codebases, such as resource loading, animation etc.

If you don't have your sights solidly set on C++, you may want to look into Unity. It can be pretty expensive, but you can use it for free. It has an excellent IDE, and I understand it has timeline functionality.

As for texture animation, the best I could suggest would be something like Cosmigo Pro-Motion, Allegro Sprite Editor or Pixen (Mac only) that are built for pixelling and (2D) sprite animation.
> 2 votes

---
Tags: c++, flash, animation
---


# Question
Title: Android : Some textures not loading after resuming twice
This is an odd one. When I press home and then restart my game I reload all my textures (checking glIsTexture on the id's first). If I do this once, all textures load as expected, but if I do it **twice or more** one of my textures doesn't load (the texture is white).

I have checked glGetError and there are no errors (assuming GLES10.glGetError() is the correct way to do this)

Do I need to do any tidying up when home is pressed? I currently call myGlView.onPause() and myGlView.onResume() when the onPause/Resume activity events are triggered. I was under the impression that's all that's needed. Is there anything else (perhaps non-openGL) that needs to be cleaned up? Perhaps I'm hitting a limit of some kind

I am also using the NDK for some physics and rendering functions if that is relevant, but all resources are loaded using java.

# Answer
Found the problem. It was hidden in some legacy NDK code ported from the iOS version. Previously I was loading and unloading textures in the native code. In the destructor in question there was a glDeleteTextures call that was removing the texture. I'm not sure why it didn't cause a problem on the first reload, but it now works
> 1 votes

---
Tags: android, opengl-es, textures, ndk
---


# Question
Title: What is wrong with my collision detection code?
I want to check collision detection between two bitmaps but I am not getting how to do it. I read several queries and tutorials but didnt get properly. I want to check by their width and height. I have implemented some logic also but not getting where I am doing wrong

```
public boolean collision(){
        for(int i=0; i<9; i++){
            for(int j=0; j<14; j++){
                if(frog.getX() < x + getX() || frog.getY() < y + getY() || frog.getX() > x || frog.getY() > y){
                //if(other.getWidth() > x && other.getWidth() < x + width && >other.getHeight() > y && other.getHeight() < y + height);
                    frog.frogShiftDown();
                }
            }
        }
        return true;
    }

public void draw(Canvas canvas){
        canvas.drawBitmap(bmp, x, y,null);
        carmove();
        collision();
    }

```

# Answer
> 4 votes
This is a problem with many, many sources across the web (if you want to do a search its called "bounding box collision detection" / "bounding box overlap")

With more background on what you are trying to do (i.e. are you detecting your collisions in a grid like tic-tac-toe, or are you doing them in a continuous space?) we can debug your code.

I'm going to describe this as pseudocode; I don't know what language you're using. If you understand the concepts as I explain them, you should be able to write the code.

Create a list called "cars".

```
Every time a car is created at the edge of the screen, put that car into "cars" array.

Every time a car is deleted at the edge of the screen, remove that car from your "cars" array.

Keep a reference to your frog (you are already doing this, i.e. your variable called "frog")

frog.left = frog.x
frog.top = frog.y
frog.right = frog.x+frog.width
frog.bottom = frog.y+frog.height

For each car in cars
   car.left = car.x
   car.top = car.y
   car.right = car.x+frog.width
   car.bottom = car.y+frog.height
   if ((car.left is between frog.left and frog.right) or (frog.left is between car.left and car.right))
      horizontalOverlap = true
   if ((car.top is between frog.top and frog.bottom) or (frog.top is between car.top and car.bottom))
      verticalOverlap = true

   if (horizontalOverlap and verticalOverlap)
      explode frog
      if lives == 0
         end game
      else
         lives = lives - 1
         place new frog back at start point (usually bottom of screen)

```

HTH. Draw your two boxes representing the current car and your frog, on a piece of paper, and you will see what is going on. The algorithm is checking overlap first along the x axis, then along the y axis. If there is overlap on both axes, then the car is on top of the frog (or vice versa), so the frog must explode.

---
Tags: android, collision-detection
---


# Question
Title: Random map generation - strategies for scattering/clustering random nodes
I am doing a simple 4X strategy game in space where each node is a point-of-interest (a planet, an asteroid and etc.).

To randomly generate a map, I would follow the steps below

1. Decide how many type of each nodes the map will have (perhaps, say, 5 Earth-like planets, 10 barren planets etc.)
2. Place each type of node on the map.

For step 2 I would like to have an even spread of each node type. So for example, I would start by placing all the earth-like planets. If I simply do a rand(map.width, map.height) to determine the position, I may end up all the earth-like planets clustering together, which will give advantage to the player who starts in that area.

Are there any methods, such as using different graph functions or noise function, which could generate a sequence of (x,y) coordinates which are spread out from each other. Likewise, are there any ways to generates coordinates which are close to each other?

# Answer
> 8 votes
The problem you're facing is that random selection doesn't discriminate, and that can mean that it's a less-than-ideal fit for what you need to do. But, there is at least one easy way to work around this:

1. Split up your space into sectors (e.g., if you have an area of 100 by 100, and you need to generate 100 of these solar systems, then split your area into a 10 by 10 grid of sectors)
2. Loop through each Sector and repeat step 3 (which will, in turn, repeat step 4 multiple times)
3. Randomly determine the number of planets for the current solar system (e.g., for a range of 3 to 7 planets, just acquire a random number ranging from 0 to 4, and add 3) in the current Sector (if you have more than one solar system in a sector, this is where you'd set up another loop)
4. Randomly assign your planets within the current Solar System identified by your loop (you can also use random numbers to increase the minimum distances between the planets); this is where you'd decide the types of planets, which could also be randomly determined with a variety of weights or whatever method you prefer to use

You may also wish to define an "out of bounds" area around the edge of each sector to prevent planets from neighbouring sectors from making direct contact with each other (just in case they were effectively randomly located side-by-side), or...

Another solution could be at the point of deciding the location of each solar system and/or each planet, to just run a quick proximity check against neighbouring sectors and adjust accordingly (e.g., move away from the edge by a minimum distance plus a random distance).

# Answer
> 8 votes
The best way to ensure even distribution is to treat each node as a sort of physical particle. First do a random distribution across a continous (floating point) xy plane. By applying forces of repulsion between each distinct pair of individual particles on the plane, you'll find they slowly spread apart. In a sense it's like collision resolution, only there is no actual contact to speak of. It's then a simple matter to convert that plane ("rasterize" it) back into an integer-indexed grid. You can simply do this from a integer-indexed grid to start with, but it might be a little more difficult to get things "nice" -- this depends on how high the resolution of your grid is... the higher, the better, in this case.

Obviously you may want to apply some sort of forces from the edges of the square plane as well, or else you may find a lot of particles "washing up on the shores". Alternatively you can create a field much larger than you need, then take a snapshot of a small area of that -- this avoids the aforementioned problem.

When you want to ensure the opposite, i.e. that clustering *does* occur, then look into "standard" or "gaussian" distribution. This is why randomly generated starfields often look fake; they use pure random distribution rather than a more naturalistic distribution model.

# Answer
> 6 votes
You can use a simple Poisson-disk distribution algorithm to get a "blue noise" distribution. This results in points in the plane which are roughly spaced equally apart from each other. This works not only in your 2D example but in 3D as well, and also in non-Euclidean spaces, but the calculations can quickly become unwieldy.

The basic idea of those algorithms is that you start with a first "seed" point, then work yourself outwards adding random or pseudo-random points in the annulus between the max and min distances you'd like to have from the point onward and eliminate those which lie too near to each other. Your algorithm then works outwards in such a manner, until either the amount of points needed is added (which gives you a roughly circular point cloud), or the space available is filled.

A fast and elegant *alternative* algorithm for generation of 2D such noise, as well as a short discussion of the properties thereof, can be found in "A Spatial Data Structure for Fast Poisson-Disk Sample Generation" by Daniel Dunbar and Greg Humphreys of the University of Virginia.

---
Tags: physics, mathematics, procedural-generation, random, procedural
---


# Question
Title: What standards should designers/artists follow when giving UI assets to coders?
How do you or your company require designers to deliver their assets to coders? Do they deliver a PSD? A series of 24-bit PNGs?

If you are a coder, what would you include in a best-practice guideline to designers? If you are a designer, what questions would you like to see answered in such a document?

Here are some ideas:

* Generally:
    + include designs for mouse-over and mouse-down states for all buttons and other interactive elements, as well as the normal state.
    + for toggle buttons, this can also include different states for both *selected* and *unselected* modes, for 6 states total: normal, over, down.
    + in drop-downs, lists, etc, please design a selected and unselected state for *each* item, if appropriate, especially where the content varies.
    + Flash is strictly an sRGB colorspace. If creating assets for Flash, make sure that your deliverables look how you expect it in sRGB.
* If delivering assets as a PSD, please:
    + label all layers clearly.
    + make sure that the dimensions of your document exactly match the dimensions of the application

What else would you include in a Visual Asset Delivery Best Practices document?

# Answer
> 7 votes
The standards should be, "whatever the code department needs, within reason". This may involve the coders writing exporter plugins for artists. But there is no standard way of distributing art since there is no standard way of consuming or using art. It's just down to what the technology pipeline requires.

However, as some rough guidelines:

* First, ask what they want. If they want a certain texture format, eg. DDS or whatever, ask and they'll say so. Check to see if you can export in this format, and if not, confer with the team to decide on how to proceed. Maybe they'll need you to install a converter, or maybe they'll let you supply the images in a different format.
* Make sure you have a consistent storage system for your assets that corresponds to the game's data. At some point you will be asked to redo assets, and therefore you will need to quickly find individual assets when told about a problem in-game.
* Use common sense. Use lossless formats when they won't be too large for little gain. Use lossy formats when they are much smaller and don't lose you significant image quality. Keep lossless versions around in your own control system so that if lossy versions are unusable, you can still generate a lossless one.
* When producing GUI elements, again, ASK how the system works. Don't waste your time producing mouse off/over/down/focused images when the system probably does not support all those, and might well implement some of them directly via hue shifts or alpha or whatever. Don't produce a precisely-sized dialog when it turns out they use a nine-slice system to allow dynamic sizing. Ask exactly what format they use, then supply it.
* Don't render text onto a background unless you have confirmed this is the right thing to do. eg. If asked to produce OK and Cancel buttons, that usually means you make ONE button and then the code will render the words 'OK' and 'Cancel' over the top. When that game is translated into French later, this means someone just has to change the 'Cancel' string to 'Annuler' and you don't have to go back and produce another set of buttons.
* When producing any asset type for the first time, deliver one to the intended recipient and get them to verify the format and dimensions are correct. You don't want to crank out 20 buttons and find out that they are all wrong.
* Establish texture sizes and overall budgets before delivering textures - coders hate it when you deliver 2048x2048 textures for something that only ever takes up 10 pixels on screen. Similarly, if the colour is uniform across the whole texture, you do not need 2048x2048, or even 128x128 - you need 1x1. More generally, deliver the smallest asset that delivers the visual quality you need.
* Establish consistent and descriptive naming conventions. If you generate buttons in off/selected/on states, name them quit\_button\_on.png, quit\_button\_selected.png, quit\_button\_off.png, etc., and repeat this across all buttons you ever make. If you generate several asset types for one object (eg. mesh, anims, textures), name them similarly if appropriate. I've known several artists who don't understand why coders have such an OCD attitude towards file names - it's because arbitrary file names waste our time. It becomes harder to find the right assets in a directory of hundreds. It becomes hard to flick from one to the next and back again easily to verify size changes and labelling is correct. It's difficult to know whether it's the code or the art which is wrong when something looks incorrect on screen but the debugger lists the texture only as "aaa34\_345b.dds".
* Do what the programmer wants - but make him help you do it. If saving in the relevant format is a burden, or checking the texture budget is impractical for you, or they want all assets in a special archive format that only one obscure piece of software can use... get him or her to write tools and plugins to help. A week spent on appropriate art tools can save both the artist and the programmer much more than a week of effort later. Don't let your code team skimp on tools.

# Answer
> 2 votes
The artists were able to keep the raw assets in any format they wanted. They would then export the files to a specific format, either from a plugin to Max/Maya that we made that would dump the data out in our format or simply saving as a PNG for photoshop and the like with the quality settings varying from project to project (ie, from target platform to target platform).

The files would then be processed into their load-time format by an asset compilation tool for faster load times.

However, this was just the way we did it. I would imagine alot of examples would follow along this line and there may have been guidelines above and beyond what I was aware of that an art director might have placed on top of the technical limitations depending on styles of art, but in general I think you will find the basic 'Artists keep it in a raw format and export it to a game engine specific format that is then further processed' as fairly standard at most large and even mid level game companies.

# Answer
> 0 votes
as a coder I just ask them what assets are the going to create, and then create a sample asset of those properties. give them the code and let them play with my app until they think output is good enough.

# Answer
> 0 votes
As a student I can't give proper advice as to what is done in the industry, however, when working on a group project the programmers were "in charge" and told the artists exactly what they needed. In addition to the guidelines provided at the beginning of the project they were also expected to follow the requirements provided by the programmers.

There was a lot of going back and forth when an artist didn't understand that the color R:254, G:0 B:254 was COMPLETELY DIFFERENT from the required R:255 G:0 B:255, was therefore unusable, and they had to start over.

---
Tags: flash, actionscript-3, gui, user-experience
---


title: Direct3D11 feature level

text:
# Question
Title: Direct3D11 feature level
If I set the directx feature level to D3D\_FEATURE\_LEVEL\_9\_3 but I have a graphics card which supports D3D\_FEATURE\_LEVEL\_11\_0 does that prevent directx11 features from working even though my graphics card supports them?

I want to ensure that my game works on 9.3 level hardware but don't have such a card to test it on. If I accidentally use higher features in my code, will setting the feature level lower when creating the device prevent those features from working even though my physical graphics card supports them?

# Answer
> 5 votes
Think of feature levels as rulesets defining what hardware abilities of a video card you are allowed to use.

So when you create a D3D11Device with D3D\_FEATURE\_LEVEL\_9\_3, you can still benefit from "software" D3D11 features which happen on driver and API level without involving hardware, such as better multi-threaded rendering, but your D3D11-capable video card will only give you the hardware abilities of a D3D9.3-capable video card. So geometry shaders and other fancy things will be unavailable, and runtime error will pop up when you try to use them.

This way your code will run on a real old D3D9.3 video card while being relatively easy to port to a higher-level device. Check this link to see how device capabilities correspond to different feature levels.

---
Tags: directx, directx11
---


# Question
Title: Where do I start if I want to independently learn game graphic design?
I want to learn how to create custom graphics, not use freely available resources. But I have been looking around for articles or tutorials on how to start with 2D game design in general, and I can't seem to find a good starting point — books or otherwise. I mostly come across resources for those that have had formal studies in graphic design (advanced stuff), but I won't have the luxury of formal studies for a good while (if at all). On the other hand, I find resources for learning the programming side of things, but not on how to create the graphics you'll manipulate.

Are there any good resources for learning game oriented graphic design? Specifically 2D, which is the one I'm most interested in, but 3D is also welcome.

# Answer
> 8 votes
Well, in my case, before I got accepted into Digital Media I had to present a folder of various 2D and 3D projects. Therefore, it's imperative that you try and get some of that formal training yourself, which isn't hard.

It really depends what you're looking for. Vector and raster art are both big fields to work in, so I recommend programs like InkScape(Adobe illustrator) or Gimp 2.0(Photoshop).

To do graphic design, you really need to know art. The best way to do art is to look at art from other's to create a personal taste (www.conceptart.org)/(www.deviantart.com) and then do it yourself! Study a lot from real-life and models so that, when you actually get to doing things digitally and free-form, you actually have some knowledge.

If you want to learn photoshop, there are a wealth of websites to do this with. Tutorials on DeviantArt are probably the most common source, but I would also recommend:

http://www.photoshoplady.com/

http://www.1stwebdesigner.com/design/30-useful-sites-where-to-submit-your-tutorials/

The second link is a bunch of links to photoshop tutorials. You will definitely figure out how to use photoshop and nifty techniques with those!

Some fine (free) 3D applications would be Blender and Google SketchUp, the latter was used to create my 3D model for the college entrance. I hadn't used it before, but found it to be intuitive and easy to learn.

These are the basics. You can always branch out to game graphic design after you have some of that formal training. There are many pixel editors if that's your kind of thing. If you try to jump into free-form game graphic design without any sort of training, then you will likely produce sub-par results that will simply demotivate you until you don't want to do any more.

Of course, you can be stubborn and try to do it anyway. Best of luck in any case ^^

# Answer
> 5 votes
SoulBeaver was correct to point out that you need to know art. A lot of the tutorials online will give you a mechanical guide on how to achieve a certain effect or how to draw with a tablet etc but if you don't know how to draw then you won't be able to produce much.

By all means learn the software, if you want to do spriting then you need to know how to use something like Photoshop, Paint.net Gimp, graphics gale etc but don't neglect your drawing skills and your ability to interpret what you have in your head into something tangible.

Someone on Reddit university is starting a course on Video game concept art and drawing It might not be exactly what you're looking for but it's free and might be worth a look.

# Answer
> 2 votes
There are lots of great tutorials around on the web for achieving different graphical styles. You'll want to pick up a copy of PhotoShop and start learning it if you already haven't. A few links to get you started:

http://tutorialblog.org/pixel-art-tutorials/

# Answer
> 1 votes
You might want to check this link to cgsociety and another one to thegnomonworkshop Good luck and have fun!

# Answer
> 0 votes
It depends on what sort of graphics you want to learn and how good you want to be. Using tutorial sites to gain a technical understanding of your tools is very helpful, to start, BUT to improve your artistic ability, it's best to mix it up with those who have similar goals.

Places like

are good places to get ideas, have your work critiqued, and to view and critiqued the work of others, which as certain people I know would say, "Serves to increase your visual literacy." *Ahem*.

---
Tags: 2d, 3d, graphics, 2.5d
---


title: Scrolling tile system

text:
# Question
Title: Scrolling tile system
I know this is a common question, but I can't find an answer to it that isn't written using a huge game library sadly.

I'm trying to write a scrollable tile system, which allows the user to move around it (from an arial perspective). I have this partially working, but it doesn't work as expected.

Could anyone help me out with this please, or link to where I can find a tutorial which doesn't use a huge **java** library?

Thanks

Edit:: http://thepb.in/private/L5elnMb3PU This is a concise example of the problem, you seem to move a lot faster when the player should be 'in the center' (Please ignore the loop for redrawing)

# Answer
Okay. I'm going to go back to basics and give you a simple model of how this should work, rather than staring at your code.

Let's say your screen res is 1024x768. Your tiles are 256x256 -- huge tiles, I know, but we're just working on the principles here. So your screen covers 4 tiles across and 3 down.

When you first run your program, the tile you're currently focused should be at the top left of your screen (0,0). It stretches down to (256, 256) on your screen.There are two tiles directly below it, and 3 directly to the right, because of the size of your screen and your tiles. Lets assume you have no offset yet, then the tile at the top left of your screen will be tiles\[0,0\].

Now, lets say your whole grid is 8x6 tiles. That means it's 2 screens across by 2 down. Starting from the top left of your map, you would be able to scroll right 7 times (8 minus 1), and down 5 times (6 minus 1), before the bottom-right-most square of the map would be at the top left of your screen -- with black (empty spaace) all around it -- the empty space around your array's bottom-right-most tile, AKA tiles\[7,5\]. Got it?

If you scrolled up and left from here, what would happen? Well, if you coded things right, you'd see some black (empty) space, because now you're looking at regions outside your array, such as tiles\[-1,-1\] etc., which obviously don't exist because in Java there are no negatively-indexed arrays. (As long as you make sure you never try to reference the array with a negative number, it will behave as I've described -- you'll see black, gray or whatever your background colour is, if you scroll out-of-bounds).

Okay. Now next up what you have is a Camera. From our human point of view, the map isn't moving, but the camera is. It has an x and a y value. And unlike the array, this camera can have any index you like, even (-42, -80). These are your offsets into (or outside of!) the map. So in my original example where you first run your program, that's when the camera offset is (0,0). If you set it to (0,1), you would now have shifted your *view* one cell down, meaning you could no longer see tiles\[0,0\], but instead you would have tiles\[0,1\] in the top left of your screen. If you shifted your camera up instead, by setting it to (0,-1), you would see tiles\[0,0\] at the middle left of your screen, and black "void" above tiles\[0,0\] (and it's 3 neighbours to the right which are also on your screen).

So whats the relationship between Camera and background? Well, the Camera's just a marker, really. It doesn't physically move, but since everything in life is relative, it may as well be. What's really moving are your background tiles. *You move the background by negative (minus one times) each of the Camera's x and y values*. And that's the key. The camera simply notes the offsets and wraps the idea of a movable camera up in an easy-to-use-and-understand sort of way, but it's the map tiles, as you draw them, that *actually* move accordingly. And as for the map array in memory? -- That stays exactly the same, of course, since it's just a model of the world, and that doesn't change just because the view changes.

How do you prevent yourself getting an array out-of-bounds error, then, when you move your camera so far to the left that it goes off the map? Well, you just need to make sure that if your *minus one times camera offset* produces either a negative x or a negative y, that you DO NOT try to index into the array to determine what type of tile it is, and this what graphic to draw. In these cases, you simply *do nothing*. Otherwise you will Java will throw an NPE.

---

This should get you started. There is other stuff, like offsetting the view by one-half of screen's width and one-half of a screen's height, so that whatever coordinate you push into the camera, instead of that tile being visible at the top left of the screen, it will be visible in the centre (for example; it could be anywhere you want it but centring is the most useful). And then the smooth scrolling we mentioned. But I think the above gives you enough to chew on for now?

One last thing. Although I mention pixel sizes in this example, for now they just aren't important. What's important is only your tile offsets. Again, you should not be thinking in terms of pixels right now, that will come later when you look at smooth scrolling. The only place in your code where pixels should come in is literally where you draw your tiles on screen each render update, something like

```
for (y = camera.y; y <  camera.y + screenHeightInTiles; y++)
{
   for (x = camera.x; x <  camera.x + screenWidthInTiles; x++)
   {
       drawTileAt(x*tileWidth, y*tileWidth); //<-- this is the only place you're working with pixels, i.e. tileHeight and tileWidth (if they're not exactly the same)
   }
}

```
> 11 votes

---
Tags: java, tiles
---


# Question
Title: Help me get my 3D camera to look like the ones in RTS
I am a newbie in 3D game development and I am trying to make a real-time strategy game. I am struggling with the camera currently as I am unable to make it look like they do in RTS games.

Here is my Camera.cs class

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace BB
{
    public class Camera : Microsoft.Xna.Framework.GameComponent
    {
        public Matrix view;
        public Matrix projection;
        protected Game game;
        KeyboardState currentKeyboardState;
        Vector3 cameraPosition = new Vector3(600.0f, 0.0f, 600.0f);
        Vector3 cameraForward = new Vector3(0, -0.4472136f, -0.8944272f);
        BoundingFrustum cameraFrustum = new BoundingFrustum(Matrix.Identity);

        // Light direction
        Vector3 lightDir = new Vector3(-0.3333333f, 0.6666667f, 0.6666667f);

        public Camera(Game game) : base(game)
        {
            this.game = game;
        }

        public override void Initialize()
        {
            this.view = Matrix.CreateLookAt(this.cameraPosition, this.cameraPosition + this.cameraForward, Vector3.Up);
            this.projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.game.renderer.aspectRatio, 1, 10000);

            base.Initialize();
        }

        /* Handles the user input
         * @ param   GameTime gameTime
         */
        private void HandleInput(GameTime gameTime)
        {
            float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            currentKeyboardState = Keyboard.GetState();
        }

        void UpdateCamera(GameTime gameTime)
        {
            float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            // Check for input to rotate the camera.
            float pitch = 0.0f;
            float turn = 0.0f;

            if (currentKeyboardState.IsKeyDown(Keys.Up))
                pitch += time * 0.001f;

            if (currentKeyboardState.IsKeyDown(Keys.Down))
                pitch -= time * 0.001f;

            if (currentKeyboardState.IsKeyDown(Keys.Left))
                turn += time * 0.001f;

            if (currentKeyboardState.IsKeyDown(Keys.Right))
                turn -= time * 0.001f;

            Vector3 cameraRight = Vector3.Cross(Vector3.Up, cameraForward);
            Vector3 flatFront = Vector3.Cross(cameraRight, Vector3.Up);

            Matrix pitchMatrix = Matrix.CreateFromAxisAngle(cameraRight, pitch);
            Matrix turnMatrix = Matrix.CreateFromAxisAngle(Vector3.Up, turn);

            Vector3 tiltedFront = Vector3.TransformNormal(cameraForward, pitchMatrix * turnMatrix);

            // Check angle so we cant flip over
            if (Vector3.Dot(tiltedFront, flatFront) > 0.001f)
            {
                cameraForward = Vector3.Normalize(tiltedFront);
            }

            // Check for input to move the camera around.
            if (currentKeyboardState.IsKeyDown(Keys.W))
                cameraPosition += cameraForward * time * 0.4f;

            if (currentKeyboardState.IsKeyDown(Keys.S))
                cameraPosition -= cameraForward * time * 0.4f;

            if (currentKeyboardState.IsKeyDown(Keys.A))
                cameraPosition += cameraRight * time * 0.4f;

            if (currentKeyboardState.IsKeyDown(Keys.D))
                cameraPosition -= cameraRight * time * 0.4f;

            if (currentKeyboardState.IsKeyDown(Keys.R))
            {
                cameraPosition = new Vector3(0, 50, 50);
                cameraForward = new Vector3(0, 0, -1);
            }

            cameraForward.Normalize();

            // Create the new view matrix
            view = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraForward, Vector3.Up);

            // Set the new frustum value
            cameraFrustum.Matrix = view * projection;
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            HandleInput(gameTime);
            UpdateCamera(gameTime);
        }
    }
}

```

The problem is that the initial view is looking in a horizontal direction. I would like to have an RTS like top down view (but with a slight pitch). Can you help me out?

# Answer
> 2 votes
I think that problem is in your view matrix. The third parameter is so called "up vector". You should maybe se it to Vector3.Forward. Or you can calculate it as this.cameraForward.cross(Vector3.right) - I don't know, if XNA syntax is like this, but there should be cross product of vector cameraForward and vector pointing to the right (or left).

# Answer
> 1 votes
```
view = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraForward, Vector3.Up);

```

that second argument for the createlookat() is a camera target.

im currently working on my first 3d rts also and the way i have it set up is my camera controls move a vector3 "target" which is set as my cameras target and the in my update() after controls:

```
"cameraposition = new vectors3(target.x,target.y + zoom, target.z-zoom)"

```

where zoom is a variable that changes with the scroll wheel

and if you want to add in camera rotation you just apply some trig to the x/z

```
if (keyboardstatecurrent.IsKeyDown(Keys.Up))
    target = new Vector3(target.X + (float)(camSpeed * Math.Cos(CamRotation)), target.Y, target.Z + (float)(camSpeed * Math.Sin(CamRotation)));

if (keyboardstatecurrent.IsKeyDown(Keys.Down))
    target = new Vector3(target.X - (float)(camSpeed * Math.Cos(CamRotation)), target.Y, target.Z - (float)(camSpeed * Math.Sin(CamRotation)));

if (keyboardstatecurrent.IsKeyDown(Keys.Left))
    CamRotation = CamRotation + 0.1;

if (keyboardstatecurrent.IsKeyDown(Keys.Right))
    CamRotation = CamRotation - 0.1;

```

Camrotation is initialized as 0 and is in radians.

```
        cameraposition = new Vector3(target.X - (float)(Zoom * Math.Cos(CamRotation)), target.Y + Zoom, target.Z - (float)(Zoom * Math.Sin(CamRotation)));

```

---
Tags: xna, camera, rts
---


# Question
Title: What would be the simplest way to create a 2D board game for Android?
I'd like to create a very simple 2D board game for Android, it would be a concept/mockup so I can see how the game works out.

Let's for the sake of this question that it's a clone of Othello - board game with score display, clickable game pieces/spots on a square grid and some animations.

I have to choose from these approaches:

* do it all myself, draw the game on Canvas - I've done one game this way, and it took some time to code it. Then, that was a casual action game and the animations would be hard to implement.
* implement it with Android widgets - I'd use RelativeLayout/TableLayout; the pieces will be ImageViews - this way I'd get the animations for free with Android tween animations. This would be the quickest of all solutions timewise, but I might run into some problems that may be a deal breaker.
* use AppInventor - it may do the task, but don't know anything about it, this approach would also require some time to go through the tutorials.
* use a proper game engine. That will take time to learn how to use it, which I view as the biggest disadvantage as I do mostly business apps, not games. And I don't know which one to choose from.

I really only want to throw this together in the shortest amount of time to see how it works, so I don't want to invest a lot of time to do it in the most "correct" way - that I'll do later if the concept works.

# Answer
> 2 votes
For a board game, my personal choice would go to creating a custom View, drawing the game on a Canvas.

As it's a board game, this would be efficient enough, and would'nt require as much animation as an action game.

My second choice would go to a "proper" game engine, probably based on OpenGL. If you already programmed a game using Canvas, it shouldn't be too hard to understand how to use a game engine (besides most of them have good tutorials and documentation).

# Answer
> 2 votes
If it's just for a prototype, I'd say go with the approach you're most familiar with or the one you think you'll get some fast results (that's usually the same as the one you're most familiar with :))

After the prototype is done, I suggest you switch to a game-engine. GUI-Frameworks for business apps might work for some games, but in the long run you'll benefit from the game engine. Also: You should switch tech to implement your real game, so you don't get tempted to just turn your prototype into the real game. This could be an excellent way to learn about a game engine.

---
Tags: android
---


# Question
Title: Best way to do a strategic map for a 4X space game on a web page?
I'm currently looking at the options regarding how to do a strategic map for a web application.

My goals here are :

* a synthethic view of what's happening in a stelar system
* the ability to management movements (through displaying trajectories of some ships and planets/star(s))
* the development should'nt take years, since we're few on the project

The usability challenges at hands are IMHO:

* scale issues: both in terms of ships/planets/stars volumes and distance. In the end, I guess markers/symbols are the way to go
* density of information: there could be much there
* frequent updates of the map needed (every 30 seconds or so, would be better if partial reload/refresh possible)

Options I'm aware of:

**use of a table, through the background image and cells images**

* \+ easy to do on my own
* \+ partial refresh possible (ajax on a per cell basis)
* \- very low resolution =\> looks poor

**JavaScript map drawing**

* \+ looks very powerful
* \- big work needed (I haven't found pre existing plugin/library/framework doing this, whereas I'm not a JavaScript guru)
* \- way to go unclear: canvas or dom manipulation?

**use of svg pictures**

* \+ resolution amazing
* \+ http://raphaeljs.com/ to the rescue
* \- I don't know much about svg

**CSS3**

* I'm rather clueless about it, what about performance/cross browser support and the like...

As a side note, I don't want to bother too much for IE.

Did I miss something obvious? What would you suggest?

thanks in advance best

BTW, a related topic but more focused on svg: Is SVG a viable technology choice for web-based game?

# Answer
> 2 votes
Before you roll your own map, I'd have a look at existing map frameworks. OpenLayers seems to be a good candidate that already has a lot of your requirements implemented.

If that doesn't fit your needs, you could still implement it yourself. SVG is particularly interesting, because you get an infinite level of zoom (given your assets are vector-graphics).

You're going to need JavaScript for the refresh code and dynamic positioning of elements anyway, so there's no way around JavaScript. Usually you'll use `canvas` to draw graphics, but you could use DOM elements (and CSS3) or SVG for your drawing. There's this question that lists some JavaScript libraries for game-dev.

Another interesting API is Paper.js which allows you to draw vector-graphics and images using a JavaScript API.

In the end it highly depends on your requirements. A zoomable map will look best with SVG but requires you to create your assets as SVG graphics. An existing framework like OpenLayers is probably the best way to get something on screen fast though.

---
Tags: maps, performance, web
---


title: Spot the difference game design help

text:
# Question
Title: Spot the difference game design help
I'm thinking of making a *spot the difference* game. But immediately I stumbled over a problem. I'm thinking of storing a "difference area" in the form of a `x,y` coordinate. However, because on a smartphone it will be difficult selecting the exact pixel at that location, I need a way of checking if the "area" is within the "touch area". I hope that makes sense. I've attached an image to help you understand

In this example the "difference point" is located at `-180,-140`. A user could touch anything within 5 pixels of that and that will be marked as a correct answer. So touching `-177, -147` would also be correct. How can I check if the touch-coordinates are within a 5 pixels radius of the correct "difference point"?

# Answer
What you need is to know the geometric distance between the user's touch (T) and your "difference point" (D).

```
distance = squareroot((T.x - D.x)² + (T.y - D.y)²)

```

Then as another answer said, just check if the distance is less than the circle's radius, 5 pixels in your example.
> 10 votes

# Answer
If you have a list of points, you're most likely doing it wrong: I'll try to explain why and how to do it correctly instead.

Once the user finds a difference, you'll have to make the difference disappear from the second image: the most straightforward way of doing that is to have one "base" image, which is the first one, and many small images which are the differences, applied to the second image at given coordinates. When the user finds the difference, you just fade out that image.

Keeping two separate images occupies much more space, and makes removing the difference after they are found a very fragile operation that will likely result in slightly garbled graphics.

To do it you usually start from two images which must have been produced with lossless formats, and use a tool you created yourself to automatically create all the differences and provide you the coordinates — then you will include in your code only the first image and the differences.

This might seem complicated, but it's actually simpler (and **much** more elegant and efficient) than writing code which have to handle images in a messy format.
> 1 votes

# Answer
If your 'click' event gives you a 2D point on the screen:

* A 2D point is inside a circle if its distance from the center of the circle is less than the circle's radius.

And if it gives you a 'hit circle', then:

* Two circles intersect if the distance between their centers is less than the sum of their radii.
> 0 votes

---
Tags: mathematics, coordinates, touch
---


# Question
Title: Loading tilemaps, entering buildings, chopping big maps
I´ve got some questions regarding the loading of tile maps. I´ve got a world with several buildings in it that guide the user to a new map. This map can be a small room, but also a big area. To change the map it seems straight forward to change the current tilegrid to the tilegrid of the new map.

But this seems pretty inefficient in some cases;

* User enters building from world map
* Small building map is loaded
* User exists building, enter world again

This scenario causes the entire world map to be loaded again. I could just hold the previous map in a variable to prevent it from needing to be loaded again. But what if the new map has several other passages, or is a big map itself. Then I would need to hold a big amount of data.

I was thinking of loading only tiles that are in a certain radius of the players viewport. But entering new maps would still cause the entire viewport area to be loaded again.

Is there a way how this type of thing is generally done?

# Answer
Of course you don't want to blit you entire world, you can :

* Use a chunked file format to store your maps, that way you can optimize how many informations you have in memory.
* Have a world, and keep the world informations while you're in the building, see the interiors as some "instance".
* Stay simple and calculate a square size you must draw, it's a pretty efficient way.

You have to find the fair middle between the performance you want to achieve and the quantity of memory you want to use.

But keep in mind that the tiles have been made in order to save memory, loading and freeing tilesets is not that heavy, maybe your system is different or your graphics lib is too slow for the resolution you choosed, you maybe should give more informations, for example did you made some measures ?
> 2 votes

---
Tags: loading, tilemap
---


# Question
Title: 3D Side-Scrolling Shooter: to use or not to use Lua scripting?
I'm programming a Side-Scroller, and I've reached the point where I need to program the enemy behaviour. I don't know what I should choose between hard-coding the enemy ships' behaviour or using a scripting language.

Going with the hardcoded way, all different kind of enemies would be different classes derived from an abstract `EnemyShip` class with a virtual function redefined for each of them. Going with the scripting instead I could do just a base class and a script manager which moves the ships as needed.

What should I do?

# Answer
> 3 votes
If you want a lot of different behaviors, go with Lua.

If your behaviors can be determined by some boolean (Aggressive, follows target, ... ...) go without.

Between the two I'd go without also (say 16 enemies and 4 bosses for example I'd hardcode all that).

My two cents are that scripting is usually for scripters, not for coders so if you feel comfortable with the language used, stick to that language, if you don't (and maybe you will want to add enemies months and months after the development was finished) you might want to go with a scripting language as it is definitely more secure than breaking up old code...

# Answer
> 2 votes
I'd go LUA every time. The fact is, even if you aren't a scripter, it's simply easier to change a text file and run the game (especially if you can do this runtime) than changing something and waiting to compile.

And then you get the added bonus of learning LUA, making it easy for people to mod, etc. etc. etc.

There are more articles on how to do this than you can ever read, so, just go with LUA, you only win ;)

P.S. When I say LUA I mean any scripting language. LUA is just the de-facto industry standard.

# Answer
> 1 votes
In my experience, LUA can be great for small scripts that control a single entity's behaviour. Not needing to compile the scripts means that you can iterate on the behaviour very quickly, making small adjustments and reloading the script to immediately see the new behaviour. When you start getting into complex logic, however, it is invaluable to have the structure that is enforced in languages like C++. Having a compiler and a debugger to catch problems can save you a lot of time.

In your case, it sounds like you are thinking of having your AI *driven* by your compiled language (i.e. at a high level, managing the game state and the entities therein in C++ or some similar language), with the behavioural logic for individual ship types in LUA. That seems like a sensible way to go. I would not, however, try to have the entire game's state handled by LUA - it could make it incredibly difficult to debug.

---
Tags: ai, scripting, side-scroller
---


# Question
Title: How to get the result of random item with different possibility?
I'm wondering if anyone can guide me with following problem... Each fruit has different chance to be called out.

```
Apple - 80%
Orange - 10%
Banana - 10%

```

Each time a user click on the random image, only 1 fruit will come out with above weight. I have no idea how I can calcuate to get that result. Pseudo code example is fine for me.

# Answer
Randomize a number between 1 and 100, then:

```
n <= 80: show Apple
n > 80 and n <= 90: show Orange
n > 90 and n <= 100: show Banana

```
> 6 votes

# Answer
```
int TotalWeight = 100;
int[] ItemWeights = new int[] {80, 10, 10};
enum Items {Apple, Orange, Banana}

Items GetRandomItem()
{
    int random = Random.Next(TotalWeight);
    int i=0;

    while (random > ItemWeights[i])
    {
        random -= ItemWeights[i];
        i++;
    }

    return (Items) i;
 }

```
> 4 votes

---
Tags: mathematics
---


title: computing gl_FragDepth

text:
# Question
Title: computing gl_FragDepth
I am trying to draw spheres using a billboard, so I have a normal map with a z component that I am sampling in my fragment shader. I just need to add this z component to the depth of my fragment to get proper 3D spheres...

How do you determine the current fragment's z-depth, add my offset and then set `gl_FragDepth`?

I've found lots of confusing contradictory hints and partially working bits of code all over the 'net, but no definitive clear answer.

***UPDATE***

final result (no shadowing) http://www.youtube.com/watch?v=88idbFlvQV0

# Answer
> 9 votes
> I just need to add this z component to the depth of my fragment to get proper 3D spheres...

First of all, this *will not work*. Unless your spheres are very small (relative to the camera), simply adding to the depth will not create a proper impostor. If the sphere is towards the edge of the screen, then you will not get a proper visualization effect. A sphere becomes oblong towards the edge of the screen, and the "up" direction for a particular point on the sphere isn't the same everywhere.

You have to use ray tracing to render a proper sphere impostor for spheres of a decent size. And if your spheres are always too small to notice, then you won't notice the lack of depth bias either.

Also, I'm not sure what good biasing the depth will do. It will certainly make interpenetrations more realistic, but that's about it. The bump-mapped lighting will do far more for your visuals than bumping the depth of the fragment.

However, if you insist on doing this without raytracing (a version *with* raytracing is available here), the first step is to take the current Z value and transform it back into clip-space. This will help linearize it. This has been asked and answered. That gets us back to clip space. But you need to take that clip-space position and go back to camera space. So you need the inverse projection matrix. Given that, you do this:

```
 vec4 cameraSpacePosition = invProjMat * vec4(0, 0, clipDepth, gl_FragCoord.w);

```

Next, you bias the camera space Z position with a *camera space* offset. It's important that the offset be in camera space; otherwise, it doesn't work.

Once you have that, you just perform the transformation back to window space:

```
cameraSpacePosition.z += bias;
vec4 clipPos = projMat * vec4(cameraSpacePosition, 1.0);
float ndcDepth = clipPos.z / clipPos.w;
gl_FragDepth = ((gl_DepthRange.diff * ndcDepth) +
    gl_DepthRange.near + gl_DepthRange.far) / 2.0;

```

# Answer
> 0 votes
According to the GLSL specification (both 1.10 and 4.20) `gl_FragCoord` holds the window relative coordinates of the fragment, from which `z` is the depth that gets written into the depth buffer (if not changing `gl_FragDepth`). So you can just write

```
gl_FragDepth = gl_FragCoord.z + depthFromTexture;

```

---
Tags: opengl, glsl, depth-buffer
---


# Question
Title: How many shadow casting lights are in modern games?
I'd like to know how many shadow casting lights are supported in modern games, such as Uncharted 2, Crysis 2, Modern Warfare 2, Halo: Reach, etc. Do they all limit themselves to just a couple of shadow casting lights, or do the numbers vary wildly?

# Answer
> 6 votes
I haven't played MW2 and Halo, but Crysis 2 and Uncharted 2 don't have lots of dynamic shadow-casting lights at the same time. I can remember mostly 2 shadow casters at the same time; naturally they wanted to keep shadow resolve quick. Generally shadows are expensive to compute, so most games will have 2-4 shadow-casting lights with several non-shadow-casting lights nearby, then shadow resolve will switch between them depending on light’s screen presence. Two shadow casters are enough for a nice visual, especially when you're targeting consoles with limited resources and have to do other lighting parts quick and beautiful, which means lots of pre-computed stuff.

I'm sure there are papers on Crysis 2 and Uncharted 2 lighting somewhere, but here is a pretty generic guess mentioning most modern techniques: detailed character shading via lighting baked into AO and diffuse maps, cascade shadows for global light source and several dynamic lights per pass via some spatial screen partitioning and a normal buffer, with the rest of the lighting baked into vertexes through some form of PRT.

That's not a very useful info for *your game*, you know. Number of shadow-casting lights depends on the approach to lighting, which in turn depends on lots of things like a renderer's architecture, expected scene complexity, chosen shadow maps for a global light, desired post-effects and overall "heaviness" of the shaders.

Also keep in mind that dynamic lights, shadow-casting or not, aren't the biggest part of overall lighting scheme, there are other important points to consider like character lighting/shading, opaque/alpha blend geometry and various post-processing effects.

---
Tags: performance, lighting, shadows
---


# Question
Title: Why does this code work for a stationary object, but not a moving one?
I use the following chunk of code to make bullets that fire towards the player's ship:

```
@Override
public void onTimePassed(final TimerHandler pTimerHandler)
{
    pTimerHandler.reset();
    if(spawnBullets){
        for(int i = 0; i < enemies.size(); i++){
            if(enemies.get(i).isShooter()){
                //shoot from this enemy to ship
                final Vector2 v = new Vector2(ship.getX() - enemies.get(i).getSprite().getX(),ship.getY() - enemies.get(i).getSprite().getY());
                v.nor();
                v.mul(BULLET_SPEED);
                createEnemyBullet(enemies.get(i).getSprite().getX(),enemies.get(i).getSprite().getY(), v);
            }
        }
    }
}

```

This works fine if the enemy is stationary, i.e. just a `Sprite` with no `Body`, but when the enemy is moving, my game completely freezes up. Sometimes it will happen immediately (on the first attempt to fire), or sometimes 1 or 2 bullets later.

It gets through this code (a log output after `createEnemyBullet` works fine), but locks up somewhere before anything else happens. Disabling this section of code makes the problem go away. What could be going wrong?

### Edit

Here is `createEnemyBullet()`:

```
private void createEnemyBullet(float x, float y, Vector2 v){
    //remove old bullet
    if(enemyBullets[enemyBulletCounter] != null){
        makeBulletExplosion(bullets[i].getX(),bullets[i].getY());
        mScene.detachChild(bullets[i]);
        mBulletPhysicsWorld.destroyBody(bulletsPhysical[i]);
        bullets[i] = null;
    }
    //create new bullet
    enemyBullets[enemyBulletCounter] = new AnimatedSprite(x +8, y +8, this.mEnemyBulletTextureRegion); //Nasty magic number, oh well
    enemyBulletsBody[enemyBulletCounter] = PhysicsFactory.createCircleBody(this.mBulletPhysicsWorld, enemyBullets[enemyBulletCounter], BodyType.KinematicBody, BULLET_FIXTURE_DEF);

    enemyBullets[enemyBulletCounter].animate(55);
    enemyBulletsBody[enemyBulletCounter].setLinearVelocity(v);

    this.mBulletPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(enemyBullets[enemyBulletCounter], enemyBulletsBody[enemyBulletCounter], true, true));
    this.mScene.attachChild(enemyBullets[enemyBulletCounter]);
    //update counter
    enemyBulletCounter = enemyBulletCounter < ENEMY_BULLET_MAX -1 ? enemyBulletCounter + 1 : 0;
}

```

# Answer
I'm going to write an answer instead of a comment.

Looking at your CreateBullet method: You are creating two new objects for each new bullet: AnimatedSprite and CircleBody You will have many short-lived instances of them. Better to recycle them. Have an object pool of both classes and initialize them as invisible/disabled. Each time a new bullet is requested just retrieve an unused object from each pool, initialize them and activate them. Bullets objects that are destroyed are returned to the pool for reuse.

A brute force "debugging" tip: To narrow the line causing the issue. Print to console between each line. This is not pretty, but will quickly show which line causes the hanging.

You also said the code works fine, if the enemy has no physical body. Could it be that you spawn new bullets inside the enemies body? That might trip the collision resolution of the physics engine.
> 2 votes

---
Tags: android, andengine
---


# Question
Title: What's the URL of the video showing an EA representative talking about game programming?
The video shows an EA representative talking about how a programmer can get into the industry by showing some demos (in fact, he shows a physics demo presented by a candidate who wanted a job at EA). The demo shown depicts kind of a ragtime doll made of yellow cobblestones.

I don't remember if I watched on YouTube or Vimeo and I frankly cannot find it after a few hours of work. I just remember the fact that it was taken at a GDC or a SIGGRAPH convention.

Thanks in advance. I'm really frustrated because I'd love to show this video to some fellow developers (coders).

# Answer
> 3 votes
I'm not sure if the exact video you're looking for is included in this collection, but the link below includes 23 different lectures by EA employees on various aspects of game development:

Electronic Arts: Game Development Lectures

If nothing else, at least hopefully you can find something interesting and worthwhile in one of those videos. Good luck!

---
Tags: software-engineering, game-industry, video
---


# Question
Title: What is the difference between the marching cubes algorithm and metaballs?
After doing some research, I found out about the marching cubes algorithm and "metaballs". How exactly do they differ?

# Answer
> 9 votes
The two are totally different. Marching cubes is a conversion algorithm, while metaballs are mathematical constructs that can be used to represent certain 3D models.

Marching cubes is a technique that lets you convert a non-polygonal 3D model (such as one represented by voxels) to a polygonal one. It works by examining cube-shaped chunks of the model and representing each chunk with a certain pre-defined arrangement of polygons based on which corners of the cube are solid.

Metaballs provide a non-polygonal way of defining 3D models mathematically as a set of 3D points (the metaballs) that sort of glob together as if they were made of magnetic goo. Metaball models tend to do well at curvy surfaces and not very well at sharp, angular, or flat ones.

Marching cubes can be used to convert a metaball model into a polygonal one that's easy to render using your everyday 3D card.

Wikipedia's articles on the topics are decent.

---
Tags: algorithm, 3d-meshes, procedural-generation
---


# Question
Title: How to get started being a game designer
I was wondering how can I get started with game design & developement because Im not really good at any programming languages that used to make games

# Answer
> 9 votes
Board games. Or card games. Or games that don't require computers at all. In some ways, these are easier than computer games, because you don't have to spend time in the code if you want to change the rules, you just change them. It's quick and easy to make a game using tokens or random craft stuff, and all you'd need is friends to play test the game. Ideally, friends who like board games or whatnot (if you don't have any such friends, search for a local board game group or similar)

# Answer
> 7 votes
## Mediums of Experimentation

Analogue mediums are great for getting started. Mediums such as card games, board game and pen-and-paper RPGs like Dungeons and Dragons require no computer skills, and teach you some universal truths to game design that carry across all mediums.

If you're gung-ho on being digital, try map making first. I'd suggest downloading the Unreal Development Kit, and getting used to it's mapping tool (UnrealEd).
Once you're comfortable with that, you can explore Kismet, which is a graphical, node-based programming tool for UnrealEd. You can program interactions without having to write a line of code.

Ultimately, though, knowledge of a simple scripting language such as Lua or Python will help in your designing a great deal, if for no other reasons than to help you structure your thoughts logically. They're easing enough to pick up, and a wealth of free resources exist to teach you.

---

## Progression of Design Expertise

When learning any art form (I consider Game Design to be an art), there are 4 stages of progress one should always undergo:

1. **Study and understand existing designs**. By expressing an interest in designing games, you've likely already done this for a while. Essentially, just look at existing games, new and retro, and try to divine the reasoning behind design choices.
2. **Recreate**. Take an existing game, and go through the process of designing it from scratch. Compare your final piece to the original product, and try to understand the reasons behind any disparities.
This is important for developing an appreciation for more subtle aspects of design that often go unnoticed, yet can make the difference between a good game, and a great one.
3. **Modify**. Take an existing design, and modify it somehow (ideally to improve upon it, but keeping it at the same final quality is also okay).
Design a Magic the Gathering card that is unique, yet balanced and powerful.
Think of how you could improve tetris or space invaders.
Modify De\_dust2 to add a greater emphasis on teamwork.
Whatever changes you make, the effect of said changes should be intentional.
4. **Original Design**. Using your experience modify games, make a new one from scratch.
Write an original DnD campaign in a new setting.
Create your own MTG-esque card game from scratch.
Design a boardgame using an under-utilised theme with appropriate original mechanics. Make your own map for CSS or TF2 or UT2k4 from scratch.

# Answer
> 3 votes
Use in-game editors, mod tools, map editors, or for something really basic try something like Stencyl.

# Answer
> 3 votes
Gamemaker is a very nice tool that doesn't require alot (if any) coding. It has a nice built in drop and drag system that will get you familiar with the basics; variables, functions etc. As you progress you can move over to inline coding at your own pace.

# Answer
> 2 votes
You could try to learn a programming language; there are many great free tutorials on the web. You could also use something like Game Maker, as omgnoseat mentioned. You could also try to find a friend who'd be willing to help you code the games, and have you design graphics or something, and work as a small team..

You weren't very specific, about what parts of game development you need help with, and what you're good at.

# Answer
> 0 votes
Try tool like Game Salad.

www.GameSalad.com

You need not have ANY programming knowledge, its so easy to use tool.

Hope you will find it useful.

---
Tags: game-design
---


title: Searching a map fewer times

text:
# Question
Title: Searching a map fewer times
... or better yet, removing the need to search the map altogether.

I'm either looking for suggestions on how to optimize my code, or a change in design.

In my component-based entity system, the Entity is comprised of Attribute and Behavior objects. The Behavior objects are just stored in an std::vector; they are no issue, I just call their update function.

Attributes, I store in a map of `<std::string, Attribute>` and they represent the path of communication between Behaviors (Behaviors never interact directly). When a Behavior needs an attribute it searches its Entity's map.

That's a bit problematic for Behaviors that access that information a few times a second, like the Rendering behavior (draws the Entity on-screen). Rendering needs to read the Position, the Orientation, and a few other things, and it needs to do that a few times a second.

How can I solve this issue? It should also be noted that the base classes Entity, Attribute, and Behavior are written in C++, but their implementations in Python.

# Answer
> 4 votes
Before I say anything else -- Is this causing problems? Because if its not causing problems, don't prematurely optimise it. I'm sorry if you already knew that, but it had to be said. If you don't know the old Knuth saying, I'll note it here for you.

Otherwise... Too much indirection is very often going to be a problem in real-time simulations. If you overarchitect things, this is the kind of wall you may well hit. You already know what the problem is; I guess it's time to make decisions about where it is *really* necessary to have that level of indirection. With entity systems, it is better to keep things very simple, as in terms of game logic this is "the metal" so to speak. Better to keep all that metal really close together.

The only other solution I can suggest is to use a much more efficient data structure... if that is possible in your case.

Why, if I may ask, is it a problem for your Behaviours (which are I think what I and I others would call entity components) to talk directly to one another?

I can suggest an article: Coding Cowboy -- Evolve Your Hieararchy. It should give you a bit of insight into how simple this can be, and has been in many games. In the article, the author is referring to the development of the early Tony Hawk games in particular.

EDIT: (In response to your 1st and 2nd comments) No, they wouldn't have to query the entity. That's the problem! Every individual EntityComponent *has to* have fixed references to other EntityComponents which it bears relevance to, or which bear relevance to it (depending on how you look at things). You problem is you're doing a lookup on every update. What I'm saying is you are meant to do this only *once*: You give each component a fixed reference to any component it depends on, from the time that these dependencies are injected, meaning, for example, that a pathfinding component is going to need to reference the spatial component; without it, it cannot know where it sits in space, and thus cannot pathfind. So you either inject all these components into your entity in the right order on entity creation (usually your entity factories will do this), or you build an intelligent system into your base entity class that rechecks all dependencies on every new component addition, and set fixed refs between them. But the fixed references are a necessity, otherwise you will face exactly the problem you are facing now -- no matter how you look at it, lookups have a cost and they do not belong at this point in your architecture, in any real-time game.

# Answer
> 1 votes
Swap the map for a hash\_map or an unordered\_map (whatever your compiler supports).

---
Tags: c++, python, component-based, optimization
---


title: Getting Past "Boring" Content Creation

text:
# Question
Title: Getting Past "Boring" Content Creation
When I'm creating games, I really love the coding part -- designing, developing the main functionality and "core" part of the game. However, most of my games are reasonably small/easy in terms of coding, but require a lot of content -- whether graphics, levels, sounds, puzzles, story narrative, etc.

I find development speeds through the coding parts, but nearly halts when it comes to content creation -- it's tough, sometimes boring work.

**What can I do to make content creation quicker and more interesting/fun?** I'm already integrating content into a working game, and building/using tools as much as possible to quickly assemble my content.

**Edit:** my question is not about learning any particular labor-/time-intensive skills like drawing assets or picking out sound effects; it's about that psychological hurdle when you have to just sit down and grind out the rest of your game, even if it's not the most fun thing in the world to do.

# Answer
> 7 votes
There's a great post on Zen Habits about this. If you can force yourself to sit down and work on whatever it is, even if just for 5-10 minutes, that will break your barriers and get you moving on your project.

# Answer
> 6 votes
When all else fails, there's always the option of finding a partner who is interested in content creation. If you have friends that play the type of game you're making perhaps one of them is interested.

Game enthusiasts who aren't necessarily programmers are likely your best bet. It doesn't even have to be people who've worked with game creation, many people with a deep love of games have the potential to create great content depending on their other talents (e.g. a writer, artist, someone who really loves puzzles, etc).

# Answer
> 3 votes
This really wont help make it fun, but what about using free assets you can find online?

For making levels, what if you could generate them via code? This wont work for all types, for it does for some games.

If you just can't stay motivated through it, what about paying someone to do it, or teaming up with somebody? For me, I do all the coding and a good fried of mine does the art, story line, etc...

What about breaking it up into more manageable pieces? Maybe tell yourself you will do 2-3 levels per week, and if it takes you 3-4 weeks to do them so be it. At least you finished! I find this helps me a lot on mundane programming tasks.

# Answer
> 3 votes
I always come across this blocker when I'm making games, particularly graphics, sound and music, so I'm going to focus this answer on graphics, sound, and music.

Finding art or an artist has been hard for me. Then Google Sketchup came along and changed the playing field for me (at least on the graphics front). There are thousands, if not millions of models that you can use for free from Google's 3D Warehouse. All of the models on Google Sketchup can be used for non-commercial purposes:

> "For the avoidance of doubt, you may modify, distribute, and create derivative works of Content uploaded by other users in 3D Warehouse" - http://sketchup.google.com/intl/en/3dwh/tos.html

FYI: I try to contact all of the modellers, thank them for their wonderful work, and tell them where I will be using it. I'd recommend you do the same.

Now... you may be thinking: "But I might want to make money one day!". And that brings me to my next point:

My game is presently free and open-source. This lets me use free resources like Google Sketchup and open-source music and sound clips. There are significantly fewer restrictions on content that you find if your project is open-source (or strictly closed source among you and your friends).

If I get to a point where I think my game is pretty awesome and I want to start selling it, all I have to do is freeze the open-source portion of the project (yes, sorry guys), pay an artist or two to change all the art & sound, add some new features to make it "better" than the free version, and away I go.

# Answer
> 3 votes
Perhaps you can attempt to create textures and sound through programming? Via procedural textures, Generative music and dynamically composing sound, you could not only create a style that's specific to your games, but "program your art". Seems like that's the best way to program AND create content.

You can always use the procedural content as a starting point too. Have your code create a level, and you can fill in the details.

Clearly this totally depends on the type of games you make, but I'm sure it could make some of the more tedious aspects more enjoyable.

# Answer
> 1 votes
If making levels and puzzles bores you, then perhaps you should stick to being a programmer and stop making games. Level and puzzle design is the very *meat* of game design. It is what separates a good game from a crappy game.

If that's not enjoyable to you, then you need a new profession.

---
Tags: process
---


title: Compressing game save data

text:
# Question
Title: Compressing game save data
I'm writing a game that needs to save a lot of detailed data (exact trajectories of some entities) to an external file. I want to save drive space and bandwidth by compressing it, but I've never done this, so I don't know if there is a preferred way to do it.

Of course the compression-decompression should not affect the speed of the game too much.

# Answer
The zlib library has bindings for most programming languages, and is quite fast. However, you should compare various comperssion algorithms, because one algorithm may achieve better compression rates on *your* kind of data than on the general case.
> 8 votes

# Answer
One, possibly extreme way of compressing data is to record only the steps/inputs used to create it. Something like what ModNation Racer does (curse those long loading times as it re-creates the track). (Google for videos of the track editor in ModNation Racer).

i.e. if i was storing some terrain, i'd store all the manipulations starting from a flat plain. i.e. apply the volcano shaped brush with this force, here. Apply the terrain smoothing operation over this area, with this force. Add my predefined object here. Using bezier-curve-like curves with 'key-frames' to construct an entire track/flight path/whatever.

Many other games do this sort of thing not just for level loading, but for gameplay too, by making the game deterministic, sending only player inputs (i think PixelJunk Shooter 2 does this).
> 1 votes

---
Tags: compression
---


# Question
Title: How to prevent fleeing monster from backing himself into a dead end?
I've been building a rogue-like for more than a year now, and so far I've only ever implemented very simple monster behaviour - such as moving toward the player when he's in the line of sight, and attacking.

I would like to implement fleeing behaviour for certain monsters that realize they're outmatched.

I have these priority based behaviour types for monsters:

* Flee
* Attack/Defend
* Investigate (event)
* Socialize / Explore / Patrol

The only code I have for fleeing is a flood fill routine which attempts to find tiles which "look" like they are doorways leading to corridors. The question is, how can I improve this to stop it from finding such tiles that deceptively look like doorways, but actually lead to dead ends?

# Answer
One thing I've done in the past is add a cornered state to the enemy. Put yourself in the shoes of the fleeing enemy. It is scared, it is hurt, it is fleeing and trying to just get away! Perfect mindset to get yourself cornered, which can be really fun for the player.

Once cornered, the enemy can do different things, ideally depending on the personality of the enemy itself:

1. They can cower and duck into the corner and wait for death. Only really works if you can convey those emotions. A single-character rogue-like enemy probably can't convey that without text or something. From here, the player could decide to leave the enemy alone, showing compassion. Could be really neat if the enemy then becomes passive. Or if healed, even become an ally of the player.
2. They could go into a blind rage and launch a last-ditch attack against the player, or unleash some kind of escape spell or skill; such as a squid squirting ink, or a lizard playing dead.

These are really more interesting than avoiding the corner in the first place. And are probably faster to compute, which will let you spend those cycles elsewhere.

But if you MUST avoid the corners at least a little, the best way I've found is to discourage walking down tight lanes. Simply check the 8 spaces that are 2 spaces away from the enemy. Such that if the enemy is on space (9,9) check spaces: (7,7)(11,11)(7,11)(11,7)(7,9)(9,7)(9,11) and (11,9). If any of these are open, check the 4 spaces around that space too. Weight movement in those directions according to the number of spaces you see. In a rogue-like, the walls are rarely even that far away, and this will encourage the enemy to stay in the same room.

Nothing is more annoying than an enemy that runs off down a long corridor, regardless of that corridors termination, and leaves the player to have to chase it down.
> 4 votes

# Answer
If your flood fill extends further, it will necessarily distinguish between dead ends and exits that lead further. The bigger the area you search, the more accurate it will be.

Alternatively, during the creation of your levels, you may want to annotate exits, so that they can be explicitly searched for. Find the nearest one and plot a path to it. Plotting paths can be done with the A\* algorithm.

Another way of using the A\* algorithm would be to pick a random point elsewhere in the level and plot a path to it. If it's reachable, that path would constitute an escape route. If it's not, you can try a different point. Ideally, you would attempt to plot a path to the exit from the level, as that would definitely be a viable escape route.
> 4 votes

# Answer
The developer of Brogue wrote an interesting article about how he uses what he calls "Dijkstra Maps" to accomplish this and other things: http://roguebasin.roguelikedevelopment.org/index.php/The\_Incredible\_Power\_of\_Dijkstra\_Maps

Basically, you run a variant of Dijkstra's algorithm to set a weight to every cell in your map. If you calculate one of these based on your player location, it provides a map of the quickest route from the player (or somewhere near the player) to any other point on the map. The global minimum will be the furthest point away from the player, which will necessarily be somewhere that wasn't blocked by a dead end.

It's probably not the most efficient solution, but on roguelike-sized maps it seems to perform fine, and there are a lot of other cool applications for it that he mentions in the article.
> 1 votes

# Answer
Basically, a dead end is a path where you can't go back to your starting point without turning back, so I think checking for that may be a simple solution, maybe not the best.

Another solution coming to my mind would be to mark dead end entry tiles with a flag.
> 0 votes

---
Tags: c++, 2d, ai, tiles
---


# Question
Title: Using 16 bit index buffers - USHORT vs UINT
In D3D11, they still have the ability to make 16 bit and 32 bit index buffers.

Few models will use more than the max (20k tri) that a USHORT index buffer can handle, but will I really pay a bad performance cost for always using an INT (32 bit) format?

Memory savings aren't that much (2 bytes per index!). For a 20k tri model, that's only 40 kB of memory we're saving for using the USHORT (compared with probably a lot more for just the vertex data for that same model).

Is it really worth ever using USHORT index buffers then, or is this just a holdover from when computers had less memory in the 90's?

# Answer
You have to consider that GPUs when fetching the data for feeding into the vertex shaders requires a lot of small calls because they can only cache a few triangles at the same time, and fetching data from the VRAM is a very slow operation. So I suppose that if you use half the bytes for the indices, the GPU will be able to fetch twice the indices for the cache to render triangles.

4MB Can be a small amount of memory for storage space, but if you have to make a complex call to only process a few bytes from them it may affect performance in a noticeable way. Nowadays video cards are powerful enough to make it irrelevant in games which don't have to process a lot of geometry, you... could do some benchmarks rendering a model with both index sizes if you really want to know.

Loading times are also faster with 16 bit indices, and actually every write or read, unless you can effectively control memory alignment and proper paging. So it's not just about the memory it requires but how much it takes to handle it. If you are working with dynamic buffers that need to be moved over the bus to the GPU at some point between Frames, then you should use 16 bit indices when possible. If you are rendering even smaller geometries, you can batch many indices in a single 16 bit index buffer for them all to get copied to the GPU in a single call.

Here you may find some information about how the newer ATI GPUs work:

ATI Stream Developer Training Resources (sorry I couldn't find the exact document) I didn't read much about the NVidia ones, but I think they work more or less with a similar approach.
> 10 votes

# Answer
While memory and CPU speeds have improved over the years, games are still often pushing the limits of hardware and software. If you're loading 100 such models, that's a savings of 4 megabytes of memory saved. In certain situations, it's worth it to save as much memory as possible. That might be enough for you to load another model, or enough to cram in a few more sound effects, or another song. For most AAA games, this sort of savings is vital to making things better than the competition.

Of course, it's all game dependent, and for plenty of projects, not really worth it. But if you want to push the hardware as far as it'll go, you'll want to find ways to save as much memory as possible, so you have room to add more cool stuff.
> 5 votes

# Answer
It's not just about memory; some hardware just flat-out cannot support 32-bit indexes and must run the vertex pipeline in software if you use them. It's getting rarer, but you can still get the occasional nasty surprise when you come across one. 16-bit indexes can also run faster in general, which can be important if you're under performance pressure, but you'll need to benchmark and weigh the benefit of extra perf from 16-bit indexes vs the tradeoff of possibly needing to split a model because there isn't one single answer to that one that's correct in all situations.
> 4 votes

---
Tags: index-buffer
---


title: Converting 2d path to 3d path

text:
# Question
Title: Converting 2d path to 3d path
What is the procedure to convert 2d path to 3d one. Maybe it's a silly question, but for example:

Let's assume that I have a path from point A to point B. And I have all X and Y coordinates of that path. Is it possible to convert that to a 3d path, so for example to animate a car driving along that path but in 3D.

# Answer
Converting a path from 2D to 3D can be fairly easy, you just have to assume that your car is on a flat plane. Then for each point on the 2D path (x, y), you create a point in 3D (x, y, z) where the third component is 0.

According to your 3D engine, the nul component will be y or z, but the idea is the same.
> 4 votes

# Answer
Your car is driving on some map, I presume, so use your X and Y to sample Z at this point of the map via ray intersection with map mesh triangles. Just google "ray intersections" for hundreds of examples. Then add some offset reflecting car's height to it, and you're done.
> 1 votes

---
Tags: 2d, 3d, path-finding
---