# Question
Title: How can I render a texture to the screen in SDL2?
I've recently started upgrading my SDL version from 1.2 to 2.0.3, and while on the SDL Wiki, I've come across SDL\_Renderer, SDL\_Window, and SDL\_Texture. I did some research and found a link at StackExchange to be particularly informative. However, I'd like to know more about the process of getting a texture on the screen with this new software version.

## My Question

By what process does SDL2 display a texture to the user's screen?

## My Current Understanding

My current understanding is that a renderer is tied to a single window, which allows the coder to blit a texture (or multiple) to a renderer, which is then displayed to the window. Is this approximation correct?

# Answer
I know how you feel, SDL2 is somewhat different from the earlier one, to make it easier, I'll explain how `SDL_Renderer`, `SDL_Window`, and `SDL_Texture` work. The code blocks are separated with explanations, but for a program they would be used together in the order given.

```
//CREATE WINDOW
SDL_Window *window = SDL_CreateWindow("Title", 100, 100, 400, 600,SDL_WINDOW_SHOWN);

```

You have created a variable named window which is in the type of `SDL_Window`, `SDL_Create_Window` creates a window and its attributes are inside the (), the first one is the title, next is the x coordinate, then the y coordinate, then the width of the window, the height of the window, then the command that the window could understand you can put `SDL_WINDOW_RESIZABLE` if you want the window to be resizable etc.

Mind you that the (0,0) coordinate is in the top left of the screen so the greater the x value, the it moves to the right and the greater the y value, the more it moves down.

```
//CREATE RENDERER
SDL_Renderer *renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED);

```

You created a variable named `renderer` which is a type of `SDL_Renderer`, as you can see, SDL is very literal, `SDL_CreateRenderer` creates a renderer, the values inside the parentheses are (name of the window, the rendering drive, the command the renderer would understand), the renderer needs to know what or where your window is, thus, it asks for it then it needs to know what drive would work on it, you can put -1 to use the default one/the one you previously used, then the command.

```
//CREATE TEXTURE
SDL_Texture* texture = IMG_LoadTexture(renderer, "FILE");

```

You created a texture variable, `IMG_LoadTexture` has the ability to load a picture and immediately convert it into a texture, it asks for your renderer since the renderer is the one that would works on it and it also asks for the file name let's say your file's name is "texture.png" then you just input that in that area, the file should be placed inside the the folder that contains the other header files.

Now just loading a texture won't give you power over it, what you want now is to gain control over it, that is why we create an rect:

```
SDL_Rect texture_rect;
texture_rect.x = 0; //the x coordinate
texture_rect.y = 0; //the y coordinate
texture_rect.w = 50; //the width of the texture
texture_rect.h = 50; //the height of the texture

```

Now, our texture should display the the top left corner since the coordinate is at (0,0) and it should be 50x50, which would make the texture be shaped like a square

```
// GAME LOOP AREA
SDL_RenderClear(renderer); //clears the renderer
SDL_RenderCopy(renderer, texture, NULL, &texture_rect);
SDL_RenderPresent(renderer); //updates the renderer

```

`SDL_RenderCopy` is responsible for making the gameloop understand that there's something that wants to be rendered, inside the parentheses are (the renderer's name, the name of the texture, the area it wants to crop but you can leave this as NULL if you don't want the texture to be cropped, and the texture's rect)

Don't forget to destroy the texture in the end to avoid memory leaks (use something like `SDL_DestroyTexture(texture)` ) \<- put this outside the gameloop so that when the gameloop exits, then this would be read.
> 12 votes

# Answer
The renderer cannot accept `SDL_Surface*`'s so you will have to convert them to textures by

`SDL_Texture* texture = SDL_CreateTextureFromSurface(render, surface)`

The renderer is basically an `SDL_Window*` that is hidden from the user where the graphics are rendered at first, then the rendered data gets switched with the window's data

To do this you must use `SDL_RenderPresent(render)`

To clear the window data, you must use `SDL_RenderClear(render)`

To copy the texture to the render, you must use

`SDL_RenderCopy(render, texture, &src, &dst)`

where `src` is the `SDL_Rect` area that you want to extract from an image, if you pass `NULL`, the whole image will be copied

and `dst` is where you want the image to be rendered at, if you pass `NULL`, it will be rendered at 0,0

there is a function called SDL\_RenderCopyEx() which is the same as the other one but can rotate a sprite rendered
> 1 votes

---
Tags: c++, sdl, graphics-programming
---


title: How can I implement a main menu?

text:
# Question
Title: How can I implement a main menu?
I have been following the tutorials at http://lazyfoo.net/tutorials/SDL/index.php and although they are all very well written and I have learned more than I would have on my own, I am not sure how to go about building a basic main menu that has the normal "new game," "settings" and "exit" options.

How would I handle such a menu inside of a normal game loop?

# Answer
> 7 votes
As congusbongus notes in his answer, many games benefit from dividing content into "scenes". A scene might represent a particular level, a room, a minigame, or lots of other possibilities, depending on the game. In such a system, menus can be implemented as scenes as well, and this works well for simple games with only a few menus.

Personally, I like to think of menus as overlays. Most games don't need more than one scene active at a time, but benefit from having a menu open while the game is running, and knowing what menu you came from if there are sub-menus. If you treat menus and scenes the same and don't allow multiple scenes to coexist, it's difficult to make a pause menu, or have menus that can be reached in multiple ways.

I find the most useful representation for menus is a stack. Such an implementation might look like this:

* When the game (application) starts, push the main menu onto the stack.
* When a sub-menu is selected, push it onto the stack.
* When a "back" button is pressed, pop the top menu from the stack.
* When the actual game begins (scene is loaded), pop all menus.
* If the stack is not empty, render its top menu after you render your current scene (if there is one). Of course, if the top menu is opaque, you can skip drawing the current scene to save time, but having a pause menu with a transparent/translucent background can be nice.
* If the menu stack is empty, dispatch input events to the current scene, otherwise, dispatch them to the top menu in the stack.

For example, if you have a main menu, high scores menu, settings menu, pause menu, and end-of-game summary menu, you might be able to get to the settings menu via the main menu or pause menu, but you can return to wherever you came from without having to deal with any special cases or complex state tracking. You can even return to the main menu from a paused game and later return to the game by having a "return to game" option on the main menu that is deactivated and invisible if the menu stack has a size of 1 (the main menu)

# Answer
> 3 votes
The typical way to implement this is using **game screens** or **scenes**.

* Your game loop updates and draws the current screen, whatever that may be
* Your menu(s) live in one screen or set of screens, your game world lives in another screen
* Choosing certain menu options (e.g. start game) switches the current screen

In this sense, it's just a plain programming problem. The difficulty is in the details though, such as how to draw and layout the menu, how to strike a balance between making it easy to modify the menu and giving it power (i.e. perform arbitrary changes to your game), handling input, different menu control types and so on. I suspect you'll have plenty of follow-up questions once you start.

For more details (including some sample code), check out this: http://www.gamedev.net/topic/521366-making-a-menu-with-sdl/

You could also try a menu library that supports SDL such as guichan. I haven't used any myself so I can't recommend, sorry.

# Answer
> 1 votes
I'm not sure if you'd like my method but based on what you said, "New Game, Settings, Exit" then I'm assuming the menu would be the main screen right? I'm a texture user , by the way, and not a surface one.

```
//Let's assume that your method of input is a mouse
//since this is long, you can create a class for this then recall it in the gameloop

//WE CREATE THE COORDINATES OF THE MOUSE
int Mx = 0;
int My = 0;
bool play1 = false;

//Let's make the menu's background
SDL_Texture *background = IMG_LoadTexture(renderer, "FilePath");
//Now the Background's rect, it should give us power to control it's size and location
SDL_Rect background_rect;
background_rect x = 0;   //X COORDINATE
background_rect y = 0;   //Y COORDINATE
background_rect w = 400; //WIDTH
background_rect h = 400; //HEIGHT
/*Now, our background should start from the top left since it's coordinates are in
(0, 0) and it should stretch 400 to the right and 400 down making it a square, 400X400*/

//The New Game button
SDL_Texture *newGame = IMG_LoadTexture(renderer, "FilePath");
//The game button's rect
SDL_Rect newGame_Rect;
newGame_Rect.x = 0;
newGame_Rect.y = 100;
newGame_Rect.w = 50;
newGame_Rect.h = 25;

//I'll just skip to the exit button
SDL_Texture *exit = IMG_LoadTexture(renderer, "FilePath");
//The exit button's rect
SDL_Rect exit_Rect;
exit_Rect.x = 0;
exit_Rect.y = 200;
exit_Rect.w = 50;
exit_Rect.h = 25;

IN THE GAME LOOP

SDL_GetMouseState(&Mx, &My); //This would constantly input the the x coordinate into Mx and the y coordinate of the mouse into My

//WARNING: THIS AREA COULD BE A BIT TRICKY IF YOU DON'T UNDERSTAND COLLISION

//Let's make an if statement that checks if the mouse is touching the New Game Button

if (Mx >= newGame_Rect.x && Mx <= newGame_Rect.x + newGame_Rect.w && My >= newGame_Rect.y && My <= newGame_Rect.y + newGame_Rect.h)

/*The if statement basically checks if the pointer is inside the area of the rect,
it may look confusing but it's actually pretty simple, since (0, 0) is at the
top-left and the going down is +y then there's no negative coordinate, that also goes
for the texture, the top left point is the origin, so basically, it checks if
the mouse's x-coordinate is greater than the origin but less than the origin plus
width (newGame_Rect.x + newGame_Rect.w to make sure that the pointer is inside, the
same goes for the y coordinate*/
{
SDL_SetTextureColorMod(newGame, 250, 0, 0 );
    /*This would make the texture change color if the mouse is inside the rect,
    it takes the name of the texture which is newGame, and the following variables
    are the r, g, and b, if you were to make all except red into 0 then the texture
    would be tinted red, I assumed you wanted the player to know that it is hovering
    over the new game so I added this as a bonus*/

if (event->type == SDL_MOUSEBUTTONDOWN)  //this calls an event, I assume that you already know how to make an event right?
{
    if (event->button.button == SDL_BUTTON_LEFT)
    {    //if it is pressed then play1 becomes true which you could use to initiate the newgame
        play1 = true;
    }
}
}
else
{
SDL_SetTextureColorMod(Gettexture(), 250, 250, 250);
    // Tints the texture white if the cursor isn't over the button
}

```

