title: Handling multiplayer operations in C#

text:
# Question
Title: Handling multiplayer operations in C#
I would like to know how do experienced c# developers structure their multiplayer messages and operations.

Basically , in my project every UDP message is translated into an operation and I have to decide what will it trigger. Here is my current structure:

```
switch(newOperation.code){
  case MessageCode.Position:
    MessageHandler.instance.PositionUpdate(newOperation);
    break;
  case MessageCode.NewPlayerJoined:
    MessageHandler.instance.PlayerJoin(newOperation);

```

Basically , for each operation I'm creating an enum and a function that will handle the received packets.

Is there a more maintainable solution?

# Answer
> 1 votes
You can annotate your packet handler methods like this

```
[PacketHandler(OpCodes.CMSG_LOGIN_REQUEST)]
public static void OnLoginRequest(Client client, ClientLoginRequestPacket packet)
{
   // Do stuff
}

```

And then have dictionary of opcodes and handlers and invoke them. So no big switch at cost of dictionary (or array) lookup and one additional method call.

This is how you register handlers

```
Dictionary<OpCode, IPacketHandler> _packetHandlers;

var types = Assembly.GetExecutingAssembly().GetTypes();
foreach (var type in types)
{
    foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
    {
        PacketHandlerAttribute attribute = (PacketHandlerAttribute)method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).SingleOrDefault();
        if (attribute != null)
        {
            OpCodes opCode = attribute.OpCode;

            Type packetType = method.GetParameters()[1].ParameterType;
            Delegate del = Delegate.CreateDelegate(typeof(Action<,>).MakeGenericType(typeof(Client), packetType), method);
            IPacketHandler handler = (IPacketHandler)Activator.CreateInstance(typeof (PacketHandler<>).MakeGenericType(packetType), del);

            _packetHandlers.Add(opCode, handler);
        }
    }
}

```

Additional PacketHandler class is nescessary to cast your IPacket to concerete packet type

```
public interface IPacketHandler
{
    void Invoke(Clientclient, IPacket packet);
}

public class PacketHandler<T> : IPacketHandler where T: IPacket
{
    public Action<Client, T> Handler;

    public PacketHandler(Action<Client, T> handler)
    {
        this.Handler = handler;
    }
    public void Invoke(Client client, IPacket packet)
    {
        Handler(client, (T) packet);
    }
}

```

---
Tags: architecture
---


title: Minimum target iOS version for games

text:
# Question
Title: Minimum target iOS version for games
I have noticed lately on the App Store many games have been updated to require a minimum of iOS 4.3 to run thus eliminating support for 2nd gen devices (iPod Touch 2nd gen and iPhone 3G).

It is now 2013, my question is what should be the minimum target iOS version and device platform for games development. If it is 4.3+ why not support older devices?

# Answer
> 3 votes
While there is no minimum version you have to support, starting from May 1, 2013, all apps *must* support retina display and iPhone 5 screen size.

Specially in the iOS ecosystem, you may suppose all users are running under the latest iOS version, so making your game run only on iOS 6 and above will probably get you a large proportion of users (and the vast majority of those who would pay for your game). Supporting iOS 5 will virtually get you every user.

# Answer
> 1 votes
Apple dropped the support for Arm v6 in Xcode 4.5, so you pretty much can't make games for iPhone 1, 3g and some of the early iPod touches.

---
Tags: ios, appstore
---


title: A custom method for events

text:
# Question
Title: A custom method for events
Basically what I am trying to do here is to create an event system for a simple game engine I am working on.

I'm trying to make this program as platform independent as possible with the C++ language so I am ruling out threading for the moment.

The basic idea that is that:

```
//outside game loop (initialization)
o_check_for_events(O_CHECK_ALL_EVENTS); // this should add the events to some sort of list

// inside game loop
event = o_get_next_event(); // return the next event in the queue
// ..
// do stuff with events

```

That would be a sample game event loop. What I want out of this though is an option that I can ask the system to wait for an event (easier of the two) and/or be able to check for events even while the game is running.

What I want to know is if it is more efficient to have methods that interrupt the flow for a short period of time, or else a threaded program that checks for events simultaneously (assume that the thread functions are safe)?

# Answer
> 0 votes
You have multiple questions here, but your question of whether or not it is more efficient to have threaded asynchronous event handling or blocking message handling is likely going to lean in the direction of asynchronous handling. Unless you are encountering some very extreme locality of reference issues, which would honestly likely be encountered regardless of threaded or not. I would recommend you do not implement an asynchronous callback system, as your engine is likely going to see far better improvements from threading other intensive operations. Callback systems are extremely low overhead.

To answer more your architectural question, I will explain a simple architecture I have seen in modern AAA game engines, and something I have written myself. Typically, the game engine framework will have an entire system dedicated to handling events, and this is often built on top of a generic messaging, or callback system. Events are triggered at specific points throughout the program flow, and are typically delivered immediately by the corresponding event/callback (unless you support time delay events). At that point, any entity, or system that implements a callback listening interface, and is subscribed to that event will receive the notification and potential payload.

As a final note, your method names == scary. :)

---
Tags: c++, events
---


# Question
Title: What is "terrain mesh generation" exactly?
I'm new to computer graphics and need to know and understand what the "terrain mesh generation" is? I read about "terrain", "mesh", "terrain generation" but can't find an article named "terrain mesh generation". So is there anyone can explain "terrain mesh generation" ?

# Answer
Terrain mesh generation is a general term for the process of... generating a mesh for the terrain.

Ok, let me elaborate.

A mesh is a generic term for a 3D model. It usually consists of vertex positions (set up as triangles), normals, texture coordinates and other information required to render the model properly. If you don't know how meshes work, you need to look into this first - this is part of the very basics of 3D rendering.

So, if a mesh is just a 3D model, why are terrains so special? For several reasons.

Terrains are usually not edited entirely by hand. Even if you want to design a specific part of your terrain by hand, most of it will be procedural (computer generated based on certain inputs). This is also important because terrains can be very large (pseudo-infinite), so creating it by hand is even less feasible. Proceduralism is a great form of compression: even infinite (or really large) terrains can be compressed down to a few integers.

Terrains also have another important property: most of the time you cannot go under them, so they can be described as a surface instead of a volume. The most common representation of this is the height-map: for each coordinate, you define the height of the terrain. This heigh-map can be procedurally generated, manually edited, infinite or finite. The heightmap also implicitly holds the surface normals.

So the process of terrain mesh generation most often refers to the process of taking the "compressed", procedural, perhaps height-mapped representation of the terrain and turning it into a 3d mesh. Of course the exact procedure depends on the system: you can generate only a few chunks of the terrain that is visible to the camera, you can have a dynamic LOD/tessellation system that makes the most visible parts more detailed than the rest, etc. So it really is just a generic term.
> 4 votes

# Answer
A *mesh* is a collection of points, usually connected into triangles, that form a shape in a (typically) 3-dimensional space.

A *terrain mesh* is a shape that is formed to resemble some terrain a video game or simulation; it can represent a landscape or even a whole planet.

So, generation of such mech involves creation of such vertices. There's a number of techniques used, such as Simplex/Perlin noise functions, that can be used to produce nicely-looking "Earth-like" terrain with minimal seed data. The term grabs all these methods and the result representation.
> 1 votes

---
Tags: terrain, mesh
---


title: create a city top view

text:
# Question
Title: create a city top view
I want to create my first game with java. I need a top view map of a city and i am stuck. Randomly there will be happening events in that city and the player should click on it.

Now is my first problem how to create the map in java. I designed a small map with tiled but not sure how to use it now:

I want to use this in the java game. I am stuck. I want to let the events happen on the streets. How do i do this? I am looking for some good tutorials but i am not sure what i am looking for so i could use some help in that direction.

