# Question
Title: How to fly enemies like galaxian game enemies?
I am developing game like galaxian and using cocos2d with box2d .I don't have idea how to create enemies like galaxian game enemies and how do they fly over the screen. http://www.youtube.com/watch?v=BmrCd5tPqpo&feature=related

Could you please help me how to do this ?

I have created the enemies but when i look at the game enemies fly how they are flying ?

# Answer
> 3 votes
Initialise and assign a movement function to each enemy as a function of time for e.g.

```
x(t) = 5 * sin(t)
y(t) = t * 0.2

final position = Point(x(t), y(t))

```

when they start flying, plug in the game elasped time since start of flight into x(t) and y(t) to give you the new X and Y coordinate of the enemy.

A boss movement function could be e.g.

```
x(t) = 10 * sin(0.2 * t)
y(t) = cos(0.2 * t)

```

NOTE: depending on the coordinate system of your game, you may need negative functions.

---
Tags: box2d, cocos2d
---


title: Moving in a diamond - enemy gets stuck

text:
# Question
Title: Moving in a diamond - enemy gets stuck
I have an enemy that I would like to move as follows:

1. Start at (0, 200, 0)
2. Move to (200, 0, 0)
3. Move to (0, -200, 0)
4. Move to (-200, 0, 0)
5. Move to start point, repeat as long as it remains active.

This is what I've done to achieve that:

```
if (position.X < 200 && position.Y > 0)
{
   Velocity = new Vector3(1, -1, 0) * speed;
}
else if (position.X >= 200 && position.Y <= 0 && position.Y > -200)
{
   Velocity = new Vector3(-1, -1, 0) * speed;
}
else if (position.X <= 0 && position.Y <= -200)
{
   Velocity = new Vector3(-1, 1, 0) * speed;
}
else
{
   Velocity = new Vector3(1, 1, 0) * speed;
}

```

It moves to the second point, but then gets stuck and appears to vibrate in place. How should I be doing this?

# Answer
> 8 votes
I think you should not try to hardcode this behavior as a series of if-elses like you're doing, because this will make it very difficult to extend or change if you need different values, or to add more positions in the path.

Instead look into adding the *capability of following any path* to your entity. Here's an example (I'll give the example in 2D but it should be the same for 3D), but there are certainly many ways to do this.

Suppose you're starting with:

```
class Entity
{
    public Vector2 position;
    public float speed;
}

```

First add this helper method to the class, which moves the entity towards a destination and returns true when the destination has been reached:

```
private bool MoveTowardsPoint(Vector2 goal, float elapsed)
{
    // If we're already at the goal return immediatly
    if(position == goal) return true;

    // Find direction from current position to goal
    Vector2 direction = Vector2.Normalize(goal - position);

    // Move in that direction
    position += direction * speed * elapsed;

    // If we moved PAST the goal, move it back to the goal
    if (Math.Abs(Vector2.Dot(direction, Vector2.Normalize(goal - position)) + 1) < 0.1f)
        position = goal;

    // Return whether we've reached the goal or not
    return position == goal;
}

```

Then add a list of positions to your entity which will hold the path for him to follow:

```
class Entity
{
    List<Vector2> path = new List<Vector2>();
}

```

And an update method that always moves the entity towards the next position in the path:

```
public void Update(float elapsed)
{
    if(path.Count > 0 && MoveTowardsPoint(path[0], elapsed))
        path.RemoveAt(0);
}

```

Finally, to make the entity follow the points you specified and make it repeat, add something like the code below to the `Update` method:

```
if(path.Count == 0)
{
    path.Add(new Vector2(0, 200));
    path.Add(new Vector2(200, 0);
    path.Add(new Vector2(0, -200));
    path.Add(new Vector2(-200, 0));
}

```

---
Tags: xna, vector
---


title: Rotate an image in a scaled context

text:
# Question
Title: Rotate an image in a scaled context
Here is my working piece of code to rotate an image toward a point (in my case, the mouse cursor).

```
float dx = newx - ploc.x;
float dy = newy - ploc.y;
float angle = (float) Math.toDegrees(Math.atan2(dy, dx));

```

*Where ploc is the location of the image i'm rotating.*

And here is the rendering code:

```
g.rotate(loc.x + width / 2, loc.y + height / 2, angle);
g.drawImage(frame, loc.x, loc.y);

```

*Where loc is the location of the image and "width" and "height" are respectively the width and height of the image.*

What changes are needed to make it works on a scaled context? e.g make it works with something like `g.scale(sx, sy)`.

# Answer
> 1 votes
First, I think it's important for you notice that what you are effectively doing is rotating the (OpenGL?) context around the center of the image by "angle" degrees. Then, with the subsequent call, you draw an image in the standard way, but being your transformation matrix changed by the rotation, you will draw a rotated image. I think it's important for you to understand this because after the call

```
g.rotate(loc.x + width / 2, loc.y + height / 2, angle);

```

all your following draw calls will be performed in the transformed context, and if you don't have this clear, it can lead to confusing draws. You can of course move back to you original matrix by applying an inverse rotation, or by performing a "push" of the matrix before the roation, and "popping" the matrix after the rotated draw.

This being said, to perform a scaled draw after the rotation it's enough that you scale your context before the draw call

```
g.rotate(loc.x + width / 2, loc.y + height / 2, angle);

```

as people have suggested. Only, remember that scaling and rotating get translated to matrix operations, therefore if you are scaling by the same amount on both axes you can perform the operations in either order, otherwise you should first rotate and then scale to have a correct result.

---
Tags: slick, transformation
---


# Question
Title: How can I make Maya export a mesh as double-sided?
I'm exporting from Maya 2009 to OBJ. The mesh I'm exporting *has* in it's Render Stats "Double Sided" checked, but when the polygon is exported, only a single side is actually exported.

What really needs to happen is for each polygon that is double sided, *two* polygons need to be exported, facing in opposite directions..

I can do this manually, but is there a way to make the OBJ exporter do it for me?

# Answer
The mesh is just exported vertices. The order in which they're exported is the standard for defining which face is drawn. If you want to have both faces drawn, simply configure your model rendering code to draw faces defined by both clockwise winding and counter clockwise winding.

With OpenGL or DirectX this can be as simple as disabling backface culling. See the documentation regarding backface culling for the technology you're using.
> 2 votes

---
Tags: maya
---


title: Pros and cons of using dlls

text:
# Question
Title: Pros and cons of using dlls
I wonder about create every game engine module (render, input, sound, etc...) into dlls (renderer.dll, input.dll, etc...). What are pros and cons in your opinion of divide game into set of dlls ? I see only need to write game module in separate dll, to have posibility to create mods.

# Answer
> 4 votes
**Pros**

* You can build DLLs separately.
* It could be faster to re-build one DLL

**Cons**

* Calling code from DLL is slower
* It would be slower to re-build hole project with all DLLs
* Function names are visible. It is easier to reverse code that uses dynamic DLLs

I do not see sense to have render.dll and input.dll But some RareUsedJoystick.DLL could be made as loadable module to release memory for those who do not use that RareUsedJoystick

# Answer
> 3 votes
Putting code into seperate Windows DLLs sounds promosing in theory, but in practice you should be aware of certain limitations.

1. You have to declare all your classes and global functions you want to use from outside as "exportable" using

```
__declspec( dllexport ) class Foo {};

```

when building the library. Clients of your DLL must "see" the include like this:

```
__declspec( dllimport ) class Foo {};

```

That is why you see a makro infront of class declarations in DLL headers.
2. Resources like FILE\* pointers can not be shared under all circumstances (different CRTs) between DLLs. That means if you open the file in one DLL, you cannot write to it from the client app or another DLL, nor close it.

http://msdn.microsoft.com/en-us/library/ms235460%28VS.80%29.aspx
3. Memory management: You cannot allocate memory in the DLL and free it in another DLL or in client application under all circumstances (different CRTs).
4. Exporting template classes can be a real pain, especially if they use static member variables.

If you just want to reuse your code without recompiling, there is another option, **static libraries** (.lib). It is precompiled code (as in the DLL) but it is linked into your application and has no such limitations as the ones mentioned above, plus Link Time Code Generation still works with the library code.

---

Update: As Sean pointed out in the comments, point 2 and 3 can work when using the same CRT version, as the MSDN link in 2 also shows. However, my advice is to design the DLL without relying on it at all, since there are so many cases where it won't work, like using 2 DLLs with different CRT's or compiled with different Visual Studio versions.

# Answer
> 1 votes
Most differences are negligible. DLL's are more flexible but make the building process more complex. I would only use DLL's if:

* Multiple applications need to access the same functionality. For example if you have separate binaries for a editor and the game itself.
* You want yourself or other people be able to replace certain components. For example in Civ IV modders could ship replacement for the game's DLL's to fundamentally change parts of the gameplay.
* You want to load them at runtime to allow to extend the application by third party plugins.

# Answer
> 0 votes
Another advantage is that it can help you structure your code correctly. Any non-logical dependencies between modules will stand out more and it will be more difficult to use such hacks.

---
Tags: c++
---


# Question
Title: How do you set the movement speed of a sprite?
I'm using Slick 2D/Java to play around with graphics. Getting an image to move is easy:

```
Input input = gc.getInput();

        if(input.isKeyDown(sprite.up)){
            sprite.y--;
        }else if (input.isKeyDown(sprite.down)){
            sprite.y++;
        }else if (input.isKeyDown(sprite.left)){
            sprite.x--;
        }else if (input.isKeyDown(sprite.right)){
            sprite.x++;
        }

```

However, this is called on every update, so if you hold up, the sprite moves to the edge of the screen in a few hundred milliseconds. Since coordinates are integers, I can't add less than 1 to slow the sprite down. I'm assuming I must have to implement a timer of some sort or something. Any advice?

# Answer
`rate * time = distance`