This should give you a proper knowledge over the menu, you could now create your own exit button and just make it execute another bool that could break your gameloop, I didnl't make a sample for the exit since it would just be similar to the NewGame button.

Happy Coding :)

---
Tags: c++, 2d, sdl, game-loop
---


# Question
Title: Libgdx. Converting Screen Click Coordinates into World Coordinates for 2D Game
I'm using the `InputHandler`'s `touchdown` method. It gives me my `screenX` and `screenY`. Is there a simple way to convert screenX and screenY to world coordinates? By my understanding, `InputHandler` returns the coordinates in relation to your screen.

# Answer
Sure.

Take your camera matrix and unproject it (or invert it). This can be done in libgdx like so:

```
 Vector3 worldCoordinates = new Vector3(screenX, screenY, 0);
 camera.unproject(worldCoordinates);

```

The documenation can be found here.
> 5 votes

---
Tags: android, libgdx, mobile
---


# Question
Title: Why do I have to switch T(v) texture coordinates while importing OpenGL to Direct3D?
I am importing my code from OpenGL to Direct3D. My `D3DTS_PROJECTION` uses `D3DXMatrixPerspectiveFovRH`, and my `D3DTS_VIEW` uses `D3DXMatrixLookAtRH` to set a view equal to OpenGL's view. My question is why do I have to switch all of my `1.0000` Tex(v) texture coordinates to "minus value" in D3D to get equal texture mapping as in OpenGL.

OpenGL:

```
//T(u)   T(v)
1.0000,  1.0000,
0.0000,  1.0000,
1.0000,  0.0000,
1.0000,  0.0000,
0.0000,  1.0000,
0.0000,  0.0000,

0.0000,  1.0000,
0.0000,  0.0000,
1.0000,  1.0000,
1.0000,  1.0000,
0.0000,  0.0000,
1.0000,  0.0000,
// ...

```

Direct3D:

```
//           T(u)     T(v)
D3DXVECTOR2( 1.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f, -1.0000f)
D3DXVECTOR2( 1.0000f,  0.0000f)
D3DXVECTOR2( 1.0000f,  0.0000f)
D3DXVECTOR2( 0.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f,  0.0000f)

D3DXVECTOR2( 0.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f,  0.0000f)
D3DXVECTOR2( 1.0000f, -1.0000f)
D3DXVECTOR2( 1.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f,  0.0000f)
D3DXVECTOR2( 1.0000f,  0.0000f)
// ...

```

Is it because Direct3D's origin (0.0) of texture coordinates lies in different place than in OpenGL?

# Answer
For texture spaces, in Direct3D (0, 0) is top-left, in OpenGL (0, 0) is bottom-left. Therefore the v-coordinate will be upside down in one of these APIs.

However, I wouldn't recommend negating the v-coordinate as this will only work if you're using a sampler with wrapping.

You can fix the v-coordinate as follows:

```
v = 1.0f - v;

```
> 4 votes

---
Tags: opengl, textures, directx, directx9
---


title: Cocos2D - Fill a Sprite with a pattern

text:
# Question
Title: Cocos2D - Fill a Sprite with a pattern
I have a CCSprite with a certain shape in Cocos2D and I would like to fill it with a pattern, as seen here:

I've seen a lot of examples where they fill a rectangle with a pattern, or even a dynamically-created polygon, but not another CCSprite. Is it possible to do so?

Thanks!

# Answer
You have to do two things here:

1. Create a repeating sprite
2. Mask it with the shape

For the repeating sprite you will need a texture that has POT (Power Of Two) sides, e.g. 256x256. When you load your tiled texture you need to set its parameters to repeat:

```
CCSprite* sprite = [CCSprite spriteWithFile:@"tiled_tex.png"];
ccTexParams params;
params.minFilter = GL_LINEAR;
params.magFilter = GL_LINEAR;
params.rapS = GL_REPEAT;
params.wrapT = GL_REPEAT;
[sprite.texture setTexParameters:&params];

```

Now when you set your sprites content size it will draw a repeated texture.

Masking part is a bit trickier it would be easiest to have a shader that takes as a parameter the masking texture. Since it is a bit bigger task, here is a mask shader for cocos2d someone else made: Mask Shader for Cocos2D. I have not used this code, but from the looks of it it should work quite well.
> 1 votes

---
Tags: textures, sprites, rendering, cocos2d
---


title: Exception in thread "LWJGL Application"

text:
# Question
Title: Exception in thread "LWJGL Application"
I'm using libGDX for my android game in which I'm trying to use bitmap fonts. I have created .fnt and .png bitmap files using Bitmap font generator of angel code.Both .fnt and .png have been placed under same folder /asset/data in my project.

Now when I try to run my project I get exception errors. Here is my sample code -

```
FileHandle handle = Gdx.files.internal("data/calib.fnt");
FileHandle handle2 = Gdx.files.internal("calib_0.png");
font = new BitmapFont(handle,handle2,true);
font.draw(batchmaker, "abcdef", x,y);

```

The error on console looks like this (showing only relevant lines):

> Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Error loading font file: data/calib.fnt . . . at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.(BitmapFont.java:809) Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Invalid font file: data/calib.fnt

I do not believe this error has something to do with issue with paths, because it gives me different errors when I play around by changing the paths.

I have been trying to fix this since almost last 2 days but couldn't come up with a solution. Can someone please let me know what could be the problem or am I missing something?

**Edit:** Or could there be some checks in which the parameters of calib.fnt is not passing (due to upper/lower case name mismatch with libGDX lib files) ? Please help!

# Answer
The issue was with the bitMap font generator tool I was using. It was BitMap Font generator from angel code. Now I switched to hiero and it works magically.
> 0 votes

# Answer
I will show you **all** the procedure of implementing BitmapFonts in LibGdx :

1. Download Hiero : https://code.google.com/p/libgdx/downloads/detail?name=hiero.jar&can=2&q=
2. Open it and generate your font (create **.fnt** and **.png** files)
3. In LibGdx :

```
BitmapFont font;

font = new BitmapFont(Gdx.files.internal("fonts/font.fnt"), Gdx.files.internal("fonts/font.png"), false);

font.draw(spriteBatch, str, fX, fY);

```
> 0 votes