Sorry for my english :(

# Answer
*Note: it's clear from this question that you understand the reasoning behind using data files, but I will leave my preamble here for the benefit of others who come across this question in the future*

> Now is my first problem how to create the map in java. I designed a small map with tiled but not sure how to use it now:

I can't comment yet but you seem to be asking:

*How can I export this map from tiled so I can actually use it in my game?*

## Why Data Files?

To answer this I should make a few things clear:

1. Since every game needs different information about what the world looks like, the types and statuses of the objects in your game, etc... there is no ideal way for that data to be stored that will be perfect for every single game.
2. At the same time it is of great importance that map editors like tiled make it as easy as possible for people to use the map data in their game. See this question. It would be great if there were some standardized way that maps from these editors could be stored so that they could be read easily by machines and (optionally) by humans. Enter data file formats like json and TMX (there are many others). Data files that follow these and other specifications store data in a structure that can be easily parsed by computer programs (such as your game). Tiled exports TMX files.
3. Q. *Oh fiddlesticks, are you telling me I have to write and debug a bunch of code to read these convoluted text files in order to get the map into my game?* A. Not necessarily. To this end there are many helper libraries available that will do much of this work for you. see this page.

## Main Answer

According to the Tiled wiki Support for TMX page:

> A library for loading TMX files is included with Tiled at `util/java/libtiled-java.`

You shouldn't even have to download anything :) You will still have to figure out how to use the loader yourself; playing with the tests would be a good start.

I hope this helps!
> 2 votes

---
Tags: java, maps
---


title: Circular Method Calls

text:
# Question
Title: Circular Method Calls
The title may be a little wrong for what I am asking, but that was the closest I could think of.

My problem is I am making a game that includes a `World` class and a `WorldObject` class. the `World` class contains a `std::map<unsigned int, WorldObject*>` in order to keep track of all objects that are in the world. On the flip side, the `WorldObject` class has an `unsigned int` as a unique ID, and a `World*` to the world that it is currently in.

When it comes time for the object to be removed from the world and deleted, I made it so that can either be done by calling `WorldObject::removeFromWorld()` or `World::removeObject(WorldObject*)`. The problem is, I'm not entirely sure how to set up these methods so the object is removed from the map in `World`, and the `World*` reference is removed from the object all in one fell swoop. I'm still relatively new to C++, so I'm not very sure how memory management works with deleting pointers and such, but this is what I was able to come up with my limited knowledge:

WorldObject.cpp

```
WorldObject::~WorldObject()
{
    world = nullptr;
}

void WorldObject::removeFromWorld()
{
    world->removeObject(this);
}

```

World.cpp

```
bool World::removeObject(WorldObject* object)
{
    if (contains(object))
    {
        objectList[object->getObjectId()] = nullptr;
        delete object;
        return true;
    }

    return false;
}

```

This seems a little too circular for me, and the main problem that I'm not sure will work or not happens if `WorldObject::removeFromWorld()` is called. If this method is called, it is placed on the stack and then calls `World::removeObject()` , but this method deletes the calling object. I know objects can "commit suicide" but I dont know if that makes it so the calling object can be deleted before `World::removeObject` returns.

Anybody who could confirm if this method works, or even give a more efficient solution (as I'm sure there is) would be greatly appreciated.

# Answer
> 3 votes
Do you really need two ways of deleting an object? If there is no concrete reason for an object to be able to destroy itself, you could scrap the `WorldObject::removeFromWorld()` method entirely.

Otherwise, your compiler will probably *allow* you to call a method that destroys the caller, but I wouldn't say this is a good idea. Consider what could happen if you added an innocent line after the removal:

```
void WorldObject::removeFromWorld()
{
    world->removeObject(this);
    this->logMyRemoval(); // oops, this doesn't exist anymore!
}

```

One option is to use smart pointers like Luke B. proposed. Another option is to turn this to a removal request: when you request removal, don't actually perform it, just mark the object for removal. And then once per frame, after every processing is done, remove all objects that are marked for removal in one step.

# Answer
> 2 votes
As far as I know, if you don't use the object after it's destroyed there is no problem (otherwise you will be accessing a deleted object which is probably undefined behaviour).

You could avoid the trouble of managing the memory by having `std::unique_ptr<WorldObject>` instead of `WorldObject*` and you would remove from the map simply by calling `objectList.erase(object->getObjectId());`

Also, making `world = nullptr` in your destructor is not necessary, since your WorldObject does not own the World pointer, you would only need a destructor if your WorldObject were to destroy the World object.

---
Tags: c++, objects, memory
---


# Question
Title: Advice on developing a random event engine
I am looking into creating a random event engine like the one found in the Paradox Interactive’s Europa Universalis franchise.

They use a ‘mean time to happen’ mechanic that applies various modifiers to both the human and AI players. This is all achieved via a scripted language.

What I have now is a system that imports my script of random events. Within that script is a 'mean time to happen' expressed in game turns. Each event is then queued with the game turn that it should fire +/- 10% (e.g. an event that should fire every 10 turns can happen every 9-11 turns).

When the game turn for an event comes up it checks all players to get a short list of eligible players. it then assigns a random player from the eligible list the event.

Once the event has fired it adds itself back into the queue with a new fire turn and waits to happen again.

What I am looking for here is a sanity check or if I am headed down a path that will work.

Beyond the sanity check does the community have a suggested method for scripting the events?

What I have is a simple eligibility flag with choices and the AI's chance to take each option.

example:

IF factionType == 'x'

EVENT\_OPTIONS

A: AI:0.6 mod\_A B: AI:0.4 Mod\_B

# Answer
> 1 votes
Create a simulation of your players and these events, create a parameterized function that does your option code. Run this isolated simulation a bunch of times to see if it works for your gameplay, adjust parameters and then the function itself until it does.

**Do not make this too complex** because *simple randomness will appear complex* to the player and debugging problems with events inside a hurricane of randomness and conditional logic is a nightmare.

Does what you have actually run? Then keep using it until it proves useful or fails to provide gameplay you want, then replace it. Such a small piece of code, your calling this an "Engine" is giving it way too much weight.

In the end, no one can tell you whether this will work because no one here is playing your game or has any idea why you're adding randomness to the timers. Only live testing can show you what works or not.

---
Tags: scripting, events, random
---


# Question
Title: How to handle the top of a slope in a 2D tile-based platformer?
I'm working on a 2D tile-based platformer that supports 45-degree slope tiles.

There are several questions on the topic, but none seem to cover this precise problem that I have. This excellent article covers almost everything I'd want to know. I'll copy the salient bits:

> * Make sure that you step X position before Y position.
> * During collision detection, the slope only counts as a collision if its closest edge is the taller (smaller y coordinate) one. This will prevent characters from “popping” through the slope from the opposite side. \[...\]
> * A full obstacle tile adjacent to the slope the character is currently on should not be considered for collision if it connects to the slope, that is, if the character (that is, his bottom-center pixel) is on a {0, \*} slope, ignore left tile, and, if on a {\*, 0} slope, ignore the right tile. You may have to do this for more tiles if your character is wider than two tiles – you might simply skip checking on the entire row if the player is moving towards the upper side of slope. The reason for this is to prevent the character from getting stuck at those tiles (highlighted yellow above) while still climbing the slope, as his foot will still be below the “surface level” by the time he comes into contact with the otherwise solid tile.

So if the character is going uphill, we essentially allow him to penetrate the slope after we've stepped the x coordinate, and then rectify that when we step the y coordinate. Let's assume we're using one contact point for the characters feet:

However, when the character reaches the top of the slope, at some point he'll step into the next tile:

As per the last bullet point above, we allowed him to move into the solid tile because it's ajacent to the slope. But now we're inside the floor, which needs to be fixed somehow.

What logic is needed to correctly resolve this situation? Simply saying "if we penetrate a solid tile, move up until we're out of it" doesn't always work, because there might be another solid tile on top of it, and we don't want the player to be teleported all the way to the top.

Can this be done without any communication between the x update and the y update, or do we need to keep some state like "I was on a slope at the start of this frame"? What is the most robust and elegant way to handle this?

# Answer
> 4 votes
The answer is to not use just SAT and plain physics/collision handling but to add a large mass of character-specific collision-handling code. Platformers are special beasts with special rules.

As the player moves, remember that he is on the ground. Adjust along the slope horizontally then snap the player back onto the ground afterward. Otherwise you end up with the player "hopping" off the top of slopes or what running down a slope, as you noted.

You may well want all kinds of special logic for slopes to deal with speed (if you only have horizontal speed, the player will move faster/farther on a slope than not), jumping (with plain SAT or such, the player will "bounce down" a slope slightly every time they land on one from a jump, since they will be pushed out along the normal of the slope rather than having their vertical jump simply stopping).

Instead of physically modeling the movement, just have multiple states: grounded and in-air. If ground, any movement should keep the player snapped to the ground unless he is walking off a vertical drop, in which case you switch to the in-air state. Go back to grounded once landing. While in air, remember to first check for separating axis along the bottom of the player to avoid the "hopping" problem on slopes.

You can use hotspots or multiple ray casts to detect if the player is half-standing on a ledge or slop for animation purposes.

Overall, player controllers and physics are very rarely tied tightly together, and platforms even more so. Your player will typically be an infinite mass kinematic object in most cases (with maybe a special "ragdoll" like mode if thrown or struck) that is explicitly managed with custom set of algorithms, using the collision system for *queries* and basic resolution but not full physical resolution.

---
Tags: tiles, collision-resolution, platformer
---


# Question
Title: GL_TRIANGLE_ADJACENCY and glDrawElements
So I've not been able to find much online about how data should be stored for triangle adjacency.

Currently I calculate my adjacent using half-edges (mention in an answer here).

But do I store this data in with my VBO? (Which means twice the vertex data) Or do I store it in my element array buffer? And if so how do I tell opengl the interleaving I would have in it?

# Answer
You can store it in your GL\_ELEMENT\_ARRAY\_BUFFER since the vertex data is just repeated for the adjacency verts.

Assuming that each consecutive 3 indices defines a triangle, and that "`unsigned *ndx`" points to an arbitrary triangle in your buffer, then 6 consecutive indices will define a triangle with adjacency, as follows:

* ndx\[0\] - index 0 of the original triangle
* ndx\[1\] - index of the vertex that completes the adjacent triangle for {0,1}
* ndx\[2\] - index 1 of the original triangle
* ndx\[3\] - index of the vertex that completes the adjacent triangle for {1,2}
* ndx\[4\] - index 2 of the original triangle
* ndx\[5\] - index of the vertex that completes the adjacent triangle for {2,0}
> 3 votes

---
Tags: opengl, geometry
---


# Question
Title: How can I render multiple windows with DirectX 9 in C++?
I'm trying to render multiple windows, using DirectX 9 and swap chains, but even though I create 2 windows, I only see the first one that I've created. My RendererDX9 header is this:

```
#include <d3d9.h>
#include <Windows.h>
#include <vector>

#include "RAT_Renderer.h"

namespace RAT_ENGINE
{
    class RAT_RendererDX9 : public RAT_Renderer
    {
    public:
        RAT_RendererDX9();
        ~RAT_RendererDX9();

        void Init(RAT_WindowManager* argWMan);
        void CleanUp();

        void ShowWin();

    private:
        LPDIRECT3D9           renderInterface; // Used to create the D3DDevice
        LPDIRECT3DDEVICE9     renderDevice;    // Our rendering device
        LPDIRECT3DSWAPCHAIN9* swapChain;       // Swapchain to make multi-window rendering possible
        WNDCLASSEX wc;

        std::vector<HWND> hwindows;

        void Render(int argI);
    };
}

```

And my .cpp file is this:

```
#include "RAT_RendererDX9.h"

static LRESULT CALLBACK MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );

namespace RAT_ENGINE
{
    RAT_RendererDX9::RAT_RendererDX9() : renderInterface(NULL), renderDevice(NULL)
    {
    }

    RAT_RendererDX9::~RAT_RendererDX9()
    {
    }

    void RAT_RendererDX9::Init(RAT_WindowManager* argWMan)
    {
        wMan = argWMan;
        // Register the window class
        WNDCLASSEX windowClass =
        {
            sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0, 0,
            GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
            "foo", NULL
        };

        wc = windowClass;

        RegisterClassEx( &wc );

        for (int i = 0; i< wMan->getWindows().size(); ++i)
        {
            HWND hWnd = CreateWindow( "foo", argWMan->getWindow(i)->getName().c_str(),
                                    WS_OVERLAPPEDWINDOW, argWMan->getWindow(i)->getX(), argWMan->getWindow(i)->getY(),
                                    argWMan->getWindow(i)->getWidth(), argWMan->getWindow(i)->getHeight(),
                                    NULL, NULL, wc.hInstance, NULL );
            hwindows.push_back(hWnd);
        }

        // Create the D3D object, which is needed to create the D3DDevice.
        renderInterface = (LPDIRECT3D9)Direct3DCreate9( D3D_SDK_VERSION );

        // Set up the structure used to create the D3DDevice. Most parameters are
        // zeroed out. We set Windowed to TRUE, since we want to do D3D in a
        // window, and then set the SwapEffect to "discard", which is the most
        // efficient method of presenting the back buffer to the display.  And
        // we request a back buffer format that matches the current desktop display
        // format.
        D3DPRESENT_PARAMETERS deviceConfig;
        ZeroMemory( &deviceConfig, sizeof( deviceConfig ) );
        deviceConfig.Windowed = TRUE;
        deviceConfig.SwapEffect = D3DSWAPEFFECT_DISCARD;
        deviceConfig.BackBufferFormat = D3DFMT_UNKNOWN;
        deviceConfig.BackBufferHeight = 1024;
        deviceConfig.BackBufferWidth = 768;
        deviceConfig.EnableAutoDepthStencil = TRUE;
        deviceConfig.AutoDepthStencilFormat = D3DFMT_D16;

        // Create the Direct3D device. Here we are using the default adapter (most
        // systems only have one, unless they have multiple graphics hardware cards
        // installed) and requesting the HAL (which is saying we want the hardware
        // device rather than a software one). Software vertex processing is
        // specified since we know it will work on all cards. On cards that support
        // hardware vertex processing, though, we would see a big performance gain
        // by specifying hardware vertex processing.
        renderInterface->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwindows[0],
                              D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                              &deviceConfig, &renderDevice );

        this->swapChain = new LPDIRECT3DSWAPCHAIN9[wMan->getWindows().size()];
        this->renderDevice->GetSwapChain(0, &swapChain[0]);

        for (int i = 0; i < wMan->getWindows().size(); ++i)
        {
            renderDevice->CreateAdditionalSwapChain(&deviceConfig, &swapChain[i]);
        }

        renderDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); // Set cullmode to counterclockwise culling to save resources
        renderDevice->SetRenderState(D3DRS_AMBIENT, 0xffffffff);   // Turn on ambient lighting
        renderDevice->SetRenderState(D3DRS_ZENABLE, TRUE);         // Turn on the zbuffer
    }

    void RAT_RendererDX9::CleanUp()
    {
        renderDevice->Release();
        renderInterface->Release();
    }

    void RAT_RendererDX9::Render(int argI)
    {
        // Clear the backbuffer to a blue color
        renderDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 0, 0, 255 ), 1.0f, 0 );
        LPDIRECT3DSURFACE9 backBuffer = NULL;

        // Set draw target
        this->swapChain[argI]->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
        this->renderDevice->SetRenderTarget(0, backBuffer);

        // Begin the scene
        renderDevice->BeginScene();

        // End the scene
        renderDevice->EndScene();
        swapChain[argI]->Present(NULL, NULL, hwindows[argI], NULL, 0);
    }

    void RAT_RendererDX9::ShowWin()
    {
        for (int i = 0; i < wMan->getWindows().size(); ++i)
        {
            ShowWindow( hwindows[i], SW_SHOWDEFAULT );
            UpdateWindow( hwindows[i] );

            // Enter the message loop
            MSG msg;
            while( GetMessage( &msg, NULL, 0, 0 ) )

            {
                if (PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
                {
                TranslateMessage( &msg );
                DispatchMessage( &msg );
                }
                else
                {
                    Render(i);
                }
            }
        }
    }
}

LRESULT CALLBACK MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            //CleanUp();
            PostQuitMessage( 0 );
            return 0;

        case WM_PAINT:
            //Render();
            ValidateRect( hWnd, NULL );
            return 0;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

```

I've made a sample function to make multiple windows:

```
void RunSample1()
{
    //Create the window manager.
    RAT_ENGINE::RAT_WindowManager* wMan = new RAT_ENGINE::RAT_WindowManager();

    //Create the render manager.
    RAT_ENGINE::RAT_RenderManager* rMan = new RAT_ENGINE::RAT_RenderManager();

    //Create a window.
    //This is currently needed to initialize the render manager and create a renderer.
    wMan->CreateRATWindow("Sample 1 - 1", 10, 20, 640, 480);
    wMan->CreateRATWindow("Sample 1 - 2", 150, 100, 480, 640);

    //Initialize the render manager.
    rMan->Init(wMan);

    //Show the window.
    rMan->getRenderer()->ShowWin();
}

```

How do I get the multiple windows to work?

# Answer
> 3 votes
This is documented on MSDN at: "Presenting Multiple Views in Windowed Mode (Direct3D 9)":

> The application typically creates one swap chain per view by using the IDirect3DDevice9::CreateAdditionalSwapChain method, and associates each swap chain with a particular window.

What you're missing in your code is the "associates each swap chain with a particular window" part - when you call CreateAdditionalSwapChain you're still using the same present parameters as you used for the original Device and it's implicit swap chain; i.e. all of your swap chains are associated with the same window.

So to fix this you need to set the hDeviceWindow member of your present parameters to the HWND of the window that each swap chain is to be associated with *before* you call CreateAdditionalSwapChain.

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


# Question
Title: XNA Creating a directional vector from two other vectors
Could somebody please tell me what I'm missing?

I have a scene where the camera is fixed in the sky looking down on a plane. On that plane is a 3D model. I want to move the 3D model in the direction of the mouse whenever the person clicks. I have accurately converted the mouse coordinates into 3D coordinates and then according to my understanding all I had to do was the following:

```
direction = new Vector3(mouseX - modelX, 0, mouseZ - modelZ);
direction = Vector3.Normalize(direction);

```

However this doesn't quite work. If I remove the normalize part and divide it by 100 it works as in it moves towards the mouse but the speed is constantly changing (as it should) since I'm just dividing by 100, so I sorta-kinda-know the rest is fine. But if I get rid of that and keep the normalize part the character goes crazy and moves towards the mouse but it moves very fast and is constantly flashing in different positions around the mouse. In 2D I had to use sin and cosine after subtracting the values from one another, is there something similar I have to do in 3D?

Thanks!

Edit - code for figuring out the mouse position:

```
nearsourceV = graphicsDevice.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), camera.Projection, camera.View, camera.World);
farsourceV = graphicsDevice.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), camera.Projection, camera.View, camera.World);

fullMouseCoord = Vector3.Normalize(farsourceV - nearsourceV);

mY = -fullMouseCoord.Y;
mY = zoomAmount / mY;
fullMouseCoord  = fullMouseCoord  * mY;

```

And then the code for updating the model position:

```
public void MoveVertices(float x2, float y2, float z2)
{
    for (int i = 0; i < vertices.Length; i++)
    {
        vertices[i].Position.X += x2;
        vertices[i].Position.Z += z2;
    }
}

```

# Answer
I think you need to add a delta time, and movement speed into the equations in `MoveVertices`. Without these, you are moving one unit per update. Something like the following will make it N units per second:

```
public void MoveVertices(float x2, float y2, float z2, float movementSpeed, float deltaTime)
{
    for (int i = 0; i < vertices.Length; i++)
    {
        vertices[i].Position.X += x2 * movementSpeed * deltaTime;
        vertices[i].Position.Z += z2 * movementSpeed * deltaTime;
    }
}

```

where `movementSpeed` is units/second and `deltaTime` is the number of fractional seconds that have passed since the last update. This will slow your character down.

You can read more about delta times here: When should I use a fixed or variable time step? and here: http://gafferongames.com/game-physics/fix-your-timestep/
> 1 votes

# Answer
1) Figuring out mouse position:

I think is easier using a Ray/Plane intersection. Seems that your plane is Y=0, then the code is:

```
  nearsourceV = graphicsDevice.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), camera.Projection, camera.View, camera.World);
  farsourceV = graphicsDevice.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), camera.Projection, camera.View, camera.World);

  direction = Vector3.Normalize(farsourceV - nearsourceV);
  ray = new Ray(nearSource, direction);
  var plane = new Plane(Vector3.UnitY,0);
  var distance = ray.Intersects(plane);
  if (distance.HasValue)
      fullMouseCoord = ray.Position + ray.Direction * distance.Value;

```

2) really you need to move the verticesd that way?

