# Question
Title: Setting the Box2D gravity for a pixel coordinate game?
I'm making a game with Box2D with a top left coordinate system. I multiply positions by an M\_TO\_PX\_RATIO of 10.0f to convert from meters to pixels.

I noticed that when I set gravity to 9.8, the simulation is rather slow. When I set gravity to 9.8 * M\_TO\_PX\_RATIO, the simulation runs at the correct speed, like normal gravity. However, the high gravity causes jittering.

Am I doing it properly? When using a top left, pixel coordinate system, must I do anything else to account for meters to pixels?

Thanks

# Answer
> 2 votes
Box2D is a meter-based physics engine, and as such, it would not behoove you to try to force it to "snap" to pixels. The easiest way to get around this is simply allow Box2D to calculate all of the physics in the background, and simply render all of your pixel sprites to the screen at the closest pixel coordinate (I like to floor my x and y value to prevent sprite jitter).

Here's an extremely simple psudo-code version of what I'm trying to explain:

```
// Draw function
mySprite.render(Floor(calculatedXLocation), Floor(calculatedYLocation));

```

This will give the illusion of the sprite being locked to the pixel grid, but will allow your physics to run however you want them to run without being hampered by an odd time-step or gravity.

---
Tags: c++, game-design, box2d
---


# Question
Title: What do I need to do to my slope collision detection to prevent the player from passing through my collision?
I've recently implemented slope collision detection for my project. The issue I'm having is that the character occasionally passes through the line.

This usually occurs when the characters MoveAcceleration is increased from 5000 to 8000 via a game mechanic. I was wondering if there is a way to make the line collision more reliable without reducing the MoveAcceleration variable ?

This is how the characters position is calculated

```
velocity.X += movement * MoveAcceleration * elapsed;
Position += velocity * elapsed;

```

This is how the slopeCollision is handled

```
private void HandleSlopeCollisions(GameTime gameTime)
        {
            isOnSlope = false;

            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (velocity.Y >= 0)
            {
                if (attachedPath != null)
                {
                    isOnSlope = true;

                    position.Y = attachedPath.InterpolateY(position.X);
                    velocity.Y = 0;

                    if (position.X < attachedPath.MinimumX || position.X > attachedPath.MaximumX)
                    {
                        attachedPath = null;
                    }
                }
                else
                {
                    Vector2 footPosition = position;
                    Vector2 expectedFootPosition = footPosition + velocity * elapsed;

                    CollisionPath landablePath = null;
                    float landablePosition = float.MaxValue;

                    foreach (CollisionPath path in collisionPaths)
                    {
                        if (expectedFootPosition.X >= path.MinimumX && expectedFootPosition.X <= path.MaximumX)
                        {
                            float pathOldY = path.InterpolateY(footPosition.X);
                            float pathNewY = path.InterpolateY(expectedFootPosition.X);

                            if (footPosition.Y <= pathOldY && expectedFootPosition.Y >= pathNewY && pathNewY < landablePosition)
                            {
                                isOnSlope = true;
                                landablePath = path;
                                landablePosition = pathNewY;
                            }
                        }
                    }

                    if (landablePath != null)
                    {
                        isOnSlope = true;

                        velocity.Y = 0;
                        footPosition.Y = landablePosition;
                        attachedPath = landablePath;

                        position.Y = footPosition.Y;
                    }
                }
            }
            else
            {
                attachedPath = null;
            }
        }

```

# Answer
> 1 votes
I see three things that bother me here:

First, the first logic path seems to rely on a variable that doesn't seem to be set up. I'm confused. Perhaps there's a bigger picture not shown here.

Second, I think the second logic path is vulnerable to floating point issues.

Note that you do **NOT** check if the second point is in an unacceptable location, but rather if the movement vector crosses the path line. If this were done in integer precision I would consider it solid. The problem is the case of when you are exactly on the line, though--you are relying on a floating point equality test to keep the next move from taking you through the line. That's scary.

Third, it seems to me that you can freely pass though anything if your y velocity is negative. I assume those are screen coordinates instead of world coordinates so -y means you're going up. The ground is sloping up more steeply than your path is, you go right through it.

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


# Question
Title: How do I ensure an appropriate payout ratio for a slot machine?
I have done a lot of research into random number generators for slot machines, reel stop calculations and how to physically give the user a good chance on winning.

What I can't figure out is how to properly insure that the machine is going to have a payout rating of (lets say) 95%.

So, I have a reel set up wit 22 spaces on it. Filled with 16 different symbols.

When I get my random number, mod divide it by 64 and get the remainder, I hop over to a loop up table to see how the virtual stop relates to the reel position.

Now that I have how the reels are going to stop, do I make sure the payout ratio is correct? For every dollar they put in, how to I make sure the machine will pay out .95 cents?

Thanks for the ideas.

I am working in actionscript, if that helps with the language issues, but in general I am just looking for theory.

**Edit:** There is real money involved only in the fact that they can buy more tokens to play more. There is not going to be real money paid out to the person, if they were to actually hit the any of the paylines.

# Answer
> 9 votes
What you're asking is related to probability theory. It's easiest to work with one reel, and then extend it to multiple reels once you understand how it works.

Consider if you had a reel you have some symbols which you want to assign to the stops. More symbols on a reel will lead to greater control over the final results, but will feel more random to the player. The goal is to balance the number of symbols and stops so the machine feels less random to the player, and like they have more of a chance.

If you had 10 symbols and 10 stops, each symbol would have a 1 in 10 chance of appearing. It doesn't matter what order the symbols are in (in theory, in practice the randomness of the game is only as good as your random number generator). In other words, you might expect to see 10 different symbols in 10 spins, or a different symbol on every spin. The chance of getting one particular symbol is 1 in 10. So for every 10 spins, you can expect to see each individual symbol once. If you picked 1 symbol to be the "winning" symbol, the player would have to play 10 times before they won. With this information it's quite straight-forward to work out the payout. If you charge them $1 for each spin, they will have to spend $10 before they land on a win. If your expected rating is 95%, the calculation is $10 x 95% = $9.50. In other words, the prize for landing on the "winning" symbol must be $9.50 to have an expected payout of 95%. Now remember that this is all based on average. There's no guarantee that the symbol will appear in exactly 10 spins, it may take 100 or 1000 spins, or even just 1 spin to appear. Taken over a long enough time the machine will pay the correct amount on on average.

To getting this to work on multiple reels you need to multiply the winning probability of each reel. Consider an example of 3 reels with 10 symbols on each reel, and 1 winning symbol on each reel as in the previous example. Lets say you wanted the player to win only when all three reels show the winning symbol at the same time. To do this, you need to work out the probability for each reel, and then multiply the probabilities together. We know from the previous example that the probability is 1 in 10. This can also be written as 1/10, or 0.1. The probability of all three reels landing on the winning symbol at the same time is 1/10 x 1/10 x 1/10, or 0.1 x 0.1 x 0.1, or 0.001, or 1 in 1000. We see that there is a much lower probability of the winning symbol appearing on all three reels at the same time. The player would need to spin 1000 times on average before they win. If each spin was $1 they would need to spend $1000 to win. The calculation for the winning percentage then is: $1000 x 95%\** = $950.00.

That's the theory in a nutshell. The rest is balancing balancing the different probabilities to make the game appear more interesting.

In your case, if you have 22 stops and 16 symbols. This means you will have 6 symbols which are the same as at least one other symbol. The exact probability of any particular symbol appearing depends on the total number of occurrences of that symbol on the reel. How many of each symbol is on each reel is really up to you.

As an example lets say you have 15 unique symbols, and 7 which are all duplicates. The chance of any one of the duplicates appearing is 7 in 22, or 7/22, or 32%. If you had 1 reel, at $1 a spin, the player would land on one of the duplicates 32 times in 100 spins. The payout is calculated as (1 / (32/100)) x 95% x $cost. So if it cost $1 per spin, you would pay the player $2.97 every time one of the duplicates appeared.

As another example, if you had 3 reels and it cost $2 per spin, you would work out the pay out as follows: (1 / (32/100 x 32/100 x 32/100)) x 0.95 x $cost = 30.5 x 95% x $2 = $57.95 payout. You can calculate the probabilities of the other non-duplicates as follows: (1 / (1/22 x 1/22 x 1/22)) x 0.95 x $cost = 10648 x 0.95 x $2 = $20231.20. That's quite a large number, but then the probability of any of the winning sequences appearing is quite low (it's roughly 9x10^-5).

In the last examples the differences are quite extreme, the player either wins $58 very often, or $20231 almost never, with no variation in between. The art of making the game engaging is in creating more opportunities to win with varying amounts. This is often accomplished by mixing reels with different probabilities. So instead of each reel having
the same number of each symbol, one reel might have more symbols, or more of one type of symbol, and so on. The formula for calculating the probability is the same as before, just remember to use the correct ratios for each reel. For example, if you have reel A with 22 stops and 3 occurrences of a symbol, reel B with 26 stops and 2 occurrences of the symbol, and reel C with 20 stops and 5 occurrences of the symbol, the formula would look like this: (1 / (3/22 x 2/26 x 5/20)) x 95% x $cost.

And that's all there is to it. Hopefully I didn't make too many mistakes in the examples so you'll still be able to find it useful :P

\** A note on notation, 95% is identical to 0.95. 32/100 is identical to 0.32, 7/22 is identical to 0.31818.. etc.

# Answer
> 7 votes
You want the expected value to be .95. In simple terms, this is the sum of `probability * payout` for each state.

A brute force method would be to iterate over all 22^3 states (assuming you have 3 reels), add up the payout, and divide the sum by 22^3. However, since most states probably don't pay out anything, it might be easier to work out all the states that do pay out instead.

For example if you had 1 Bell sybols per reel, then the probability of

```
[Bell] [Bell] [Bell]

```