# Answer
You should either not pass the .png file at all in your `BitmapFont` constructor (since the glyph images for your font are loaded from the font .png provided along with the .fnt file anyway, if you don't indicate some other texture region), or at least indicate the same path in the `FileHandle` initializing row as in the one for the .fnt file. You said they are both in the same location, so make it to be the same in your code as well (one is `"data/calib.fnt"` and the other one is `"calib_0.png"`).
> 0 votes

---
Tags: libgdx
---


# Question
Title: How to store an array into a texture and sampler the texture in vertex shader correctly?
I'm a new learner about OpenGL and GLSL. I'm coding a program in which i wanna store a group of datas in a texture and get the data by sampling the texture in vertex shader. Then i want to set the datas as the y coodinates of terrain positions. But i get a trouble that it's failed and i can't get a correct value\___all the y coodinates are 0.

The main code is below:

```
GLuint  terrainShader;      // The perspective demonstration shader
GLint   locMVP,locTex;                 // The location of the uniform in vertex shader

GLuint  vao;                    // The VAO
GLuint  vertexBuffer;
GLuint elementBuffer;
GLuint vertexTexture;

const int n=127;
float verteces[n*n*2];// vertex array
GLuint vIndexFine[(n-1)*2*n];//index array
GLsizei countFine[n-1];
GLvoid* offsetFine[n-1];

float *data=new float[n*n];
    terrainShader = gltLoadShaderPairWithAttributes("terrain.vp", "terrain.fp", 1,
                                    GLT_ATTRIBUTE_VERTEX, "vVertex");

    locMVP = glGetUniformLocation(terrainShader, "mvpMatrix");
    locTex = glGetUniformLocation(terrainShader, "vertexTexture");

    //creat a terrain with size of n*n
    for(int i=0;i<n;i++)
    {
        int sum=i*n;
        for(int j=0;j<n;j++)
        {
            verteces[(sum+j)*2]=float(j);
            verteces[(sum+j)*2+1]=float(i);
        }
    }
    //initialize the index array
    for(int i=0;i<n-1;i++)
    {
        if(i==0)                //the first line
        {
            for(int j=0;j<n;j++)
            {
                vIndexFine[2*j]=j;
                vIndexFine[2*j+1]=j+n;
            }
        }
        else
        {                   //if it's not the first line,then just add n to get the indexes of new line
            for(int k=0;k<2*n;k++)
            {
                vIndexFine[i*2*n+k]=vIndexFine[(i-1)*2*n+k]+n;
            }
        }
    }

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verteces), verteces, GL_STATIC_DRAW);
    glVertexAttribPointer(GLT_ATTRIBUTE_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray(GLT_ATTRIBUTE_VERTEX);

    glGenBuffers(1, &elementBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vIndexFine), vIndexFine, GL_STATIC_DRAW);
        //initialize data array with random integers between 1 and 100
    for(int i=0;i<n*n;i++)
        data[i]=float(rand()%100)/100.0;

        //creat a texture and store data
    glGenTextures(1, &vertexTexture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, vertexTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, n,n, 0,GL_RED, GL_FLOAT, data);

    //compute every trianglestrip's indexcount and offset
    int temp=n*2*sizeof(GLuint);
    for(int i=0;i<n-1;i++)
    {
        offsetFine[i]=(void*)(temp*i);
        countFine[i]=GLsizei(n*2);
    }

    glUseProgram(terrainShader);
    glUniform1i(locTex, 0);

    modelViewMatrix.PushMatrix(viewFrame);
    modelViewMatrix.Translate(-n/2.0, -10.0f, -n/2.0);
    glUniformMatrix4fv(locMVP, 1, GL_FALSE, transformPipeline.GetModelViewProjectionMatrix());
    glMultiDrawElements(GL_TRIANGLE_STRIP,countFine,GL_UNSIGNED_INT, (const GLvoid**)offsetFine,n-1);
    modelViewMatrix.PopMatrix();

```

the vertex shader:

```
#version 410

uniform mat4    mvpMatrix;
uniform sampler2D vertexTexture;
in vec2 vVertex;

void main(void)
    {
    vec2 vTexCoords=vVertex/127.0;
    float height = texture2DLod(vertexTexture, vTexCoords,0.0).x*100.0;
    vec4 position=vec4(vVertex.x,height,vVertex.y,1.0);
    gl_Position = mvpMatrix * position;
    }

```

i think the mistake must be the part of storing datas in application or the part of fetching datas from the texture in vertex shader. can sombody point it out for me?

# Answer
> 3 votes
Try setting the texture's minification filter to `GL_NEAREST` or `GL_LINEAR` after `glTexImage2D()`:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

```

The OpenGL default is to use mipmaps and you didn't send any which makes the texture incomplete and will disable that texture image unit.

Then you can use`texture(vertexTexture, vTexCoords)` inside the shader instead of the deprecated `texture2DLOD()` version with the explicit LOD access.

---
Tags: opengl, glsl, terrain
---


# Question
Title: Should "games played this week" be computed from a fixed or running time span?
I'd like to create a leaderboard that shows how many games each player has played. This works fine for the "all time" section in Game Center, since I can just submit the total number. But what I really want to display is the number of games each player has played in a week, not for all time.

As I understand it, I would have to calculate the weekly numbers myself (if I submitted the all-time totals, the weekly tab in Game Center would still just show the total all time numbers from that week, not the weekly totals).

What would be the best way to do this? Count a user's tasks beginning on Monday, and reset them on Sunday? Or have everyone on their own unique 7 day timer?

# Answer
> 2 votes
In general, the big disadvantage of the fixed window approach (Monday through Sunday) is that new players will need to work very hard to achieve a competing leaderboard count in that first week, relative to old players, unless they happen to start playing on the first day of your score tracking period).

The disadvantage of the running window approach is that you can't even post a new player's count to the leaderboard for a week, *and* all players are potentially using a completely different time window.

The first disadvantage is much smaller than the second: it applies only once, whereas the disadvantage for the running window approach lingers for the lifetime of your game. This makes it a lot more difficult to perform aggregation reports on data for a player's lifetime. For example, if you are generating reporting information purely on the leaderboard statistics (so you don't have the origin of each player's unique week window), getting information about play counts per month is going to be tricky since months are not all a fixed time period.

Consequently, you should track these events using a fixed time window.

---
Tags: ios, game-center, statistics
---


# Question
Title: How can I obtain a HBITMAP or HICON from a Direct2D bitmap?
Is there any way to obtain a `HBITMAP` or `HICON` from a `ID2D1Bitmap *` using Direct2D? I am using this function to load the bitmap.

The reason I ask is because I am creating my level editor tool and would like to draw a PNG image on a standard button control.

I know that you can do this using GDI+:

```
HBITMAP hBitmap;

Gdiplus::Bitmap b(L"a.png");
b.GetHBITMAP(NULL, &hBitmap);

SendMessage(GetDlgItem(hDlg, IDC_BUTTON1), BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);

```

Is there any equivalent, simple solution using Direct2D? If possible, I would like to render multiple PNG files (some with transparency) on a single button.

# Answer
Direct2D bitmaps are hardware device dependent resources and not generally easily accessible from the CPU side of the system. They don't even have lock or map methods. This makes it difficult to get at the pixels of a bitmap; it's not really designed to be used that way.

If you only have the D2D bitmap object available, you can render it to a `HWND`-backed render target, and from there you can get the `HWND`'s device context and with that you can create a compatible bitmap and blit from the render target DC to your new bitmap's DC. This is obviously exceedingly clunky.

*However*, in your link you indicate that you are passing through the WIC bitmap source object to load your pixel data. If you cache that object for your level editor, you can more easily obtain the pixels, since `IWICBitmapSource` has `CopyPixels` method you can use to dump the bitmap data into a raw byte array (although the `Lock` method may be better if you want to avoid a lot of copies). From there you can create an `HBITMAP` or `HICON` from the raw bytes in the traditional fashion.

(If your bitmap ended up backed by a D3D texture or DXGI surface instead, you could also use the pixel access methods of those interfaces.)
> 1 votes

---
Tags: c++, direct2d
---


# Question
Title: How do I programmatically remove an image's background color?
I have a sprite sheet (image) and want to draw it on screen.

```
image  = sprite sheet image
x      = player x position
y      = player y position
width  = player width
height = player height

public class main extends japplet
{
    ...

    public void paint(Graphics g)
    {
        g.drawImage(image, x, y, x+width, y+height,
                   0, 0, 40, 40 ,sprite_sheet.m1);
    }
}

```

On the sprite sheet, I have the image of a player with a blue background color. Calling `drawImage` shows the blue background too. I could remove the color with Photoshop, but I really don't want to, because it would remove part of my player.

Can I remove the background color with Java code?

# Answer
It seems you want to do some color keying, which Java cannot do on the fly with the Graphics2D library you are using. Due to this, you will need to create the alpha channel yourself, move to something that has color key support (SDL). Most engines nowadays do not support this operation as it is computationally expensive and you will need to do this "on the fly" to convert it anyway.

I have a nice answer here on why you should use alpha transparency instead.

If you have a large code base or insist on writing your rendering back end in Java2D with color key mapped images, then you can always decide to do something by hand. As linked in the comments, there is a a good post on StackOverflow on how to do this here.
> 2 votes

---
Tags: java, image, transparency, color
---


# Question
Title: Detect obstacles in path on a tile-based map
I'm creating a 2d game with a tile-based map, but smooth movement. I currently use A\* in combination with some other tricks for pathfinding, and one issue what I've been dealing with is getting the units to move smoothly despite tile-based pathfinding.

My solution at the moment is the use raycasting to determine if there is an obstacle between a unit and its target. If there is, it uses A\*. Otherwise, it just sets its next move directly as the coordinates of its target. In the case that it uses A\*, I also use raycasting to determine which point in the path the unit should move to next, by finding the nearest point in the path that is not obstructed from the units current location, and setting that as the next move. This is necessary so the unit doesn't have to move in a jerky fashion based on the tile-based path that the A\* found.

Raycasting is faster than A\* every time, but it still has some overhead with a large number of units since it checks every point on the line in small increments. (More so since I'm doing double raycasting each time to account for the size bounds of the unit)

**My question is: Is there a better algorithm than raycasting to determine if there is an obstacle between two points (independent of the tiles structure) on a tile-based map? My thought is that there is some way to take advantage of the tiled nature of the map.**

# Answer
By using continuous agent positions on a tiled map, the translation from a tile-list path to a points-list path is best served by a Funnel Algorithm. Basically doing what you have been, but only checking intermediate tile-vertices on the path that are next to an obstacle (which will naturally be where the tile-path has a bend).

I see ray-tracing as fundamental to discovering unobstructed path segments on your polygonal map, but one can use broad phase checks to potentially speed it up. Its sorta like having bounding boxes for the obstacles, if the tile stores yes/no/maybe clearance then the ray can return a result from intersecting the tiles (which are cheap to find due to regular pattern) and not need to check the contained (arbitrary polygon) obstacles.
> 0 votes

---
Tags: collision-detection, path-finding, tilemap, raycasting
---


title: How do I animate a tilemap in Flixel?

text:
# Question
Title: How do I animate a tilemap in Flixel?
I am trying to animate a tilemap using Flixel 2.55. I found this code that apparently enables the use of sprites as tiles.

*To my understanding*, this loops over the tilemap's graphic and replaces the tile's pixels with the sprite's pixels each time they change. I have implemented the class and it's working, but not completely; the tiles get replaced, but do not animate unless the camera moves. Here's is the relevant part from `LevelLoader.as`, which only instantiates the `AnimatedTilemap`s (piece of code from forum) and pushes sprites into an array:

```
// AnimatedTile is just an extended FlxSprite
private var _waterTop1:AnimatedTile;

// Create ground tilemap
_groundTilemap = new AnimatedTilemap();
_groundTilemap.loadMap(_rawXML.Ground, Assets.OverworldGround, 8, 8);
FlxG.state.add(_groundTilemap);

_waterTop1 = new AnimatedTile(8, 8, Assets.WaterTop, 100);
// .Animate only adds and plays an animation, with a startAtFrame param.
_waterTop1.Animate('run', [0...47], 10, true, 0);

```

It seems as though the sprites are updating. I tried tracing the `update()`s, and they are running for both the sprites and the tilemap. The sprites are even changing frames. Using only `AnimatedTile`s and *hard*-placing them (giving a `x` and `y`) works and animates. What troubles me is that they only update when the camera moves.

I've been stuck on this for a week now. I am also open to other solutions for animating tilemap tiles.

# Answer
> 1 votes
You might need to mark the buffer as "dirty". Looks like you can do this via setDirty().

These threads touch on "dirty" a bit:

My understanding is that Flixel has some optimizations that pre-compute values for drawing and it will only recompute them when the "dirty" flag is set. In your case moving the camera is probably marking the tilemap as "dirty", hence it updates when the camera moves.

---
Tags: animation, tilemap, flixel
---


title: Moving background animation

text:
# Question
Title: Moving background animation
How can I create a moving background animation with corona like in this game? https://www.youtube.com/watch?v=dyXxyApKtvM

it looks like it uses a single image and stretches it in a loop. I've search over corona docs but can't find anything that would enable me to manipulate an image in such way.

# Answer
You are looking for a Scrolling Background. You can follow this tutorial for Corona: http://thatssopanda.com/corona-sdk-tutorials/create-a-scrolling-background-going-up/

It uses at least 2 images that are moved at the same speed, when one of the images goes outside the viewable area, it is moved to the other side of the screen to create that "continuous scrolling effect"

Hope it helps
> 0 votes

---
Tags: corona-sdk, image-effects
---


# Question
Title: Adding a new highscore before or after an equal score?
I'm making a highscores list for my 2048 replica. An entry in the list consists of a name and a score (e.g. "John" and 2100.) When I add a new entry, the code runs through the list and inserts the new entry when the score for the new entry is greater than the currently indexed entry. So imagine this list:

```
Roman   17000
Sergei  12500
Dean    8000
Andrew  1400

```

If John was inserted into the list, the new list would look like:

```
Roman   17000
Sergei  12500
Dean    8000
John    2100
Andrew  1400

```

The question is, what do I do when inserting the entry for "Steve" whose score is 8000. Does he go before or after Dean? Is there a convention for this?

# Answer
Though it is (to my knowledge) most common for newest score to be entered at the top, I would argue that the OLDEST score would deserve the first position.

For this simple reason:

The first player to achieve the high score had LESS TIME to achieve that score, than people making later/following attempts, thus deserving a higher position as (s)he was the quickest to achieve the level of skill required to make that score.

Inspired by this you might track time spent in each game, and sort the list so that LEAST time spent on creating a similar score goes FIRST.
> 7 votes

# Answer
Just sort them alphabetically.

And if you have numbers to call out the position, be sure to handle the tie case appropriately so you aren't calling one person 3rd and another 4th even though it's the same position.
> 6 votes

# Answer
I don't believe there is a standard. From what I've seen, and what I use, who ever got to the top first should keep their position.
> 2 votes

# Answer
If you're looking to encourage competition and activity, it might make more sense to have the more recent score replace the older one. Players wouldn't be able to simply achieve a high score and become complacent, because their score is at risk of being replaced at any point.

In fact, if you really wanted players to rue being replaced, you could have the higher scores on the list displayed in a style that is more rewarding than the older ones (e.g. more colorful, stylized, etc.) This way when a player's score is tied, not only do they move down, but they also lose whatever superficial qualities were associated with that spot on the list.
> 2 votes

# Answer
Tradition says new scores on top. No idea why, though... now that I think about it, it makes more sense the other way around, you should award a player for achieving an equal score in less time. But that's just my personal opinion, in the end the choiche is up to you :)
> 2 votes

# Answer
Now the choice is up to you, but I would spend some time to add more to the highscore board so it can track different achievements of a player throughout the play-time, and then compare them to the player who has equal score.

Placing Steve on top would be unfair for Dean. Placing Steve below Dean will make Steve angry. One of many things that might lead to a forum war. It's a minor but you got my point.
> 1 votes

---
Tags: game-design, leaderboards
---


# Question
Title: Finding the correct speed for AI to turn to reach goal
I have a ship that travels at max speed `maxSpeed` and can turn `rotationSpeed` degrees per second. The ship always moves in the direction it is facing which means that the faster the ship is travelling the larger its turning radius is.

I know my position, and rotation and the target's position.

What I would like to figure out is whether a target is inside my turning radius at this speed, or better, what is the maximum speed I can travel at is in order to make the turn to the target without continually circling around it.

Is there an efficient(ish) way to do this?

Here is what I am thinking so far: because I know how far I am travelling per step and how much I am rotating per step, I can figure out where I will be in the next two frames. My current position is p1, my next position is p2 then p3. I can take the perpendicular bisectors of (p1, p2) and (p2, p3). Their intersection point will give me the center of a circle. I can then test if the target is in that circle.

I'm unsure if this will work in 3D (I'm unsure how to calculate a sphere with my inputs). This solution also doesn't help too much with finding the right speed at which to travel, I would have to try a few times with different speeds to find a reasonable one.

Can anyone shed some light on a better solution?

# Answer
There are two ways an AI controlled unit with a bound rotation speed and an adjustable movement speed could reach a goal.

First, lets consider the challenge we are presented with so we could understand it better:

If the player is moving and rotating in constant speeds while trying to reach a goal that is on its right or left side, it will move in circles forever, never facing it's goal. The two areas that the player will circle are marked in red above.

The circular area marked in red can be computed like this:

```
radius = movementSpeed / rotationSpeedInRadians;
circlesCenterX = unitX + cos(unitAngle + / - PI) * radius;
circlesCenterY = unitY + sin(unitAngle + / - PI) * radius;

```

This results in the red circles' position and radius. We can use this to determine if a certain goal is outside the reach of the AI controlled unit if it continues to turn towards the goal's direction.

To find out if a certain item is within one of the circles, we simply calculate the distance from the circles's center:

```
if ((circleX - goalX)^2 + (circleY - goalY)^2 < radius^2) //goal is within red circle

```

There are two possible solutions for this:

1.

Build up some distance until the goal is outside the circular red area and then turn around in a u-turn like fashion. This is simple, let the unit keep moving until the check returns that the goal is not within this circle. Then you can turn around.

The other option require a bit more work to compute:

We draw an imaginary line between the AI unit and the goal. Using the angle between them:

```
angle = Math.atan2(goalY - unitY, goalX - unitX);

```

Now you need to do the following in order to compute the correct speed:

```
correctSpeed = rotationSpeedInRadians * (distance / 2) / cos(angle);

```

In order to get it working in the 3d case:

Find the plane on which the following three points reside:

1. The goal point.
2. The position of the AI unit in the previous frame.
3. The current position of the AI unit.

You could use that plane to compute the speed in the 2d way. You just need to convert the dots from their 3d values to the 2d values embedded on their common plane.

You might want to use this:

How to convert a 3D point on a plane to UV coordinates?
> 18 votes

---
Tags: c#, unity, ai, steering-behaviors
---


# Question
Title: Is it possible to develop web-based games using Corona SDK?
Some clients asked me to develop 2D web-based games and later on they might want to release those games on mobile platforms.

I know Corona and I don't want to rewrite my code twice. Is it possible to create web-based games using Corona (the free SDK)?

# Answer
> 1 votes
Currently Corona is beta testing Corona Cards. It will support embedding Corona in a Html document. (AKA Corona on web!)

Check out their site for more: http://coronacards.com/

# Answer
> 2 votes
No, Corona does not build for web platforms.

---
Tags: lua, web, corona-sdk, webapp
---


title: libgdx: Rotate sprite on 3d plane

text:
# Question
Title: libgdx: Rotate sprite on 3d plane
Im trying to create a game on a 3d plane but with 2d objects. I have a perspective camera and the ground plane drawn. I can't seem to get sprites onto it.

I am trying to render the sprites, then to rotate over the x axis up into the 3d world. Is this even possible the way I'm trying it? If not how can I go about achieving this?

What I'm going for is almost like a Paper Mario look for the game objects, but on a larger 3d plane.

# Answer
The trick is to read more libgdx documentation.

I found that Decals work like sprites and do exactly what I want. They can be created from TextureRegions just like Sprites, and easily displayed with a DecalBatch.

```
// Load a Texture
Texture image = new Texture(Gdx.files.internal(imgPath));
// create a decal sprite
sprite = Decal.newDecal(w, h, new TextureRegion(image), true);

// create a DecalBatch to render them with just once at startup
decalBatch = new DecalBatch();

```

Displaying is as easy as adding to the DecalBatch, then flushing the DecalBatch.

```
    spriteBatch.add(AssetLoader.starDecal);
    spriteBatch.add(AssetLoader.bgDecal);
    spriteBatch.flush();

```
> 4 votes

---
Tags: java, libgdx
---


# Question
Title: How do I randomly spawn objects in 2D game?
How do I randomly spawn few different sprites on screen so they're not overlapping or half visible on render. The sprites should immediately start shrinking until they disappear.

I've tried to demonstrate what I have so far using JS, however it's overlapping and not shrinking:

http://jsfiddle.net/SamuraiFox/CVX7D/

Specific to Unity, I've made these sprites prefabs and have put them into the scene from where script would spawn them into game.

# Answer
> 1 votes
You need a couple of things here -

* Something that will randomly spawn things
* Some way of knowing where sprites already exist so you don't spawn there

It looks like you have a handle on the former so I will cover the latter here.

For unity sprites you have a component called SpriteRenderer from which you can obtain the size of a sprite:

```
Vector2 size = GetComponent<SpriteRenderer>().bounds.size;

```

Assuming your pivot is in the top left corner, you can add this size to the transform.position to get the area the sprite takes up.

```
Rect objectArea = new Rect(transform.position.x, transform.position.y, size.x, size.y);

```

The Rect object has a handy method called contains. If you keep a list of all the Rects you've made, you could use that, or this method:

```
public static bool Intersect(this Rect rectA, Rect rectB)
{
    return ( Mathf.Abs(rectA.x - rectB.x) < (Mathf.Abs(rectA.width + rectB.width) / 2))
        && (Mathf.Abs(rectA.y - rectB.y) < (Mathf.Abs(rectA.height + rectB.height) / 2));

}

```

To see if the objects intersect, if they do, try another random position.

Also depending on your use case, look into particle effects (shuriken).

---
Tags: 2d, unity, textures, random
---


title: Skeletal animation with Unity2D?

text:
# Question
Title: Skeletal animation with Unity2D?
I want my character to aim with the mouse so, arms and head must move following mouse cursor and when the character is stand still it could change its stance a bit to accommodate the arms position. I used to use skeletal systems and in this situation I would use a bone that would move both arms at once but it seems Unity animation only supports tweenings. Can this be done with this system?

On the other hand how would you setup the character to easily make it follow shooting position with head and arms without moving all elements from code? As an example, if I had bones I would have set one parent bone for arms and use it to move both at once, etc. I guess IK and constrains is the way to go.

# Answer
Use the excellent Unity Sprites and Bones: https://github.com/Banbury/UnitySpritesAndBones

Didn't make it to the asset source due to being completely free and open source. It has inverse kinematics and you can use it for this use case.
> 0 votes

---
Tags: 2d, unity, animation, skeletal-animation
---


# Question
Title: Distributed Multiplayer Game Server Architecture
I'm programming a multiplayer game for mobile phones.I'm working on a distributed server architecture for handling lots of concurrent players.

Here is my architecture on my mind:

Some questions about that architecture:

1-) How can i provide a secure login on Login Server?Here is what i'm thinking:

* Client connects to login server.
* Login server sends its public key(RSA encryption)
* Client encrypts its username and password with login server's public key.Then sends that packet to login server.
* Login server verify username-password information with connecting database server.
* Login server creates auth token and sends back to client.

2-) How can i secure database queries?Also can that be so slow?Here is what i'm thinking:

* Client sends its auth token with query packet.Also client sends its random public key.
* Database server verify that auth token.
* Database server replies with encrypted(with clients random public key) reply packet.
* Client decrypt it with its private key.

3-)How can i merge game servers working like a single game server?

Am i on the right way of doing a mmo server design?I'm using Java and Kryonet library for server programming.

# Answer
> 3 votes
Do *not* have a client talk to a database server. The client talks only to the frontend game server, and *nothing* else. That server then distributes client requests to the appropriate backend server.

The frontend servers and (most) of all the other servers are distributed geographically. Not distributing the front-end server as in your diagram defeats almost the entire point of having per-region servers. The only thing you really want to share is an account server, and then only as little as possible.

Client connects to the frontend server. The frontend server then connects to the login/account server, ecommerce server, chat server, and game/map server. The servers can talk amongst themselves as needed since they're all in your private network. The only point of attack is the public frontend servers.

For communication between servers, you can usually use a message queue service of some kind, like RabbitMQ or one of the bazillion similar software packages.

There have been a number of GDC talks and paper on this issue over the years and there's no reason to invent your own architecture when they've already been designed and tested in real-world environments for you. GDC Vault free content

---
Tags: java, architecture, networking, client-server, security
---


title: How can I mock Google Play purchases?

text:
# Question
Title: How can I mock Google Play purchases?
I would like to know what best practices should I do for testing the functionality when a user buy an item/power-ups via Google Play and purchased with real money?

For example, basically, creating a simple test of purchasing and saving an item stored in the inventory during the game using a game money. (e.g. Gil from *Final Fantasy* series or Zenny from *Tron Bonne* for the PlayStation 1) I know how to make money purchase update only via game money when I'm programming in Unity3D or Eclipse w/ LibGDX library.

Now, let say I have to create a program that checks the user if actually purchase a power-up items using real money. Next, the system needs to check for online status. If connected, it will simply go to the Google Play dialog and asks the user if he/she wanted to proceed purchasing of items. If yes and the credit card balance is sufficient, then goes back to the game app and check if the boolean returns true, then item that the user is bought will be saved.

Another example is that the amount of real money will be calculated via programming and if insufficient, the user asks to add more real money value by purchasing it via Google Play. If return true, then, the real money value will be reloaded.

This concept is basically needed for game developers. However, is there a safe way to test the real money purchase test stuff without using a credit card value or something before the actual publishing of the game app in Google Play along with this feature? Is there a tutorial, start-up guide, recommendation or something for this? Please, I would like to know how will I start. Thank you.

# Answer
You'll need to setup a test account and then publish your build as a draft application in order to successfully test purchases and the workflow as a normal user would. This is what Google has to say on the matter of test accounts:

> The Google Play Developer Console lets you set up one or more test accounts. A test account is a regular Google account that you register on the Developer Console as a test account. Test accounts are authorized to make in-app purchases from applications that you have uploaded to the Google Play Developer Console but have not yet published.

http://developer.android.com/google/play/billing/billing\_admin.html#billing-testing-setup

It should also be noted Google provides some mock product IDs you can test again, these are:

* android.test.purchased
* android.test.canceled
* android.test.refunded
* android.test.item\_unavailable

These are pulled from here.

This is known as **static response testing**. Your code can query against product IDs that are known to give good responses, thus allowing you to write your code in a way that lets you test the workflow without actually making any purchases.

A lot more goes into this, so the above two links will tell you more.
> 22 votes

---
Tags: software-engineering, monetization, google-play, powerup
---


# Question
Title: How do I query a server with visible map tiles?
In my game, I need to retrieve data of items in the visible tiles based on what tiles are visible in the viewport. I am planning to make a batch AJAX request with the visible tiles, containing image tags like Google Maps. The item information will be in JSON format.

What is the best approach for this? I currently have a class that determines the visible columns/rows and offsets relative to the visible area shown.

# Answer
> 0 votes
Actually, in most cases the client does not need to "query" the server for anything. Generally in an MMO or online game. Well, it depends on your definition of query I suppose... let us take a look at this in the context of your traditional game.

**This answer assumes a stateful simulation, and not a stateless one in which a web-app might utilize (like Google Maps). This is more useful for games.**

Let us suppose we have the following diagram:

The box highlighting the character to the left of is the **viewport of a client.** This would have been determined in one of a few ways:

* The client sent up a value (resolution in a 2D game) in which they can see and the server has interpreted that and stored it
* The game has a fixed viewport for all players, decided ahead of time.

Now, how can we define this viewport? This viewport is known as the **area of interest**. When something happens in the game world that involves other items are objects, one can query this area of interest viewport to see if it applies. For example, lets consider that "Some Player" wishes to move but our client does not know about them yet.

As long as "Some Player" does not enter the box defined on our client, the client will not know anything about "Some Player" or even that they are moving. However, lets consider this:

Suddenly, the area of interest viewport is now intersecting with "Some Player". This means that updates about and items and information about "Some Player" should now be broadcast. The following should happen when area of interests update:

* If the object does not exist on the client, it should be created.
* All state should be synchronized immediately and updates that are relevant should be subscribed to

Conversely, when an object leaves one can unsubscribe and optional terminate the object in client memory.

This method can apply to a wide variety of games, including top down MMOs, FPS games, and other games where information about a certain "view" needs to be hidden.

---
Tags: javascript, tilemap, ajax
---


title: Clamping large content to smaller area

text:
# Question
Title: Clamping large content to smaller area
I'm using *OpenGL* (with *LWJGL*) in Java, but the question is language independent.

I have some region (a rectangle for simplicity), and, let's say, a big tiled map which I want to show in this area. The area is not the whole screen, I want to render something around it.

I can think of two approaches, but they are not very good and hard to do.

* Render the whole tiled map and everything else, including background and the frame, on top - leaving the window. Yes, works, but it'd be pain.
* Render only visible tiles and only the visible portions of the border tiles. This is not possible if I for example render a font using external library - there I don't have such fine control.
* Some OpenGL trick?

Please, guide me.

# Answer
> 2 votes
You should be able to use `glViewport()` to limit rendering to a specific portion of the screen. Just keep in mind that you might have to adjust your matrixes as well.

In C++, the call would be as simple as this:

```
glViewport(left, top, width, height);

```

You should find a wrapper for this in LWJGL as well.

`glScissor()` would be another alternative if you don't want to worry about transformations.

# Answer
> 0 votes
you can try drawing with a clipping mask, you could have a rectangle (or even irregular shapes) for the mask that represents that space.

looks like LWJGL has that functionality (https://github.com/mattdesl/lwjgl-basics/wiki/LibGDX-Masking).

however if you want to make some kind of minimap i think @Mario sugestion is more appropriate.

---
Tags: opengl, java, graphics, lwjgl
---


# Question
Title: Bounding Box in Monogame for mouse picking - Ray perspective
My mouse ray is screwing up precision. I don't really know how to fix it, maybe you guys can help.

problem : (5.6mg gif) https://www.dropbox.com/s/v0z67afso88hsd1/perspective\_ray.gif

how i create the mouse ray:

```
 private Ray GetMouseRay(GraphicsDevice gd, ref Matrix view, ref Matrix proj)
    {
        //create source positions
        // i dont really understand why the 0 and the 1, since the near/far clip plane are totaly diferent, but from experimentation, this is a must
        Vector3 nearsource = new Vector3((float)MousePosition.Value.X, (float)MousePosition.Value.Y, 0.0f);
        Vector3 farsource = new Vector3((float)MousePosition.Value.X, (float)MousePosition.Value.Y, 1.0f);
        //Console.WriteLine("nearsource :" + nearsource.ToString() + " farsource :" + farsource.ToString());
        //Matrices needed are the view proj and this world
        //we are positioning the mouse ray in the origin(model origin, its a 3Dspace ray)
        Matrix world = Matrix.CreateTranslation(0, 0, 0);

        //unproject mouseposition in the clipping planes
        Vector3 nearPoint = gd.Viewport.Unproject(nearsource, proj, view, world);
        Vector3 farPoint = gd.Viewport.Unproject(farsource, proj, view, world);
        //Console.WriteLine("nearPoint :" + nearPoint.ToString() + " farpoint :" + farPoint.ToString());
        // Create a ray from the near clip plane to the far clip plane.
        Vector3 direction = farPoint - nearPoint;
        direction.Normalize();
        return new Ray(nearPoint, direction);
    }

```

How i am drawing the ray: CDebugShapeRenderer.AddLine(mouseRay.Position, mouseRay.Position * mouseRay.Direction * 1000, Color.Red);

how i am calculating the Obb:

Bounding Box in Monogame for mouse picking

How i am calculating the collision: Line: 349 https://github.com/CartBlanche/MonoGame-Samples/blob/master/CollisionSample/BoundingOrientedBox.cs#L349

So how can i create a mouse ray that is accurate? or remove that perspective somehow.

Roger.

Edit: I forgot to add the matrices used

```
 proj = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, this.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000.0f);
 view = Matrix.Identity;