1. Establish a rate of movement in whatever units of measure you want (such as pixels per millisecond).
2. Get the time since the last update that has passed (elapsed time).
3. Establish the direction of movement (you're already doing that).
> 5 votes

# Answer
Use separate real numbers to store position with sub-pixel accuracy and then cast them into integers to draw. If you can't modify your sprite class to contain real numbers, just create a new wrapper class that contains a sprite and real coordinates. Something like:

```
class Entity
{
  Sprite sprite;
  double x;
  double y;
  ...
  void translate( double dx, double dy )
  {
    x += dx;
    y += dy;
    sprite.x = (int) Math.floor(x);
    sprite.y = (int) Math.floor(y);
    // floor() prevents weirdness dealing with negative numbers like -0.1
    // (int)(-0.1) rounds up to 0 but (int)Math.floor(-0.1) rounds down to -1
  }
}

...
Entity entity = new Entity( sprite );
...
if(input.isKeyDown(sprite.up)) entity.translate(0,-0.1);

```
> 2 votes

---
Tags: java, sprites, movement, slick
---


title: frame lock networking

text:
# Question
Title: frame lock networking
I'm developing an RTS game and I want to add multiplayer support to my game.

I picked the easiest technique to implement for start frame locking technique.

1. I used server client networking architecture (I think it's my first mistake I think using peer to peer is a better one for this)
2. On game update every clients send their commands and maybe receive some command then render the frame and wait for all clients to send their update complete message then all of them can go for the next frame.

I send commands and all logic is calculated on the clients based on commands but the clients can go out of sync easily. Every AI controlled units make different decisions on each clients

What I have to do to sync my game? Do you suggest me a better network architecture or technique?

# Answer
Games like Megaglest use TCP networking for multiplayer.

It may be that all your players are using the same compiler on the same OS on the same hardware; but more generally, you have to use a portable math library e.g. streflop. You have to use a pseudo-random number generator and specify the initial seed for it. If you use streflop and, say, streflop's Mersene Twister for all game-related actions then your game is deterministic across all clients.

My Ludum Dare 24 game Cage Flight uses TCP sockets and illustrates the poor user experience naked lock-step. What you really need is prediction and correction. There is a nice intro series here.
> 3 votes

# Answer
Use sockets, send every action immediately through them. You will save bandwidth for sending only actions instead of lots of information about state of units, and this will also proof the game against hacking.

As Jonathan Connell said, your algorithms must be deterministic, however I don't think not using ints is the issue. If you're rounding a float number into an int, assuming both players use same clients compiled in same language, these numbers should be rounded in same way. But if you use randomizing functions, or if you give different input to deterministic functions, then obviously there's a big chance you will get a different output, and thus, desynchronization.

Now, server should response to you and send same info to another player, with:

* confirmation that the command (there could be a command's ID) was sent successfully
* timestamp of when the command was processed
* information the client couldn't know, e.g. what damage was randomized on server

Or it could also wait for it's simulation 'tick', summarize all changes and then send the summary to both players.

So in example:

1. Player A selects a tank and orders it to go into fog of war, coordinates X:100, Y:215. This command is sent immediately.
2. Server calculates path for the tank (client can't do this because of the fog)
3. TICK! Server sends part of the path to Player A (with timestamp), and nothing to Player B, as this part is in Player B's fog of war.
4. Player A's client starts to move the tank (after about 100-200 ms)
5. Player A selects a ship and orders it to go onto Player's B waters. I assume both players see whole water on map, so player A sees this part of the map, and so the path is calculated on client and sent to the server.
6. Player B selects a building and starts to build an airplane. And sends it to the server.
7. TICK! Server sends to Player B a timestamp when exactly he started to build the plane, plus path of the ship, and to player A also timestamp and confirmation the path is valid.
8. Both players see the ship started to move, and player B also sees his airplane's progress bar finally moved.

That's easy. The problem is, it's very annoying to see your units respond even 200 ms after your click. That's why you should try to predict what will happen. It's easiest to explain on point 6:

* player B selects a building and starts to build an airplane at 11:50:12.530
* player B sends data to Server
* time to build an airplane is 20 seconds, therefore the plane should be finished at 11:50:32.530
* player B knows average ping to server is 170 ms, therefore it offsets end of airplane construction to 11:50:12.530 + (170/2) = 11:50:12.615
* player B starts to update airplane's progress bar, knowing the construction will take 20 085 ms, and so filling 1% of the bar per 200.85 ms.
* Server gets the command at 11:50:12.620, and sends back confirmation with such timestamp
* at 11:50:12.720 player B gets the confirmation of timestamp being 11:50:12.620.
* player B (or rather it's client) now knows he estimated the time wrong, and has to smoothly transition from it's prediction to the true result.
* in this case it's save to go for maximum smoothness of the transition
* so far 190 ms have elapsed. This means progress bar is filled with (190/200.85)% = 0.95%.
* There are 19 895 ms left to make 99.05% of the plane. That means since now, filling every next 1% of the bar will take 19 895 / 99.05 = 200.86 ms.
* (I know the difference is almost none here, but it's only an example, and would make more sense with a severe lag)
* so now progress is calculated as 0.95% + time\_from\_server\_response / 19 895 * 100%
* if the airplane has some rally point, it's movement will be synchronized with server (if server knows the rally point), because calculating his movement will have same, synchronized input - end of it's construction.
> 2 votes

# Answer
Jonathan Connell felt I did not support my case against Frame Locking well in the original answer and while it is a subjective matter, I believe I can present objective advantages in using an alternative technique to frame locking. While we all agree it could work for your game. It is by no means definitely the best or only was to achieve what you are are working to create.

So hear me out:

Minimizing lag in a RTS

RTS and action games are not the same animal. In fps, you constantly transfer tiny precise movements to the server. RTS need to manage armies, sometimes hundreds of units where each unit needs to do path-finding, auto-attack(be aware of environment) and that means the units are somewhat independent. That is why people came up with Event-Locking.

With frame locking, the client sens an update every frame with the user's input. The sever processes input and replies with the result of all moves made by the players. This method is great for low latency networks like home networks if you play with your friends through wifi without using the Internet. This does not do wonders when you play online and there is latency, especially if your server is not ideal for multi-player gaming. This is without mentioning that the real world is not ideal, maybe one of the players is using a torrent client that is slowing the connectivity and causing additional latency and packet loss. Maybe another player has a poor connection, using a cellular device to play the game? Nobody knows what could happen during a network game online. That is why the system has to be as foolproof as possible. That is why I do not recommend frame-locking personally.

If all the clients send updates at the same pace things will work. What happens if an update is not received due to networking issues? The server and the rest of the clients need to 'freeze' and wait for that update. If the server and the other clients proceed the game will not be synchronized which is what we are working to prevent.

Depending on your game architecture, the player could see the results of her actions. What about the rest of the players, the packet did not make it, they do not see it.

You can adjust the system to compensate by adapting to the communication lag. This will make the system less responsive when there is a little more lag.

We need a system that avoids this, you are using a server, not all players need to be slowed down to the speed of the currently slowest player's connection.

Instead, it is much better to send requests for commands and moves. For example you have a commando you wish to move from point A to point B. The player who owns the commando unit will click it and then select to move it. The player issued the command with the destination, now the server is checking if the command is feasible. Maybe the player is a hacker or a cheater and does not have a commando, maybe the road is blocked and maybe the unit just died. If the command is accepted by the server after checking, the "Move(Commando,Destination)" packet is sent to all clients including the original player (as a seal of approval) with the time-stap and all needed data. The same thing can be done with "Attack(Commando, Jeep)" commands and Collect(Harvester, resource) commands. You need to present resources as neutral units.

Not all clients will get the reply packet in the same time, remember the time-stamp? To compensate for the delay, a client that gets the order too late, can either animate the unit slightly faster or "teleport" it to it's current correct location. On the player side the movement will start automatically assuming in advance that it is legal to prevent slow response time. If the movement is not accepted, the unit will move backwards which should only happen on very rare occasions.

Sometimes it will not be enough to send only the command such as Move(Commando, (x,y)) and you will need the server to send the resulting orders and way-points to all players. That is because some new building or unit is blocking the shortest path.

I will elaborate if people feel this is valuable.
> -3 votes

---
Tags: networking, rts
---


# Question
Title: How to Generate Spritesheet from a 'problematic' animated Symbol in Flash Pro CS6?
In the new Flash Pro CS6 there is an option to generate spriteheet from a symbol. I used these tutorials:

http://www.adobe.com/devnet/flash/articles/using-sprite-sheet-generator.html

http://tv.adobe.com/watch/cs6-creative-cloud-feature-tour-for-web/generating-sprite-sheets-using-flash-professional-cs6/

And it works really well!

An artist I'm working with created a bunch of assets for a game. One of them is a walking person as seen from a top-down view.

You can find the .fla here:

https://docs.google.com/folder/d/0B3L2bumwc4onRGhLcGNId1p2Szg/edit (If this does not work let me know, it is the first time I used Google Drive to share files)

1 .When I press ctrl+enter I can see it is moving. When I look for the animation, I do not seem to find it. When I select to create a spritesheet, flash suggest creating a spritesheet with one frame in the base pose and no other (animation) frames.

What is causing this and how do I correct it?

2 .I want to convert it to a sprite sheet for 32 angles of movement. Is there any magical easy way to get this done? Is there a workaround without using Flash CS6 to do the same thing?

# Answer
I have experience with flash but not with CS6 version. With the version that I've worked is CS, but from the description I can tell you the following:

1) If you press Ctrl-Enter and you see the animationm then in the stage you have a MovieClip. If you double click on it, you will see the timeline.

2) Probably Flash need all the frames to generate a spritesheet, you can do the following: enter in the movieclip, select all the frames, right click "Copy frames", then go back to the stage, select a frame in the timeline, then right-click "Paste frames". This sould put all the movieclips frames on the stage, and Flash will "see" all the frames.

3) Or you can transform the movieclip into "Graphic", and select the option "Play until the end"(?? I don't remember the right text, sorry), and in the timeline add many frames as the total length of the movieclip. You have to be able to see the animation, and I'm pretty sure that Flash will can export an spritesheet.

Let me know if you were success.

PS: Sorry if I have many grammar errors. I wrote this very fast for my knowledge of english, :P
> 1 votes

---
Tags: animation, flash, actionscript-3, spritesheet
---


title: How is an HTML5 game sold?

text:
# Question
Title: How is an HTML5 game sold?
*(I know this site doesn't give legal advice, but what I'm dealing here with isn't anything serious at all. Also, I apologize to JP for being annoying over this.)*

Someone found a game I made on the Internet, and expressed interest in buying it. We agreed upon a price, and, in the meantime, I removed the game's source from the Internet, just to be sure.

Now, I'm wondering what to do next.

These are the terms:

* He gets the game's source code, and only that, without the graphics (which weren't made by me).
* He gets the right to develop and sell the game.
* I get to keep the ownership of the original game, meaning that I can use it in my portfolio when applying for jobs, for example.
* The game gets to stay on its original site.

But I am not sure how can I legally realize this. Which license can I use?

# Answer
> 4 votes
It does not matter which license is used. What you pass to the buyer is the copyrights. He can then choose any license.

When you make the agreement, note that you are transferring copyrights over the engine(code) and not the game assets. Also note, that you retain license over the game in it's original form, to distribute it and showcase it for any purpose without infringing on the copyrights of the game's engine(code). You will keep the code secure to protect the interests of the buyer in this contract.

So to keep things short and sweet:

Make a contract that states the following:

1. The buyer receives full copyrights on the game engine(code) and receives no rights over the game assets.
2. The seller retains the license to distribute the game in it's original form without modifying and/or reselling the engine(code).

This is no replacement for legal advice. In this case where you choose to avoid professional legal advice it may suffice to draft a contract like this yourself. That is your responsibility.

# Answer
> 0 votes
what you're looking at is a standard Game Distribution Agreement. The buyer gets to modify properties of your game and commercialize them, but you maintain all intellectual property rights (covering the game's original source code and assets ).

Just like any other agreement, make sure you're signing it with someone who has reputation. Avoid at all costs people you don't previously know, or do not belong to a certain gaming community. A buyer who is a legitimate game company would be ideal, because they'll understand the distribution agreement.

---
Tags: html5, legal, publishing
---


# Question
Title: Is 2 lines of push/pop code for each pre-draw-state too many?
I'm trying to simplify vector graphics management in XNA; currently by incorporating state preservation. ***2X*** lines of push/pop code for ***X*** states feels like too many, and it just feels wrong to have 2 lines of code that look identical except for one being push() and the other being pop().

The goal is to eradicate this repetitiveness,and I hoped to do so by creating an interface in which a client can give class/struct refs in which he wants restored after the rendering calls.

Also note that many beginner-programmers will be using this, so forcing lambda expressions or other advanced C# features to be used in client code is not a good idea.

---

I attempted to accomplish my goal by using Daniel Earwicker's Ptr class:

```
    public class Ptr<T>
    {
        Func<T> getter;
        Action<T> setter;

        public Ptr(Func<T> g, Action<T> s)
        {
            getter = g;
            setter = s;
        }

        public T Deref
        {
            get { return getter(); }
            set { setter(value); }
        }
    }

```

an extension method:

```
        //doesn't work for structs since this is just syntatic sugar
        public static Ptr<T> GetPtr <T> (this T obj) {
            return new Ptr<T>( ()=> obj, v=> obj=v );
        }

```

and a Push Function:

```
        //returns a Pop Action for later calling
        public static Action Push <T> (ref T structure) where T: struct
        {
            T pushedValue = structure; //copies the struct data
            Ptr<T> p = structure.GetPtr();

            return new Action( ()=> {p.Deref = pushedValue;} );
        }

```

However this doesn't work as stated in the code.

**How might I accomplish my goal?**

---

Example of code to be refactored:

```
    protected override void RenderLocally (GraphicsDevice device)
    {
        if (!(bool)isCompiled) {Compile();}

        //TODO: make sure state settings don't implicitly delete any buffers/resources
        RasterizerState oldRasterState = device.RasterizerState;
        DepthFormat oldFormat = device.PresentationParameters.DepthStencilFormat;
        DepthStencilState oldBufferState = device.DepthStencilState;
        {
             //Rendering code
        }
        device.RasterizerState = oldRasterState;
        device.DepthStencilState = oldBufferState;
        device.PresentationParameters.DepthStencilFormat = oldFormat;
    }

```

# Answer
Your `Push<T>` function isn't going to do what you want it to do. The `Ptr<T>` you create inside it is only accessible inside that function. In fact I would hope that the C# compiler would optimize away that call since it's effectively a noop.

The way to solve this problem is to make all of your possible state data classes instead of structs. Structs are a very unique thing in C#. They should absolutely only be immutable, data under every conceivable circumstance. Useful for quickly associating a bunch of values, or implementing numeric types like Vectors and special ID-type values.

The quick solution is to implement Push like this:

```
//returns a Pop Action for later calling
public static Action Push<T>(Ptr<T> pt) where T: struct
{
    T pushedValue = pt.Deref; //copies the struct data
    return new Action( ()=> {pt.Deref = pushedValue;} );
}

```

See example program here: http://pastie.org/4925186

Your clients *must* have knowledge of Ptr for it to work. In order to make the transition from value-type land to reference-type land in these Push/Pop functions, you have to pass around the Ptr.

Now that being said, you mentioned this should be for beginners. Why are you making them thinks about pointers in C#? Or maybe you aren't, but that's a consequence of this approach.

If you are actually going to be pushing and popping state, why not maintain an actual stack? (Or List that you use with Stack semantics). Or maybe just always copy the user data to a temp state before you render, leaving their own data untouched? Without seeing how your code would use this feature, it's tough for me to recommend a good approach.

I can see some beginners liking see both Push() and Pop() in their code though, since they can better understand then what's going on instead of assuming it's all magic.
> 1 votes

# Answer
Much of OpenGL is basically a state machine. The important thing is that at each point where drawing occurs, that the correct state is set for all values; that there's no old, leftover invalid state left lying around.

Sample code typically ensures this by immediately turning everything off after using it, or through a push/pop system such as the one you mention in the question.

Real games typically implement a render state manager to sit in between the rendering engine and OpenGL, to optimise the state changes which are sent through to OpenGL. So instead of implementing push/pop, rendering code requests the specific features it wants from the state manager, tells the state manager to apply the changes, and then de-requests those features, and *doesn't* tell the state manager to apply to de-requests.

The code flow typically looks something like this:

```
m_state.SetBool( UsingVertexArray, true );
m_state.SetBool( UsingColorArray, true );
m_state.Flush();
ActuallyRender();
m_state.SetBool( UsingVertexArray, false );
m_state.SetBool( UsingColorArray, false );

```

The render state manager maintains its own internal state; it knows both the last setting it's told OpenGL about, and the most recently requested values. When "Flush()" (sometimes called "Apply()" or some other name) is called, it finds the settings with changed values, and only informs OpenGL about those changed values.

So if the next thing which renders after our sample code above turns "UsingVertexArray" and "UsingColorArray" back on again, m\_state.Flush() does nothing, since there's been no change to the requested state compared against the last time "m\_state.Flush()" was called.

This sort of approach has the advantage of being quite simple to understand, while still only sending real state changes to OpenGL; not spamming it with turning the same values on and off again over and over again, when everything actually wants them to be turned on.
> 0 votes

---
Tags: xna, c#, architecture, graphics, graphics-programming
---


# Question
Title: Seeking first-hand information about cow intelligence, compared to other barnyard animals
Does anyone have **first-hand** information about cows? Specifically, how smart is the *average* cow compared to other common barnyard animals?

examples: Sheep, goats, dogs, cats, turkeys, pigs, horses

This will help me with level progression plus related goal objects. No need for a dissertation, I'd just like these things to "ring true".

# Answer
If you were to ask Temple Grandin, she would tell you they're pretty smart. While cows are not as intelligent as pigs, there is evidence that they're a bit smarter than people give them credit. Watch some of Grandin's videos (or her movie) and you'll learn a lot about the mentality of cows. This should help you simulate them better.

Your cows should have a strong herd mentality. When left alone they should seek the group. They won't like going into dark places and they'll be able to perform simple path finding. They have no depth perception (or a very poor sense of it) so their attack abilities should miss often. This also affects their desire to go down steep ramps or stairs, so they'll likely avoid those situations.
> 1 votes

# Answer
Humans are very self-centered creatures. Any information you will find about cow intelligence is probably biased by how much is the animal is willing to cooperate and respond to orders from humans or interact with humans in a way that is pleasing to them(see cats).

I have not had much interaction with cows in my life to judge their intelligence from a first hand perspective. I personally like dogs, I think we all agree they take the cake.

I do have a very interesting article about horse intelligence here:

The horse was able to judge human response like in a poker game and make decisions based on the slightest nuances in body language and facial expressions and answer math questions based on that even though the horse evidently did not understand math. The only other animal that has proven such insight under stressful situations is a dog. That is why when a dog is trained to find drugs in luggage, none of the people allowed in the room know in which suitcase the drugs are. If we are in the subject of dog intelligence and abillities, did you know dogs can detect cancer by smell with nearly 99% accuracy?

References.

http://en.wikipedia.org/wiki/Clever\_Hans

http://en.wikipedia.org/wiki/Canine\_cancer\_detection

http://www.damninteresting.com/clever-hans-the-math-horse/

So I think horses are exceptional creatures in their ability to figure out human emotions and they must have very high Emotional Quotient. I hope that helps.
> 0 votes

---
Tags: character
---


# Question
Title: Marmalade SDK 6.1: missing Studio UI Builder
Marmalade SDK 6.1 they removed the UI Studio builder tool used in previous versions to construct the UI for apps. http://www.madewithmarmalade.com/devnet/documentation#/tools/uibuilder.html

now is there any alternative to the tool or we have to construct the UI programmatically ?

Thanks

# Answer
```
C:\Marmalade\6.0.6\tools\UIBuilder\Readme.txt

```

> The Marmalade Studio UI Builder has been removed from the Marmalade SDK. This means it is no longer a supported part of the product.
>
> We have removed the UI Builder because we believe that, going forwards, it is better for the Marmalade UI runtimes to support a standard UI markup rather than our proprietary markup. In the 6.1 release, we plan to support a standard UI markup, meaning that developers can leverage multiple 3rd party tools (including free tools) that support that markup.
>
> Our plan for the 6.0.1 release is to make the UI Builder source code publicly available, together with full instructions on how to build it. In the meantime, developers can still use the UI Builder tool by installing the most recent 5.2.x SDK version.
>
> There is no plan to abandon support for the current ITX markup for the IwUI runtime. Developers can continue to create ITX markup, either through the UI Builder tool or by hand, and be sure that the ITX markup will be usable in future versions of the IwUI runtime.
> 2 votes

# Answer
There's a XML UI builder available for Marmalade too. You can check it out here.
> 1 votes

---
Tags: marmalade
---


title: ricocheting off a wall

text:
# Question
Title: ricocheting off a wall
I have a capsule (sphere sweep) that I've computed the collision on a mesh with.

I know the point of impact and normal of the face it collides with.

My moving object - I'm using a capsule to represent it for collision purposes - has a quaternion describing its direction of travel.

How do I compute the new quaternion for the object to travel in on the bounce?

# Answer
If your object has a *forward* direction *fwd=(x,y,z)* and an *up* direction in its rest position (they all have in 3D, unless they're points or lines), then your quat orientation gives you the current *fwd* and *up* vectors.

Perform collision resolution and obtain *fwd'* and *up'*.

These two vectors then give you an orientation (a frame) that you can convert to a matrix and get the quat out of it describing your object's new direction of travel and *up* direction.
> 1 votes

# Answer
Once you have the collision normal (not the normal of the face because corner collisions won't work right that way), you can just split the velocity (which should really be a vector, not a quaternion) into two: normal velocity and tangent velocity.

```
normalVelocity = dot( collisionNormal, linearVelocity ) * collisionNormal;
tangentVelocity = linearVelocity - normalVelocity;

```

Now you can just invert the normal velocity to make the object bounce off the collision and recombine both into the new linear velocity vector.

```
normalVelocity *= -1;
linearVelocity = normalVelocity + tangentVelocity;

```

I won't cover quaternion-to-vector (and reverse) transformations in this answer because a quaternion isn't the most effective representation of the data. A simple 3D vector does the job as expected and has been already used practically everywhere.
> 1 votes

---
Tags: mathematics, geometry
---


# Question
Title: How to build a turn-based multiplayer "real time" server
I want to build a TCG for mobile devices that is multiplayer over the web (not local wifi or bluetooth). As a player plays cards I want the second player to see what is being played in "real time" (within a few seconds). Only one player can play at a time.

Server requirements:
1) Continuously listens for input from Player 1
2) As it receives input from Player 1, sends the message to Player 2

I know some PHP, but it seems like unless I had a loop that continued until I broke it (seems like a bad idea) the script would just receive one input and quit.

On the mobile side I know I can open sockets using various frameworks, but what language allows a "stream-like" behavior that continuously listens/sends messages on the server?

Or if I'm missing something, what would be the best practice here?

---

EDIT: I might have not made it clear before, but the mobile apps are native not web-based.

I guess I'm asking for specific suggestions on what some of the best tools or platforms for this scenario could be used i.e., PHP sockets, etc.

# Answer
> 3 votes
If you want to use sockets, you should probably choose a different language, perhaps Python or Node.js (server-side JavaScript); PHP is best suited for generating HTML in response to requests. Sockets would be used for truly real-time data, but PHP would be adequate for data that can be a few seconds delayed; you would just need to have the client keep polling the PHP page for updates.

We have a number of questions already covering making multiplayer games with PHP. Try searching for PHP multiplayer and looking through those questions & answers.

The only difference in your case is that you want a mobile app as the client. For a native app, just have the app make a background HTTP request to the PHP page, then parse the data that comes back. Do this repeatedly, as frequently as you need. Your PHP page would probably respond in a computer-readable format, so research REST, JSON, and SOAP.

Or you could just make the webpage that the PHP generates mobile-device-friendly, perhaps using something like PhoneGap to have an actual app (and also take advantage of device features like GPS if you need them).

As for the actual PHP page(s), my recommendation would be to just have them poll a database, and use the database to store the state of the game. Timestamp everything, the first login request responds with the current state, and then each update request from the client should include the client's last update timestamp, and the PHP page should just gather the data from the database that's newer than the client timestamp and send it back, along with the new timestamp.

And of course, when the client performs an action, just store it in the database with the timestamp.

# Answer
> 1 votes
You should go for a Real-Time Web server, allowing you to achieve full-duplex bi-directional communication between each client and the server. One of the most mature Real-Time Web servers is Lightstreamer (of which I am the CTO). It includes client-side APIs for all the platforms. On the server side, you can implement your own Data Adapter to inject your logic.

Check it out at http://www.lightstreamer.com

---
Tags: networking, multiplayer, server, turn-based, websocket
---


# Question
Title: Now that Device Central is dead, how can I test my Flash Lite applications?
I'm trying to use Flash Lite to make a simple game for my girlfriend, who only has a Nokia 5530, but I just realized in CS6 Adobe killed Device Central, so there's no way for me to test it without the device (and it's supposed to be a surprise).

Is there any other way for me to test it? I know I can just export the movie and use Flash Player, but Device Central allowed me to test drag and drop and memory/processor usage for example...

tl;dr, is there an alternative to Device Central for testing Flash Lite in older devices?

# Answer
> 3 votes
New answer:

After getting more intell on the situation, I suggest installing CS5 in addition to CS6 until you no longer require use of the Device Central. It will work according to online resources. If you wish to make sure you could try superuser.com for additional advice.

Good luck making that game. :)

As you probably know CS6 allows to save projects as CS5 (with some limitations).

Old answer:

Read about: Adobe AIR mobile simulation

> Simulate common mobile application interactions like screen orientation, touch gestures, and accelerometer to help speed up testing.

I have not tested it. I think it looks promising.

There is a tutorial here:

http://www.youtube.com/watch?v=iMCnLJylDgc

---
Tags: flash
---


# Question
Title: Can these game be fully coded in html5/javascript?
I mean the mechanics of the game. Would it be possible?

-Pokemon GBA series, rendering the world would be easy, but what about battle mechanics? -MapleStory, after seen dragonbound.net which is an identical copy of Gunbound I would think it's rather possible, but I'm still not sure if javascript can handle all the mechanics of the world. It would be heavy on resources I guess?

I'm asking this because I'm really interested in html5 game develop(I really think in a future will destroy flash on game dev ground). I want to have an idea of how far games developed with the html5/javascript technology can go. I got especially inspired by dragonbound. I really think it pushes htmlt/javascript to the limits (game dev).

# Answer
> 1 votes
HTML5 can do basically anything, with the `Canvas` you can manipulate every pixel of the display, if you have the right techniques and skills you can do all you want. It even suports WebGL, as soon as browsers add hardware acceleration, you will be able to use all the rendering power of the user machine.

Canvas can be used to make 2D games, almost any of them.
And WebGL can be used for big variety of casual and indie games.

There are some good people working on making 3D dev easier with PlayCanvas, and the power of HTML5 2D can be demonstrated with the Bastion version for Chrome.

Hope I helped.

# Answer
> 1 votes
In HTML5/JavaScript you can get input from user and display pictures. Just like in many other programming languages. And your are already on the internet, so internet stuff should be easy too. Which is all you need to make a game.

The problem is not what is possible and what is not, because in theory anything is possible, but whether trying *many things* together would be still *fast enough*. Which depends: on computer speed, on computer, on browser speed, perhaps even on internet connection speed. And all these data change from player to player, from year to year.

So you could start with an analysis: what do you want your game to be able to do, when the screen is most full? For example, to display 50 monsters, each of them 300x300 pixels large, plus 300 bullets, each of them 10x10 pixels large, animated at least 20 frames per second. Now you have something to be measured. And the answer would be that it requires computer with processor speed *X* and memory *Y* to do that.

If the number is realistic, just do it. If the number is just a bit high, do it anyway... it will take you some time to complete the game, and meanwhile the computers will become at least twice faster.

If the number is too high, you might rethink your game. Is it really necessary to have 50 monsters on screen at the same time? Could they be smaller? Could we get some speed by avoiding partial transparency in bitmaps? Less particles in explosions? Etc. You probably can make some sacrifice.

I think you can do it. Remember, the computers are getting faster.

# Answer
> 0 votes
By what grounds do you feel it would be resource intensive? There are plenty of RPG developed for AS3 and battle mechanics are not something you are limited to programming in any certain language. They are a collection of conditions and logic that could be expressed in any language.

MapleStory, any MMO that is not extremely heavy on 3d graphics that would require C++ to optimize performance could probably be implemented. The only limitation would be server capacity hardware wise. If you have a lot of clients, you may need several powerful servers to handle the load well.

If you are interested in html5 do not waste time making predictions about it's future and start making a game now.

There is no tangible limit to the things you can achieve with nearly any of the popular languages that are available today aside from some issues with performance.

The main variable is the game developer.

---
Tags: 2d, physics, javascript, game-mechanics
---


# Question
Title: XNA GameTime TotalGameTime slower than real time
I have set-up an empty test project consisting of a System.Diagnostics.Stopwatch and this in the draw method:

```
spriteBatch.DrawString(font, gameTime.TotalGameTime.TotalSeconds.ToString(),
new Vector2(100, 100), Color.White);

spriteBatch.DrawString(font, stopwatch.Elapsed.TotalSeconds.ToString(), new
Vector2(100, 200), Color.White);

```

The GameTime.TotalGameTime displayed is slower than the stop watch (by about 5 seconds per minute) even though GameTime.IsRunningSlowly is always false, why is this?

The reason this is an issue is because I have a server which uses stopwatch and it is faster than my client game. For instance my client notifies the server it has dropped a mine which explodes in one minute. Because the stopwatch is faster the server state explodes the mine before the client and they are out of sync. I don't want to have to notify the client when the server explodes it as this would use unnecessary bandwidth.

# Answer
> 7 votes
The answer is in the MSDN entry for GameTime http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gametime.totalgametime.aspx

> Fixed-step clocks update by a fixed time span upon every clock step. This results in uniform clock steps **that may not actually track the wall clock time**. Fixed step clocks were popular on console systems where one had tight control over code and a fixed system performance. Fixed-step clocks are also useful when trying to achieve deterministic updates for debugging, offline rendering, or other such scenarios.

So basically `game time != real time`

The solution to your problem is to not have the server tell that a mine was placed and that it will explode in one minute, but to have the server first tell that a mine was placed and then after a minute have it tell that the mine exploded. This will roughly make all clients run at the same speed. (However to really do this right you should run in lockstep.) As usual with these kind of questions I refer you to the excellent Gaffer on Games article 'fix your timestep'. You might also want to take a peak at this article since it talks about synchronizing time dependent state via the server (it doesn't apply to just physics)

---
Tags: xna, time-management
---


# Question
Title: How do I implement deceleration for the player character?
Using delta time with addition and subtraction is easy.

```
player.speed += 100 * dt

```

However, multiplication and division complicate things a bit. For example, let's say I want the player to double his speed every second.

```
player.speed = player.speed * 2 * dt

```

I can't do this because it'll slow down the player (unless delta time is *really* high). Division is the same way, except it'll speed things way up.

How can I handle multiplication and division with delta time?

**Edit**: it looks like my question has confused everyone. I really just wanted to be able to implement deceleration without this horrible mass of code:

```
else
    if speed > 0 then
        speed = speed - 20 * dt
        if speed < 0 then
            speed = 0
        end
    end
    if speed < 0 then
        speed = speed + 20 * dt
        if speed > 0 then
            speed = 0
        end
    end
end

```

Because that's way bigger than it needs to be. So far a better solution seems to be:

```
speed = speed - speed * whatever_number * dt

```

# Answer
This is where you want to use a little more physics than just modifying the position by some constant value. Give your player a velocity and an acceleration. Then, when you update you can do this:

```
player.velocity += player.acceleration * dt;
player.x += player.velocity * dt;

```

Then it's a simple matter of making the acceleration `0` to maintain a constant velocity, or you can make it a positive number to increase velocity or a negative number to decrease velocity.

If you want to "decelerate" just just a negative acceleration, that's all friction is. Friction is just another force like accelerating.
> 6 votes

# Answer
As others have noted, the correct formula for deceleration due to dry friction is

```
velocity += constant * dt * -dir( velocity )

```

where `dir(v)` returns a vector of unit length pointing in the same direction as `v`. (For one-dimensional movement, `dir(v) = 1` if `v > 0` and `dir(v) = -1` if `v < 0`.) One way to calculate it is as

```
dir(v) = v / abs(v)

```

where `abs(v)` gives the length or magnitude of the vector `v`.

To keep objects from jittering after they come to a stop (and to avoid dividing by zero if we try to calculate the direction of a prefectly stationary object), we should also ensure that the change in velocity never exceeds the original magnitude of the velocity — that is, friction should never cause an object to start moving backwards. Putting all this together, a reasonable implementation of friction in a game is:

```
friction = constant * dt;
speed = abs( velocity );
if ( friction < speed ) {
    delta_v = friction * -( velocity / speed );
} else {
    delta_v = -velocity;    // the object stops, or was stopped already
}
velocity += delta_v;

```

Note that this works even if the object is moving in more than one dimension, so that `velocity` is a vector. (Of course, the actual code for doing this with vectors might look somewhat different, depending on what notation your language uses for vector arithmetic.)

You can add other velocity changes before or after this code; if you add them before, then small enough forces may be completely canceled by friction, which is actually realistic. In fact, for further realism, you may want to implement static friction by having the constant in the friction calculation vary depending on whether or not the velocity of the object was non-zero at the beginning of this timestep.

Also, if you want to be really accurate, you should take acceleration during the timestep into account when updating the object's position. That is, instead of just doing

```
velocity += delta_v;
position += velocity * dt;

```

you should do

```
velocity += delta_v;
position += ( velocity - delta_v / 2 ) * dt;

```

where `velocity - delta_v / 2` is the average of the velocities before and after adding in `delta_v`.

This latter approximation to Newton's laws of motion is actually exact as long as `acceleration = delta_v / dt` is constant, and in any case is a better approximation than the former even for changing `delta_v`. However, for games with a small and constant timestep `dt`, the difference is generally not noticeable, at least without side-by-side comparison. The main advantage of the more accurate form is that it makes object trajectories less sensitive to changes in `dt`.

I should also point out that (dry) friction is not the only force that can slow down moving objects. For example, objects moving through water or air experience drag, which follows a formula that generally looks something like

```
delta_v = ( a * speed + b ) * -velocity * dt

```

where `a` and `b` are constants that depend on a lot of things such as the density and viscosity of the fluid and the mass, size and shape of the object moving through it. (See the Wikipedia link above for details; `a` above corresponds to Newton drag, while `b` corresponds to Stokes drag.)

For macroscopic objects moving through fairly inviscid fluids like water or air, `b` should be very small or even zero, whereas a viscous fluid like lava or molasses calls for a higher `b`. For game purposes, just play around with the values until you get the effect you want.

Note that, unlike with dry friction, drag forces never bring a moving object to a complete stop, so we generally don't need to worry about accidental direction reversals. The exception to this is if `(a * speed + b) * dt > 1`, which can happen if `dt` is too large or if the object somehow acquires an unusually high velocity; if that might happen, the solution is either to dynamically adjust `dt` to be smaller for fast-moving objects or to use a higher-order motion integrator (which really goes beyond the scope of this post).
> 5 votes

# Answer
In these cases you should use exponential functions instead of a normal multiplying. meaning :

```
player.velocity.x = player.velocity.x * pow(CONSTANT_FACTOR, dt);

```

It's pretty simple to explain why: when write `player.velocity.x += CONSTANT * dt`, assuming your game is running @60fps you are adding `CONSTANT * 1/60` to velocity 60 times per second, meaning in each second your speed will increase by `CONSTANT * 1/60 * 60 = CONSTANT`.

Now you want playing velocity to get twice or three times every second, so after one second you'll have `new_velocity = old_velocity * CONSTANT` you can break this into smaller multiplications and write

```
new_velocity = old_velocity * CONSTANT ^ (1/60) * CONSTANT ^ (1/60) * ...
             = old_velocity * CONSTANT ^ (1/60 * 60)
             = old_velocity * CONSTANT ^  1 = old_velocity * CONSTANT

```

which means in each frame you need to multiply velocity by `CONSTANT^dt`

*EDIT*

Based on the edits the edits you made in your question, you don't really need to implement this exponential method. Assuming you are going to simulate friction, you can also implement more physical method:

Physically friction reduces speed by linear manner, assuming Object mass doesn't change over time. It's applying a force to the object, exactly in opposite direction as object's current velocity. For example let's assume Friction always reduces speed by two units every second, you need to find velocity's current direction, reverse it, and reduce a vector of length two in that direction multiplied dt. here is some code to help you understand:

```
Velocity_Direction = Velocity / Length(Velocity)
Friction_Power = 2
Friction_Direction = -Velocity_Direction
New_Velocity = Old_Velocity + Friction_Direction * dt

```

there is one small little thing that you might want to notice, by that code if speed is too low, the Object will jitter in it's position. That's because `Fricton_Direction * dt` is bigger than velocity itself, which will lead to object moving exactly in opposite direction in the next step, instead of standing still. to fix that you need to add an if statement to check if Velocity is too low and Object should be completely stopped. I'll do it like this:

```
Friction_Power = 2

if(Length(Velocity) > dt * Friction_Power)
    Velocity_Direction = Velocity / Length(Velocity)
    Friction_Direction = -Velocity_Direction
    New_Velocity = Old_Velocity + Friction_Direction * dt
else
    New_Velocity = Vector(0)

```

note that `Length` is a function which gets a vector as an input and returns it's length. for example if your game has a 2d world `Length (Velocity) = Sqrt(Sqr(Velocity.x) + Sqr(Velocity.y))`
> 4 votes

# Answer
Without reading more into your question and answering your question as is, this is a simplification of your code:

```
speed = (speed>0)?MAX(speed - 20 * dt, 0):MIN(speed + 20 * dt, 0)

```

But as others have stated, to achieve a more realistic (i.e. Newtonian) result, you should implement an "acceleration" variable and update your entity like so:

```
position = position + velocity * dt + acceleration * dt * dt * 1/2
velocity = velocity + acceleration * dt

```

Here velocity would be (presumably) your "speed" variable. (If I recall correctly from physics, "speed" is technically ABS(velocity), therefore should be always \>= 0)
> 3 votes

# Answer
To make that code shorter, you could do the following:

```
//define a constant somewhere in your code so you could adjust the value later
DECCELLARATION_RATE = 20;
//Checks if the speed is positive or negative so we will decrease it's absolute value:
sign = (speed >= 0? 1 : -1);
//Decrease the absolute value of the speed while maintaing it's sign
speed -= sign * DECCELLARATION_RATE * dt
//If the object is moving too slowly, the above command will change the speed's sign and with it the direction of the movement.
//What we want to do is stop the object in this case.
if(sign != (speed >= 0? 1 : -1)) speed = 0;

```

The operator `(condition ? value_if_true : value_if_false )` is called the ternary operator. You can read about it more here:

http://en.wikipedia.org/wiki/Ternary\_conditional\_operation
> 0 votes

---
Tags: physics, movement
---


# Question
Title: Accessing managers from game entities/components
I'm designing an entity-component engine in C# right now, and all components need to have access to the global event manager, which sends off inter-entity events (every entity also has a local event manager).

I'd like to be able to simply call functions like this:

```
GlobalEventManager.Publish("Foo", new EventData());
GlobalEventManager.Subscribe("Bar", OnBarEvent);

```

without having to do this:

```
class HealthComponent
{
    private EventManager globalEventManager;

    public HealthComponent(EventManager gEM)
    {
        globalEventManager = gEM;
    }
}

// later on...
EventManager globalEventManager = new EventManager();
Entity playerEntity = new Entity();
playerEntity.AddComponent(new HealthComponent(globalEventManager));

```

How can I accomplish this?

# Answer
I solved it by creating a singleton called GlobalEventManager. It derives from the local EventManager class and I use it like this:

```
GlobalEventManager.Instance.Publish("Foo", new EventData());

```

*Thanks Byte :p*
> 1 votes

# Answer
Although your solution works, you are losing testability by using singleton. In addition you are highly coupled with your global objects. If you will ever think of unit tests for your new components, you will have specially prepare your GlobalEventManager and ensure that your tests are not run in parallel.

One option is to use Factory pattern. Something like:

```
 playerEntity.AddComponent(componentFactory.createHealth());

```

Or read about dependency injection frameworks.
> 6 votes

# Answer
Why not just use C#'s native event system? That way any components that want to subscribe to a component's events can do so from *outside* the class.
> 1 votes

---
Tags: c#
---


# Question
Title: Finding shapes in 2D Array, then optimising
I've just been allowed an image...The image below from my game shows some darkened blocks, which have been recognised as being part of a "T" shape. As can be seen, the code has darkened the blocks with the red spots, and not seen the "T" shapes with the green outlines.

My code loops through x/y, marks blocks as used, rotates the shape, repeats, changes colour, repeats.

I have started trying to fix this checking with great trepidation. The current idea is to:

* loop through the grid and make note of all pattern occurrences (NOT marking blocks as used), and putting these to an array
* loop through the grid again, this time noting which blocks are occupied by which patterns, and therefore which are occupied by multiple patterns.
* looping through the grid again, this time noting which patterns obstruct which patterns

That much feels right... **What do I do now?**

I *think* I would have to

* try various combinations of conflicting shapes, starting with those that obstruct the most other patterns first.**How do I approach this one?**
* use the rational that says I have 3 conflicting shapes occupying 8 blocks, and the shapes are 4 blocks each, therefore I can only have a maximum of two shapes.

(I also intend to incorporate other shapes, and there will probably be score weighting which will need to be considered when going through the conflicting shapes, but that can be another day)

I don't think it's a bin packing problem, but I'm not sure what to look for. Hope that makes sense, thanks for your help

**EDIT** Despite clarity of question, everyone seems to have understood, yes,

**I want to find the maximum "T" shapes within each colour**

(because if I gave you points for two and you had made three, you'd be a bit annoyed)

# Answer
Let me see if I got it right, the red marked blocks, were blue and the algorithm found a T shape and marked them red, is that correct? Your goal is to find as many T shapes as possible with same colored blocks, correct so far I hope. Currently you mark them out once you find them and that diminishes the usefulness of the algorithm(Since you could be missing the optimal solution). You are planning on searching for all shapes and then picking which ones to use and which one not to use. Am I correct so far? Cause you wish to maximize the amount of blocks that are contained inside the T shapes when the algorithm is done.

If I am correct the following is the optimal solution for your situation in my opinion.

We will use Integer Linear Programming.

I believe I used this one in the past:

http://sourceforge.net/projects/lpsolve/

http://lpsolve.sourceforge.net/5.5/Java/README.html

(You can get it to work with many languages, I used it with PHP, Java and C)

What we will do is register every possible T shape on the board and then use ILP to maximize the amount of blocks that are covered. ILP is exponentially complex. Considering the size of your board, that will not be a problem. I have ran much more complicated min/max questions on graphs with ILP and it only took a fraction of a second to complete and up to 30-90 seconds with hundreds of vertices(in your case it falls in the fraction of a second).

What I would recommend to do:

1. Find all possible Line shapes
2. Find all intersections between line shapes of the same color
3. Find all possible T shapes, searching all intersection.
4. Define a Boolean variable in the Linear Problem for each T shape (`0 <= Bi <= 1`) Since the values are integers, that leaves 0 or 1.
5. Make the conditions for each couple of T shapes that intersect (`Bi + Bj <= 1`)
6. The objective function will be (sum of blocks in "T" Shape (i) * Bi)
7. Run the solver and darken the T shapes where the solver's corresponding Boolean(s) where 1 in the optimal solution.

This is valuable knowledge, I used linear solvers often for work projects.

ILP is basically a way to solve selection problems where you want to achieve a maximum or a minimum for some linear function.

You can read more here, using Integer Linear Programming and Linear Programming is the same for the programmer only that Integer is far more complex for the computer which may result in long running times. Not in your case, It is very simple and should only takes less than milliseconds in the worst case.

I guess you could read more here:

http://en.wikipedia.org/wiki/Integer\_linear\_programming#Integer\_unknowns

This explains it well:

http://fisher.osu.edu/~croxton\_4/tutorial/

It is basically a decision problem solver, how to make decisions that maximize the result you want. This assumes the function that judges the result is linear which in your specific current case it is. The function that judges the result in this case, sums up the blocks for all the T shapes you decided to darken.

Mathematically, how to set the variables: in our current case Booleans(Did I darken T shape with index i or not) to the optimal values to maximize the result we want: darkening as many blocks as possible without darkening intersecting T shapes. As long as the result you want can be calculated with a linear function when you have all the variables set it will solve it. In our case, we check which T shapes we darkened and sum the blocks they cover.

I know this is not trivial so if you choose to take the leap, feel free to comment and I will elaborate.
> 3 votes

# Answer
Once you have a list of all (possibly overlapping) T-shapes occurring in your grid, what you're left with is a maximum set packing problem.

In general, this is an NP-complete problem. However, your grid is small enough (and typically breaks up into even smaller independent subproblems) that it may well be feasible to obtain exact solutions.

---

**Addendum:** Here's a basic backtracking search algorithm that might do the trick:

```
function max_packing_recursive ( set A, set S, set M ):
    if |M| < |S| then let M = S;
    for each shape X in A do:
        remove X from A;
        let B = A;
        remove all shapes that intersect with X from B;
        if |M| < |B| + |S| + 1 then:        // upper bound
            let M = max_packing_recursive( B, S + {X}, M );
        end if
        if |M| >= |A| + |S| then return M;  // shortcut
    end for
    return M;
end function

function max_packing( set A ):
    return max_packing_recursive( A, {}, {} );
end function

```

Here, `{X, Y, Z}` denotes the set containing the elements `X`, `Y` and `Z` (with `{}` being the empty set), and `|Q|` denotes the size of the set `Q`.

In the recursive function, the set `A` contains the shapes available for the remaining solution, `S` contains the shapes in the current solution candidate, and `M` is the maximal solution so far (which you may want to store as a global variable instead of returning it back up the call chain). The important optimization is on the line marked with `// upper bound`, which prunes branches of the search tree that cannot possibly return a better solution than `M`.

(Actually, since we know that each T-shape contains exactly four sites, a much better upper bound could be obtained by replacing `|B|` with the number of distinct sites covered by the shapes in `B`, divided by four and rounded down (and similarly for `|A|` on the line marked with `// shortcut`). The algorithm as given above, however, works for arbitrary collections of shapes.)

A possible additional optimization, which I haven't implemented above, would be to check at the beginning of the recursive function whether `A` divides into multiple subsets that are independent, in the sense that no shapes in different subsets overlap, and if so, apply the algorithm to each of the subsets separately. (In any case, you'll definitely want to do this at least once at the top level *before* calling the recursive algorithm.) Sorting the shapes in `A` appropriately before looping over them, e.g. in increasing order by number of overlapping shapes, could also help.
> 4 votes

---
Tags: algorithm, grid, puzzle, patterns
---


# Question
Title: How to emulate Mode 13h in a modern 3D renderer?
I was indulging in nostalgia and remembered the first game I created, which used Mode 13h.

This mode was really simple to work with, since it was essentially just an array of bytes with an element for each pixel on the screen (using an indexed color scheme).

So I thought it might be fun to create something nowadays under these restrictions, but on modern hardware. The API could be as simple as:

```
public class Mode13h
{
    public byte[] VideoMemory = new byte[320 * 200];
    public Color[] Palette = new Color[256];
}

```

Now I'm wondering what would be the best way to get this data on the screen, using something like XNA / DirectX / OpenGL.

The only solution I could think of was to create a texture with the same size as the `VideoMemory` array, write the contents of `VideoMemory` to it every frame, then render that texture in a full screen quad with the correct aspect ratio and using point texture filtering for that retro look.

Is there a better way?

# Answer
Using OpenGL I think the best way to do it is to create a texture with the size of your buffer and updating it using glTexSubImage2D. Then you just have to render a texture quad, the filtering used should be GL\_NEAREST. Also be sure to disable mipmapping to gain some performance on updates.

I wanted to do the same thing and apparently this is the best way to do it with modern hardware, plus it allows easy scaling.

There is also a library made for this, PixelToaster :

http://code.google.com/p/pixeltoaster/
> 3 votes

# Answer
> Is there a better way?

Not that I can think of. In case you were keen on using XNA to do this, here's an expansion on your idea:

```
public class Mode13h {
    public RenderTarget2D VideoMemory;
    public Texture2D[] Palette;
    public Texture2D[][] Pixels;

    public Mode13h() {
        this.Palette = new Texture2D[256];
        this.Pixels = new Texture2D[320][200];
        this.VideoMemory = new RenderTarget2D( GraphicsDevice, 320, 200 );

        // initialize and populate the color palette
        foreach( Texture2D color in this.Palette) {
            color= new Texture2D( GraphicsDevice, 1, 1 );
        }
        this.Palette[0].SetData<Color>( new Color[] { Color.Black} );
        // ... do the above 255 more times :P or find some way to do it in the loop

        // initialize pixels
        for( int i = 0; i < 320; i++ ) {
            for( int j = 0; j < 200; j++ ) {
                this.Pixels[i][j] = new Texture2D( GraphicsDevice, 1, 1 );
                this.Pixels[i][j] = this.Palette[0]; // default black
            }
        }
    }
}

```

I think you can already see where I'm going with this, but I'll spell it out just to be clear:

* Pre-populate `Palette` with each of the 256 colors that will be used by the game.
* `VideoMemory` is your *backbuffer* which represents an old-school 320x200 display.
* `Pixels` is a representation of each pixel on that display.

## Update Phase

After accepting input and adjusting *sprite* positions, you'll want to clear out your `Pixels` array by copying a black pixel from the `Palette` to each one of the many (many) `Pixels`. You can then modify your `Pixels` by copying the appropriate colored pixel references from the `Palette` (probably by referencing an array of sorts from your sprites -- assuming you've *been-there-done-that*).

## Render Phase

All you have to do now is loop through all of the screen pixels in `Pixels` and draw them to `VideoMemory`, then draw `VideoMemory` to the game window / screen. Because everything is a `Texture2D`, you can use `SpriteBatch` which makes this a bit easier.

## Possible Improvements

I'm not sure if this would help, but it might be useful to create a single texture with one pixel for each color that you want to use in your palette. Then use that single texture to derive each one of the `Texture2D` in `Palette` by using a source rectangle. That might improve rendering with SpriteBatch since you would in effect, have one texture. It may even be better to store `Palette` as an array of `Rectangles`...
> 1 votes

---
Tags: graphics
---


title: Dynamic Components

text:
# Question
Title: Dynamic Components
I am attempting to design a component-based architecture that allows `Component`s to be dynamically enabled and disabled, much like the system employed by Unity3D. For example, all `Component`s are implicitly enabled by default; however, if one desires to halt execution of code for a particular `Component`, one can disable it.

Naively, I want to have a boolean flag in `Component` (which is an `abstract class`), and somehow serialize all method calls into `strings`, so that some sort of `ComponentManager` can check if a given `Component` is enabled/disabled before processing a method call on it. However, this is a pretty bad solution. I feel like I should employ some variation of the state paradigm, but I have yet to make progress.

Any help would be greatly appreciated,

# Answer
If you mean to disable an entire system simply remove the system from your active loop.

If you mean to stop a particular component from being active remove if from the pool (array/list?) of active components in your system.

If you want to stop an entity from being active (before destruction for example) simply stop all of its components.

---

**Edit**: The entire behavior of your components depends on the way they are implemented. I assume components can receive messages through a system which they can chose to disconnect from.

If you wish your components to stop being active actors the system will stop processing them:

* an AI component will not run
* a physics component will stop reacting to physics and be ignored by the rest of the world
* a render component will not be drawn.

But there is also the handling of messages. There you probably want your components to stop receiving them, this way they will not process requests and apply changes they are not supposed to. But this part entirely depends on your approach to the whole inter-components communication.

If the system is in charge of managing the communication to the component it can disable the entering communication as well. i.e. close all channels the component opened.
> 6 votes

---
Tags: architecture, unity, component-based, design-patterns
---


# Question
Title: Can a high FPS negatively affect how a program runs?
Yeah I know this is a broad question and will get down rated, I'm just hoping for some answer before it gets closed.

Anyway, I'm using Slick 2D/Java to play around with graphics. I'm having some trouble with trying to move an image. The weird thing is, the code works just fine on my laptop, but the image sporadically moves to (0,0) and stops on my desktop. The only difference between the two is that it says the FPS is about 500 on my laptop and 6600 on my desktop. Can that affect it or does someone have any ideas for what to check on?

# Answer
> 5 votes
Not really, no.

There's one scenario: you're calling the draw method so often you don't leave yourself the resources to do anything else. That's not your FPS negatively affecting how the game runs, though. The cause would be a badly written game, engine or framework; the FPS would just be a side-effect.

You have a glitch that surfaces on your desktop. Your desktop also achieves a crazy FPS rate. It's doubtful the latter is causing the former; but maybe they have a common cause and the high speed of your desktop is making surprising things happen.

Are you running into multithreading gotchas?

# Answer
> 2 votes
Check this out: http://www.mysecretroom.com/www/programming-and-software/android-game-loops

It explains a good way to setup and control the speed of your games update and rendering. It might help you out.

# Answer
> 2 votes
You should implement a proper game loop to keep your game at a steady frame rate. By industry standards right now it should be 30-60 fps.

The disadvantages of having high frame rate:

* Hugs system resources therefore slowing down any other activity the user likes to do.
* Consumes more power, something to keep in mind when you are using a laptop.

Disadvantages of having a variable (not consistent) frame rate:

* Your sound effects will be triggered at different times on different platforms.

# Answer
> 1 votes
If you want your game to have consistent behavior across platforms, you *really* should have a fixed frame rate for your game logic and physics code. That way, your time step will be constant, which means that any (inevitable) roundoff and other errors caused by the finite time step will be the same for all players.

The one major exception to this is games that don't (always) run in real time. For such games, you want to keep the time step constant *in game time*, but you can allow game time to run as fast compared to real time as the player wants and the platform can handle.

It's OK — and, in fact, often very useful — to allow your graphics front-end code to have a variable frame rate, but even then, there's obviously no point in letting the graphics frame rate *exceed* the physics frame rate. (Actually, that's not *completely* true; if your drawing code can interpolate / extrapolate movement between physics updates, it *may* be useful to run it more often. However, doing that well involves some relatively advanced issues.)

There's also no point in letting your graphics frame rate exceed the screen refresh rate (which is typically around 60 to 75 Hz), even if your physics frame rate is higher than that e.g. due to accelerated game time. Any effort spent on drawing more than one frame per screen refresh is completely wasted, since the player is only going to see *one* of those frames anyway.

---
Tags: java, movement, image, frame-rate, slick
---


# Question
Title: How to stop my object once a collision is detected in XNA?
I have collision detection but I don't know how to stop an object after a collision and then move the object backward.

Any ideas?

# Answer
In addition to Marton's answer you could also let your object "bounce" off the wall by reflecting its velocity vector:

---

* **V** is the velocity vector of your object
* **N** the normal of your wall
* **R** reflected velocity vector

```
Vector ReflectVector(Vector V,Vector N)
{
    //Save vector lengths to restore later..
    float vLength = V.Length();
    float nLength = N.Length();

    //Normalize
    V.Normalize();
    N.Normalize();

    //R is our output vector
    Vector R = V;

    //"Reflect" the vector using the DOT product
    R = -2 * (V.Dot(&N))*N + V;

    //Restore lengths
    V *= vLength;
    R *= vLength;
    N *= nLength;

    //Return the reflected vector
    return R;
}

```

example usage could be:

```
if(Collision)
{
    Vector N(1,0); //Imaginary wall (Left side)
    ObjectVelocity = ReflectVector(ObjectVelocity,N);
}

```
> 2 votes

# Answer
A simple solution would be to implement a check during your movement code. If the player attempts to move right, check if there is an object that would stop the object moving in that tick and if so move the player next to that object and set the velocity to 0.

For example:

```
if (player.X + movespeed >= wall.X) {player.X = wall.X - xOffset;}

```
> 1 votes

# Answer
There are many solutions, depending on what kind of effect you want to achieve. Here's a simple 'rebound' solution:

When a collision between object 'A' and the wall is detected, do the following:

1. Get a Vector **V\_r** which points from the collision point to A's center point (let's call the center point **P\_A** ).
2. Set the object's new position **P\_An = P\_A + (V\_r * d)**, where **d** is a distance. This distance must be so, that after you set **P\_An**, the object is no longer colliding with the wall. So **d** depends on your collision detection method. With pixel perfect collision, **d** must be large enough to put **P\_An** on a different pixel than which **P\_A** is on.
3. Let's name the object's velocity vector right before the collision **V\_v**.
4. Set the object's new velocity to **V\_vn = -V\_v * c**, where **c** is a constant value somewhere between zero and one. This will provide the effect of some "inertia loss".
> 0 votes

---
Tags: xna, collision-resolution
---


# Question
Title: How to limit click'n'drag movement to an area?
I apologize for the somewhat generic title. I'm really don't have much clue about how to accomplish what I'm trying to do, which is making it harder even to research a possible solution.

I'm trying to implement a path marker of sorts (maybe there's a most suitable name for it, but this is the best I could come up with).

In front of the player there will be a path marker, which will determine how the player will move once he finishes planning his turn. The player may click and drag the marker to the position they choose, but the marker can only be moved within a defined working area (the gray bit).

So I'm now stuck with two problems:

First of all, how exactly should I define that workable area? I can imagine maybe two vectors that have the player as a starting point to form the workable angle, and maybe those two arcs could come from circles that have their center where the player is, but I definetly don't know how to put this all together.

And secondly, after I've defined the area where the marker can be placed, how can I enforce that the marker should only stay within that area? For example, if the player clicks and drags the marker around, it may move freely within the working area, but must not leave the boundaries of the area. So for example, if the player starts dragging the marker upwards, it will move upwards until it hits he end of the working area (first diagram below), but if after that the player starts dragging sideways, the marker must follow the drag while still within the area (second diagram below).

I hope this wasn't all too confusing. Thanks, guys.

**Edit:** In case this makes a difference, I'm using C++ with Marmalade SDK.

# Answer
You can define a workable area like the one in your question with three values:

```
float innerRadius;
float outerRadius;
float maxAngle;

```

These values will be based off a center point which *may or may not* be the player's position. The shape of the workable area depends on where you place this point.

In the example above the center position lies a certain distance (let's say 50 units) *behind* the player. This could be easily calculated as:

```
float offset = -50;
Vector2 centerPosition = playerPosition + offset * playerForward;

```

To limit the position of the marker to that workable area, first **move the marker** as you normally would. Then **validate the distance** between the center point and the marker:

```
Vector2 direction = markerPosition - centerPosition;
float distance = direction.Length();
direction.Normalize();
markerPosition = centerPosition + direction * clamp(distance, innerRadius, outerRadius);

```

Finally, **validate the angle** of the marker to the specified range. I'll use pseudocode for this one:

```
- Find angle between vector C->M and vector playerForward
- If abs(angle) <= maxAngle Then do nothing
- Else If angle > 0 Then rotate M around C by maxAngle-angle
- Else If angle < 0 Then rotate M around C by -maxAngle-angle

```

Look around on how to rotate a point around another. It can be done either with trigonometry or a transformation matrix.

You might also want to take into account the marker's size and make the radius and angle a little smaller to compensate.

Edit: On second thought, it might look more natural if you validate the angle first, then the distance, so try both alternatives!
> 8 votes

# Answer
I was thinking how the problem could be solved if the shape was irregular, and one couldn't define it mathematically. Warning: this is a dirty solution, not for the faint of heart.

**1. Take your area:**

**2. And convert it to a monochromatic bitmap:**

and name it scale\_0

**3. Clone the bitmap and scale it down to 50%:**

and name it scale\_1

**4. And so on, until there's a bitmap less then 4 pixels wide/tall:**

scale: 2, 3, 4, 5, 6

**5. Now we have our area as monochromatic bitmaps of different resolutions:**

**6. Take the last image (here "scale\_6") and iterate through all of it's pixels.**

* translate each pixel's coordinates to screen coordinates: `x = Math.pow ( 2, scale_level );` where scale\_level is the number we added after "scale\_". We could also call it a quad tree level, though we're not really working with a quad tree. Do same with y.
* check if pixel at translated x & y is black. If not, then it's not part of the shape, and you should just `continue` to next step of the loop
* check if the pixel is closer to mouse cursor than previously checked pixel - if yes, save coordinates of the pixel - use the coordinates before translation, that is coordinates inside the bitmap.
* at the end of the loop, multiply these coordinates by 2: `x *= 2; y*=2;` to translate them to coordinates in next image (previous scale)

**7. Take previous image (here "scale\_5"), but don't loop through all pixels;** start at x = saved\_x and end with x = saved\_x + 2, same with y. That is, since now you will only loop through 4 pixels for every level! The rest is as in p. 6.

**8. Take first image (the biggest = the one with biggest resolution), again loop through 4 pixels, and you finally have the pixel that is closest to mouse cursor:**

**9. However, I'm treating "M" as a point here.** If you want it to be a circle that fits completely, you need to contract (shrink) the shape by `circle.radius` pixels first.

I thought I'd add that this algorithm will only work if you will use not monochromatic but grayscale images and treat a pixel as "full" if it's not white, and as "empty" if it's exactly white... OR if your resizing algorithm changes every group of 4 pixels into 1 black pixel every time when at least one of these 4 pixels wasn't white.
> 10 votes

---
Tags: movement, geometry
---


# Question
Title: Given a RGB color x, how to find the most contrasting color y?
> **Possible Duplicate:**
> Making a symbol appear on any colour

I have to mark a certain item in a way that will make it stick-out in the background. I need it to be surrounded with the color that contrasts the background as much as possible so it will pop out and easily noticeable by the player.

Lets say I know the background is color 'x', how do I find 'y' such that it will be very contrasting to 'x' and easy to notice in a background where 'x' is a dominant color?

I first thought about inverting color 'x' and then I noticed that when 'x' is a medium shade of gray, if I invert 'x' to get 'y', then 'y' is also a medium shade of gray which does not work.

# Answer
A quick and easy way - though not 100% precise one - is to consider just the five extreme points white, black, red, green and blue.

First, let's transform RGB into linear space. Officially this is usually done by this formula (assuming the source data is in sRGB, which is the default for most graphic card operations on 8-bit data and nearly every image you see displayed on the web):

... where *a* = 0.055 for *C* = {R, G, B}

Or, if you just want a quick approximation, use *C*linear = *C*srgb2.2.

## Black or White?

You can then calculate two helpful values, luminance *Y* and saturation *S*. Useful formulas (for our linear-space RGB values) are:

*Y* = 0.2126 *R* \+ 0.7152 *G* \+ 0.0722 *B*

*S* = (max(*R*, *G*, *B*) - min(*R*, *G*, *B*)) / max(*R*, *G*, *B*)

The second one is the calculation from the HSV colour space.

If the saturation is low enough (pick any value you like; something between 0.3 and 0.5 would work fine), check the luminance; if that's \> 0.5, your contrasting colour is **black**, else if it's \< 0.5 the colour is **white**. For exactly *Y* = 0.5, both work.

## Red, Green or Blue?

For colours with high saturation, you can calculate a hue *H* and decide according to it. Since I'm lazy, I'll just copy the calculation from Wikipedia (hue is named H2):

If your hue is between 60° and 180°, your colour is **green**, if it's between 180° and 300°, it's **blue**, else it's **red**. Extend it to yellow, turquoise and magenta for more variation, or just use the opposite of the just-calculated hue at maximum saturation and lightness.
> 49 votes

# Answer
The most contrasting color would be the color that is as far as possible from color X. It's easy to get it this way (assuming 0,0,0=black and 1,1,1=white -- floating point colors):

```
y = rgb_color(
    x.r > 0.5 ? 0 : 1,
    x.g > 0.5 ? 0 : 1,
    x.b > 0.5 ? 0 : 1
);

```

The result is quite ugly though, so you might want to consider a few more things:

1) generate only black / white colors:

```
v = ( x.r + x.g + x.b ) / 3 > 0.5 ? 0 : 1;
y = rgb_color( v, v, v );

```

2) change the values "0" and "1" to something less sharp

3) work in the HSV color space:

```
y = hsv_color(
    ( x.h + 0.5 ) % 1,
    x.s > 0.5 ? 0 : 1,
    x.v > 0.5 ? 0 : 1
);

```
> 11 votes

# Answer
Just to distill Martin Sojka's excellent answer into something simple to apply, here's how to decide whether black or white text would have higher contrast on a given background color `(R, G, B)` in the sRGB color space:

```
const float gamma = 2.2;
float L = 0.2126 * pow( R, gamma )
        + 0.7152 * pow( G, gamma )
        + 0.0722 * pow( B, gamma );

boolean use_black = ( L > pow( 0.5, gamma ) );

```

This assumes that `R`, `G` and `B` are floating-point numbers ranging from 0.0 to 1.0. If what you have is, say, integers from 0 to 255, convert them to floats and divide them by 255.

(I would *not* suggest using colored text, both because the human eye has much poorer spatial resolution for color than for luminance, and also because combinations of highly saturated complementary colors tend to be irritating to look at.)

Note that, if `L` is close to 0.52.2 ≈ 0.2, small changes in the background color could cause the most contrasting text color to flip from black to white or vice versa. To avoid this happening too frequently, you could save the previous text color and only change it if `L` moves too far from the threshold:

```
if ( L > 0.3 ) {
    use_black = true;
} else if ( L < 0.1 ) {
    use_black = false;
} else {
    // keep previous text color
}

```