would be 1/22^3. And if you had 2 Cherries per reel, then the probability of

```
[Cherry] [Cherry] [any]

```

would be 1/11^2.

---

EDIT: The above only tells you how to check that the payouts give the desired return rate. As a simple example, lets consider a game where you pay $1 to flip 2 coins. Here are three payout schemes that all give a return rate of .95:

1. Two heads pays $3.80, everything else pays nothing
2. Two heads or two tails pays $1.90, everything else pays nothing
3. Two heads pays nothing, everything else pays $1.26

Which one is more "fun"? You tell me...

# Answer
> 1 votes
The easier and more reliable way to do this is not by simulating reels but rather have an internal die that chooses what the player wins and then just populate the reel procedurally(or have a large set of them saved somewhere but that will probably take longer to make).

# Answer
> 0 votes
The others haven't touched this bit:

> ..how to properly insure that the machine is going to have a payout rating..

If you use completely random numbers, there's no way to be sure. However, you can keep statistics of the payouts and adjust the probability of a payout at runtime using a feedback loop.

If there hasn't been a payout for some time, make it more probable to win, and vice versa.

You can run simulations of the runs (a couple billion iterations should do) to make sure your feedback loop works as intended.

# Answer
> 0 votes
Note that all answers so far assume that you have a perfect RNG to work with. A pure software RNG is actually a pseudo-RNG, or PRNG for short, because the same input value (seed) will always generate the same sequence of random numbers, so a PRNG is inherently predictable.

Of course, it is a hard problem to distinguish "true" from "pseudo" RNGs on the client side, especially with a small sample size, but there is a difference - in an application where money and legal liability is involved, I would not take chances. If you need an RNG, the only thing worse than having no RNG is having a broken RNG without knowing it, so this is one area where your company should never cut corners or learn on the fly.

There are good PRNGs algorithms, but they will never match a physical source of entropy. So, for the maths to work in practice as well as in theory, make sure you use the best RNG possible - it's in your company's best interest, both legally and financially.

# Answer
> 0 votes
A very simple approach could be just iterating over every possible spin outcomes and adding up the combined winnings, versus total monies collected.

Start by creating the wheel layouts, allow duplicate symbols if desired. Determine the winning patterns and payouts you want. Run wheel pattern though an algorithm to determine total payout, divide by money collected, this is your payout ratio.

If it is too high, add more blank spaces, or lesser paying symbols, OR lower the pattern payout (ie. three single bars can be $10, or $5). Rerun the algorithm until the desired payout ratio is determined.

This allows you to keep even value payouts (not $4.58 for a winning pattern, you could use $5). You may not be able to come up with an exact payout of say 95%, but with tweaking you can get close.

Here's an example algorithm to determine a wheel layout's pay ratio:

```
payout = 0.0
collected = 0.0
ratio = 0.0
bet = 1.0
FOREACH symbol1 IN wheel1
  FOREACH symbol2 IN wheel2
    FOREACH symbol3 IN wheel3
      payout = payout + DetermineWinnings(symbol1, symbol2, symbol3, bet)
      collected = collected + bet
    NEXT
  NEXT
NEXT
ratio = payout / collected

```

---
Tags: flash, actionscript-3, game-mechanics
---


title: 3d Collision detection help xna?

text:
# Question
Title: 3d Collision detection help xna?
I was hoping if you could help me out here. I'm developing a 3d table tennis game, and got the collision detection working perfectly when the ball hits the racket. However, now I would like the ball to move depending on where it hit the racket (example if it hit the far left side, it goes to the left etc..) Heres the collision detection I used:

```
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
    {
        for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
        {
            BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
            sphere1 = sphere1.Transform(world1);

            for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
            {
                BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
                sphere2 = sphere2.Transform(world2);

                if (sphere1.Intersects(sphere2))
                    return true;
            }
        }
        return false;
    }

```

Any help would be greatly appreciated as to how i could improve this so as to get what I desire. Thanks

# Answer
> 2 votes
What I think you're looking for is:

If the Racket's center position is Vector **A** and the center location of the ball at its current location is Vector **B** then **A** \- **B** will give you a vector pointing from the center of the racket to the ball meaning it now points in the proper direction of the "perpendicular to the tangent" or also called the "Reflection Normal" - though you'll have to .Normalize() it to make it unit length. Once you have done so, a regular Vector3 reflection equation will take care of the rest for you. If you don't have that equation it's pretty straightforward and google "Vector3 reflection" will give it to you straight away. The ball's original heading vector is the "Incidence Vector" in those equations.

# Answer
> 0 votes
If you're using a physics engine (which I think you're not, but you might consider it) I'd recommend you use an actor impostor for the racket. Instead of doing collision against the proper model of the racket, create a version for the physics which has convex and concave surfaces designed to bounce the ball according to where it intersects. In fact, you might use two actors, one for the netting so that you can return the ball with close to the full force it hits the net and one for the framing since a ball that hits the framing usually loses a lot of momentum in addition to radical direction changes.

---
Tags: 3d, xna, collision-detection
---


# Question
Title: Why does changing the diffuse color of my model's effect change it for all models?
I want to change color of individual model in my game. But when I use

> effect.DiffuseColor = newColor

then all of models which were loaded from same model file change color too.

How can I do ?

# Answer
you are changing the Diffusecolor in the same effect.

there is no easy way to clone a model

so the answer is before draw set the color properly for each model

```
// Draw method
foreach (ModelMesh mesh in m.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
       effect.DiffuseColor = newColor;
    }
    mesh.Draw();
}

```
> 2 votes

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


# Question
Title: What graphics library should I use for line rendering for a raycasting renderer?
I want to develop simple RPG with ray casting rendering. I chose SDL for graphics and input. The problem is there is no native line drawing in it, which I need to start prototyping a ray casting engine.

I know about SDL\_gfx, which can do this, but I am asking if there is any alternative to SDL with primitives drawing functions for C++, which is easy to learn, and is also used by indie game developers?

# Answer
> 3 votes
Rasterisation is not a requirement for raycasting. Since generally you are casting a ray per pixel, pixel-plotting is all you need:

```
void SurfaceUtils::putPixel32( SDL_Surface *surface, int x, int y, Uint32 pixel )
{
    //Convert the pixels to 32 bit
    Uint32 *pixels = (Uint32 *)surface->pixels;

    //Set the pixel
    pixels[ ( y * surface->w ) + x ] = pixel;
}

```

(...from the SDL docs.)

Since I'm assuming you want a raycaster in the Doom/Wolfenstein style, all you need to do is plot pixels up or down each vertical scanline till you reach the end of the screen. If you're aiming for a per-pixel raycaster instead, warning: this is **slow**.

PS. I've a working per-pixel voxel raycaster and heightmap voxel raycaster, both written using SDL. No extra graphics libs were needed.