```

# Answer
I totally forgot about this, so the problem was on how my view matrix was built.

So my view port was located just in front of the ray cast, messing everything up, i was projecting into the right place, i was just looking at it wrong.

I just needed to adjust my view matrix and done.
> 1 votes

---
Tags: graphics, monogame, mouse, raycasting, bounding-boxes
---


# Question
Title: Developing a general use multiplayer API
I'm tasked with the development of a general use multiplayer API in JavaScript, with a Node.js back-end. The goal of the API is to provide a service to JavaScript mobile game developers so they can develop multiplayer games with an easy to use API and existing back-end.

The project also includes the development of implementations, a Node.js server and a test game, otherwise I can't test it ofcourse. So it's more accurate to call it the development of an entire library.

The problem I'm having is trying to figure out how to provide a nice mechanism for game synchronization. The library can provide room- and connection-management, friendlists, registration and soforth because those things are using the same mechanism in every game. However, game synchronization logic can be very game-specific and that is absolutely not allowed in a general use library and server.

I'm using the following libraries/frameworks for development:

* Node.js as a game server.
* Socket.io on client- and server-side for websocket communication.
* Require.js client-side to enable modular development.
* Redis as a database for persistent storage.

To clarify the goal of the library:

* Support for a wide range of games, from a turn-based strategy game with 100 syncable objects to a multiplayer top-down shooter where latency is of the utmost importance.
* No client has to act as 'server' of some sort.
* Minimize manual setup client-side.
* Accurate synchronization without synchronizing the entire gamestate.
* Server-client architecture without the server containing game-specific code.
* Shouldn't pose restrictions to the developer and shouldn't demand certain coding practices.
* Provide an easy to use abstraction to use the generic synchronization mechanism.
* The whole range of games has to be supported by the same generic server logic.
* Lag compensation must be automatic in the API or on the server, but not game specific.

So for the main question: is this possible or should I just provide a way to easily cast, multicast and broadcast messages, and leave the actual synchronization mechanism to the developer? How would you go about it?

# Answer
It would be hard (and probably overkill) to try to provide anything besides casting, multicasting and broadcasting of generic messages for real-time multiplayer games.

You could even make it more generic by creating simple key-value (string-JSON) room storage behind websocket service with operations like:

* set(key, value)
* get(key)
* observe(key)
* maybe something like setReadOnly(key, bool)
* or more sophisticated permissions API
* maybe API for operations on arrays

It would be easy to use it as a broadcast by observing the same key ("/msg/broadcast") in each client. With API like that you can even have multiple broadcast channels (keys like "/event/broadcast" and "/chat/broadcast"). It could be also used for direct communication and for storage of game-state information (available for players that join the room during the match).

BTW: You can look at Google Play Game Services. They have (among other things) REST API for turn-based matches.
> 1 votes

---
Tags: javascript, multiplayer, node.js, websocket
---


# Question
Title: Farseer: What can I do so that a body can move through a special kind of bodies?
I have three different kinds of rectangles. Black, white and blue rectangles. The rectangles are moving and can collide with each other. But with one exception, the blue rectangle can collide normally with the black rectangle, but the blue rectangle should move through the white rectangle if it's touching the white rectangle. The white and black rectangles can collide normally.

How can I do that? In the moment, the blue rectangle isn't moving through the white rectangle if it's touching the white rectangle. What can I do so that the blue rectangle can move through the white rectangle, but not through the black rectangle?

**I solved the problem with CollisionWidth.**

For expamle: Body.CollisionWidth = Categorie.Cat5

In this case, the body just collides with bodies which have the CollisionCategorie 5.

# Answer
It's been a while since I've touched farseer, but if I remember right, it shares a very similar API to Box2d.

So you should have something like: `Fixture.filter.categorybits;
Fixture.filter.maskbits;`

So let's say your blue box is setup: `Fixture.filter.categorybits = 0x0001;
Fixture.filter.maskbits = 0x003;`

Your black box is setup: `Fixture.filter.categorybits = 0x0002;
Fixture.filter.maskbits = 0x0007;`

And your white box is setup: `Fixture.filter.categorybits = 0x0004;
Fixture.filter.maskbits = 0x0007;`

What this means is that each maskbits specifies what categories it collides with. So both black and white boxes collide with everything (0x0007 = 00000111), while blue boxes collide only with blue and black boxes.
> 1 votes

# Answer
Lets say you have a player and a bunch of tiles.

Then you can set a category on each. This is done by a bit-value.

A bit contains 0000.0000 places to be assigned.

Best thing you can do is use values like 2, 4, 8, 16, 32, 64.

In between values may cause collision within the bit and cause it to drop a category or a mask.

So first create to categories.

```
short PLAYER_BIT = 2;
short BLOCK_BIT = 4;