Ps. If you wanted an even quicker approximation, you could round the exponent `gamma` down to 2.0, allowing you to replace the `pow()` with a simple multiplication:

```
float L = 0.2126 * R*R + 0.7152 * G*G + 0.0722 * B*B;

```

This approximate formula is still within ±0.05 of the correct luminance calculated with the official piecewise formula given by Martin (or with the `gamma = 2.2` approximation used above, which itself is within ±0.01 of the official formula), and so more than close enough for this purpose. Besides, you can mostly compensate for the error simply by adjusting the threshold slightly.

Finally, note that, if the background has a very busy texture, it's possible that *no* single color may stand out from it very effectively. In such cases, you may want to consider using combinations of colors, such as black text with a white outline.

---

**Ps.** Earlier versions of this answer suggested using the uncorrected threshold `L > 0.5`. However, this suggestion ignores the fact that the gamma correction used in the RGB color space approximates the perceptual non-linearity of the human eye, so that the shade of gray that *looks* about halfway between black and white is indeed close to RGB(0.5, 0.5, 0.5). Thus, to get an accurate measure of *perceptual* luminance, we really need to apply a final inverse gamma correction to the linear luminance `L` — or, equivalently, just apply gamma to the thresholds as well.

This perceptual non-linearity also explains why just linearly mixing the uncorrected RGB components into a luma value, and basing the decision on that, also works reasonably well:

```
float luma = 0.2126 * R + 0.7152 * G + 0.0722 * B;
boolean use_black = ( luma > 0.5 );

```

This formula does tend to overestimate the brightness of highly saturated colors; for example, for pure green it gives `luma = 0.7152`, whereas properly applying gamma correction would give `pow(L, gamma) ≈ 0.478`. Fortunately, for saturated colors, either black or white will provide a decent contrast anyway.
> 11 votes

# Answer
Since there is some subjectivity to any answer here, I'll offer one that is easy to understand and easy to compute. Whether it suits you and your needs is up to you.

Imagine color space represented by R, G, and B values each on the interval \[0,1\]. Imagine the RGB value being a vector in color space, where that vector is confined to a cube. For any RGB value in that space, the most contrasting value would be geometrically as far away from that value while still being on that cube.

Offset the cube, so it is centered at the origin, with new values r, g, and b on the interval \[-0.5, 0.5\]. Do the by subtracting 0.5 from all of the original RGB values. Now compute the sign of each component of rgb and multiply by -0.5. This will put you at one of the vertices of the offset color space cube. Add 0.5 to each value to restore the values to the original color space cube.
> 3 votes

# Answer
It depends how you invert the color, the standard way of doing so is something like:

```
newColor = new Color(255-oldColor.r, 255-oldColor.g, 255-oldColor.b);

```