When you draw a model is usual to pass a model transform matrix as argument to the shader, use it to translate your model.

```
  // This is a good place to rotate and scale your model too
  var ModelTransform =  Matrix.CreateTranslation( model_position );

```

3) As pointed before if you want move with constant speed towards mouse point:

```
  model_movement_direction = Vector3.Normalize(fullMouseCoord-model_position);
  model_position += model_movement_direction * speed * elapsed_frame_time;

```

or doing some easing

```
  model_position +=  (fullMouseCoord-model_position) * 0.05f;

```
> 0 votes

---
Tags: xna, vector
---


title: Monster attack is not randomising right

text:
# Question
Title: Monster attack is not randomising right
I have a code that I've been messing around with and the monster attack (monster.ma) isn't randomising after the first time it's called upon (elif statement). I've tried to make it a tuple since they are immutable but it doesn't randomise after the first time. I was told to make a class and that's what I have done but it still doesnt work right. My attack variable (att) works right, but monsters' attack gets stuck. I know I can code the monster's attack into the elif statement, but I want to be able to just call upon it when needed.

```
import random

class monster():
    hp=50
    ma=random.randint(5, 20)
    xp=random.randint(15, 30)
a=1
exp=0
while a==1:
    if monster.hp<=0:
        exp+=monster.xp
        print"you have killed the monster"
        print("you get, "+str(monster.xp)+" exp from monster"
              "you now have, "+str(exp)+" exp")
        break
    elif monster.hp>=0:
        print"swing your sword"
        att=random.randint(5, 15)
        monster.hp-=att
        print"you do, "+str(att)+" damage to monster"
        print"monster does, "+str(monster.ma)+" damage to you" #<----------------here

```

# Answer
> 6 votes
It's only randomized the first time because you're only calling the random function one time (when you create the monster object). When you have `ma=random.randmint(5, 20)` in your class then you are creating that variable with a random amount at that time, but you are not altering it. In order to get a random value every time you need to reset the value every time you perform an attack. Notice how you do this when you set `att`; you need to do it the same way with `monster.ma`.