```

Then when creating an object and you have made an `FixtureDef()` for this item.

```
    FixtureDef fdef = new FixtureDef();
    fdef.shape = shape;
    fdef.density = 1.062f;
    fdef.filter.categoryBits = PLAYER_BIT;//This is the catagory, which type it is in bits.
    fdef.filter.maskBits = BLOCK_BIT;//The mask, which it can collide with.

```

Now for the block(s) you the do the exact opposite.

```
fdef.filter.categoryBits = BLOCK_BIT;//Because it is a block.
fdef.filter.maskBits = PLAYER_BIT;//Because block can only collide with player.

```

You can also assign multiple masks or categories but, you need to know bit-operators. Here is some info on bit-operators. I hope this helps.
> 0 votes

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


title: rotating menu with Actors in libgdx

text:
# Question
Title: rotating menu with Actors in libgdx
I am intending to build a circular menu, with menu items equally distributed around the circle. When clicking on a menu item the circle should rotate so that the selected item is facing the top. I am using libgdx and I am not very familiar with the Actors concept, so I intuitively tried to implement an Actor, who is drawing a texture and then transforming it by using Actions, with no success:

```
    class CircleActor extends Actor {

    @Override
    public void draw(SpriteBatch batch, float parentAlpha) {
        batch.draw(texture1, 100, 100);
    }

    @Override
    public Actor hit(float x, float y) {
        return this;
    }

}