Which means that something grey like `(128,128,128)` will turn into something very grey `(127, 127, 127)`. You may want to try inverting the hue instead. Convert your color to HSV mode and invert the hue `color.hue = 360-color.hue`.

You could additionally invert the saturation.

Ultimately, it sounds like you're the one choosing the original colors here. So just choose colors that invert nicely.

Another option would be to check for colors that won't change much. Something like:

```
if((255-oldColor.r)-oldColor.r < 10)
    newColor.r = 0;

```
> 0 votes

---
Tags: graphics-programming, color, ui-design
---


# Question
Title: Do I need to obtain a license to use real car brands in a game?
We are small team which working on car racing game but we don't know about licensing process for branded cars like Nissan, Lamborghini, Chevrolet and etc.

Do we need to buy any licence for using real car brand names, models, logos,... or we can use them for free?

Second option we think about using not real brand with real models is it possible? If someone have experience with that, fell free to share it. Any information about that is welcome.

# Answer
> 37 votes
Yes. Their names, logos, and body designs are all trademarked and cannot be used in any capacity outside those explicitly allowed by trademark law, which almost certainly excluded use in your game. And expect to be completely incapable of acquiring those licenses for reasonable terms, as the licenses are generally very expensive and come with a mile long list of stipulations.

Even though you will be paying them, the companies will be seeing your game as another advertisement for their cars. They will completely reject working with you unless they believe your game will make their cars look awesome and make your players want to buy them.