# Answer
> 0 votes
You basically have three options. You can use OpenGL in addition to SDL (OpenGL has support for drawing lines, and is a fairly commonly used API for graphics. You can install and use SDL\_gfx or some other library for SDL that includes line drawing. Or you can try SFML, which has support for drawing lines, and is designed for C++, as opposed to SDL, which is designed for C.

---
Tags: c++, sdl, raycasting
---


# Question
Title: How can I initialize 15-20 sprites with the same starting position?
How can I load 15-20 sprites in Cocos2D at the same point (`ccp(20,20)`, which is an alias for `CGPointMake`) using `NSArray`? This is what I'm doing now, and it doesn't work:

```
int i,endvalue=3;
NSMutableArray *levelStar = [ [NSMutableArray alloc] initWithCapacity:9 ];
for(i=1;i<=endvalue;i++)
{
    CCSprite *star = [CCSprite spriteWithFile:@"image"+i+".png"];
    star.position = ccp( 20,20);
    [levelStar addObject:star];
    [self addChild:star];
}

```

# Answer
While it is extremely unclear what you are doing and what you are considering behavior that "doesn't work," I want to point out that there is a huge discrepancy with your question (which asked about setting up 15 to 20 sprites) and your code, which may be the root of your troubles. Specifically, you have this loop:

```
int i, endvalue=3;
for(i = 1; i <= endvalue; i++) {
  ....
}

```

This loop only executes three times. So you're only setting up and adding three sprites to the array total. Perhaps you meant to write your loop this way?

```
for(int i = 0; i < 15; ++i) {
  ...
}

```
> 2 votes

---
Tags: iphone, cocos2d-iphone, ios, cocos2d
---


# Question
Title: Is there a 3D animation tool that meets these requirements?
I'm searching a 3D physics / transforms animation editor. It should be able to import 3D meshes from OBJ or FBX, then it should be able to animate transforms. I need such a tool for my 3D games, where many dynamic and inorganic elements appear, like doors, traps, robots, lifts, and so on.

Where I can find such a tool?

# Answer
> 2 votes
It's probably the case that you're only going to find what you want as part of a larger 3D art production suite.

For example, Blender should be able to do this, as should any other 3D modelling package (such as Max or Maya, although those are non-free and in fact quite expensive).

Blender and the other tools of its class are very powerful and can do all that you need (and much more), but they do have a bit of a learning curve associated with them. Fortunately Blender has a lot of documentation and tutorials available.

---
Tags: 3d, physics, animation, tools
---


# Question
Title: How can I make message passing between threads in a multithreaded engine less cumbersome?
The C++ engine I'm working on currently is split up into several large threads- Generation (for creating my procedural content), Gameplay (for AI, scripts, simulation), Physics, and Rendering.

The threads communicate with one another through small message objects, which pass from thread to thread. Before stepping, a thread processes all of its incoming messages- updates to transforms, adding and removing objects, etc. Sometimes one thread (Generation) will create something (Art) and pass it to another thread (Rendering) for permanent ownership.

Early in the process and I've noticed a couple things:

1. The messaging system is cumbersome. Creating a new message type means subclassing the base Message class, creating a new enum for its type, and writing logic for how the threads should interpret the new type of message. It's a speed-bump for development and is prone to typo-style errors. (Sidenote- working on this has me appreciating how great dynamic languages can be!)

Is there a better way to do this? Should I use something like boost::bind to make this automatic? I'm worried that if I do that I lose the ability to say, sort the messages based on type, or something. Not sure if that kind of management will even become necessary.
2. The first point is important because these threads do so much communicating. Creating and passing messages is a big part of making things happen. I'd like to streamline that system, but also be open to other paradigms that might be just as helpful. Are there different multithreaded designs I should think about to help make this easier?

For example, there are some resources which are infrequently written, but frequently read from multiple threads. Should I be open to the idea of having shared data, protected by mutexes, that all threads can access?

This is my first time designing something with multithreading in mind from the ground up. At this early stage I actually think it's going really well (considering) but I'm worried about scaling, and my own efficiency at implementing new stuff.

# Answer
> 10 votes
To your broader problem, consider trying to find ways to reduce inter-thread communication as much as possible. It's better to avoid synchronisation issues altogether, if you can. This can be achieved by double buffering your data, introducing a single-update latency but greatly easing the task of working with shared data.

As an aside, have you considered not threading by subsystem, but instead using thread spawning, or thread pools to fork by task? (see this in regards to your specific issue, for thread pooling.) This short paper outlines the pool pattern's purpose and usage concisely. See these informative answers also. As noted there, thread pools improve scalability as a bonus. And it is "write once, use anywhere", as opposed to having to get subsystem-based threads to play nice each time you write a new game or engine. There are plenty of solid third party thread pooling solutions out there, too. It would be simpler to start out with thread spawning and work your way to thread pools later, if the overhead of spawning and destroying threads needs to be mitigated.

# Answer
> 5 votes
You asked about different multi-threaded designs. A friend of mine told me about this method that I thought was pretty cool.

The idea is that there would be 2 copies of every game entity (wasteful, I know). One copy would be the present copy, and the other would be the past copy. The present copy is strictly *write only*, and the past copy is strictly *read only*. When you go to update, you assign ranges of your entity list to as many threads as you see fit. Each thread has write-access to the present copies in the assigned range and every thread has read-access to the all past copies of the entities, and thus can update the assigned present copies using data from the past copies with no locking. Between each frame, the present copy becomes the past copy, however you want to handle the swapping of roles.

# Answer
> 4 votes
We've had the same problem, only with C#. After thinking long and hard about ease (or lack thereof) of creating new messages, the best we could do was to make a code-generator for them. It's a bit ugly, but usable: given only a description of message contents, it generates message class, enums, placeholder handling code etc - all this code that is almost the same each time, and really typo-prone.

I'm not entirely happy with this, but it's better than write all that code by hand.

Concerning shared data, the best answer is of course "it depends". But generally, if some data is read often, and needed by many threads, sharing it is worth it. For thread safety, your best bet is making it *immutable*, but if that's out of the question, mutex might do. In C# there's a `ReaderWriterLockSlim` class, specifically designed for such cases; I'm sure there is a C++ equivalent.

One other idea for thread communication, that probably solves your first problem, is to pass *handlers* instead of messages. I'm not sure how to work this out in C++, but in C# you can send a `delegate` object to another thread (as in, add it to some kind of message queue), and actually *call* this delegate from the receiving thread. This makes it possible to create "ad hoc" messages on the spot. I only toyed with this idea, never actually tried it in production, so it might turn out bad in fact.

# Answer
> 1 votes
I'm only in the design phase of some threaded game code, so I can only share my thoughts, not any actual experience. With that said, I'm thinking along the following lines:

* Most game data should be shared *for read-only access*.
* Writing data is possible using a kind of messaging.
* To avoid updating data while another thread is reading it, the game loop has two distinct phases: read and update.
* In the read phase:
* All shared data is read-only for all threads.
* Threads can calculate stuff (using thread-local storage), and produce update *requests*, which are basically command / message objects, placed in a queue, to be applied later.
* In the update phase:
* All shared data is write-only. Data is to be assumed in an unknown / unstable state.
* This is where update request objects are processed.

I think (though I'm not sure) in theory this should mean that during both the read and update phases, any number of threads may run concurrently with minimal syncing. In the read phase no one is writing the shared data, so no concurrency issues should arise. The update phase, well, that's trickier. Parallel updates on the *same* piece of data would be a problem, so some synchronization is in order here. However, I could still run an arbitrary number of update threads, as long as they are operating on different data sets.

In all, I think this approach would lend itself well to a thread pooling system. The problematic parts are:

* Syncing the update threads (make sure no multiple threads try to update the same data set).
* Making sure that in the read phase no thread can accidentally write shared data. I'm afraid there would be too much room for programming mistakes, and I'm not sure how much of them could be easily caught by debug tools.
* Writing code in a way such that you can't rely on your intermediate results being available for reading right away. That is, you can't write `x += 2; if (x > 5) ...` if x is shared. You need to either make a local copy of x, or produce an update request, and only do the conditional in the next run. The latter would mean a whole lot of additional thread-local state preserving boilerplate code.

---
Tags: c++, multithreading
---


# Question
Title: Is it possible to develop multiplayer games with HTML5?
I know HTML5 is great for web games, but I don't really know if it's possible to develop online games with multiple users, keeping everybody synchronized and handling logins, et cetera. Is it possible to do this?

# Answer
> 7 votes
You can't write it with HTML5 alone. You will always need scripting and a server to handle communication between users, because of the security limits of browser scripting, and also to prevent cheating.

Many people have written multiplayer html5 games, even I have. The use of html5 itself is probably not the most important part of it. Most of the things needed (if not all) have been available in html 4.01 as well. The exception is canvas, but canvas is slower than svg, and svg was available in lots of browsers already.

I think what really spawned the "html5 game" mania is the ability to make server side apps in javascript. This means that all the client side programmers can suddenly make the entire system themselves, and they are usually the creative people when it comes to stuff like games. Not to mention that JS is so easy that even your grandma could program with it. Maybe.

## Update after comment from OP:

A common architecture for a browser game would be

```
          Client                                     Server
|-----------------------|                   |---------------------|
View - input/output logic - Communication - Validation - Game World
              |                                              |
   client database (if needed)                    server database (if needed)

```

Or in terms of actual "languages":

* Client view: HTML5 (possibly with angular.js, haven't tested how fast it is with LOTS going on yet. also check out raphael.js for "graphics")
* Client logic: JavaScript (jquery/vapor/plain/whatever)
* Client database: WebSQL (part of the HTML5 "suite" I suppose)
* Communication: JSON (Javascript object notation, essentially serialized javascript objects) over socket.io (JS library for automatically detecting optimal communication protocols)
* Server language: also JS (node.js if you have TONS of concurrent users on few cores, other solutions are available too)
* Validation: just making sure your INCOMING game data (from client) is valid. Outgoing does not need to be checked, not even on client. It is assumed correct. *Always*.
* Game World: a collection of VERIFIED data that is redistributed to all clients as they come in
* Server database: couchdb, mongodb, whatever database that gives you raw json objects to work with.

There you are. A complete internet game written only using javascript and html. Lovely.

# Answer
> 3 votes
Take a look at the article at http://smus.com/multiplayer-html5-games-with-node and also the source provided with the article. Note that this also uses JavaScript for networking.

---
Tags: multiplayer, html5
---


# Question
Title: What is the game development market shifting towards?
Aimed at the professionals who are there in the industry, what is the game development market shifting towards? Web-based or Mobile or Consoles/PCs. I have developed a decent knowledge of JavaScript and html5, so I want to know if this is entirely useful(on a game development perspective) or maybe I should learn some other language from scratch?

# Answer
From what I've read, the PC market continues to grow, while next-gen consoles have had their releases delayed for some time in major part due to the recession. The ability to improve your PC hardware bit-by-bit, on the other hand, means an easier buy for those with limited funds, aside from the age old argument that PCs have better overall value than consoles anyway, since they are usable for work -- which counts in hard times ;)

C/C++ remain the industry standard, preceded (chronologically) only by assembly language, which is still used for performance-critical code -- albeit far less so now that GPUs pack so much heat. If you can use the former two effectively, you can use just about language you set your heart on, including the GPU shader languages which are C-based.

JS/HTML5 is certainly growing, but the limitations on fully-implemented HTML5 features across browsers, and the fact that JS will always be an interpreted, managed language means that as fast as it may get, it will never pull maximal performance from a machine the way that native code can. I recently ported some Flash code to C++ for a 15x performance increase, for instance, meaning that much more AI and dynamic environment logic I can fit in on the side -- and across multiple cores. Gameplay is king (regardless of tech used), but getting the most bang for your performance buck is a huge part of what game development is about, for this reason.
> 10 votes

# Answer
It's not helpful to think of it as one market. There are different markets for different sectors and different companies work within each, some across several. Generally speaking web-based games are rapidly rising but that doesn't mean your Javascript and HTML knowledge will help you at a typical game development company.

> maybe i should learn some other language from scratch?

This implies that you have a hidden agenda that you didn't actually state in the question, eg. to get into the game development industry. If that is the case then you need to decide which part of the industry you want to be in, because the Farmville end is very different from the Modern Warfare end, which is very different from the Braid end, and so on.
> 9 votes

# Answer
The game industry is not **shifting**, exactly; it's just that different sides of it are doing different things. Most individual teams in the industry haven't changed what they're doing; just that some teams are growing, and others are shrinking.

What is happening right now is a combination of four simultaneous movements happening in three different parts of the industry:

1. Increasing costs to develop top-tier games is reducing the number of top-tier games which can be produced, and this in turn limits the amount of experimentation which companies can afford to perform on these games. The mainstream game industry is currently in the process of **shrinking**, with designs that are **contracting** around FPS games. This has been a slow process which has been going on for the past decade or so (although consoles are relatively new to that party; they had been contracting around God-of-War-style brawlers until only perhaps five years ago).
2. Middle-tier games (mostly) stopped being financially viable with the crash of the US dollar during the GFC. Studios which produced these middle-tier games have now mostly **vanished**, or else moved into contracting work to support the top-tier games being made by other studios.
3. Increasing (and frighteningly high) revenues from pairing addictive (in the gambling sense) game mechanics with micro payments is leading to a lot of smaller and/or simpler games in web browsers and mobile devices. This part of the industry is currently (rapidly) **growing**, despite ethical concerns raised by some observers.
4. Decreasing costs and expanding market for games for mobile devices, combined with a lot of talent being suddenly unemployed (see #2, above), is leading to a **huge increase** in the number of small one-or-two-man development studios.
> 6 votes

---
Tags: game-industry
---


# Question
Title: Better to use fixed sprite size or variable sprite sizes in a sprite sheet?
you have N frames for an animation (an idle animation for example) of a 2D character. What is the best resolution to use for each frame? The problem is that if you save the N frames such that each of them has the size of the minimal bounding box enclosing the character, when using a call like:

```
// draw frame i at (0,0)
sprite.frame(i).draw(0, 0)

```

your character movement will be wrong, that is, it will move back and forth. The other option is to set the width and height of every frame to the maximum width and height calculated using every frame.

What is, in your experience, the best practice to follow?

# Answer
Both methods you describe are commonly used, each having their pros and cons.

---

**Fixed sprite size**

*Pros:*

* Easy to use. Some simple math can tell you the offsets

*Cons:*

* Wasteful. You may end up storing a lot of useless whitespace in the video-memory

---

**Variable sprite size**

*Pros:*

* Low video-memory footprint

*Cons:*

* Harder to set up, you typically need a sprite packer and a way to store and read sprite offsets
* You need a more complicated sprite handler than a fixed-size sprite engine would require

---

If you are on a memory constrained device, or are using an engine that supports variable sprite sizes out of the box, I would do that. Otherwise, it's a minor issue and I would recommend using fixed sprite sizes until you have proven that you need the additional video memory.
> 6 votes

# Answer
If you weren't going to just center the sprite animation in a frame large enough to handle the data, you'd have to have additional meta data for the "anchor" of the sprite, so that you're drawing the sprite at the right location. Obviously this is a lot of wasted space.

Fortunately, any half decent texture packing tool will atlas all of those images and give you the appropriate offset for you to use.
> 4 votes

---
Tags: 2d, animation, sprites
---


# Question
Title: How does one avoid hundreds of copies into a vertex buffer each frame?
Assume a Direct3D9-based 2D game, high resolution, very busy. Performance critical.

A particle system has 2,000 particles. They are scattered throughout the world with only a subset visible on screen at any time. Thus the global array of particles contains a lot of particles that won't be rendered this frame.

Obviously they should be rendered in one call in a vertex buffer. I use an index buffer as well.

The slow bit is in the copying all of the vertex data to the buffer. I actually do this twice: once to a big buffer, then as a single copy from the big buffer to the locked vertex buffer. Regardless, I'm looking at 2,000 iterations and maybe 200-500 `memcpy()` calls that shuffle 4 vertices at a time.

There must be a better way. Maybe copying them *all*, and changing the index buffer instead? Or just rendering them all and let the off-screen ones get clipped (I'm not sure this is scalable though)?

How do people normally handle this?

# Answer
> 2 votes
It might be worth considering using the geometry shader (or point sprites) to construct the quad. That would cut it down to one vertex per particle.

You could also consider doing a GPU based particle update, where position is simply a function of time and a few constants which you can set up once and store in the vertex when the particle is created.

A third option is to have more particle systems with less particles each that are closer together to improve frustum culling.

You could also move most of your particle system work to a separate CPU thread, and have the main thread only do lock(); memcpy(); unlock();

Which combination of the above options you want (if any) is difficult to guess without more information. For example is your game mostly GPU bound or CPU bound? What proportion of frame time is spent processing particles?

# Answer
> 1 votes
Don't shuffle vertices around. Shuffle pointers to vertices.

You say that you have a vector in which to store raw vertex data and memory, so go along with that, and keep a second vector that contains pointers to elements in your vector of vertices (your memory buffer). Incidentally, this is the same way I figured out how to cull hardware-instanced meshes individually in the same draw call.

In short:

1. Update all the particles' positions
2. Cull the non-visible particles
3. Assign pointers to visible particles to the beginning of a vector
4. Copy vertex data referenced by the pointers to the vertex buffer
5. Draw vertex buffer with no. of visible particles as no. of vertices

You will add the following items to your particle system:

```
class ParticleSystem
{
    std::vector<ParticleVertexInfo> particleData;
    std::vector<ParticleVertexInfo*> visibleParticles;

    const int maxParticles = 2000;
    int visibleCount;

// your other ParticleSystem components...
}

```

*particleData* and *visibleParticles* are of the same length, defined by *maxParticles*. Initially, populate *visibleParticles* with pointers to all of *particlesData* just to avoid null data. *visibleParticles* will be partially overwritten in each frame anyways.

After updating the position of each particle, cull every vertex in *particleData*, and keep two numbers to increment. The first is *visibleCount* which will be reset to zero each frame before culling begins. A second number is inside the loop to increment by one for each vertex. For every vertex that is in view, assign a pointer to particleData.at(i) to visibleParticles.at(visibleCount), then increment visibleCount by 1.

Here's a trimmed down example of how a culling procedure might look for rearranging visible particles:

```
visibleCount = 0;

for (int i = 0; i < maxParticles; i++)
{
    if (visible(particleData.at(i))
    {
        visibleParticles.at(visibleCount) = &particleData.at(i);
        visibleCount++
    }
}

```

Keep in mind that I am describing a brute-force culling method with linear time. If you are using quad-tree or other spatial culling algorithm, you would need to give a unique number identifier to each particle and use that to in place of i when assigning pointers.

Now, visibleParticles is at least partially updated with different pointers, but when it's time to render, you'll only be using the ones from the start of the vector to *visibleCount*. Still, you'll be able to copy the entire thing into the buffer.

Lock the vertex buffer, memcpy the *visibleParticles* vector into the buffer, and unlock. You now have all the updated vertices updated with one memcpy call. memcpy should be okay here, since you're guaranteed not to change the number of maximum particle elements in the vector.

Finally, draw the particles by using the value of visibleCount for the numVertices parameter in DrawIndexedPrimitive.

---
Tags: directx, particles, vertex
---


# Question
Title: What do I need to know for writing code for both OpenGL and OpenGL ES 2.0
I am developing an engine that uses both OpenGL and OpenGL ES 2.0. I am well seasoned in OpenGL but not ES (although I am aware it is a subset of OpenGL). I could not find a set of differences that I should be aware of so that I can write code to take those differences into account and allow the engine to robustly handle the situation where a feature is not supported in OpenGL ES.

For example, the following forum post mentions a couple *gotchas*: http://forums.arm.com/index.php?/topic/13799-tips-tricks-opengl-vs-opengl-es/

A link to an exhaustive list would be nice.

# Answer
> 1 votes
I found it fairly helpful to look through the OpenGL ES 2.0 API. You might, for example, look at your current project / a project you've done recently and find all gl calls that you currently make, then see which of those are available in the OpenGL ES 2.0 API. If you're starting from scratch, I'd recommend writing to the OpenGL ES 2.0 API, as it is mostly a subset of OpenGL 2.1.

Writing shaders that support both OpenGL and OpenGL ES can be tricky as well. In the end, I had to use some #ifdef's to inject some statements into my shaders based on the current platform. I don't remember the details, and there may be ways to avoid what I did, but in the end I am able to use the same shader on multiple platforms.

The OpenGL ES 2.0 API Quick Reference Card is also helpful.

# Answer
> 3 votes
OGLES 2.0 is like OpenGL 2.1. But there are many differences:

* No glBegin/glEnd
* No polygons, only triangles
* GLSL 1.2 only
* many unused options in blending or texture flags
* ETC1 support mandatory on OGLES 2.0

You can use OpenGL ES 2.0 simulator on windows to try your code. ARM (Windows) or Imagination (Linux & Windows). On OS X, you can use iPhone simulator.

---
Tags: c++, opengl, opengl-es
---


title: Beyond "Novice" Game Projects

text:
# Question
Title: Beyond "Novice" Game Projects
I was reading this answer on the type of math a game developer should know and this part really stood out at me:

```
How do I move my game object? The novice might say:

"I know! I'll just do:" object.position.x++.

```

That is how I would think to do it so I guess that shows my skill level. At least for the types of 2D side-scrolling, arcade-style games that I've made in the past, that's all I needed. That and a bit of trigonometry.

In fact, I haven't used much linear algebra or even heard of quaternions before reading that post. Is it because these math don't show up until you work with 3D or is it because my 2D games are fairly simple that I got away with naive implementations.

**Follow up question:** If I want to get familiar with that type of math, what type of projects should I undertake? IE: write a game engine, work on a 3D game, etc.

# Answer
The real trick with this is high school-level science; which you *should* have done. In the event that you didn't a quick Google search will get you started. To explain how you avoid the 'novice' mindset take the lunar lander example.

Once you have read that `[change in position] = [velocity] * [time passed]` it becomes clear that would need to keep track of those variables:

```
float x, y; // Your X and Y co-ordinates.
float vx, vy; // Your X and Y velocity.
float deltaTime; // Change in time.

```

Following that you would simply apply the velocity to the position each frame:

```
// Change X by the velocity multiplied by the time.
x = x + vx * deltaTime;
y = y + vy * deltaTime;

```

Now we would like to alter the velocity each frame so that we can add gravity. According to the exact same source `[change in velocity] = [acceleration] * [time passed]`. Therefore we can apply the exact same principle:

```
const float gravity = 9.8f; // The gravity of the earth.

// Add gravity to the vertical velocity.
vy = vy + gravity * deltaTime;
// Change X by the velocity multiplied by the time.
x = x + vx * deltaTime;
y = y + vy * deltaTime;

```

Now you need a way for the player to control his spacecraft. From reading more about basic physics you will learn that motion is the result of force - I can't find a source but `[change in acceleration] = ([force] / [mass]) * time` (as far as I remember). So when the player presses a key you would simply set the `fx` and `fy` variables to something and apply the equation during your update.

Ultimately you need to think about the physics around the objects in your game - and instead of trying to make them move in the way you would think, rather *look up the equation*.

*Future Note:* Remember that this is definitely not the best way to do physics (this is called Euler Integration and can lead to some odd scenarios at low frame rates) - you need to look into other ways of doing things (That article has quite a nice write-up on the bare basics as well). However, stick with Euler Integration for now, as it is means you are trying to learn one thing less.

Which games would teach you how to think in the correct mindset?

How would you test that you have done things correctly and with the correct mindset? Insert a `Sleep(10 milliseconds)` in your game loop and everything should still move and react the same way as the full framerate.

Finally, please keep well away from 3D (and thereforce Quaternions and Matrices) until you have a good amount of experience with making 2D games work. I would venture to say that quite a few game developers don't actually know how Quaternions or Matrices work - but merely know how to use them - approach them much later on (or never, 2D games are a lot of fun and can be quite successful). You don't really need to know linear algebra and so forth to do this at the basic level (but it really does help, so go to some night classes if you can).

*Final bonus:* One thing my art teacher always told me is "don't draw what you *think* you see, draw what you see." The same thing applies here "don't model what you *think* happens (`object.position++`), model what happens (\`object.position += velocity * time)" - at least to reasonable limits (you are not modelling a perfectly accurate system, but make something that is a good immitation).
> 16 votes

# Answer
I think parts of the answer you linked to are a bit elitist in their presentation. Extolling the virtues of vector math then saying an object needs a position, direction, and acceleration is inconsistently specific because it's really just going to boil down to something like `object.position.x += (object.velocity.x + object.acceleration.x) * deltaTime`—which, fundamentally, isn't that different from `object.position.x++`. Quaternions are one of many ways to represent rotations; I like them but they're not essential to understanding 3D rotations. Despite what many Quaternion users will imply, they are not the Holy Grail of rotational math.

The principles of linear algebra are present in simple 2D movement, rotation, etc. but the math is more simple because there are only two dimensions. Here's an example.

There are plenty of ways to learn/improve your knowledge of linear algebra:

1. I've considered taking a course in linear algebra but my courseload is already pretty heavy so I haven't been able to justify the extra work.
2. My understanding of linear algebra has grown much more significantly as I've taken a series of game engine programming classes. For me, use of Vectors, Matrices, etc. has been (generally speaking) more prevalent on the engine side of things than on the game side. Of course, that's not to say I haven't used matrices in game code—I just don't use them as often as I have in engine coding. ymmv
3. There are also plenty of books that can help you understand the math you'd need to know, as well. I like this book which has a chapter titled "3D Math for Games."

Lastly, if the design of your games doesn't call for the complex math, don't use it. :) But, of course, don't let that stop you from delving into designing a game that does.
> 3 votes

# Answer
Quaternions for 2D would be complete overkill, not to mention computationally way too expensive. Bitmap rotation (2D) is handled by a great many platforms/libraries implicitly, because it's so fundamental to writing any application, and even where it isn't, rotation of 2D bitmaps is nothing more than a bit of simple trig. In 3D, things become considerably less intuitive to the average human being, unless of course said human being grew up writing 3D code when they should've been out riding bike.

Linear algebra is applicable to 2D as it is to 3D and should be something you're familiar with even if you only did junior high school math. If you've ever done line intersections, or periodic plotting on a line (integration), then you've used linear algebra.

Learning 3D math usually starts with placing a simple object (like a cube) in 3D space, and implementing a movable camera which can view that object from different perspectives, and that perspective can start out orthogonal to keep things even simpler. It's about projecting points onto a 3D plane representing your screen (formula here, you would extend this to x and z axis in addition to y). Really, that's the beginning of writing any 3D engine, irrespective of your level of experience. Flash and Processing.js are two great ways to prototype something like this easily.
> 0 votes

# Answer
You're right on track that linear algebra and more complex math usually involves 3D graphics and 3D space. But there's still more math that can be done within 2D games. Physics math can get pretty hardcore, and it gets more complex if you consider soft body physics and B-spline dynamics (and still in 2D, keep in mind)

Try building or dissecting a physics library that will cover collision handling and response for common 2D shapes. Linear algebra is pretty useful for calculating trajectory vectors for collisions. The dot product is quite related to the unit circle used in trigonometry. Yet, the complexity of rigid body physics increases exponentially when applying it in 3D.

3D graphics gives you a greater understanding of matrix calculations, quaternions, linear algebra, and some applied calculus. The first thing you'll probably pick up on is using matrices to move and manipulate objects in 3D space.
> 0 votes

# Answer
If you're writing 2D games, you're probably using linear algebra already.. you just don't know it! Formally learning at least the basics about vectors is pretty easy, but goes a long way in simplifying thinking about otherwise-complex movement.

For example, we get a lot of questions here about what equations to use to simulate curved movement, such as for a cannonball shot from a cannon, or a homing-missile. But if you understand vectors, the only "equation" you need is that for adding two vectors together. Not only that, but adding things like air-drag or friction becomes incredibly simple - just calculate the drag-vector, and add it to the velocity. Presto!
> 0 votes

---
Tags: mathematics, software-engineering
---


title: Set sprite to face direction of mouse

text:
# Question
Title: Set sprite to face direction of mouse
I'm building a html5 canvas game and I need a way to get my sprite to face the mouse cursor. I have the X and Y co-ordinates for the sprite, and also the X and Y co-ordinates of the pointer. All I'm stuck with is the math involved to make the sprite face the pointer. It's all in a 2D world, so I can't imagine it'll be too complicated, but I have very little experience with this stuff.

Also any helpful links to articles/blog posts about this sort of thing would be awesome (2D game programming in general, not specifically Javascript).

To add, i should note that I need an angle in degrees that will point me towards the cursor using its X and Y position.

How can i know the co-ordinates of the cursor and where do i put all of this stuff ?

# Answer
> 11 votes
Not knowing the API's at your disposal, here's the basic math behind getting an angle in degrees:

```
angle = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi;

```

The `* 180 / math.pi;` converts it from radians to degrees.

---
Tags: 2d, html5, html-canvas
---


# Question
Title: What elements make a game machinima-friendly?
What types of things should a game have in order to make it machinima-friendly? I imagine that a spectator mode helps, but are there other important elements? Perhaps support for mods?

Are there any example of games that are known for being especially easy to make movies with?

# Answer
RuneScape has put forth some effort into supporting the machinima community. They introduced an in-game item, the "Orb of Oculus". A player holding the Orb of Oculus is able to freely move and rotate the game camera (to an extent, of course); this essentially makes that player into a "cameraman", and they can record other players from interesting angles (since the camera in normal operation is always hovering above and centered on the player's character).

Here is the manual page on the Orb of Oculus (and other fun items for provoking emergent gameplay), and here's the news post which links to the blog post about it. You can, of course, see the results by searching on YouTube for RuneScape machinima videos.

It has also been used to look at the other sides of impassable boundaries and find hidden unreachable areas, and to discover how two areas which might appear to be in two completely different places in the game world, are actually just off screen of each other.
> 3 votes

---
Tags: video
---


# Question
Title: XNA doesn't compile my XML to an XNB, because of namespaces?
I am sorry, because I know, that this question came up before, but that thread doesn't help me so I decided to aks my own question.

My problem is the following: I have a XML-file with the following content:

```
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent xmlns:Generic="System.Collections.Generic">
<Asset Type="System.Collections.Generic.List[ArenaFighterClasses.Weapon]">
<item>
  <Name>Pistole</Name>
  <Strength>5.0</Strength>
  <Cadency>300</Cadency>
  <ImageName>gfx/Weapons/Weapon1</ImageName>
  <BulletImageName>gfx/Weapons/Bullets/Bullet1</BulletImageName>
</item>

<item>
  <Name>MG</Name>
  <Strength>7.0</Strength>
  <Cadency>100</Cadency>
  <ImageName>gfx/Weapons/Weapon1</ImageName>
  <BulletImageName>gfx/Weapons/Bullets/Bullet1</BulletImageName>
</item>

<item>
  <Name>Shotgun</Name>
  <Strength>10.0</Strength>
  <Cadency>500</Cadency>
  <ImageName>gfx/Weapons/Weapon1</ImageName>
  <BulletImageName>gfx/Weapons/Bullets/Bullet1</BulletImageName>
</item>

```

Now I have the class Weapon (as you can see in the tag). But everytime I try to compile my project I get the following errormessage:

> There was an error while deserializing intermediate XML. Cannot find type "ArenaFighterClasses.Weapon".

I don't know where this error comes from. I did it the following way: I have my main project, where all the content like images, sounds and xml files is. Then, in the same projec map I have another Project with all the classes. And, finally in the same project map there is a project of the type Content Pipeline Extension Library in which the ContentTypeWriter for the Weapon is written.

Here is the code of the ContentTypeWriter:

```
  namespace XMLContentExtension
  {
  /// <summary>
  /// This class will be instantiated by the XNA Framework Content Pipeline
  /// to write the specified data type into binary .xnb format.
  ///
  /// This should be part of a Content Pipeline Extension Library project.
  /// </summary>
  [ContentTypeWriter]
  public class WeaponContentWriter : ContentTypeWriter<Weapon>
  {
    protected override void Write(
            ContentWriter output,
            Weapon value)
    {
        output.Write(value.Name);
        output.Write(value.Strength);
        output.Write(value.Cadency.Milliseconds);
        output.Write(value.ImageName);
        output.Write(value.BulletImageName);
    }

    public override string GetRuntimeReader(
            TargetPlatform targetPlatform)
    {
        return typeof(WeaponContentReader).AssemblyQualifiedName;
    }
   }
  }

```

And this is the relevant Code of the Weapon class and the ContentTypeReader:

```
 namespace ArenaFighterClasses
 {
 public class Weapon : GameEntity
 {
    #region Static Fields
    //Fields used to initialize this class
    public static string sXMLPlayerWeaponsFileName = "XML/PlayerWeapons";
    public static string sXMLEnemyWeaponsFileName = "XML/EnemyWeapons";
    public static List<Weapon> lwPlayerWeaponsTemplate = new List<Weapon>();
    public static List<Weapon> lwEnemyWeaponsTemplate = new List<Weapon>();
    #endregion

    #region Static Methods
    public static void InitalizeWeapons(ContentManager pConMan)
    {
        lwPlayerWeaponsTemplate = pConMan.Load<List<Weapon>>
                 (sXMLPlayerWeaponsFileName);
    }
    #endregion

    public Weapon(string pName)
    {
        Name = pName;
        Strength = 0.0f;
        Cadency = TimeSpan.Zero;
        ElapsedTime = TimeSpan.Zero;
        Rotation = 0.0f;
        Speed = 0.0f;
        Position = Vector2.Zero;
        BulletImageName = "";
        ImageName = "";
        Image = null;
        BulletImage = null;
        BulletImage.IsActive = false;

    }

    public Weapon()
    {
        Name = "";
        Strength = 0.0f;
        Cadency = TimeSpan.Zero;
        ElapsedTime = TimeSpan.Zero;
        Rotation = 0.0f;
        Speed = 0.0f;
        Position = Vector2.Zero;
        BulletImageName = "";
        ImageName = "";
        Image = null;
        BulletImage = null;
        BulletImage.IsActive = false;
    }

    public override void Update(GameTime gameTime)
    {
        Image.Update(gameTime);
    }

    public void LoadImages(ContentManager pConMan)
    {
        Image = new IngameImage(pConMan.Load<Texture2D>(ImageName), Position, 16,
                                 16, 1, 0, Color.White, 1.0f, true);
        BulletImage = new IngameImage(pConMan.Load<Texture2D>(BulletImageName),
             Position, 8, 8, 1, 0, Color.White, 1.0f, true);
    }
}

public class WeaponContentReader : ContentTypeReader<Weapon>
{
    protected override Weapon Read(ContentReader input, Weapon existingInstance)
    {
        Weapon weapon = new Weapon();

        weapon.Name = input.ReadString();
        weapon.Strength = (float)input.ReadDouble();
        weapon.Cadency = TimeSpan.FromMilliseconds(input.ReadInt32());
        weapon.ImageName = input.ReadString();
        weapon.BulletImageName = input.ReadString();

        weapon.LoadImages(input.ContentManager);

        return weapon;
    }
  }
 }

```

I really hope someone can help me, because I really have no more idea what to do.

For everybody who speaks german (sorry, but the english tutorial is no more available) here is the tutorial where my code is based on: http://www.xnamag.de/article.php?aid=26

# Answer
> 2 votes
This one is pretty simple. Your **content project** (not the content pipeline extension) needs to have a reference to the assembly (or project) that contains the `Weapon` type.

Because your game will depend on both the `Weapon` type and the content project, you will need to put the `Weapon` type in an assembly that is separate from the game itself.

---
Tags: xna, xml, xna-content-pipeline
---


# Question
Title: UVW: better explanation, and how to implement with GLES texture2D()
UVW texture coordinates, as opposed to UV texture coordinates, do not get very adequate explanation on the web. Many people offer the simple exlanation, "UV is for 2-dimensional textures and UVW are for 3-dimensional textures." I don't buy this.

I have found a small handful of explanations that I find inadequate. This and this seem to be the best I've come across.

The first link talks about an analogy of shining a laser on a wall. At a perpendicular to the wall, the beam will project as a circle. As the angle increases, however, the beam projects increasingly as an elongated ellipse (it skews).

This sounds to me strikingly like the math involved in lighting equations in that the outcome is related to a vector pointing perpendicular to the surface. *How can this relationship be adequately described with a single scalar, the W coordinate (assuming my basic understanding is appropriate)? Can you explain the relationship between the UVW coordinates and the current model-view matrix?*

More importantly, I have some models that describe texture coords with a non-zero W coordinate (about 1/3 of the tex coords, or so, and most non-zero values are nowhere near zero.) I'm using OpenGL ES 2.0, where my shading language only provides calls to texture2D(). *First off, how significant is the effect of the W coordinate for typical models (think something shaped like an airplane)? (I suspect this question is unfair since it should depend equally on the texture itself.) Is the call to texture3D() required for this, and if so, how can I achieve the desired effect with texture2D()?*

# Answer
What you've read is probably confusing because there are at least four different cases where you might see three-component texture coordinates.

1. Volume textures (i.e. 3D textures). They are like a stack of 2D textures with the third component selecting which image out of the stack you want. (And you can get filtering, mipmapping etc. in the third dimension just like the first two.)
2. Projective textures. In this case you have a UV and a W that works just like the W value of the float4 position you output from your vertex shader. That is, the U and V are divided by W before accessing the texture. This allows you to do things like project a texture onto a wall as if from a slide projector, or reproject a render target onto the scene (for shadow mapping and various postprocessing techniques). But the texture itself is still 2D.
3. Cubemaps. You sample them by providing a 3D vector from the center of the cube toward the desired point. It's uncommon to actually store cubemap vectors in a model since they're usually generated on the fly, e.g. by calculating a reflection vector from the surface normal and eye vector. However, it's conceivable that these are cubemap vectors.
4. Some totally unrelated piece of data, such as ambient occlusion. Since graphics hardware works in terms of four-component vectors, but texture coordinates usually only use the first two, game developers have gotten in the habit of stashing extra data in the remaining components, which may have nothing to do with textures at all.

Unfortunately, unlike with XYZW vectors, there's no standard naming convention for UVs beyond the first two components. So "UVW" may refer to any of the possibilities above. If you have a model with some mysterious-looking third component data on it, and no documentation from the person or tool that created the model, there's no easy way to know what to do with that data. If you have regular-looking 2D textures for your model, I'd try just ignoring the third component to begin with, and see if the model looks right just using the U and V components in a regular texture2D() call.
> 5 votes

---
Tags: mathematics, textures, opengl-es, matrix
---


# Question
Title: Why not show progress towards achievements/badges?
**Achievements** are everywhere now — Xbox Live, iOS Game Center, many individual games, and even in social communities with gaming elements like Stack Overflow.

A common user request of Stack Overflow is to show progress toward badges.

This has been denied by SO, as seen in this uservoice request, where Jeff Atwood made the following statement:

> this is modelled on the xbox live achievements model, and that does not show progress, either.. by design

Jeff defers to the design of Xbox Live when denying the request to show progress. Certainly, SO is technically nothing like Xbox Live, so it can be inferred that this is a *design decision*, not a technical one.

I am working on a game where we have achievements and right now the intention is to show progress. So, I have two questions:

1. If it's known that Xbox Live achievements "by design" do not show progress, is there a source for this?
2. Why is this "by design"? In other words, in terms of game design, what reason is there to intentionally *not* show achievement progress?

# Answer
> 12 votes
Progress should be shown whenever possible, with achievements and with other goals. Part of the great thing about explicit achievements is that it gives the player/user something to strive for, and a feeling of, yes, *progress* toward that goal. Each time the player makes a step toward her goal, she can get a micro-reward of a progress update, which encourages her to continue and reminds her of the goal. These updates should be spaced out enough that they don't get annoying, but the player/user should always be able to intentionally view her progress at any time.

The only times this progress technique should be avoided is if progress is unmeasurable or if the goal is deliberately obfuscated. If progress occurs due to a single atomic event ("First bounty you manually awarded on another person's question"), has become impossible ("Actively participated in the private beta" after release), or is kept secret to avoid spoiling a surprise ("Defeat the 3 friends who betrayed you"), then you shouldn't track progress for those achievements.

Tracking progress does raise some ethical issues. Achievements, especially ones that give frequent progress update micro-rewards, can tie pretty strongly into the base impulses that gambling also touches. If your achievement system is making people play just to get that next progress update, rather than enabling people to have fun with your actual game, then you might want to readjust what achievements you're awarding and how you track them.

As for why the Xbox system doesn't do this, I suspect it's a combination of minimizing UI clutter in case a game implements their progress milestones poorly, simplifying the achievement API, and a desire for simplicity of mechanics (either you get the gamer points or you don't).

# Answer
> 5 votes
I haven't seen an explicit statement about this for XBL achievements, but when using Xbox Live, it's plainly clear that the system itself doesn't display achievement progress.

Some games do show progress towards achievements as you mention yours does, but it's done from within the game, not as part of the overall achievement framework.

As for why, my guess would be that it's done to simplify said framework. Control over how progress is determined and communicated is the kind of decision that's best left to individual games. Coming up with a unified interface that'd work for every possible achievement scenario just sounds like more effort than it's worth. It's a lot easier to make the framework binary (either you have an achievement or you don't) and let the game itself take care of the details -- some might choose to show a percentage completed, some would go for a "You found X of Y widgets" message, some would pick a different approach entirely or not show any progress.

As for why StackOverflow feels that achievement progress isn't worth implementing, that really belongs on Meta, but I recall reading somewhere that the idea is that badges are not a goal and achieving them isn't meant to be something you do on purpose. Some badges aren't achievable at all without a time machine and some are consolation prizes, not accomplishments.

# Answer
> 2 votes
> Is there a reference for this statement about Xbox Live achievements?

The Xbox system pretty clearly does not provide a mechanism to track or display the progress of achievements (although some games may do this themselves via their own internal technology). I don't know of any official public statement anywhere that indicates that Microsoft intended this to be the design of the system, but given that it is a thing that hasn't changed since the achievement system was introduced I think it's fairly safe to assume that it is a design decision.

> Why is this "by design"? In other words, what is gained by not showing achievement progress?

"By design" doesn't necessarily mean that there is any specific gain in the choice. It simply means that a choice was made, intentionally. That said, I think the system is easier for developers to handle when you don't have to implement progress tracking. It also likely simplifies any TRCs around achievements (what is or is not acceptable in terms of "tracking progress" for an achievement that is unlocked by reaching a particular point in the game's plot, for example?)

EDIT: **In the general case**, I think it could be argued that exposing the progress towards an achievement could expose too much of the underlying "spreadsheet" of the game. Whether or not that matters depends on the style of the game, I guess -- if you really want to encourage suspension of disbelief, maybe it's better to hide more of these mechanics that to show them.

# Answer
> 0 votes
From a UX perspective:

To me I am not decided on the value of showing progress towards a badge, however badging is defined as different from earning points. It is also said it should reward quality rather then quantity, so not playing 10 games but winning 10 games, or trying out a new feature rather then doing something often. Which would indicate showing progress is irrelevant.

It's probably worth also browsing some pattern websites like http://developer.yahoo.com/ypatterns/social/people/reputation/achievements.html UI-Patterns or Patternry. You can also check the UX version of Stackexchange https://ux.stackexchange.com/questions/1231/should-i-use-user-generated-badges-to-reward-users

---
Tags: game-design, achievements
---


# Question
Title: How is this glowing with colors radiating outward 2D effect accomplished?
I'm currently totally at a loss as to how this effect is done: http://www.youtube.com/watch?v=zp8MHUNp7Cg

The glowing on the ship and the changing color. I want to do this effect in XNA 4.0 any hints and tips?

# Answer
> 10 votes
It looks like simple vertex colouring where the colour index is function of the distance to the centre of the ship, plus time.

This can be implemented using a texture storing a palette. It could also be done proceduraly if the desired colour gradients are simple enough.

If using a palette, the vertex shader would be something like this:

```
uniform float4 in_ShipCenter; /* Centre of the ship */
uniform float in_Time;        /* Elapsed time */
/* ... */

void main(float4 in_Position : POSITION,
          uniform sampler1D in_Palette,
          /* ... */
          out float4 out_Color : COLOR)
{
    /* ... */
    float distance = length((in_Position - in_ShipCenter).xyz);
    float time = in_Time;

    /* Simple distance/time combination */
    vec2 colorIndex = vec2(distance + time, 0.5);

    /* Other possible effects:
     * vec2 colorIndex = vec2(A * distance + B * time, 0.5);
     * vec2 colorIndex = vec2(distance, time);
     * vec2 colorIndex = vec2(distance + A * time, time + B * distance); */

    /* Query the colour in the two-dimensional texture palette. */
    out_Color = tex2D(in_Palette, colorIndex);
}

```

**Edit**: account for the fact that XNA doesn't support 1D palettes. If you still want to access the pixels of a 2D palette as if it was a 1D palette, see this question.

---
Tags: xna, shaders, effect
---


# Question
Title: What is the best way to draw a big 3D model
I am currently using ModelMesh.Draw() to draw the each mesh of the model and thus the whole model. Note that my models are very heavy -- around 30MB of data, I think if there is any other way to draw the models which is more efficient then performance of my application will better.

# Answer
> 5 votes
> I think if there is any other way to draw the models which is more efficient then performance of my application will better

Don't guess -- profile. Determine where your bottleneck is (provably) before you go jumping at random ideas about what might be slow. You may not be bound by the performance of the GPU at all, there may in fact be some other bit of code that runs on the CPU in your game that's killing your performance.

Your best bet is going to be actually sitting down and analyzing the performance of your program with various tools to determine if you are CPU or GPU bound, and then looking into profiling *that*. If you end end CPU bound, look for regular C# code profilers to examine your application. If you are GPU bound, consider something like this.

That said, a typical technique for improving render performance is to reduce draw calls, but you have limited capability to do this with XNA's model objects. As far as I know, you'd have to re-export the model such that there was only one large mesh part that contained the entire thing, and this might actually make the model much larger (if each mesh part's vertex buffer had different attributes) and is complicated by the fact that you'd have to use the same texture and shader for the entire thing, which could also result in much larger textures due to the necessity of having to pack multiple images into one texture object.

Furthermore, if the object is *really* big you could actually reduce your performance this way, because you couldn't apply any kind of culling to the model to entirely remove draws for parts that are completely off-screen or occluded. It's not always a simple solution, which is why analysis tools and metrics are so important.

---
Tags: xna
---


# Question
Title: How can I randomly generate a unit instance based on a probability?
I want `AirUnit` to return a value between 1 and 3. I want `LandUnit` to return a value between 4 and 6. I want `WaterUnit` to return a value between 7 and 9.

The Array is suposed to be inside this function:

```
public function getRandom():Unit
{
    // Array
}

```

# Answer
Choose a random number, and then write an `if` statement to return the appropriate new object based on the number.

I'm not an ActionScript coder so I don't know if this is correct, but generally it would look **something like** this:

```
// have an array called 'units' of three elements: an AirUnit, a LandUnit, a WaterUnit
random_num = Math.floor(Math.random()*9)+1; // random number from 1 to 9 inclusive

if(random_num <= 3) {
    return units[0]; // the AirUnit
} else if(random_num <= 6) {
    return units[1]; // the LandUnit
} else {
    return units[2]; // the WaterUnit
}

```

Again, that might not be exactly correct ActionScript, but that's the general code for what you seem to be asking for...
> 2 votes

# Answer
Your chances in your example are always even and therefore do not add any more randomness to the whole situation despite increasing their range, each choice always has the same number of chances to occur. For execution of speed you should just generate a random number of 0, 1 or 2 and use that as an index into the array to return the unit you want. The way most people generate random numbers between a 0 based range is to use a normal rand() call that returns a huge number and then use the modulus operator on it (the % symbol in most languages but I will admit I have not worked in action script in a very long time). So rand() % 3 would give you a number between 0 and 2.

If however what you are asking is for a way to change those values so you can say you will get a land unit 50% of the time, an air unit 30% of the time and a water unit 20% of the time, then the if statements mentioned by others could be changed to accommodate that sort of functionality. Just your original scenario does not show this.
> 1 votes

# Answer
> I want to put WaterUnit, LandUnit and AirUnit in a Array and if the generated number of the array is 1-3 its a WaterUnit and if the generated number is 4-6 its a LandUnit and if the generated number is 7-9 its a AirUnit.

Your end result really has nothing to do with an array -- you just want to generate a random number between 1 and 9 (inclusive) and then, if that number is \<= 3, return one type of object, otherwise if it is \<= 6, return another type, et cetera.

In pseudo-code, that might look like this:

```
public function getRandom() : Unit {
  value = Math.RandomNumberBetween(1,9);
  if(value <= 3 ) {
    return new WaterUnit();
  } else if(value <= 6) {
    return new LandUnit();
  } else {
    return new AirUnit();
  }
}

```
> 0 votes

---
Tags: actionscript-3
---


# Question
Title: ID3D10Device::RSSetState to be called every frame?
I am trying to create a ID3D10RasterizerState with direct3D10, and then call

ID3D10Device::RSSetState() with the proper information. However, whenever the window get rescaled, or when the app goes fullscreen, the rasterizerstate seems to reset to the default state. I have tried to set the state with WM\_SIZE messages, but awkwardly, nothing seems to happen...

It works properly when I call RSSetState() every frame, but that seems highly inefficient.

Does anyone know a solution to this? It seems to be poorly documented on msdn.

**Code:**

```
bool TestGameApp::InitGame()
{
    D3D10_RASTERIZER_DESC desc;
    desc.AntialiasedLineEnable = TRUE;
    desc.CullMode = D3D10_CULL_NONE;
    desc.DepthBias = 0;
    desc.DepthBiasClamp = 0.0f;
    desc.FillMode = D3D10_FILL_SOLID;
    desc.FrontCounterClockwise = false;
    desc.MultisampleEnable = true;
    desc.ScissorEnable = FALSE;
    desc.SlopeScaledDepthBias = 0.0f;

    m_pD3DDevice->CreateRasterizerState(&desc,m_pRSState);
    m_pD3DDevice->RSSetState(m_pRSState);

    //...more code
}

```

***WndProc:***

```
switch( message )
{
    case WM_SIZE:
    {
        m_pD3DDevice->RSSetState(m_pRSState);
        break;
    }
}

```

# Answer
Go ahead and call it every frame. It's not inefficient; that's the way you're supposed to do it. Game engines often call it (and other SetState methods) *many* times per frame in order to switch render states for different parts of the frame.
> 3 votes

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


# Question
Title: Calculating bullet travel knowing coordinates and radian
I have a player sprite that has a x and y coordinate and also a radian. The radian determines which way the sprite faces in a top-down game interface. In this case, the radian points from the player sprite to the mouse cursor, so the player is always facing the mouse.

I'm calculating it like this:

```
this.radian = Math.atan2(inputs.mousey - this.ypos, inputs.mousex - this.xpos);

```

Now I want the player to be able to fire bullets. The bullet sprite is 5x5 pixels, and I want it to fire directly away from the player in the players direction (so it's basically firing in the direction of the mouse cursor). The bullets the player fires are held in an array called (conveniently) `bullets`. It's a 2-dimensional array that looks like this:

```
var bullets = [
    [xpos, ypos, radian], // first bullet
    [xpos, ypos, radian], // second bullet
    [xpos, ypos, radian]  // third bullet
]

```

The bullet is to travel 5 pixels on each game tick, in the direction determined by the radian. But I'm having trouble working out the math for this. I already have the bullet being drawn to the canvas, and I can make it move, but have no idea how to make it follow the direction the radian is pointing.

Could anyone lend a hand, perhaps a code sample? Thanks.

# Answer
```
speed = 5.0; // pixels per tick
xVelocity = speed * cos(radian);
yVelocity = speed * sin(radian);

```
> 4 votes

---
Tags: javascript, html-canvas, bullet-physics
---


# Question
Title: Is there a way to use an arbitrary number of lights in a fragment shader?
Is there a way to pass an arbitrary number of light locations (and colors) for the fragment shader, and loop over them in the shader?

If not, then how are multiple lights supposed to be simulated? For example with respect to diffuse directional lighting, you can't just pass a sum of the light weights for the shader.

# Answer
> 30 votes
There are generally two methods for dealing with this. Nowadays, they are called forward rendering and deferred rendering. There is one variation on these two that I will discuss below.

### Forward rendering

Render each object once for every light that affects it. This includes the ambient light. You use an additive blend mode (`glBlendFunc(GL_ONE, GL_ONE)`), so each light's contributions are added to each other. Since the contribution of different lights are additive, the framebuffer eventually gets the valu

You can get HDR by rendering to a floating-point framebuffer. You then take a final pass over the scene to down-scale the HDR lighting values to a visible range; this would also be where you implement bloom and other post-effects.

A common performance enhancement for this technique (if the scene has a lot of objects) is to use a "pre-pass", where you render all of the objects without drawing anything to the color framebuffer (use `glColorMask` to turn off color writes). This just fills in the depth buffer. This way, if you render an object that is behind another, the GPU can quickly skip those fragments. It still has to run the vertex shader, but it can skip the typically more expensive fragment shader computations.

This is simpler to code and easier to visualize. And on some hardware (mainly mobile and embedded GPUs), it can be more efficient than the alternative. But on higher-end hardware, the alternative generally wins out for scenes with a lot of lights.

### Deferred rendering

Deferred rendering is a bit more complicated.

The lighting equation you use to compute the light for a point on a surface uses the following surface parameters:

* Surface position
* Surface normals
* Surface diffuse color
* Surface specular color
* Surface specular shininess
* Possibly other surface parameters (depending on how complex your lighting equation is)

In forward rendering, these parameters get to the fragment shader's lighting function either by being passed directly from the vertex shader, being pulled from textures (usually through texture coordinates passed from the vertex shader), or generated from whole cloth in the fragment shader based on other parameters. The diffuse color may be computed by combining a per-vertex color with a texture, combining multiple textures, whatever.

In deferred rendering, we make this all explicit. In the first pass, we render all of the objects. But we don't render *colors*. Instead, we render *surface parameters*. So each pixel on the screen has a set of surface parameters. This is done via rendering to off-screen textures. One texture would store the diffuse color as its RGB, and possibly the specular shininess as the alpha. Another texture would store the specular color. A third would store the normal. And so on.

The position is usually not stored. It is instead reconstituted in the second pass by math that's too complex to get into here. Suffice it to say, we use the depth buffer and the screen-space fragment position as the input to figure out the camera-space position of the point on a surface.

So, now that these textures hold essentially all of the surface information for every visible pixel in the scene, we start rendering full-screen quads. Each light gets a full-screen quad render. We sample from the surface parameter textures (and reconstitute the position), then just use them to compute the contribution of that light. This is added (again `glBlendFunc(GL_ONE, GL_ONE)`) to the image. We keep doing this until we run out of lights.

HDR again is a post-process step.

The biggest downside to deferred rendering is antialiasing. It requires a bit more work to antialias properly.

The biggest upside, if your GPU has a lot of memory bandwidth, is performance. We only render the actual geometry once (or 1 + 1 per light that has shadows, if we're doing shadow mapping). We *never* spend any time on hidden pixels or geometry that isn't visible after this. All of the lighting pass time is spent on things that are actually visible.

If your GPU doesn't have lots of memory bandwidth, then the light pass really can start to hurt. Pulling from 3-5 textures per screen pixel isn't fun.

### Light Pre-Pass

This is sort of a variation on deferred rendering that has interesting tradeoffs.

Just as in deferred rendering, you render your surface parameters to a set of buffers. However, you have abbreviated surface data; the only surface data you care about this time is the depth buffer value (for reconstructing the position), normal, and the specular shininess.

Then for each light, you compute just the lighting results. No multiplication with surface colors, nothing. Just the dot(N, L), and the specular term, completely without the surface colors. The specular and diffuse terms should be kept in separate buffers. The specular and diffuse terms for each light are summed up within the two buffers.

Then, you re-render the geometry, using the total specular and diffuse lighting computations to do the final combination with the surface color, thus producing the overall reflectance.

The upsides here are that you get multisampling back (at least, easier than with deferred). You do less per-object rendering than forward rendering. But the main thing over deferred that this provides is an easier time to have different lighting equations for different surfaces.

With deferred rendering, you generally draw the entire scene with the same shader per-light. So every object must use the same material parameters. With light pre-pass, you can give each object a different shader, so it can do the final lighting step on its own.

This doesn't provide as much freedom as the forward rendering case. But it is still faster if you have the texture bandwidth to spare.

# Answer
> 4 votes
You need to use deferred rendering or pre-pass lighting. Some of the older fixed-function pipelines (read: no shaders) supported up to 16 or 24 lights - *but that's it*. Deferred rendering eliminates the light limit; but at the cost of a much more complicated rendering system.

Apparently WebGL supports MRT which is absolutely **required** for any form of deferred rendering - so it might be doable; I am just not sure how plausible it is.

Alternatively you could investigate Unity 5 \- which has deferred rendering right out of the box.

Another simple way to deal with this is to simply prioritize lights (maybe, based on the distance from the player and whether they are in the camera frustum) and only enable the top 8. A lot of AAA titles managed to do this without much impact on the quality of the output (for example, Far Cry 1).

You could also look into pre-calculated lightmaps. Games like Quake 1 got a lot of mileage from these - and they can be quite small (bilinear filtering softens up stretched lightmaps quite nicely). Unfortunately pre-calculated excludes the notion of 100% dynamic lights, but it really does look *great*. You could combine this with your limit of 8 lights, so for example, only rockets or such would have a real light - but lights on the wall or such would be lightmaps.

*Side note:* You wan't to loop over them in a shader? Say goodbye to your performance. A GPU is **not** a CPU and isn't designed to work the same way that, for example, JavaScript does. Remember that each pixel you render (if even it gets overwritten) has to perform the loop - so if you take running at 1920x1080 and a simple loop that runs 16 times you are effectively running everything inside that loop 33177600 times. You graphics card will run a **lot** of those fragments in parallel, but those loops will still eat older hardware.

# Answer
> 2 votes
You can use a pixel shader that supports n lights (where n is a smallish number like 4 or 8), and redraw the scene multiple times, passing a new batch of lights each time, and using additive blending to combine them all together.

That's the basic idea. Of course there are lots of optimizations needed to make this fast enough for a reasonable sized scene. Don't draw all the lights, just the visible ones (frustum and occlusion culling); don't actually re-draw the *entire* scene each pass, just the objects within range of the lights in that pass; have multiple versions of the shader that support different numbers of lights (1, 2, 3, ...) so you don't waste time evaluating more lights than you need to.

Deferred rendering as mentioned in the other answer is a good choice when you have many small lights, but it is not the only way.

---
Tags: lighting, webgl
---


# Question
Title: How do I find a point given an angle and distance to it?
I'm working on a school project creating a tank team in the programming game Robocode. (It's a tank battle game with self-programmed bots, in Java).

I'm programming a scout bot that scans, finds enemies and reports them to the commander bot. I only have the distance and angle to the scanned enemy bot. How can I find its X,Y-position using only these known variables?

Here's a diagram:

# Answer
Simple?

```
NewPos = new Vector2(825 * sin(85 degrees), 825 * cos(85 degrees));

```

Most libraries use radians not degrees, so:

```
radians = degrees * PI / 180

```

If you want the coordinates in the world reference frame, you will need to get the direction of the Tank, subt add the centre Tanks origin to the result:

```
NewDir = TankDir + 85;
NewPos = new Vector2(825 * sin(NewDir), 825 * cos(NewDir));
NewWorldPos = NewPos + TankWorldPos

```
> 6 votes

# Answer
I think this will be enough if you don't use scale.

```
float Angle = RotationTankA - RelativeAngle;

PosTankB = PosTankA + new Vector2(cos(Angle), sin(Angle)) * Distance;

```
> 3 votes

# Answer
I have just made up an example in C#/XNA and got it to work perfectly.

Here is the current function

```
public Vector2 GetPosition(Vector2 CurPos, float angle, float distance)
        {
            //Get SOH
            float op = (float)Math.Sin(angle) * distance;
            //Get CAH
            float ad = (float)Math.Cos(angle) * distance;
            //Add to old Vector
            return (CurPos + new Vector2(ad, op));
        }

```

Note that angle 0 means that the CurPos Tank Sprite is pointing **right**, In the example I made, I simple used the Left and Right arrow keys to + or - the current angle, and when drawing would simple use...

```
        batch.Draw(BaseSprite, Position, null, Color.White, BaseRotation, new Vector2(BaseSprite.Width / 2, BaseSprite.Height / 2), 1, SpriteEffects.None, 0);

```

Obviously this is in C#, but i'm sure it wouldn't be too hard to convert to Java, seeing as both languages are quite similar anyway.
> 1 votes

---
Tags: java, mathematics, vector, angles
---