```

and the rotate action:

```
    CircleActor circleActor = new CircleActor();
    circleActor.action(Forever.$(RotateBy.$(0.1f, 0.1f)));
    // stage.addActor();
    stage.addActor(circleActor);

```

The texture is rectangular, but it doe not work. 1. What is wrong? 2. Is it a good approach to solve the task?

# Answer
In your draw method, you are currently drawing without taking into account the position or rotation of your actor. You are just telling it to draw the texture at `100, 100`. So moving or rotating the actor have obviously no effect.

Update your batch.draw call to pass in the rotation and position of your actor. You can choose between these overloaded methods to do the work.

```
batch.draw(Texture texture, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, int srcX, int srcY, int srcWidth, int srcHeight, boolean flipX, boolean flipY)
batch.draw(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation)
batch.draw(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, boolean clockwise)

```

See the SpriteBatch documentation or read about SpriteBatch on the wiki.

With that said your method of doing it looks good. You may want to investigate if you can use some existing actors instead. There are actors like Button, ImageButton, Image, Label etc. that you probably can reuse. Just be warned that some of them don't support rotating. (You can rotate them, but they will do as you; ignore the angle when drawing :p ).
> 7 votes

# Answer
To rotate them in a circular manner, you have to set your actor's origin first:

```
image.setOrigin(image.getWidth() / 2,image.getHeight() / 2);
image.addAction(Actions.rotateBy(360, .2f));

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: How to Integrate Unity with Google Play Game Services for iPhone and Android games
I want to integrate Google Play Game Services for Apple's iOS and for Android. How can I do this efficiently?

# Answer
> 2 votes
You will have to use a plugin to do that. I've used this one and it was straightforward to set up and use (works for both iOS and Android):

https://github.com/faizann/UnityGPGPlugin