There was a "car czar" for the Forza 4 team. His full time job was to make sure their car models and car performance matched the various licensing agreements they had, to make sure the cars were modeled accurately, and so on. You need a full time guy just to do that if you want to license cars.

And expect weird incompatible licensing terms to happen and look forward to wasting tons of time resolving them. E.g., two manufacturers who want their car to be the fastest car in your game, or who refuse to allow one player selectable color to be applies to their car, or to refuse to allow damage to apply to their car, or to demand that the car can only be used if you model every little mechanical detail to a level of accuracy that your artists or your engine possibly can't handle.

As with all things in the small game and indie space, you are far better off being original and unique.

Also remember that if you try to make games that have the same selling points as AAA titles (like having real cars like Forza does), your game is going to get compared to those games, and is highly unlikely to come out with high marks. Strive to be unique so your game can stand in its own rather than be compared to games with tens of millions of dollars put into them.

# Answer
> 5 votes
As @Sean suggests, trying to go with real branding can be a nightmare, and is unlikely to serve you well.

An alternative is to use fairly true-to-life models, but omit any branding and use your own alternative names for the vehicles. A good example of this is the Grand Theft Auto series, in which the vehicles are modelled on actual "real-world" vehicles, typically don't have any badges or other branding, and have a unique "nickname" that isn't trademarked.

If you do this, you can probably\* get away with having models that are fairly realistic copies of real designs. Even if it's clear that your model is a Lamborghini Gallardo (for example) just from the look of it, that's probably ok so long as you don't actually call it that without Lamborghini's permission.

---

* IANAL - if in doubt, its probably best to just dream up your own cars.

---
Tags: models, legal, licensing, car
---