If you want to be able to generate a random attack, you need to create a method to do it. Something like this in your monster class:

```
def get_attack():
    return random.randomint(5, 20)

```

Should work whenever you call monster.get\_attack(). Note however that it's generally a bad idea to use hard coded "magic numbers" like this. It would be a good idea to define a monsters attack stats as members of the monster class. It seems like you're making monster a class because you read somewhere that it should be a class and not because you're going for an object oriented structure. Read up on object oriented programming

# Answer
> 0 votes
I'm very rusty with python, but usually what you want to do is create new monsters.

For example,

class monster(): def **init**(self): self.ma = random.randint(5,20)

or something. That way, you can create new monsters with m = monster() and then use their attack. I'm not sure this is perfectly correct, but it should help.

---
Tags: python, pygame, random
---


# Question
Title: Collision Detection: Simulation Inexplicably Slowing Down/How To Efficiently Calculate Extremes In Each Dimension
**BACKGROUND:** As discussed here: Fast 2D collision detection in an unbounded space I am working on a collision detection algorithm for a simulation. The catch that makes this case unique is that the objects in the simulation could all be in a very small area (e.g. 1000x1000) or in a very large area (e.g. 9 bil x 10 bil). Moreover, changes like this could occur very rapidly because of high object velocities, so I needed a somewhat sophisticated algorithm to deal with this situation. In the end, I went with quadtrees (http://en.wikipedia.org/wiki/Quadtree). When I finished writing the quadtree class and determined that it was functioning correctly, I uploaded it into my simulation.

**THE PROBLEM:** At first, the quadtree worked wonderfully. I was just testing it out for the first time, so instead of feeding it updated bounds every time step of the objects with the least x value/greatest x value/least y value/greatest y value, I just fed is a large area that I knew would be good enough for the test case (10 mil x 10 mil).

In a test involving 1600 objects, my simulation ran almost four times faster than the brute force solution of checking every object against itself! (about 28 fps instead of 7 fps) Wonderful! ***I then proceeded to feed the quadtree the updated "bounds" of the simulation by finding the min/max x/y each frame (this is where the problem begins).*** After updating each object's position, I simply checked to see if it was the new min/max extreme in each dimension:

```
    double tempradius = (*getMoveableEntityVector()[n]).Retradius();
    double tempx = (*getMoveableEntityVector()[n]).Retxpos();
    double tempy = (*getMoveableEntityVector()[n]).Retypos();

    if (n == 0) { //if it's the first object initialize the variables based off it
        minx = tempx - tempradius;
        maxx = tempx + tempradius;
        miny = tempy - tempradius;
        maxy = tempy + tempradius;
    }
    else { //all other objects
        if (minx > tempx - tempradius) { //if this object has the lowest x value
            minx = tempx - tempradius;
        }
        else if (maxx < tempx + tempradius) { //if has the highest x value
            maxx = tempx + tempradius;
        }

        if (miny > tempy - tempradius) { //if has lowest y value
            miny = tempy - tempradius;
        }
        else if (maxy < tempy + tempradius) { //if has highest y value
            maxy = tempy + tempradius;
        }
    }

```

Running through this simple code a mere 1600 times per time step slowed the simulation back down below the speed of my original brute force implementation! (about 7 fps)

**WHY THIS DOESN'T MAKE SENSE TO ME:** The original brute force implementation had to run through the relatively computationally intense distance formula (http://math.about.com/library/bldistance.htm) about 1600\*1600 times per time step, or more exactly, 1600\*1599/2 = 1,279,200 times per time step. I would think running through the above code once would be about as computationally intensive as doing the distance formula once. How is going through the above code only 1,600 times costing me as much processor time as going through the distance formula more than a million times?!?

*EDIT: The question is not directly about the quadtree; it is about the code above that finds the objects with the least/greatest x/y coordinates. (This code feeds its calcuations to the quadtree so the quadtree knows where to start, but it is definitely not quadtree code). **The quadtree code ran quite fast until I added the above helper code**. The only reason I mentioned the quadtree and the background to this issue is because the quadtree/background stuff gives context on why I think that this code should be going much faster (1000 comparable checks vs 1,000,000!)*

**TLDR (TOO LONG DIDN'T READ):** Check out the code above. Is there something making it take up WAY more (about 1000x more!) processor time than I think it should be taking?

Thanks in advance for the time and help!

# Answer
First, my apologies to Patrick and RandyGaul; I originally phrased my question poorly, but through this misunderstanding they did in fact point me towards the right answer.

The answer is that even though the code was building the quadtree from scratch each time step, having the constant bounds drastically decreases the time required to build the quadtree, even when I have 10,000 objects all moving rapidly. Solution? Round the bounds to the most appropriate multiple (round up for the greater bounds and down for the lesser bounds) of x, where x is some very large number. This "smooths out" the changes in the quadtree's bounds and solves the issue.

The reason why this works is beyond me, but if someone else wants to address that issue that would be awesome. Obviously (well...maybe) it has something to do with fewer bits in the cache being rearranged. Speaking of the mechanics of the cache, the video that congusbongus posted is great; I highly recommend it, although I don't think it gets into the topic deep enough to answer the "why" of why my solution is an effective solution.
> 1 votes

---
Tags: c++, collision-detection, efficiency, quadtree
---


title: What is the proper name for a 2D voxel?

text:
# Question
Title: What is the proper name for a 2D voxel?
I know pixel might be right, but pixel means something different, especially if a "2D voxel" isn't exactly one pixel (it isn't, in my game).

I've also heard "texel," but that seems to refer to a repeating texture, which this isn't. I guess I'm just getting hung up on words, but is there a proper term for this?

(For an example of the thing I'm referring to, look at Terraria.)

# Answer
> 15 votes
Pixel.

The term *voxel* is short for "volume pixel" or "volume picture element." Consequently a voxel without the "volume" bit is just a regular pixel.

The term for gameplay structural unit in a 2D game that can be deformed, damaged or destroyed in the course of game play (as in Terraria and games of its ilk) would most commonly be called a "tile," although you're likely to see more variety in terminology there.

I'd venture to guess what has you confused is that you're assuming a voxel represents a unit-of-destruction in 3D (because it does, or at least appears to, in Minecraft). This is not, however, necessarily true. It's just a particular pattern that has been popularized by the Minecraft-like genre of games right now (especially since historically complex voxel models have been CPU-intensive and it was a useful optimization to keep them one-to-one).

However, just like a pixel need not represent a unit of destruction in 2D, a voxel need not do the same in 3D.

---
Tags: voxels
---


title: How to display top-down 2D online game

text:
# Question
Title: How to display top-down 2D online game
I'm new to game development (but not new to software development). As a personal/learning project, I'm designing an overhead-view 2D online RTS game (static, no scrolling). The first cut will pretty much only require simple sprites, with typical menus, text, and buttons.

Most of the game logic will happen server-side, with unit positions and other vitals sent to the browser at about 30 fps. The client won't do much, aside from the display and UI. The server stuff is easy for me, but I need a little guidance on the browser display.

Having read up on several new browser technologies/HTML5 libraries, I'm getting more overwhelmed by the options, not less! I don't necessarily need the absolute best tool; what I want is a technology that will make it easy to implement a simple sprite-based game, and do a decent job of it.

I know JS itself well enough, but not any of the fancy graphics/game libraries. I know Flash/AS3 (doing what I want in Flash would be easy enough, but the mobile browser support concerns me--should I steer clear if I want iOS support?). I have the entire Adobe suite (subscription), if that helps. I'm not averse to learning a new language/API/tool, of course, but the more I can put what I know to good use, the better.

So, my question (yes, there is one in here somewhere!) is, what are my (best) options today for implementing the in-browser (display) part of said 2D online browser-based game, based on the above goals and stated skillset/available tools? Since it may be difficult to be completely objective, please do include a little rationale on why you believe your answer is the right tool for this job. I'm not asking for a doctoral thesis, here, just a paragraph or two. :-)

# Answer
You may want to take a look at this, the speaker is giving an overview over different technologies.

I have done some small games with HTML Canvas and found it very easy to pick up. I think it should be sufficent for your amount of sprites.

If you program your game with HTML and JS is should be quite easy to port it for mobile platforms. Again I was able to port a browserbased game into a native Windows 8 Store game with just one line of code change.

If you want to dig a bit deeper into game engines I suggest you take a look at this overview, most of tem are JS based and can offer you some nice additions.
> 1 votes

# Answer
hm, quite a lot of ambition for your first game. Most people find tetris a challenging enough game to implement when they don't have experience with game engines. That being said; I would probably go for simple jQuery and maybe something a plain as gifs for animations.

I am fully aware that HTML5/CSS3 provides better functionality though, but that is beyond my experience (I have mostly done XNA games)
> 0 votes

---
Tags: browser-based-games, online
---


# Question
Title: Where should I go looking for low-polygon 3D assets?
The biggest problem for me as a game programmer (who isn't also an artist) is getting good quality 3D models. I have checked out some of the 3D model market places like The 3D Studio and Top 3D Models but I have had difficulty finding the artwork I am looking for and, when I do find something I like, getting the level of detail appropriate for my platform.

Do people have any suggestions for sites they have dealt with successfully in the past? Am I better off building a relationship with an individual artist?

# Answer
I would suggest meeting artists and building relationships. One of my friends is big on asking them to do a trade off. He'll do some game programming for them and, in return, they give him some art or models he needs for his games. It's worth a shot.

Also, I've used TurboSquid to get some assets for prototyping and demos.
> 2 votes

# Answer
Making games is not a one man show. So doing it yourself you will always lack some assets, be it code, graphics, models, sound, animation, marketing, support.

So building a relationship with an artist is a good plan.

You can check out the polycount forums for some great modelers / artists
> 3 votes

# Answer
The whole problem is that good models is not a well defined term. A good model can be good for you and at the same time is be a bad model as per someone else's requirements. For you a good model is on which has appropriate polygon count and really nice looking textures with appropriate resolutions. So most of model websites will have high polygon models which you can use and convert to low polygon 'good'(appropriate poly count) models for your requirements. Follow the post below for more details on how to do this conversion. https://blender.stackexchange.com/questions/2936/creating-game-models-for-android
> 0 votes

---
Tags: assets, 3d-meshes, low-poly, art
---


# Question
Title: How to simulate cylinder shape in collision detection?
AFAIK, many physics engines like Physx and Havok don't incorporate cylinder as basic shape because it is expensive than sphere, box and capsule. But bullet engine does incorporate cylinder as a basic shape. Do they found any fast algorithm to simulate the cylinder and what is that?

# Answer
I don´t know about the speed or exact nature of the cylinder shaped collider in bullet, but this paper gives a nice overview about cylinder collision.

If you are only after the implementation of their collision you may want to start here and try to recreate what they are doing with it.
> 3 votes

---
Tags: collision-detection, algorithm
---


# Question
Title: Version number not supported by gl2 in andengine
I am new to andengine. From various forums, i got to know that my system should support hardware virtulisation. I have installed "Intel X86" and my system didn't throw any problem regarding "HAX" now. But now i am getting error in logcat as follows

```
09-13 22:20:43.195: E/AndroidRuntime(1509): FATAL EXCEPTION: GLThread 83
09-13 22:20:43.195: E/AndroidRuntime(1509): org.andengine.opengl.shader.exception.ShaderProgramCompileException: Reason: ERROR: 0:1: '' :  Version number not supported by GL2
09-13 22:20:43.195: E/AndroidRuntime(1509): Source:
09-13 22:20:43.195: E/AndroidRuntime(1509): ##########################
09-13 22:20:43.195: E/AndroidRuntime(1509): uniform mat4 u_modelViewProjectionMatrix;
09-13 22:20:43.195: E/AndroidRuntime(1509): attribute vec4 a_position;
09-13 22:20:43.195: E/AndroidRuntime(1509): attribute vec2 a_textureCoordinates;
09-13 22:20:43.195: E/AndroidRuntime(1509): varying vec2 v_textureCoordinates;
09-13 22:20:43.195: E/AndroidRuntime(1509): void main() {
09-13 22:20:43.195: E/AndroidRuntime(1509):     v_textureCoordinates = a_textureCoordinates;
09-13 22:20:43.195: E/AndroidRuntime(1509):     gl_Position = u_modelViewProjectionMatrix * a_position;
09-13 22:20:43.195: E/AndroidRuntime(1509): }
09-13 22:20:43.195: E/AndroidRuntime(1509): ##########################
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.shader.ShaderProgram.compileShader(ShaderProgram.java:187)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.shader.ShaderProgram.compile(ShaderProgram.java:143)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.shader.ShaderProgram.bind(ShaderProgram.java:122)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.shader.PositionTextureCoordinatesShaderProgram.bind(PositionTextureCoordinatesShaderProgram.java:86)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.vbo.VertexBufferObject.bind(VertexBufferObject.java:162)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.texture.TextureWarmUpVertexBufferObject.warmup(TextureWarmUpVertexBufferObject.java:97)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.texture.TextureManager.updateTextures(TextureManager.java:257)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.engine.Engine.onDrawFrame(Engine.java:613)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at org.andengine.opengl.view.EngineRenderer.onDrawFrame(EngineRenderer.java:105)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1462)
09-13 22:20:43.195: E/AndroidRuntime(1509):     at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1216)
09-13 22:20:43.275: E/OpenGLRenderer(1509): Error while compiling shader: ERROR: 0:1: '' :  Version number not supported by GL2
09-13 22:20:43.304: E/OpenGLRenderer(1509): Error while compiling shader: ERROR: 0:1: '' :  Version number not supported by GL2

```

I am getting similar kind of error when i tried to execute my program in BlueStacks and my application gets crashed. Pls help me regarding this. Thanks in advance

# Answer
> -1 votes
At last I was answered by an expert. The problem was that my emulator/bluestack device didn't support OpenGL ES version 2.0. I downloaded Andengine GL ES 1 and now it works.

---
Tags: opengl, android, andengine, opengl-es2
---


# Question
Title: What makes Unity3D games look so similar?
For some reason, I'm quite good at guessing whether or not a game (both 2D and 3D) is made with Unity3D. But I can't really figure out why that is.

What makes Unity3D games look similar? Is it because people use the same textures? Or is it the texture filtering? The lighting? Something else? I'd really like to know for educational purposes.

# Answer
> 3 votes
Trevor Powell has a very good answer.

Also if you consider that Unity3D, while big enough to be known, is not used by major company's. Bigger Company's like Blizzard, EA, Bethesda, and Square Enix, will build their own engine, or purchase the rights to use something like the Unreal engine. And then will put lot's, and lot's, of time into making the game large, unique, and in general try to come up with something original. Something that's never been done before.

On the other hand people starting up, or working for free, aren't worried or spending 2 year's of full-time work with a team of 100 people, to make an original idea come to life as the next big internet sensation. For example you can find THOUSANDS of different games of tetris, created by people trying to learn to program. And they all look the same! Regardless of if they where programmed in Basic, C++, DirectX, or OpenGL, it's tetris. However, There aren't many people trying to remake Skyrim.

Unity3D fall's kinda in the middle-ground between those two end's of the industry. It's got people who are aiming for something more complicated than tetris, and people who are copying idea's, and mechanics, from a variety of very well known (modern) games/genres. So you wind up seeing something fairly familiar but still somewhat impressive, though not spectacular. And people making that form of game happen to typically use Unity for it's familiarity, power, and lack of expense.

In effect, your not recognizing games made with Unity. Your recognizing some basic trait's of the developers, who tend to use Unity.

# Answer
> 2 votes
I hate to answer my own question and I'd rather not accept this answer, but I'm also quite convinced that this is *not* just confirmation bias.

Digging a bit deeper, it looks like some Unity users actually agree. The closest technical explanation is apparently:

> If you spend few months with any other engine you will notice that models in any engine look the same or at least you can easily recognise them becouse not due to one feature but rather many features that are implemented in engine. Image effects, lighting, shader quallity are usually the most important things where you can determine if model is rendered in one or other engine.

I'm not really happy with this answer, because I was wondering what kind of shaders or filtering mechanisms in particular make Unity games look alike.

---
Tags: unity
---


title: Fair spawning of players on a 2D grid

text:
# Question
Title: Fair spawning of players on a 2D grid
As new players enter a game, they are given a location on a large grid. The first player is given the location in the center.

Now, how should the *second player* be placed? Then, the *third* and *so on*?

New players should be placed reasonably near some other players, but not so close as to cause bunching.

My current thinking is to trace a clockwise spiral around the first player, gradually moving further and further out from that initial point. But I keep thinking this must have been done before and that a general solution must exist.

This is for a strategy resource game (similar to CoC or Throne Wars etc).

How do I do this?

# Answer
I'll address the general problem and issues you'll face, regardless of what game-specific rules you have for spawning players. You'll want these three parts:

1. Something that generates a potential spawn point, let's call it `GenerateSpawnPoint()`
2. Something that checks whether a spawn point is valid, let's call it `CheckSpawnPointIsValid(spawnPoint)`
3. Make sure that you eventually make a correct guess, or handle things if you cannot make one

So the pseudocode is:

```
loop for some time:
    point = GenerateSpawnPoint() // #1
    if CheckSpawnPointIsValid(point): // #2
        SpawnPlayer(point) and end
if we have not spawned:
    do something else // #3

```

It may seem that guessing and checking repeatedly like this is inefficient, but most games have very complex rules for whether a spawn point is valid. Your game rule may dictate that players can't intersect each other, or over certain objects. Your map may have inaccessible areas. You may want to spawn close to some things, or further away from others. It doesn't take many of these rules to create quite a complex `CheckSpawnPointIsValid()` function, and certainly one that is too complex to guarantee your guesses are successful. Therefore unless you are spawning hundreds and thousands of players per game tick, this sort of loop should be ok, even if you iterate hundreds of times in this spawning loop (just make sure the loop terminates).

Another advantage with this approach is that it's very easy to make; your game probably already has routines to check whether spawn points are valid, as part of your normal gameplay.

`GenerateSpawnPoint()` can be as simple as creating a random point. Just be careful that it makes a good enough guess, such that the guess has a reasonably good chance of being valid. For instance, avoid using a completely random guess over your entire world dimensions if your map is very sparse. Your idea of using a spiral is good because points next to existing players are more likely to be valid spawn points; just be aware that your suggested algorithm will tend to spawn players close to others than further.

Finally, the reason why we should handle the extraordinary case where we don't manage to find a valid guess is that, for non-trivial game rules and map layouts, it's hard to guarantee that we'll find a valid point, in all cases. For example, you may (inadvertently) specify game rules that players should not spawn in sight of any existing players, but apply it on a wide-open small map (where every point is in sight). Therefore you should think about what should be done if you cannot find a valid spawn point - is it ok to try spawning again later, or spawning in a position that breaks some of the rules, or not spawning at all?

These are the general issues you should be keeping in mind.
> 1 votes

# Answer
I read up an answer on these board about this, I tried to search for the link it because it was more detailed, but I couldnt find it back. to give you a summary about it : it was about how AI decide where to build town in Civ game. I'm not sure what a CoC game looks like, but since its resources base it should be similar.

You just basicly build a basic town placement AI. When you generate a map, you give a startingValue integer to each "square" or hexagone, or however you split your map. You recalculate to adjust the value whenever a player makes a new town, or "spawn"

You have to determine what gives a good value to a starting location, and give it an score. to be fair, spawn to player at locations with similar score, even if the resources differs, as long as the total point is similar, it should be fair.

close to a gold mine = +5 points

distance to nearest enemy \> 5 = +3

distance to nearest enemy \< 10 (encourage aggression) = 5 point

on water's edge (port, fishing, etc ) +3

close to XXX luxury resources = 2 points

close to food resources = 8 points.

...

you can add a lot of options here. if you want to force players be to relatively close to each other, only spawn startingValue point ( thus making these valid for a new player) in the 15 radius-square closest to the 1st player, etc.

Now just decide how you want to spawn your player, and what you consider to be fair.

Ex : You have 3 player, you spawn them on locations with 10,11 and 11 points, even if you have 2 other location worth 15 points, since it wouldn't be fair to the third player.
> 0 votes

---
Tags: maps, spawning
---


title: Custom timeout for xna wp7 Webclient

text:
# Question
Title: Custom timeout for xna wp7 Webclient
Since there is no timeout for responce in windows phone xna version of WebClient i need to implement one. The idea is to make `MyWebClient` derived class from `WebClient` with timer. But i got stuck on it. Is there any way to implement timer here without using `Update` for every instance of `MyWebClient` so that i can use it like `WebClient`?

# Answer
What about using a DispatcherTimer ? You could start the timer with your timeout a Interval value and register a tick event. When the event fires you throw a exception for a timeout (or do whatever pleases you). You could even hook up the DownloadProgressChanged event of the webclient and reset the timer or smth. like this.
> 0 votes

# Answer
Problem solved by using static varible `TotalGameTime` in main game `Update`

```
protected override void Update(GameTime gameTime)
        {
            TotalGameTime += gameTime.ElapsedGameTime.TotalSeconds;
        }

```

And then in `MyWebClient` save start state of `TotalGameTime` and compare with current gameTime

```
while (currentGameTime - startGameTime < timeout)
                    {
                       //
                    currentGameTime = Game1.TotalGameTime;
                    }

```

I dont find this solution clean but anyway it solves the problem.
> 0 votes

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: Is it possible to render controls inside controls in XNA?
I want to know if there is an easy way to render sprites in XNA inside other sprites or something similar (I don't know if sprite is the best or unique way to draw in XNA). For example, I want to draw an object called SCENE that defines a rectangle. Inside the rectangle there are some SQUARES. I'd like to code something to draw all the SQUARES when the SCENE are draw. At the same time, if I draw the SQUARES on the SCENE, the movement of the SQUARES are limited by the SCENE size.

Is this possible in XNA?

I did this with Pygame and is very easy to make.

Thanks in advance.

# Answer
The way that you would do this would be to use the power of C# and create some objects.

You would create a Scene object, that would have a Square object, which internally would have a collection of Squares inside it.

The `.Draw()` method of Scene would know it had to draw its own background, as well as tell the Square object to draw itself and all its children.

This is relatively easy with C#, extremely common, and probably the most simple way to do what you just mentioned in your post. A quick sample you might start with:

```
public class Scene
{
    public Texture2D background;
    public SquareList Square;

    public class SquareList : List<Square>
    {
        List<Square> Items;
        public void Draw(SpriteBatch batch)
        {
            foreach(var item in items)
            {
                // store position of each item instead of hardcode
                batch.Draw(item, new Vector2(0,0), Color.White);
            }
        }
    }
    public class Square
    {
        Texture2D myTexture;
    }
    public void Draw(SpriteBatch batch)
    {
        batch.Draw(background, new Vector2(0,0), Color.White);
        Square.Draw(batch);
    }
}

```

In this case, containment seems to make the most since, but you may want to have some of your objects inherit from a common base, such as "Sprite" or similar. It is beyond the scope of a single answer on this site to explain all of that. I recommend that you review some of the XNA sample code and see how they do things, and come back and ask us specific questions when you get stuck.
> 1 votes

# Answer
I think what he wants is viewports ...

try this http://msdn.microsoft.com/en-us/library/bb313965.aspx
> 0 votes

---
Tags: xna, sprites, rendering
---


# Question
Title: What are the benefits of capping frames per second? (If any)
I am working on a simple game in OpenGL, using SDL for display initialization and input, and it appears in terms of timing I have two options available to me. Number one being just sleeping for the optimalTimePerFrame - theTimeTakenToRender, when the optimalTimePerFrame in seconds = 1/theFramerateCap. (I'm not entirely sure if this is necessary, as it is equivalent to using vsync, which may be more accurate. If my assumption is correct then please tell me wheter or not SDL + OpenGL has vsync by default, and if not how to enable it.) The other is to measure the time since the last frame was rendered, and merely adjust movement accordingly. (The shorter time taken to render a frame, the less far entities move in that frame). In terms of performance, and decreasing flicker etc, what are the advantages and disadvantages of these two methods?

# Answer
If your frame time is unpredictable (whether or not this is your fault; the OS may be using resources occasionally, etc), capping to a predictable frame rate that is somewhat lower than your achievable framerate will do a lot for predictable *latency*, which can make the game feel a lot better.

Changing how long between when you process input and render changes related to that input can feel bad -- even if on average you're achieving *less* latency between the two, the "jitter" can be noticeable to humans (consciously or unconsciously).

See the Microsoft GameFest presentation What's In a Frame: Tearing, Latency, and Frame Rate for some insight here. Carmack also has a series of blog posts that are useful in this.

Also be aware that some math can break down when you run frames using low `deltaT` values -- or even when you use variable `deltaT` at all (things can become harder or even intractable to do in a "stable" and predictable manner, which is important for things like replays and some forms of network synchronization). See Fix Your Timestep for some insight here.
> 15 votes

# Answer
You will end up using a lot less CPU (multi taskers will thank you) and people on mobile devices will appreciate this, too.
> 13 votes

# Answer
**You should never, ever, ever, ever, ever use Sleep to control framerate**.

This has been gone over before and I'll refer you to the other question for discussion of the reasons why. One thing *not* mentioned there is that at the typical modern refresh rate of 60Hz, and with the typical 1 millisecond granularity of Sleep calls, it's actually impossible to Sleep for the correct amount of time between frames.

I'm **not** saying that yielding CPU if you've nothing to do is a bad thing; far from it. But it's not the same thing as controlling framerate and Sleep is a solution that's appropriate for the former but not the latter.

Instead check for time elapsed, and if it's time to run a frame, then do so, otherwise - and if you want to yield some CPU - Sleep for the bare minimum of time - 1 millisecond. Also ensure that your sleep timer is set up appropriately for your platform so as to give you good resolution; i.e. that when you issue that "Sleep (1)" call you actually stand a chance of really Sleeping for 1 millisecond, rather than something like 15, 20 or 30 (which would be the case otherwise). I believe that SDL will do this automatically for you.

You can also build some slack into it, so that if it's getting near time to run a frame, you stop Sleeping and start running flat-out until the frame runs, which can help you hit your desired frame interval more accurately.

What this ends up looking like is a whole bunch of Sleep (1) calls interspersed with the occasional frame, and that's OK. You're still giving up CPU when you don't need it, but your frames will still be able to run on time.
> 10 votes

# Answer
Probably the most important benefit of capping frame rate is that it can help to prevent literal physical damage to the machine. They forgot to do this on Starcraft II, which turned out to be very problematic (and expensive) for some users until they patched it.
> 1 votes

# Answer
As was mentioned earlier, it lowers CPU usage. On the flipside, and increasingly important, that also drains battery life. As a good example, FTL runs at nearly 100% CPU on my MBA. As a result, it drains the battery in \> 2 hours and runs very hot. ( As a more direct result, I uninstalled and no longer play it... ). A frame cap would have prevented this.

Another unmentioned advantage is, if its a multiplayer game, you also level the playing field by giving everyone the same experience.
> 0 votes

---
Tags: opengl, sdl, frame-rate, vsync
---


# Question
Title: Does interleaving in VBOs speed up performance when using VAOs
You usually get a speed up when you use interleaved VBOs instead of using multiple VBOs. Is this also valid when using VAOs?

Because it's much more convenient to have a VBO for the positions, and one for the normals etc. And you can use one VBO in multiple VAOs.

# Answer
> 3 votes
A VAO is purely a software/driver-side construct designed to manage state changes, and doesn't have much parallel in hardware, so whether or not a VAO is used is largely irrelevant in the case of this question.

What interleaving does is provide your vertex data with better cache-coherence; i.e. all of the attributes to specify a vertex will fit in a GPU cache line and can be read by the hardware in a single operation, rather than having to jump around multiple disjoint memory locations. Irrespective of whether or not you use VAOs, if you don't interleave you're going to have to do that jumping around.

Where a VAO *may* help is by batching state changes required to specify your vertex layout into a single operation, but again this would be irrespective of whether or not you interleave. They really are completely separate concepts.

---
Tags: opengl, vertex-arrays, vertex-buffer
---


title: UV Coordinates of "curve" (or "bend")

text:
# Question
Title: UV Coordinates of "curve" (or "bend")
I am looking for some tutorial or equation how to map texture from square to "curve" or "bend". (Example on image below) I have tried to convert coordinates of unit circle to UV, but that gives me incorrect result around corners.

# Answer
It sounds like you just need plain rectangular UV coordinates. The inner radius is `V = 1`, and the outer radius is `V = 0`. That angular procession from the bottom up is from `U = 1` to `U = 0` (or the opposite depending on tech). The vertex locations can be arranged in a curve, but the texture coordinates don't have to be.
> 3 votes

---
Tags: textures, uv-mapping
---


# Question
Title: Need to translate a Rotation Matrix to Rotation y, x, z OpenGL & Jitter for 3D Game
I am using the Jitter Physics engine which gives a rotation matrix:

```
M11 M12 M13
M21 M22 M23
M21 M32 M33

```

And I need it so OpenGL can use it for rotation

```
GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

```

Initially I Tried

```
xr = M11
yr = M22
zr = M33

[1 0 0]
[0 1 0]
[0 0 1]

```

Which did not work, please help, I have been struggling on this for days :(

**Re-Edit**

*The blocks are stored in text files with Euler angles so it needs to be converted or the rendering engine will simply fail.*

I am now using the matrix in the text files.

Example Block

```
1,1,1                      'Size
0,0,0                      'Position
255,255,255                'Colour
0,0,0,0,0,0,0,0,0          'Rotation Matrix

```

# Answer
> 2 votes
Doing that is possible, though I imagine insanely difficult, and since there is a better way, unnecessary. I'm also assuming that your using OpenGL 2.1, since glRotate was deprecated in OpenGL 3.x.

So, Using OpenGL 2.1, instead of reversing the matrix from your physics API, I suggest you just plug that matrix straight into OpenGL. This can be done with `glLoadMatrix`. Using that function, whatever matrix you input will be the matrix used to transform your model. That is, any translations, rotations, and scaling transforms will be used.

For Example:

```
float PhysicsTransformMatrix[16];

// code to get your matrix loaded into PhysicsTransformMatrix

glMatrixMode(GL_MODELVIEW);

while(gameIsRunning)
{
    // prep stuff...

    glPushMatrix();
        // takes the place of the usual `glRotate`, `glTranslate`, and `glScale` calls
        glLoadMatrix(PhysicsTransformMatrix);

        // rendering stuff...
    glPopMatrix(); // you could use `glLoadIdentity()` instead of glPush/glPop
                   // but there is a noteable difference.
}

```

**Edit:** Found a PDF document detailing how to find the possible solutions. The document has a lot of math. Though if your familiar with Matrices, and have gone through Trig, it shouldn't be too hard. It seems to have a problem with large parenthesis, I'm not sure it that's a problem with the document or the viewer.

---
Tags: physics, matrix, rotation, .net
---


# Question
Title: When two moving objects collide, which one sends the message, and which one recieves it?
I am writing a platform game using an entity-component system. Entity-World collisions are robust and work very well, and I'm now working on collisions between entities.

Just to be clear, in my code an `Entity` is a collection of `Attributes` (data) and a collection of pointers to `Components` (logic).

My `Entity` class has a `sendMessage(messageType type, char* messageData)` member function, which adds the `messageType` and `messageData` to a queue which is then used by the `component` interested in that message type. So in this example `CollisionMessage` is used by `CollisionComponent` and processed at the end of the tick with other messages (after normal collision checks).

My problem is that with every collision, I have two messages sent per collision, from each `Entity` to the other. This means that either I need to halve the forces I apply since it applies to each entity twice or I need to set up some Entities to only send collision messages and some to only receive collision messages.

So far things work fine when a player collides with an item, as it just gets picked up and removed from the world, but collisions between players and enemies are proving troublesome.

Is there a better way, or is there anything fundamental I've missed?

Thanks.

# Answer
> 1 votes
I don't think the collision should be handled by the entities at all, or by a component per entity, that need to be called by each entity.

If you only have two generic type of objects, for example actors and walls. Each time you collision detection loop runs, it will check the type of each object (a component provides this information?), for actor-wall one logic is executed, for actor-actor, another logic is executed. Lets assume walls cannot move without being promoted to actors (by changing the value of the relevant component), to maintain the system as simple as possible. No message is sent, anything happens inside the collision detection loop. For actor-actor, for example, each involved actor moves back half the length of the penetration vector. For actor-wall, the actor moves back full the length of the penetration vector, the wall does not move.

That is only an example. Having only two types of objects may not adapt to your game. And having the logic as part of the collision detection loop may not be suitable if you need many types of objects, or if all the types of objects are not known at design time (new types may be provided by loading a library later).

In resume: When two moving objects collide, which one sends the message, and which one receives it?

Answer: Do not use a message system at all. A message system is not suitable for this. The logic that handles the collision for a pair of entities must not by in the entity (or per entity component) and must run only once per pair, not two.

# Answer
> 1 votes
After discussion with @teodron, and some tinkering on my own, I think I've found something satisfactory and hopefully architecturally sound:

So previously any `Entity` that needed to collide with other objects and the world would have their position checked and modified in `CollisionComponent`. I've moved the tile/world collision code into a separate `WorldCollisionComponent` (which does detection and resolution) and I created a new `EntityCollisionDetectionComponent`, which will only do detection.

Previously, and here's where I think I was getting confused, I would do collision detection and resolution at the same time, and then I would send an additional message. I had the mental model of a `Component` acting on a particular `Entity` so each iteration was from the 'perspective' of the entity.

Instead, the `EntityCollisionDetectionComponent` will detect pairs of entities colliding and send each `Entity` a message with the details of the entity it collided with. Essentially, I'm marking an entity as collidable if it contains an `EntityCollisionComponent`.

I will have an `EntitiyCollisionResolutionComponent`, which will wait on messages and modify the `PositonAttribute` and `VelocityAttribute` of the `Entity`. Entities that don't need to be moved on collision (e.g. coins and other pickups) won't need this component added to it.

In code this would be something like:

```
class EntityCollisionDetectionComponent : public Component
{
public:
    void init() { /*...*/ }
    void cleanup() { /*...*/ }
    void update()
    {
        for (size_t i = 0; i < entities_.size(); ++i)
        {
            for (size_t j = i; j < entities_.size(); ++j)
            {
                if (collision(entities[i], entities[j])
                {
                     entities[i]->sendMessage(ENTITY_COLLISION, entities[j]->data);
                     entities[j]->sendMessage(ENTITY_COLLISION, entities[i]->data);
                }
            }
        }
    }
private:
    // Actually a part of the base class.
    std::vector<Entity*> entities_;
}

class EntityCollisionResolutionComponent : public Component
{
public:
    void init() { /*...*/ }
    void cleanup() { /*...*/ }
    void update()
    {
        while (!messageQueue_.empty())
        {
            CollisionResponseMessage* msg = reinterpret_cast<CollisionResponseMessage*>(messageQueue_.front());

            Entity* entity = getEntityById(msg->entityId);
            /*

            ... (compute new position, velocity, etc) ...

            */

            messageQueue.pop();
        }
    }
private:
    // Actually a part of the base class.
    std::vector<Entity*> entities_;
    std::queue<char*> messageQueue_;
}

```

I'm not going to accept this answer, because although it's a starting point for my solution, there's still a couple of holes (e.g. I realized I should send messages to a message handler which then forwards it to components, instead of sending it to entities; I happened to read an article which talks about converting an existing codebase to Entity-Component design where the compatibility makes sense).

Also, I'm sure someone will have something to say about my use of char\* and reinterpret\_cast!

Perhaps if/when I refine my system I'll come back and update the answer and accept it, if no-one else has any other ideas.

# Answer
> 0 votes
The answer greatly depents on how you store your entities. A very straightforward solution could just check collisions against entities that are stored "after" the one currently being processed e.g. if you store your entities in an array and update in a for-loop do collision checks only on entities with a higher array index than that of the current entitiy. This way each possible collision is only triggered once.

---
Tags: c++, architecture, entity-system, collision-resolution
---


title: How to use modern OpenGL for 2D games?

text:
# Question
Title: How to use modern OpenGL for 2D games?
I've found a plethora of "modern" OpenGL (3.0+) tutorials for 3D, but I have found next to nothing when looking for information on how to use it for 2D game development. How can I get started using OpenGL for 2D gamedev?

Specifically, I'm interested in getting answers to the following topics:

* How should I set up my various matrices for orthographic projection?
* Are shaders as heavily used in 2D applications as in 3D ones? If so, what is their purpose in the 2D setting?
* How should I handle the massive number of textures obviously required for a 2D game?

I apologize for the relatively broad question, but I've spent a long time searching and I've found very little useful information that applies to modern OpenGL.

# Answer
* How should I set-up my various matrices for Orthographic projection?

Your goal is 2D, right? So you don't need any projection. Projection is the act of condensing a 3D world to a 2D plane. Set the shader so it defaults the Z coordinate of every vertex to `0.0` and you should be set.

You might use a scale matrix for the X and Y coordinates though. Scaling it so `-10.0` to `10.0` becomes `-1.0` to `1.0`. For references sake, the matrix to do that is:

```
0.1   0.0   0.0
0.0   0.1   0.0
0.0   0.0   1.0

```
* Are shaders as heavily used in 2D applications as in 3D ones? If so, what is their purpose in the 2D setting?

They can be. They can still be used for Per-Pixel lighting, giving some fake depth to objects. They can also be used for texture effects, water effects, image-generation... you could even use them to do physics calculations with a bit of trickery.

Another way to put that is: Everything they are used for in 3D. It's just applied differently, and isn't as well documented. Though the people playing 2D games probably aren't going to be getting on your case if you don't have lifelike effects, so they're not required either.

Though you're going to need to know the basics of shaders to render a sprite anyway.

* How should I handle the massive number of textures obviously required for a 2D game?

Just as you do in 3D. Bunches of Texture Objects, PBO's, and a Texture Atlas or a few. Probably a few structures/classes, and headaches as-well. I think that would be called "Asset Management", or something similar.

* How can I get started with 2D gamedev?

There are probably a few tutorials out there. Though, since the 3D version is more common, I would say to learn OpenGL for 3D and then apply what you learn to it's 2D counterpart. 3D and 2D are very similar, 2D just doesn't keep track of the Z coordinate.
> 12 votes

---
Tags: opengl, 2d
---


# Question
Title: Getting different x and y coordinates for touched location on a zoomed view
I'm using Cocos2d for developing a game. I need to be able to pan and zoom when necessary, so for this reason I've added CCLayerPanZoom extension to my project. Recently I've noticed a problem with zoomed layers. The thing is if I touch on a zoom-panable layer before doing zooming or panning I get correct x,y coordinates. But if I zoom the layer, the touched location coordinates are different than the earlier ones. Here's how I get the touch location:

```
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch=[touches anyObject];
    CGPoint touchedLocation=[touch locationInView:touch.view];
    touchedLocation=[[CCDirector sharedDirector] convertToGL:startPoint];
}

```

You might ask how I determine whether the two points are different before and after zooming. I have a sprite located on a predetermined point in the view. When I touch the sprite I log the position of both the sprite and the touchedLocation. Before zooming these points are almost the same, only a few units of difference in x and y. But after zooming they're totally different points and I guess this difference is directly proportional with the zoom scale. I don't want to ask how to have the touched location the same before and after zooming, I rather want to ask what I should do in this case.

# Answer
OK, I finally got where my mistake was. I forgot the fact that when I add a sprite on a layer and later refer to its position, it always shows the same point. So for instance, if I add a sprite and set its position to 100,100 and then pan or zoom the layer and finally get the position of the sprite I'll still get 100, 100, even if the sprite is not inside the bounds of the screen for the moment. So when I touch the sprite after the layer is panned or zoomed I touch to a different position, not 100,100. That was what made me confused. To handle this issue I just subtracted the x,y of the layer's position from those of the touched location. This way I was able get the two points - the sprite's position and the touched location- to be the same. Note: The anchor point of the layer is ccp(0,0);
> 0 votes

# Answer
```
int Width = 2500;

int Height = 1500;

CCLayerPanZoom *Zooming = [[CCLayerPanZoom alloc] init];

self.Zooming.mode = kCCLayerPanZoomModeSheet;

self.Zooming.panBoundsRect = CGRectMake( 0, 0, mapWidth, mapHeight );

// zooming level

self.Zooming.minScale = 1.0f;

self.Zooming.maxScale = 8.0f;

self.Zooming.rubberEffectRatio = 0.0f;

// center in the view

self.Zooming.position = ccp( 512, 384 );

// the position just seems to make it all more or less weird, this is for testing

View.position = ccp( mapWidth * 0.5f, mapHeight * 0.5f );

[self.Zooming addChild:View];

[self addChild:self.Zooming];

```
> 1 votes

# Answer
You can refer to this code block:

```
- (void) layerPanZoom: (CCLayerPanZoom *) sender
       clickedAtPoint: (CGPoint) point
             tapCount: (NSUInteger) tapCount
{
    NSLog(@"CCLayerPanZoomTestLayer#layerPanZoom: %@ clickedAtPoint: { %f, %f }", sender, point.x, point.y);

    if (tapCount == 2) {
        // Toggle zooming all the way in and all the way out.

        float midScale = (sender.minScale + sender.maxScale) / 2.0;
        float newScale = (sender.scale <= midScale) ? sender.maxScale : sender.minScale;

        // Zoom towards the tap point.  Note that scaling is performed "around" the anchor point.
        // Thus, we need to account for how far the layer should be translated after its scaling
        // change is performed.

        CGPoint anchorPointNodeSpace = ccp(sender.anchorPoint.x * sender.contentSize.width,
                                           sender.anchorPoint.y * sender.contentSize.height);

        CGFloat deltaScale = newScale - sender.scale;

        CGPoint deltaPos = ccpMult(ccpSub(point, anchorPointNodeSpace), deltaScale);

        // Scale and translate in parallel.  We negate the direction since to zoom to the point
        // we want to move the layer in the opposite direction.

        [sender runAction:[CCSpawn actions:
                           [CCScaleTo actionWithDuration:0.4 scale:newScale],
                           [CCMoveBy actionWithDuration:0.4 position:ccpNeg(deltaPos)],
                           nil]];
    }
}

```
> -1 votes

---
Tags: cocos2d-iphone, touch
---


title: Tile Map World Background

text:
# Question
Title: Tile Map World Background
I am making a 2D top-down game in Java using the Slick2D library. However, this question applies to all ways of making games of this nature.

My question is: How would I do a background for the world. Currently it looks like this:

Obviously, this isn't the best example, as the right side has an area that allows the player to walk into the 'background'. However, I am asking how this is done in other games, such as Pokemon.

# Answer
> 1 votes
If you're working on a plain style map, you can either stop the map from scrolling and make the player move "beyond" the center of the screen OR stop the map from scrolling BEFORE you've reached your limit minus half your screen size.

# Answer
> 1 votes
If you don't want to use the method Byte56 linked, another option is to just make a bigger map. You don't have to put transition points right at the edge of the background. If you can see up to 20 tiles away, ensure that the "playable area" of the map is within a 20 tile border of the map. Note that this can be a bit jarring/annoying to players if you don't somehow make it very visually clear where the transition point.

Games like Neverwinter Nights (2002 version) would automatically extend a tiled map out but shade out the extended area. Thus a pathway that led right up to the "edge" of a map wouldn't just end in darkness but would visually appear to stretch out into the fog. The darkened shader along with NWN uses a clickable highlight region for transition areas made it clear and obvious where these transitions were but also make the map edges look less like an entire map was inside a box and instead part of an expansive, endless world.

# Answer
> 0 votes
There's also approach Heroes of Might and Magic chose - they render a border around the map and fill the abyss with stone texture:

---
Tags: java, slick, tilemap
---


# Question
Title: MonoGame crash trying to load font from .xnb file
My MonoGame project uses a pre-compiled .xnb file to load a sprite font, and it works fine on Windows XP. The .xnb file is marked as content and copied to the output directory.

I've copied the project across to a machine running Windows 7, and now the game crashes when I try to load the sprite font. There is no exception thrown. The application just exits with code -1073741819 (0xc0000005).

Both machines have MonoGame 3.0 installed. The Windows XP box (where the game works) also has XNA 4.0.

I can't remember exactly how I generated the .xnb file! I originally just took it from the output of an XNA project, but when I switched from MonoGame 2.5 to 3.0, I remember having some issues with it and tried to use the MonoGame content pipeline instead. So my .xnb file could be from either method.

How can I work out why spritefont loading is failing?

# Answer
> 1 votes
By looking at the application error in Windows Event Viewer, I could see that the error occurred in nvoglv32.DLL, which is an Nvidia dll.

Upgrading my drivers fixed the problem.

---
Tags: xna, windows, monogame, fonts
---


# Question
Title: Method for interpolation between 3+ quaternions?
I'm currently using spherical linear interpolation (slerp) to interpolate between two quaterions with a weighted value. But, I'm having a difficult time coming up with a method to interpolate between 3, 4, 5, etc quaternions with normalized weights.

I.E. I want a final quaterion which is 60% of QuaterionA, 30% of QuaterionB and 10% of QuaterionC.

Thanks, Cameron

# Answer
You could try slerping between A and B based on their relative weights, then slerping the result to C based on its weight.

For instance, in your example, A and B have a total weight of 90%. Use this to normalize their weights to get A' = 66.7% and B' = 33.3%, so slerp from A to B by 33.3% (or B to A by 66.7%, equivalently). Then slerp from that result to C by 10%.

For ordinary linear interpolation this is equivalent to adding up points weighted by barycentric coordinates (i.e. the usual method of interpolation for triangles). As you would expect, for linear interpolation it doesn't matter what order the points are in - you get the same answer regardless.

In the case of slerping, I don't know if you get the same answer regardless of the order of points, but you could try it and see.

For more than 3 points, you could extend this method to incorporate points one by one, using weights normalized by the sum of weights of all the points you've incorporated so far.
> 3 votes

# Answer
A more generic approach is detailed on Wikipedia. Essentially, that article explains there's no non-iterative method to find the generalized combination of N quaternions with weigths w\_i. Nevertheless, if you can supply an approximation of that quaternion "mean", you can iteratively refine it using these update equations:

So you could start with m\_0 as Nathan Reed suggested and apply how many iterations you need.

More details on quaternion calculus can be found on Dave Eberly's site.

Special care must be given when juggling hypercomplex logarithms and exponentials as they're not entirely similar to their lower dimensional homologues. (I think the log, for example, isn't injective). More details on what applies and what doesn't are given here. (most nice properties are preserved for unit quats).
> 6 votes

---
Tags: mathematics, quaternion, interpolation
---


# Question
Title: Can Entities Have Their Own Shader In Deferred Rendering?
Since you need to use the general g-buffer shader to fill g-buffer, how can entities have their own shaders, like giving a box normal mapping feature ? As I remember, you can't use two shaders at the same time. So there is a possible solution that every object will have their own renderers, but If I have to make each entity have their own renderers that also include g-buffer filling in their shaders, wouldn't there be unnecessary g-buffer shader code everywhere, extra variable passings to GPU ?

# Answer
> 3 votes
You can use any shader to fill the g-buffer, it doesn't have to be generic. That's not the point of deferred, the point of deferred is when you come to do the lighting pass you combine the various render targets in the g-buffer with your lights; your lighting pass is confined to pixels on-screen (rather than shading pixels which may be occluded). But it's quite agnostic as to how the individual render targets get filled, so in the case of normal mapping you can use a shader with normal mapping here, and output the result of it to your normals buffer.

---
Tags: opengl, deferred-rendering, deferred-shading
---


# Question
Title: How to draw point sprites with transparency in OpenGL without depth sorting?
I am trying to render point sprites with alpha transparency and because I render millions of points depth sorting would kill performance. My issue as you can probably imagine is that artifacts appear in some of the borders when the draw order is not correct:

My code for drawing:

```
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_POINTS,0,nSamples);

```

In my shader I just specify a alpha value in the output color depending on how close to the point center we are.

Is there any way to get rid of the artifacts and get a correct transparency render?

# Answer
> 3 votes
If you can change your blendfunc to one that is order-indpendent you may get good results, but then again you may not; it depends on whether or not the output meets the requirements of what you're trying to do.

Another semi-trick I've used before - for a particle system - is to group particles by emitters, then depth-sort the emitters. It's not 100% accurate of course, but if it works well enough for you then it may be worth trying.

# Answer
> 2 votes
Some things to consider:

Do you really need to draw millions of points? Perhaps you could get away with only drawing the points on the surface, in which case you check to see if `point center > radius of the sphere - some threshold`, and only draw it if it's true.

Secondly, depending on how you're generating the points, you could generate them at initialization and sort them once before any rendering is done. Ensure your vertex array is sorted back to front and the frontmost will overwrite the ones back further back.

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


# Question
Title: What's the purpose of layers in map editors?
I have a question regarding map editors, like Tiled, for example. I am currently making my own map editor, and I wondered if someone could explain to me what is the purpose of layering in tiled for example. What purpose does it serve in creating a map?

# Answer
> 17 votes
Layers are needed not only the most basic use of a tile map, but also allow more artistic expression and play features. Layers define the draw order of the sprites used in your world. They're simply a way to say, "Draw sprite X after sprite Y, so that sprite X will appear on top of sprite Y". They're typically generalized into layers so you don't need to define the depth for each sprite (though you could also think of defining the depth as setting the layer). This process is referred to as the Painter's Algorithm.

The most basic use is from having the player (or any non-map item) on top of the map. The map is one layer, and the player and other items are in another layer on top of the map.

(Source for image is a nice tutorial for making a simple game)

The artistic expression and play features include allowing players to walk "behind" other objects in the world or have placeable structures/items.

Layers are not only limited to visuals. You can also have layers that define non-walkable areas, like in the example above, layer 3 could be defined as "blocking" meaning the player isn't allowed to move onto anything in that layer. This effectively creates player boundaries to help with map creation. This can expand to the physics system where you may only want some sprites to collide with sprites in their same layer. This is a simple way of disabling friendly fire for example.

Layers also allow for effects like parallax scrolling. This gives a 2D game a feeling of depth.

# Answer
> 1 votes
Having different layers makes it possible to have things that the character can walk "behind" by putting the part in front of the player. This article explains this fairly well.

---
Tags: tiles, maps
---