Some things to keep in mind (because the debugging log messages shown won't help you understand what really happens, all of them reporting that the application w/ the given key was not found on the server):

* When sending your .apk over to Google, enter the SHA-1 from your certificate manually (extract your certificate from the .apk and run the keytool on it). Sometimes Google screws up automatically doing this and the services won't work afterwards.
* Be sure to log in with a preset test account when testing (obviously).

---
Tags: android, unity, ios, google-play
---


# Question
Title: Accurate way to calculate swipe direction based on delta vector
I am trying to calculate the direction of a swipe on a touch device screen. Lets say the screen size is 1024 wide and 768 high. The bottom left x and y coordinate is 0,0 and the top right coordinate is 1024,768.

For any given swipe, I will receive a delta vector which indicates the movement on the x and y axis. For instance, if I start a touch at 100,100 and the end the touch at 500,150 I will receive a delta vector of 400,50 and I know from this that the swipe was to the right (and a tiny bit up).

From any given delta vector, is there a formula I can use to determine which direction the vector most resembles, allowing for diagonal swiping too (i.e. left, right, up, down, up-left, up-right, down-left, down-right). I do have some code which calculates the closest with an allowed margin for error - but it occurred to me there must be a mathematical way to solve this without having to check each direction and the margin.

Hope that makes sense, Thank you.

P.s. Already tried to post this in the math overflow site, but got shot down as apparently it's not a math problem. Which actually it is. Hope this is a better choice!

EDIT:

Bornander: The solution you gave (which is very clever) provides the detection as shown in this image...

Where what I'm realistically after is a slightly turned version like this...

# Answer
You can take the unsigned angle of the vector;

```
angle = angle < 0 ? (2 * PI + angle) : angle;

```

and if you then scale that so that it ranges from zero to one;

```
fraction = angle / (2 * PI)

```

then if you multiply that fraction with the number of available "directions" and round it to an int you'll get the direction (provided you enumerate the directions in a uniform counter clockwise direction).

In C# it might look something like this;

```
using System;

namespace Angles {

    enum LimitedDirection {
        Right, Up, Left, Down
    }

    enum Direction {
        Right, RightUp, Up, LeftUp, Left, LeftDown, Down, DownRight
    }

    class Vector
    {
        public double X { get; private set; }
        public double Y { get; private set; }

        public Vector(double x, double y)
        {
            X = x;
            Y = y;
        }

        public override string ToString()
        {
            return String.Format("({0:00.###}, {1:00.###})", X, Y);
        }

        public double Angle
        {
            get {
                var angle = Math.Atan2(Y, X);
                return angle < 0 ? 2 * Math.PI + angle : angle;
            }
        }

        public static explicit operator LimitedDirection(Vector v)
        {
            var fraction = v.Angle/(2*Math.PI);
            return (LimitedDirection)(fraction*4); // Four directions
        }

        public static explicit operator Direction(Vector v) {
            var fraction = v.Angle / (2 * Math.PI);
            return (Direction)(fraction * 8); // Eight directions
        }
    }

    class Program {
        static void Main(string[] args)
        {
            var vectors = new[] {
                    new Vector(1, 0), new Vector(1, 1), new Vector(0, 1), new Vector(-1, 1),
                    new Vector(-1, 0), new Vector(-1, -1), new Vector(0, -1), new Vector(1, -1)
                };

            foreach (var vector in vectors)
            {
                Console.WriteLine("{0}@{1:0.####} {2} {3}", vector, vector.Angle, (LimitedDirection)vector, (Direction)vector);
            }
        }
    }
}

```

Hope that helps.
> 3 votes

# Answer
Here is an approach to get the direction regardless of the how many directions you have and how many space dimensions:

```
unsigned int getDirection(vector v, vector[] direction_vectors, float angle_threshhold )
{
    for(unsigned int i = 0;i < direction_vectors.size();i++)
    {
        if(acos(dot(v,direction_vectors[i])) < angle_threshhold )
            return i;
    }
    return direction_vectors.size();
}
//usage:
//directions: up/right/down/left
vector my_directions[]= {vector(0,1),vector(1,0),vector(0,-1),vector(-1,0)};
unsigned int dir = getDirection(my_vector,my_directions,45.0);
if(dir < my_directions.size())
{
    //have a direction equivalent to the definition of my_directions
}
else
{
    //undefined direction
}

```

Requirement: `v` and `my_directions` must be normalized, `angle_threshhold` and `acos()` must be in the same space(radians or degrees)

Also for 8 directions you must specify all 8 directions vector and the angle\_threshhold must be `22.5`
> 1 votes

---
Tags: monotouch, gestures
---


# Question
Title: How do I dynamically set a WheelJoint's anchor points?
I've created a car in RUBE and imported it into my game. The game has a tuning menu, allowing the ride height of the car to be adjusted with a slider.

I can't work out how to change the position of the `WheelJoint` relative to the car body. The result I'm looking for is as if I had changed the `anchorA` Y-value in RUBE. I thought this would be equivalent, but it isn't:

```
    car.rearWheelJoint.getAnchorA().set(xvalue,yvalue);

```

I've tried instead creating a whole new jointdef:

```
        WheelJointDef d = new WheelJointDef();

        d.initialize(car.rearWheelJoint.getBodyA(), car.rearWheelJoint.getBodyB(),
                car.rearWheelJoint.getAnchorA().add(0,(val-100)*0.01f),
                car.rearWheelJoint.getAnchorB());

        car.rearWheelJoint = (WheelJoint) game.world.createJoint(d);

```

...but I think this is messing up the pointer to the wheel joint.

How can I do this?

# Answer
> 1 votes
To answer your question directly, no, you cannot change the anchor point dynamically. You only destroy the joint and re-create it.

---

You should be able to change other joint parameters at run-time though.

In real life the ride height of a car is determined by the equilibrium position reached by the springs:

> m*g = k*x

where m is the mass of the car body, g is the acceleration due to gravity, and k is the spring coefficient. You can solve this for x:

> x = m\*g/k

Our goal is to minimize x. We can't change g without affecting other parts of the simulation, and we can't change m without destroying the fixture, so we need to edit k.

Unfortunately box2d does not let us edit the spring coefficient directly. But we do know that the natural frequency of a 1D mass-spring-damper system is:

> w = sqrt(k/m)

and we do have control over the natural frequency, w. So if we increase w then k must increase. When k increases, x decreases (inverse relationship).

Below is the result when I vary the natural frequency of the wheel joints in RUBE: From left to right the natural frequencies are 2, 5, and 10.

Note that increasing the spring stiffness also changes the car dynamics as well as the ride height. Stiffer springs result in a bumpier ride. This may be desirable for your game.

If you really want to try and limit the ride height to an aesthetic change then you need to use a distance joint and revolute joint:

For each of the above unicycles, the wheel is connected via a revolute joint to the intermediate body (small square). That intermediate body is connected to the 'car' body with a prismatic joint and a distance joint. The setup is almost identical to before, except we have control over one more parameter: the length. The length parameter specifies the equilibrium position of the spring (distance joint). In libgdx this parameter can be set with the `DistanceJoint::setLength` public member function.

Finally, keep in mind that if you do go the distance joint route, you will still be changing the angular dynamics of your car (i.e. a longer distance joint length or ride height will raise the center of gravity, making it more likely to flip over).

---
Tags: libgdx, box2d
---


# Question
Title: How can I determine if an object hit the top of a tile rectangle in MonoGame?
I've been implementing an AI system in my 2D game using MonoGame.

In some situations when a collision between two objects occurs, I need the NPC to move in different directions depending on the direction of the collision. With the simple `Rectangle.Intersects` method I can't handle this, because it only detects if two rectangles intersect and doesn't tell me *how* they intersect.

Basically I need to know if the top of the NPC rectangle collides with the bottom of a tile rectangle, and so on.

This question talks about something similar but I don't think there is `CollisionDetection2D.BoundingRectangle` in MonoGame.

# Answer
> 0 votes
There are several solution to your problem. The first solution i can think of is instead of using one rectangle you can use 4, or even 9+ if you need more detail. Put a top-left, top-right, bottom-left, bottom-right rectangle within your main rectangle. When you have the collision you currently have you can check on the more detailed rectangles and see where it collides.

Another option would be to check it manually. If you just want to know if the top of a rectangle intersects with the bottom of another you can use the default Rectangle properties (`.Bottom`, `.Top`, `.Left`, `.Right`) and check there positions manually.

```
if (intersect)
{
    if (Math.Abs(rec1.Top - rec2.Bottom) < rec2.height / 2)
    {
        //rec1 is intersecting in the bottom half of rec2.
    }
}

```

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


# Question
Title: How can I make an attached gameobject behave correctly on character flip?
I have a character that on start-up is equipped with another gameobject/prefab as a weapon, attaching it to a hand.

```
void Start()
{
    handFront = transform.Find ("root/Hip/BodyBone/OverArmFrontBone/UnderArmFrontBone/HandFrontBone/HandFrontMount");

    instance = (GameObject)Instantiate(Resources.Load<GameObject>("VioletClub"), new Vector3(-0.5f,2f,1f), new Quaternion(0f,0f,45f,-45f));
    instance.transform.parent = handFront;
}

```

As long as I move the character in the initial direction (right) the attached object behaves as it should, staying in the hand no matter the animation played. But when I flip the character, the attached object doesn't flip correctly. In the initial position (standing still) it looks correct but when I start to move the character, the item flips and rotates the wrong way. It does not follow the arm movement like it should.

This is what I do on flip:

```
void Flip ()
{
    facingRight = !facingRight;

    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;

}

```

When I flip the character back to the right again it all work as it should.

Can anyone help me?

# Answer
You need to rotate the object 180 degrees on the X-axis instead of using scale for this.

Use: http://docs.unity3d.com/Documentation/ScriptReference/Transform.Rotate.html
> 2 votes

---
Tags: 2d, unity, animation, transformation
---


title: Unity Grid System

text:
# Question
Title: Unity Grid System
I'm creating a tower defence game and I've been struggling on one of the core parts of the game. What I'm trying to do is create a plane that the user can clink on and build a tower at that location. Although I've searched for a while I could not find an tutorials or useful code on this subject.

The theory is simple. I started with making a script that creates small cubes to shape the platform the game will be played on.

```
public Transform PlatPrefab;
public Vector3 Size;
public int platX, platY, playZ;

// Use this for initialization
void Start () {
    MakeGrid();
}

// Update is called once per frame
void MakeGrid(){

        for (int x = 0; x < Size.x; x++) {
                for (int z = 0; z< Size.z; z++) {

                Instantiate(PlatPrefab, new Vector3(x+platX,platY,z+playZ), Quaternion.identity);
        }
    }
}

```

This is the part I'm stuck on, how do I develop a system that gets the coordinates of the single cube clicked on? I've worked with Raycast Hit and I'm only comfortable with it by simply using tags and if the mouse clicks on an object with the tag then do something. However I can't wrap my head around how I'm supposed to do this with Grids. Won't they need to be labeled for my to pick one individually?

# Answer
I have done this before in a quick and dirty way - using colliders. Put a collider and a script with an OnMouseDown method on the prefab, the method will trigger when the tile is clicked
> 1 votes

# Answer
This is untested, but it should get you on the right path. You can replace "Platform" with whatever layer you end up putting your platform cubes in.

```
if (Input.GetMouseButtonDown(0)) {
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   RaycastHit hit;
   // An arbitrary distance value. Increase or decrease this value, or you could set to Mathf.Infinity.
   float distance = 100;
   // Only perform these raycasts against this particular layer.
   int platformLayer = LayerMask.NameToLayer("Platforms");
   if (Physics.Raycast(ray, out hit, distance, 1 << platformLayer)) {
      // The ray hit something! hit will have lots of information about what was hit.
      Debug.Log("Platform at position " + hit.transform.position);
   }
}

```

This should get you the position of the particular platform cube that was hit. Of course, there are other ways to perform raycasts, but this is one example.

Note that in order for the Raycast to detect something, your objects need to have a collider attached.
> 0 votes

---
Tags: unity, grid
---


# Question
Title: How do I use createPattern with a spritesheet?
Say that I have a spritesheet like this

And I want to use the dirt tile at (1, 1). I know that I can repeat an entire image using `createPattern` but how do I create the pattern from just the tile section of the image? So far I have this

```
var pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(x, y, w, h);

```

I know I could use repeated calls to `ctx.drawImage` but is it possible to get the same effect using patterns?

# Answer
> 2 votes
Here's what I found out by following this link.

`context.drawImage` can take an *img*, *canvas*, or *video* element. So you can decide to use the contents of an off-screen canvas as a pattern.

```
// First we create a canvas to draw our pattern on
// Doesn't actually have to be in the DOM
var offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = textureWidth;
offscreenCanvas.height = textureHeight;

// Grab it's context and render to it
var offscreenContext = offscreenCanvas.getContext('2d');
offscreenContext.drawImage(
    texture,       // the Image
    sourceX,       // X offset on the spritesheet
    sourceY,       // Y offset on the spritesheet
    textureWidth,  // Width of the sprite
    textureHeight, // Height of the sprite
    0,             // Destination X
    0,             // Destination Y
    textureWidth,  // Destination width
    textureHeight  // Destination height
);

```

Now here's the fun part: creating a pattern from our "invisible" canvas.

```
// Can use 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'
var pattern = context.createPattern(offscreenCanvas, 'repeat');
context.fillStyle = pattern;
context.fillRect(x, y, textureWidth, textureHeight);

```

As an added bonus, this is much faster than making multiple `drawImage` calls.

---
Tags: html5, html-canvas, spritesheet
---


title: How do I right-align text?

text:
# Question
Title: How do I right-align text?
I'm using `SpriteBatch.DrawString`, which seems to not have an overload for text alignment. How can I draw aligned text?

# Answer
> 1 votes
I created a helper class in Ruminate MonoGame GUI that takes in the following arguments and lets you align or center the text within a Rectangle both vertically and horizontally. Passing in neither enum results in the same behavior as the default `SpriteBatch` function.

The options for the emuns are.

```
public enum TextHorizontal { LeftAligned, CenterAligned, RightAligned }
public enum TextVertical { TopAligned, CenterAligned, BottomAligned }

```

And the math in the function of interest is quite simple.

```
    public void Render(SpriteBatch spriteBatch, string value, Rectangle renderArea,
        TextHorizontal h = TextHorizontal.LeftAligned, TextVertical v = TextVertical.TopAligned) {

        var location = new Vector2(renderArea.X, renderArea.Y);

        var size = SpriteFont.MeasureString(value);

        switch (h) {
            case TextHorizontal.CenterAligned:
                location.X += (renderArea.Width - size.X) / 1.9f;
                break;
            case TextHorizontal.RightAligned:
                location.X += renderArea.Width - size.X;
                break;
        }

        switch (v) {
            case TextVertical.CenterAligned:
                location.Y += (renderArea.Height - size.Y) / 1.9f;
                break;
            case TextVertical.BottomAligned:
                location.Y += renderArea.Height - size.Y;
                break;
        }

        spriteBatch.DrawString(SpriteFont, value, location, Color);
    }

```

---
Tags: xna, spritebatch, text
---


# Question
Title: How to have the game world get rendered on just a part of the screen?
I am implementing a game on both Desktop and Android.

The Desktop version will just rely on the keyboard to handle the user input on the game screen, whilst the Android one will have to have a set of buttons placed in a bar at the bottom of the game screen, using a `Stage`.

Consequently, I am expecting the game world to take up the entire space available on the Desktop screen, whilst on Android it should expand to the entire width of the screen, and to the screen height minus the height of the buttons bar I've mentioned.

What would be an appropriate approach of handling space sharing between the game world and the buttons bar?

Thank you.

# Answer
This is typically handled with different viewports. This isn't really ideal for controls as it's not something it's designed for, but you could certainly adapt it for that without many issues. It's similar to how many split screens game work: there is one world simulation, but two different views associated with it. `Viewport`s are supported by libGDX, as seen in this article.

Essentially, you could have something like this:

The divide is because there are two different viewports, both taking up 1/2 of the screen. Each Viewport has its own **camera**. In your case, you could define a viewport that takes up 9/10 of the screen (or any number you require) and have the UI on the bottom. Although, I recommend simply overlaying the controls.
> 3 votes

---
Tags: java, libgdx
---


# Question
Title: How do I split a texture into differently shaped pieces with libgdx?
I want to split a texture into variously shaped pieces with libgdx, like the pieces of a puzzle game. `TextureRegion.split()` is not an option, as it splits into equally sized rectangular texture regions.

The "Similar Questions" section here is helpful (particularly this question How do I break an image into 6 or 8 pieces of different shapes?), but I'm not sure yet if it's possible to implement the solution with libgdx.

Any pointers?

# Answer
> 1 votes
I assume you want to create something like a "jigsaw" puzzle. Off the top of my head, an algorithm that might get you started is as follows.

* Begin by splitting your image into equal pieces, it seems like the `TextureRegion.split` can do this for you.
* After this, you will have some pieces that have been split. Generate a 2D array mapping each puzzle pieces position. For example:

Essentially, the top left would be your "top left" piece, and everything running across `y = 0` excluding the end points would be your "top centers".

* With your array in hand, you can map these pieces accordingly:

You should be able to come up with some logic based on your array on how each piece should be created. Then, using some texture manipulating you can punch "holes" in the texture pieces if you're trying to create a jigsaw effect.

---
Tags: java, textures, libgdx
---


# Question
Title: How can I make the player stop at the collision point and not before?
I am making a Java platform game (I have created many top-down games, but nothing with gravity like a platformer) and I have implemented terminalVelocity, etc.

My problem is that, say when the player is falling at a rate of 8 pixels, I check collision for the player 8 pixels ahead before it moves, and if there is a collision the player does not move. But, say that there are 4 pixels until a block but the player is moving at 8 pixels, the collision detection stops the player because 8 pixels ahead there is a block, but the player hovers because there is a 4 pixel gap.

How would I make the player fall those extra 4 pixels?

# Answer
Well what I do for my 2D game is that inside of checking before the players moves, I deal with collision after the player moves. Before I used to run into problems like yours because of the fact that when you check before hand, you stop the player from moving. Here's what you have to do, let's say that there is a block at some x, y, width and height

```
........o.......//o is the player
................
................
................
.......[].......//The block

```

We'll keep making the player fall and after we do so we check if it is inside of a block

```
player.y += 8;
if(player.x < block.x + block.width && block.x < player.x + player.width && player.y < block.y + block.height && block.y < player.y + player.height)
{
  //reaction
}

```

if the player is inside of the block, we'll push it upwards

```
player.y -= (block.y + block.height);

```

Now it's right onto of the block and no gap :D

Am currently making a platform - sandbox game with java for android and this is how I deal with the collision.
> 1 votes

---
Tags: java, collision-detection
---


# Question
Title: Why do I get an error about being unable to change rasterizer states in this code?
I'm trying to toggle between wireframe and full mode while drawing a 3d model. So far I have this

```
 rs = new RasterizerState();

```

In my update method:

```
  if (state.IsKeyDown(Keys.V))
        {
            rs.FillMode = FillMode.WireFrame;
        }

        if (state.IsKeyDown(Keys.C))
        {
            rs.FillMode = FillMode.Solid;
        }

```

and in my draw method:

```
  GraphicsDevice.RasterizerState = rs;

```

But I get the error:

```
 Cannot change read-only RasterizerState. State objects become read-only the first time they are bound to a GraphicsDevice. To change property values, create a new RasterizerState instance.

```

What am I doing wrong here?

# Answer
The error you are getting appears to explain both the problem and the solution:

> Cannot change read-only RasterizerState. State objects become read-only the first time they are bound to a GraphicsDevice. To change property values, create a new RasterizerState instance.

You can't change rasterizer state objects once you have bound them to a graphics device (which happens the first time you assign `rs` to `GraphicsDevice.RenderState`). Instead, create a new rasterizer state with your desired settings and assign that to the device.

Save the previous reference if you expect to ever want to reuse that old state (as you probably do, once you disable the wireframe mode).
> 2 votes

---
Tags: xna, c#
---