# Question
Title: Rendering tilemaps at a specific position libgdx
I'm making an endless side scroller game like gravity guy with libgdx.

To test this I'm just creating two tiled maps with the same .tmx file to render then one after another, like:

```
                            [map1][map2][map3][map4]...

```

The thing is I'm not succeeding to do this, and I already have searched related problems... I found one topic related with this but I couldn't understand very clearly.

Would be very happy if someone could help me on this!

# Answer
Currently there is no way to set the position of a `TiledMap`. All you can do is move the camera to make it seem as though the map is moving. To do this you would have to create your own rendering code that allows for drawing position input.

A workaround that you could try would be making the map twice in Tiled (i.e. in one tmx file, have the map repeat once, or as many times as needed), then once the player moves one screen width into the second half, move the character and the camera back to the first half. The reason you need to move at least one screen width is because you don't want to see any empty space behind you when you "teleport" back to the first half, although you can adjust the extra space as needed.
> 1 votes

---
Tags: java, android, libgdx
---


# Question
Title: How do I use _com_ptr_t with RenderTargetView and DepthStencilView?
I have successfully used `_com_ptr_t` with the `ID3D11Device` and `IDXGISwapChain` but when applying the same reasoning to the `RenderTargetView` and `DepthStencilView`, the function `m_spD3DImmediateContext->OMSetRenderTargets(...)` sets the `m_spRenderTargetView` smart COM pointer to null! Then, subsequent draw calls fail on `ClearRenderTargetView` and `ClearDepthStencilView`.

Is it because I am passing the smart pointer incorrectly?

```
HR(m_spD3DDevice->CreateRenderTargetView(pBackBuffer, 0, &m_spRenderTargetView));
...
HR(m_spD3DDevice->CreateTexture2D(&stDepthStencilDesc, 0, &m_spDepthStencilBuffer));
...
m_spD3DImmediateContext->OMSetRenderTargets(1, &m_spRenderTargetView, m_spDepthStencilView);
assert(m_spRenderTargetView); // <=== FAIL

```

I think the smart pointer overloads the `operator&` so that it returns an `Interface**` (see Extractors in `_com_ptr_t` class).

# Answer
> 2 votes
The issue you are hitting is that `OMSetRenderTargets` does not take a pointer to the RenderTargetView object. It takes a pointer to an array of pointers to RenderTargetView objects to support Multiple Render Target (MRT) rendering configurations.

```
void OMSetRenderTargets(UINT NumViews, ID3D11RenderTargetView *const *ppRenderTargetViews,
    ID3D11DepthStencilView *pDepthStencilView );

```

The default operator& overload for \_com\_ptr\_t and Microsoft::WRL::ComPtr assume you are using the pattern like in `CreateRenderTarget` so it Releases the object and sets the pointer to null before returning the address of the contained pointer. This avoids a leak. Note the older ATL CComPtr's operator& did not Release and instead asserted the pointer to be null.

```
HR(m_spD3DDevice->CreateRenderTargetView(pBackBuffer, 0, &m_spRenderTargetView));

```

With Microsoft::WRL::ComPtr, you can use the explicit `GetAddressOf()` or `ReleaseAndGetAddressOf()` methods to get the 'right' behavior. This is why generally ComPtr (or the older ATL CComPtr) is preferred to \_com\_ptr\_t for Direct3D programming.

```
HR(m_spD3DDevice->CreateRenderTargetView(pBackBuffer, 0, m_spRenderTargetView.ReleaseAndGetAddressOf()));
...
HR(m_spD3DDevice->CreateTexture2D(&stDepthStencilDesc, 0, m_spDepthStencilBuffer.ReleaseAndGetAddressOf()));
...
m_spD3DImmediateContext->OMSetRenderTargets(1, m_spRenderTargetView.GetAddressOf(), m_spDepthStencilView);

```

With \_com\_ptr\_t you need to use something like:

```
ID3D11RenderTargetView* rtv = m_spRenderTargetView.GetInterfacePtr();
m_spD3DImmediateContext->OMSetRenderTargets(1, &rtv, m_spDepthStencilView);

```

---
Tags: directx11
---


# Question
Title: Blender exported model has reduced quality in Unity when normals applied
I know this topic comes up a lot in forums, however I have spent the last 2 hours googling it and can not find a solution for my specific problem...

I have exported this model from Blender, but when I import the model into Unity with normals set to "none" it appears as it does in Blender (see left image).

However, when I try to select `import` or `calculate normals`, it distorts the character mesh making it look less detailed and less human like (see right image).

I have tried messing with normals settings in Blender, tried changing quality settings etc. in Unity but I can not get it to look 1:1 with normals applied (obviously it needs lighting and shadows so I need it to have normals).

If anyone can provide assistance to fix this or a work around, I would really appreciate it a lot!

# Answer
The problem here seems, that you don't have lighting in blender. Add a light source and try rendering it there. You will probably have the same artifacts as in unity, because your geometry isn't ideal.

To prevent those weird shadows, you'll probably have to remake parts of the model. Especially stretched triangles can result in very strange lighting issues. For organic modelling you should always have a few rules in mind:

* If possible, ONLY have quads in your models. They will be converted to triangles in unity, but the geometry will be more even and result in less artifacts.
* The quads, or triangles if you have to use one, should not be stretched. If a part of the geometry is stretched, the lighting will bleed out on the whole part.

Generally the renderer in unity will be more unforgiving than renderers like cycles, because it relies more on approximations to gain speed. If you want to see the artifacts in blender, you could either use the blender internal renderer, or maybe the real time viewpoint shading. You can activate that by creating a light source and going into the textured view mode.
> 1 votes

---
Tags: unity, blender, normals, import
---


# Question
Title: SneakyInput joystick touch event ends when CCButton is pressed
I've added a joystick to my iOS game using the latest SneakyInput joystick code for cocos2d v3. It works well, but when a `CCButton` I have is pressed, the joystick touch event ends.

Based on my research, I've already set multitouch:

```
[CCDirector sharedDirector].view.multipleTouchEnabled = YES;

```

I've even tried setting `multipleTouchEnabled` for every button/joystick node, but still nothing works. Every time I touch the button, the joystick `touchEnded` method is called.

Here's the joystick code:

```
leftJoy = [[SneakyJoystickSkinnedBase alloc] init];
leftJoy.position = ccp(96,96);
leftJoy.backgroundSprite = [ColoredCircleSprite circleWithColor:[CCColor colorWithCcColor4b: ccc4(21, 21, 21, 127)] radius:64];
leftJoy.thumbSprite = [CCSprite spriteWithImageNamed:@"joystick.png"];
leftJoy.joystick = [[SneakyJoystick alloc] initWithRect:CGRectMake(0,0,128,128)];
leftJoy.joystick.multipleTouchEnabled = YES; // just testing
leftJoy.multipleTouchEnabled = YES; // just testing
[self addChild:leftJoy];

```

And my button code:

```
fire = [CCButton
                  buttonWithTitle:nil
                  spriteFrame:[CCSpriteFrame frameWithImageNamed:@"fire-enabled.png"]
                  highlightedSpriteFrame:[CCSpriteFrame frameWithImageNamed:@"fire-active.png"]
                  disabledSpriteFrame:[CCSpriteFrame frameWithImageNamed:@"fire.png"]];
fire.position = ccp(x,y);
fire.multipleTouchEnabled = YES; // testing
[fire setTarget:[World sharedWorld].player selector:@selector(fire:)];
[self addChild:fire];

```

The joystick works fine. Until the fire button is pressed.

I *could* redesign my buttons to use the sneakyinput button, but they work fine as-is except for this one issue.

# Answer
> 1 votes
Use `CCSprite` instead of `CCButton`.

Handle every `CCSprite` touch event in TouchDelegate method.

Inherite class where you are using SneakyInput joystick by `CCLayer` with Touch Enable.

Link : https://github.com/sneakyness/SneakyInput

---
Tags: cocos2d-iphone, objective-c
---


# Question
Title: Game development for high-school with C++ and OpenGL
I've been teaching high-school students (12th grade) game programming in the last 2 years. The way I did this till now, was first to give them "half made" classes (for Point, Polygon, etc.) and they've completed them with my help/their friends/themselves, and then they were free to design their models, and write their game logic.

The programming language was C++ and I used GLUT. I gave the students the base class that does all inits for OpenGL so they didn't work on it (except some high-motivated students that wanted to extend their graphics).

My goal was to teach them the fundamentals of C++ using OOP, by implementing their own classes rather than teaching them methods from OpenGL/GLUT API. It's also important to notice that most of those students never programmed in their life and all they knowledge comes from theory in high-school computer science.

I write this post here to get your opinions about the way I handled this class until now, do you think I've done wrong not teaching the OpenGL/GLUT API? do you think I need to utilize OpenGL power to implement basic models, or it's good practice to let them implement models by themselves? Maybe I don't need to use GLUT anymore because there are modern libraries these days that does better work, or it doesn't matter as long as it's for learning purposes?

I really want to give the students motivation by demonstrating what they can do in modern game programming, but I still got my limits which I wrote here, and also time limit (the class is one year, one lesson each week).

Thanks for your help!

# Answer
> 4 votes
"My goal was to teach them the fundamentals of C++ using OOP", following this, I think you're making the right choice. I find the OpenGL API doesn't lend itself to OOP( in the programming sense, anyway ) very well. I'm surprised you're even exposing 12th grades to C++ and OpenGL. Most university courses I've seen avoid both of these like the plague.

So, yes, I would suggest keeping the OpenGL API out of learning focused on OOP. The OpenGL way of creating and binding objects really doesn't go well with RAII or many C++ concepts. That should be a course of it's own.

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


title: Rotate camera with mouse?

text:
# Question
Title: Rotate camera with mouse?
Once again, using tutorial 10 at NeHe.

I want the code

```
if (keys[VK_RIGHT])                         // Is The Right Arrow Being Pressed?
{
    yrot -= 1.5f;                           // Rotate The Scene To The Left
}

if (keys[VK_LEFT])                          // Is The Left Arrow Being Pressed?
{
    yrot += 1.5f;                           // Rotate The Scene To The Right
}

```

and

```
if (keys[VK_PRIOR])
 {
    lookupdown -= 1.0f;
 }

if (keys[VK_NEXT])
 {
    lookupdown += 1.0f;
 }

```

to be done with the mouse instead of left/right arrow and Page Up/ Page Down. I tried everything I could think of. Can anyone help?

EDIT: I tried using WM\_MOUSEMOVE message. I just could not figure it out.

EDIT2: I am using pure OpenGL to do this. No window management system or other libs such as GLUT, GLFW, SDL, SFML etc. Just OpenGL. OpenGL and GLEW.

EDIT: Issue has been solved.

# Answer
If you want to do it using **Win32 API** then here's code :

```
// the Windows Procedure event handler
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
    case WM_MOUSEMOVE:
        // save old mouse coordinates
        oldMouseX = mouseX;
        oldMouseY = mouseY;

        // get mouse coordinates from Windows
        mouseX = LOWORD(lParam);
        mouseY = HIWORD(lParam);

        // these lines limit the camera's range
        if (mouseY < 200)
            mouseY = 200;
        if (mouseY > 450)
            mouseY = 450;

        if ((mouseX - oldMouseX) > 0)             // mouse moved to the right
            angle += 3.0f;
        else if ((mouseX - oldMouseX) < 0)     // mouse moved to the left
            angle -= 3.0f;

        return 0;
        break;

```

Now in your rendering function do this :

```
void Render()
{
    radians =  float(PI*(angle-90.0f)/180.0f);

    // calculate the camera's position
    cameraX = lookX + sin(radians)*mouseY;     // multiplying by mouseY makes the
    cameraZ = lookZ + cos(radians)*mouseY;    // camera get closer/farther away with mouseY
    cameraY = lookY + mouseY / 2.0f;

    //... your drawing code below this ...

```

Full code for above project can be found here : https://code.google.com/p/dino-game-engine/source/browse/trunk/KLAB/terrain/?r=179#terrain%2FOPENGLTG\_Src%2FCode

If you are using **GLUT** then here's code for that : http://www.lighthouse3d.com/tutorials/glut-tutorial/mouse-putting-it-all-together/
> 1 votes

---
Tags: c++
---


# Question
Title: Does scaling affect performance in OpenGL?
I've never been able to understand the best practice in this context. I usually want to ship my game with as minimum size as possible. So whereever possible, I try to use scaling of my graphics. Let's suppose I have to draw a 1000 X 300 px wall of yellow color in my game. So I usually just use a 3 X 3 px yellow image and stretch it in game (using nearest neighbor filter). Is this the right approach?

Let us consider another situation. Let's suppose I wish to render rain in my game. Basically 2 X 30 px blue white gradient streaks . Let us suppose at any time 200 drops max are going to be rendered . Now if I just ship a 2 X 6 px streak with the game and scale it at runtime , will it affect performance?

In short, how does scaling affect performance in OpenGL?

# Answer
I'm don't have any sources confirming it, but as far as I've tested till now, that approach provides better performance compared to using a texture of that size.

I suspect the reason for getting better performance is the fact that with smaller texture there is less memory loopups gpu needs in order to render the texture, while it's still doing all the calculations needed to compute both texture coordinate (per texel) and fragment position.
> 1 votes

---
Tags: opengl, libgdx, graphics, opengl-es2
---


# Question
Title: Accurate sprite rotation with mouse movement
I am using the current mouse position to aim the player sprite, but I am not getting the best results.

It will often by off by a noticeable amount, or even a complete ~180 off if I go from one side, through the player, to the other side.

```
boolean mouseMoved(int screenX, int screenY) {
    mouseX = screenX;mouseY = screenY;
    rot = MathUtils.radiansToDegrees * MathUtils.atan2((float)mouseY - (float)player.y, (float)mouseX - (float)player.x);
    if (rot < 0) rot += 360;
    player.setRot(rot);
}

```

Update 1:

When I am at 90/270 it seems to pickup the angle fine. But for 0/180, the angle is off depending on how far away my cursor is to a certain point (not the player's point).

Update 2:

Added in semi-fix, but I'm still having the same exact problem

Update 3:

I was mistaken the semi-fix wasn't actually a fix. I fixed it for real, though. The problem was that libgdx has (0,0) at the bottom left, but the InputProcessor has (0,0) at the top left. What I had to do was adjust the mouse position so that it's (0,0) was the bottom left. I did this by

```
mouseX = screenX;
mouseY = Game.HEIGHT - screen y;

```

This will give the player coordinates & mouse coordinates the same origin, and then the formula will work.

# Answer
> 0 votes
The problem was that libgdx has the origin `(0,0)` in the bottom left corner, but the mouse movement from the InputProcessor has `(0,0)` in the top left. What I had to do was adjust the mouse y position so that its `(0,0)` was the bottom left. I did this with:

```
mouseX = screenX;
mouseY = Game.HEIGHT - screenY;

```

This will give the player coordinates and mouse coordinates the same origin, and then the formula will work.

Here is the entire working code snippet:

```
boolean mouseMoved(int screenX, int screenY) {
    mouseX = screenX;
    mouseY = Game.HEIGHT - screenY;
    rot = MathUtils.radiansToDegrees * MathUtils.atan2(mouseY - player.y, mouseX - player.x);
    player.setRot(rot);
}

```

# Answer
> 0 votes
Try using different math techniques for the rotation: Instead of degrees, try using Quaternions. It's the most used rotation technique for 3D objects in professional engines, because degrees don't work as well in 3D.

There's more on Wikipedia and I found some Libgdx code.

I have more materials, but I can't include them due to my low reputation, but you can find lots on Google.

# Answer
> 0 votes
Try multiplying the y value with -1.

And make sure to convert the mouse and playercoordinates to the world coordinates.

I had this exact problem yesterday. It has to do with wrong conversion - think about the two different coordinate-systems (Viewport- and World-coordinates)

# Answer
> 0 votes
First, inverse the player position and the mouse position. This way, you will have the real angle from the player to the mouse, and not the opposite.

Second, atan2 takes the y difference as the first argument, and the x difference as the second. That is probably why your code looks like it fails.

Your code should look like this with the 2 corrections I mentioned:

```
boolean mouseMoved(int screenX, int screenY) {
    mouseX = screenX;
    mouseY = screenY;
    // Inverted mouse and player position as well as X and Y axis
    float angle = (float)Math.toDegrees(Math.atan2(mouseY - player.y, mouseX - player.x));
    players.setRot(angle);
}

```

Source: Experience. Here's a link demonstrating the X and Y axis in the atan2 function (notice how Y comes first).

---
Tags: java, libgdx, rotation
---


# Question
Title: Deferred Lighting - How to map to the generated texture?
I'm trying to implement deferred lighting and I have done the first and second pass but I'm stuck on the third as I don't know how to map from the current pixel being drawn to the generated texture with the light.

Generated texture with light calculated

Current picture

I would appreciate it if someone could help me figure out how to map my generated texture with the current pixel I'm drawing.

I don't know if it matters, but I'm working with DirectX but an explantion with OpenGL would also be welcomed.

# Answer
> 1 votes
You just need to load the lighting value at the position of the pixel.

```
// Example pixel shader DX11
float4 PixelShader(PixelLocation : SV_Position) : SV_Target0
{
     //...

     int3 SampleIndex = int3(PixelLocation.xy, 0);
     float4 lighting = LightingBuffer.Load(SampleIndex);

     //...
}

```

Info on Load here.

---
Tags: directx, hlsl, deferred-rendering, deferred-shading
---


# Question
Title: Is it possible or not to share a geometry among many meshes and apply a different shaderMaterial for each?
I instantiate one PlaneGeometry, then I instantiate 200 meshes sharing this geometry and with their own instance of a given shaderMaterial. Here is a simplified version of the code :

```
...
var geom = new THREE.PlaneGeometry(10,10,2,2);
var meshes = [];
var material=null;

for (var i=0 ; i<200 ; i++)
{
   var elevations = getElevations(i); //return an array of 9 values, values are different for each mesh
   var mat = new THREE.ShaderMaterial({
               vertexShader : vsAlti, //process displacement on y coordinate of the vertex
               fragmentShader : fsAlti,
               attributes : { elevation :  { type : 'f',value : elevations }}
            };
   meshes.push(new THREE.Mesh(geometry , mat));
}
...

```

Although the array value of the elevation attributes is different for each mesh, only one is applied for all of them. It looks like only one instance of shaderMaterial is applied to all the meshes. I would rather expect that for each mesh the shader with the matching attribute elevation values would be applied.

Here is the jsFiddle illustrating the problem : http://jsfiddle.net/McNulty/L584j/119/

# Answer
> 1 votes
You need to clone() the geometry before you use it.

Here is a fiddle with the solution http://jsfiddle.net/ekwk2nxf/

---
Tags: webgl, three.js
---


title: Problem with texture's quality in Unity

text:
# Question
Title: Problem with texture's quality in Unity
.

After setting a texture to GameObject, it looks bad. Some pixels can be seen and colors are distorted. The image itself is in good quality but after importing it to Unity, it looks ugly.

Screenshot explanations:

* left, image attached to the GUITexture GameObject
* middle, image before importing to Unity
* right, after importing (shown in inspector)

# Answer
The shape distortion you're seeing (especially in the right picture) is probably related to how you're drawing the texture. Ensure that you're using dimensions that maintain the aspect ratio of the image.

The blurriness is probably from the import settings of the image. By default the image is put through a bi-linear filter, the maximum resolution is 1024, the image is stored as a power of 2, and compression is enabled. All of these settings can cause what you're seeing with image quality.

In your case I'd say go to the texture importer and change the import settings for "Texture Type" to `GUI (Editor/Legacy)`, change the "Filter Mode" to `Point`, the "Max Size" to what ever is closest to your native resolution, and change "Format" to `Truecolor`. Experiment with the last step of changing the format, since Truecolor is no compression whatsoever, and the image will take a large amount of memory.

Also look at tutorials for ways you can "coerce" the image into working well with compression by codifying the colors you use a little.
> 2 votes

# Answer
Did you insert on the Pixel Inset the right coordinates?

Somethimes i have the same problem, the problem with Unity is that you cant have pixel perfect its very hard, because 1 unit in Unity is not necessarily 1 pixel in the image. But indeed is 1 unit in Unity its about 1 meter, so may have to do some math on it.

If you are using an orthographic camera maybe this can help.

http://indiehoodgames.wordpress.com/2013/07/27/pixel-perfect-calculator-for-orthographic-camera-unity3d/

My suggestion is that you use a Plane, and try to put the texture on it, and scale it where is the best look by trial and error.

Best of luck
> 0 votes

---
Tags: unity
---


title: Scrolling effect after touch

text:
# Question
Title: Scrolling effect after touch
i'm making map for a game and need to make scrolling of map, so the main thing what i need is to calculate speed and move layer after player remove finger from screen.

I make it my own, but i think that it must be better decisions:

```
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    _isDragging = YES;
}
// ON TOUCH MOVING
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint previous = [[CCDirector sharedDirector] convertToGL:previousLocationOne];
        CGPoint current = [[CCDirector sharedDirector] convertToGL:touchLocationOne];

        CGPoint delta = ccpSub(current, previous);
        _gameLayer.position = ccpAdd(_gameLayer.position, delta);
}

- (void)update:(CCTime)delta {

    CGPoint position = _gameLayer.position;
    static float friction = 0.86f; //0.96f;

// AFTER MOVING ENDED
    if(!_isDragging) {
        _velocity = ccp(_velocity.x * friction, _velocity.y *friction);
        position = ccpAdd(position, _velocity);
        _gameLayer.position = position;
    } else {
        _velocity = ccp((position.x - _lastPos.x)/2, (position.y - _lastPos.y)/2);
        _lastPos = position;
    }
}

```

This method is working, but i think that in update method if !\_isDragging i need to calculate speed of layer with delta isn't it ? So the question is: If my method is good for "after touch scrolling effect, or i need to use delta ? Sorry for english.

# Answer
> 0 votes
Instead of updating your velocity by initialising x and y subcomponents and calculating velocity as average of last position and current position, try using this format

```
CGPoint velocity = CGPointMake(0, 1); // Move up
CGPoint velocity = CGPointMake(0, -1); // Move down
CGPoint velocity = CGPointMake(1, 0); // Move right
CGPoint velocity = CGPointMake(-1, 0); // Move left

```

To make it move in a specific direction

and update new position by

```
position = ccpAdd(MainSprite.position, velocity);

```

And for scrolling effect you need to play with these

```
Sprite.position = CGPointMake(screenSize.width/2, screenSize.height/2);
[self addChild:MainSprite];

```

This will rule out your isDragging method, also your code not inside the update is working fine, You can use delta also, but the code where you update velocity by average of current and last can go rouge, if user slides entire screen, then average gives center,and there is no change in position, so delta might fail,

**METHOD 2** or use advanced function for same thing as (a+b)/2= a+ (b-a)/2

Not sure whether method 2 will work in your case, but using method 1 is safest choice.

Hope this helps...

---
Tags: cocos2d, objective-c, scrolling
---


title: making a monster encounter method

text:
# Question
Title: making a monster encounter method
I'm currently making my own little 2d text based game and I've got a 11 / 11 grid where a monster spawns in the middle and when i stand on it's position and it brings me to another 11/11 grid where i fight the monster. I'm going to make it a turn based theme where it starts on my turn and i can only move a certain amount of spaces and the monster can only move a certain amount of spaces and when are abilities are in range we can use them etc etc etc,

I want it so every time i encounter a monster it sees where i am on the grid and see's if its a low level area or a high level area, if it's a low level area it will spawn a Slime , wolf or pig. or high level area it will spawn a dragon , giant etc. Is there a better way to do it than what i'm currently doing it. Right now I've started to low level area.

What i'd like it to do

if monster = pig,wolf,slime , give it a certain amount of stats and health then start the fight

if monster = giant,dragon , give it a certain amount of stats and health then start the fight

Is the current way i'm doing it good or is there a better way?

```
  public static void monster_encounter() {
  Random gen = new Random();
  final int monster_gen = gen.nextInt(3);
  if( monster_gen == 0) {
  System.out.println("You're fighting a: Wolf");
  }
  else if( monster_gen == 1) {
  System.out.println("You're fighting a: Slime");
  }
  else if( monster_gen == 2) {
  System.out.println("You're fighting a: Pig");
  }

  }

```

# Answer
Long term it might be better to create either monster classes that all inherit from a single monster class that contains all methods you need. Then each class can simply override these methods (make them abstract). That will be more scalable. A second good method is to create just 1 monster class and put the variables that monsters use in there (in this case just a single string with the name of the monster). You can then add in a map which maps various numbers towards various numbers (an encounter table). That would be something like this:

```
encounterTable Map<Integer,Monster> = new Map<Integer,Monster>;
encounterTable.put(new Integer(0),new Wolf);
encounterTable.put(new Integer(1),new Slime);
encounterTable.put(new Integer(2),new Pig;

```

then an encounter looks like this:

```
  Random gen = new Random();
  final int monster_gen = gen.nextInt(3);
  Monster m = encounterTable.get(monster_gen);

```

where monster looks like this:

```
public abstract Monster{
   abstract void  printname();
 }

```

Where pig looks like this:

```
public Pig extends Monster{
     void printname(){
     System.out.println("You're fighting a: Pig");
          }
    }

```

Wolf can look like:

```
public Wolf extends Monster{
     void printname(){
     System.out.println("You're fighting a: Wolf");
          }
    }

```

I will leave slime as an exercise to the reader.

The second method is using just a single Monster class thus we get:

```
public Monster{
     String name;
    public Monster(String monsterName){
        name=monsterName;
    }
   public void printname{
        System.out.println("you are fighting a: "+ name);
   }
}

```

And now you set up the encounter table as following:

```
   encounterTable Map<Integer,Monster> = new Map<Integer,Monster>;
    encounterTable.put(new Integer(0),new Monster("Wolf");
    encounterTable.put(new Integer(1),new Monster("Slime"));
    encounterTable.put(new Integer(2),new Monster("Pig");

```

Your current method is going to become really long and a bit confusing soon (next you are going to have to give each monster an attack,number of hit points,special powers ext.).
> 1 votes

---
Tags: java, game-mechanics, spawning
---


title: Mouse input and structure in JS

text:
# Question
Title: Mouse input and structure in JS
I am creating a simple concept where I have a small menu to choose a tool from and then I can click and drag to build.

For example, I click on the rails tool and then I can click and move the mouse to create a rail segment.

I'm coding it something like this(missing some variables for temp values and objects):

```
var toolSelected = false;//if I click the rails button, it changes to 'rails'

renderer.domElement.addEventListener('mousedown', function(event){

    //here I check which is the tool selected
    if(toolSelected === 'rails'){
        //create rail object starting in event coordinates
    }

});

renderer.domElement.addEventListener('mousemove', function(event){

    //here I check which is the tool selected
    if(toolSelected === 'rails'){
        //pass the mouse movement to the rail object to update end coordinates position so I can drag and see the potential rail
    }

});

renderer.domElement.addEventListener('mouseup', function(event){

    //here I check which is the tool selected
    if(toolSelected === 'rails'){
        //indicate that the rail should be finished and build it with the mouse up coordinates
    }

});

```

The question is, is there a better or recommended way to structure these mouse events? Or do I have to, under each mouse event, check which tool is selected and perform the appropriate actions?

# Answer
It's really your *tools*' responsibility to respond appropriately to events, so I'd recommend representing each of your tools as an object containing functions that handle mouse events and delegating the event handling to the currently active tool.

In practice, you can do this by defining your tools

```
var railsTool = {
    onMouseUp : function(event) { /* Whatever */ }
    // ... further event handlers
};
// ... further tools

```

and storing the active one in a globally-scoped `activeTool`-variable.

The event listener can delegate to the active tool's handler by doing something like

```
addEventListener('mouseup', function() {
    if (typeof activeTool.mouseUp == "function")   // Handler implemented?
        activeTool.mouseUp.apply(this, arguments); // Call it
});

```

and similarly for the other event types.

That should avoid repetitive code and keep tools cleanly separated.
> 1 votes

---
Tags: javascript, html5, browser-based-games, mouse
---


# Question
Title: How can I prevent the viewport from stretching/distorting?
Basically, I want to know how I can remove distortion or stretching of the rendered image when the viewport/window size changes.

The following images exemplify the distortion/stretching I'm talking about:

## Original Image (Square Window)

## Distorted/Stretched Image (Rectangular Window)

**Ideally, the second image should display the sphere without the horizontal stretching, and would expose more of the scene to the user to account for the larger window size.**

**How can this be done?**

I'm working with OpenGL to render the image, and I make use of the perspective projection via the calls:

```
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, window.width/window.height, 0.01f, 100.0f)

```

The aspect-ratio `width/height` is in accordance to all of the documents/tutorials I've come across, so I don't expect it to be incorrect. However, my suspicion is that it is affecting the stretching problem.

---

# After thought

Honestly, as I think about the issue more, I'd led to believe that the solution involves a directly proportional relationship between the fovy (field of view in the y-direction) angle and the aspect-ratio.

Using the above image as a reference, if the width grows (causing a horizontal stretch), it seems very plausible that the fovy angle must increase to cause a vertical stretch that 'fixes' the proportionality of the rendered image.

Likewise, a decrease in width requires a decrease in the fovy angle.

**Update:**

So, after investigating this further, I've decided to change the way I've set up the viewing frustum like this:

```
gluPerspective(60 * (float)window.width/window.height, (float)window.width/window.height, 0.01f, 100.0f)

```

And my expectations were correct, that solved the proportionality issue. However, it doesn't achieve my desired results. When the window width increases, the rendered image becomes smaller (but the sphere is indeed circular). Instead, the sphere shouldn't change size at all; only the amount of scene that is displayed should change.

# Answer
In fact, the original question is 1 cast away from the solution.

## Original Code

```
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, window.width/window.height, 0.01f, 100.0f)

```

## Fixed Code

```
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, (float)window.width/window.height, 0.01f, 100.0f)

```

The problem was that `window.width` and `window.height` are integers, which caused the aspect-ratio to be the result of an integer division.

Casting one of the dimensions to a float causes the result to use floating-point division instead.

Because the aspect-ratio is now correct, there is no more stretching as seen in the original post.

**EDIT:** The code in the original post (and the answer) is simply pseudo-code for the calls to the GPU; the actual program used to output the images above is written in Java. To those not working with Java, I've not researched to see if the integer/floating-point division is implemented in the same way. Regardless, the solution is about making sure that the aspect-ratio is indeed correctly computed.
> 16 votes

---
Tags: opengl, perspective, viewport, aspect-ratio
---


# Question
Title: Why does this game loop stop my process from responding?
I implemented a fixed time step loop for my C# game. All it does at the moment is make a square bounce around the screen. The problem I'm having is that when I execute the program, I can't close it from the window's close button and the cursor is stuck on the "busy" icon. I have to go into Visual Studio and stop the program manually.

Here's the loop at the moment:

```
public void run()
    {
        int updates = 0;
        int frames = 0;
        double msPerTick = 1000.0 / 60.0;
        double threshhold = 0;
        long lastTime = getCurrentTime();
        long lastTimer = getCurrentTime();

        while (true)
        {
            long currTime = getCurrentTime();
            threshhold += (currTime - lastTime) / msPerTick;
            lastTime = currTime;

            while (threshhold >= 1)
            {
                update();
                updates++;
                threshhold -= 1;
            }

            this.Refresh();
            frames++;

            if ((getCurrentTime() - lastTimer) >= 1000)
            {
                this.Text = updates + " updates and " + frames + " frames per second";
                updates = 0;
                frames = 0;
                lastTimer += 1000;
            }
        }
    }

```

Why is this happening?

# Answer
> 3 votes
You need to handle windows events in order to get things like the close button and mouse interaction to work.

Either set up an event poll in your game loop or a callback function to handle events.

# Answer
> 1 votes
I think your window isn't responding because its message loop isn't handled. If that's the case and since you are using WinForms, adding `Application.DoEvents();` somewhere inside your main loop should fix that. (The standard `Application.Run()` won't work because it's creating its own loop, so yours won't be executed until the window is closed.)

I expect your old `Main` method (when using timers) looked something like this (the VS standard template):

```
public static void Main(string[] args) {
    Form1 f = new Form1();
    Application.EnableVisualStyles();
    Application.Run(); // this handled the message loop for you
}

```

whereas your new `Main` method should look something like this:

```
public static void Main(string[] args) {
    Form1 f = new Form1();
    f.run(); // you need to handle the message loop on your own in there
}

```

Of course, replace `Form1` with your corresponding Form class.

For more information, see the relevant documentation.

# Answer
> 0 votes
You are using C# so chances are that all the window message loops are already being handled by WinForms or WPF (if you are using one of those), so I don't think that is the problem. However since it did work when using a timer I think the problem is that you just don't give the application (or windows) time to handle the events since your loop is running as fast as possible because of `while(true)`. Just add `Thread.Sleep(0)` to the bottom of your loop. This will cause the thread to yield so the rest of the application can do some processing until the Windows Thread Scheduler restarts the thread again.

---
Tags: c#, game-loop
---


# Question
Title: Enabling Unity GUI drawtexture permanently?
I'm trying to get an image to show in Unity based on a certain criteria. I would like the position of the image to be randomized every time on play.

However since GUI.DrawTexture shows the image for a single frame only, I end up with the image flashing across the screen in random areas. I would the first location to be randomized and the image to remain still there.

Any advice on how to perform this will be greatly appreciated.

Code:

```
void OnGUI(){
 if(HP>=0.9f){
   GUI.DrawTexture(new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300) aTexture);
  }
}

```

# Answer
You need to store the random position outside the scope of your `OnGUI` method. If the position is already set, use the set position, otherwise create a new one.

```
Rect textureRect;
bool positionSet = false;

void OnGUI(){
    if(HP>=0.9f){ //We need to draw the texture
        if(!positionSet) { //Is the position already set? If not, set it
            textureRect = new Rect (Random.Range(0,1000), Random.Range(0,700), 500, 300);
            positionSet = true;
        }
        //Draw using the position set above or in a previous frame
        GUI.DrawTexture(textureRect, aTexture);
    } else {
        //If not drawing the texture unset the position so it's random for next time
        positionSet = false;
    }
}

```
> 0 votes

---
Tags: unity, random
---


# Question
Title: How to add nice effects to my menu in Unity
I have a simple menu but I would like to spice it up with some of what I thought would be simple effects. I have 4 buttons that are just rectangle with some GUIText centered on the button and when the button is clicked or even when the button first shows up on the screen I would like it to animate by flipping on the x-axis.

Here is the sample buttons from my game.

So I would like for it to flip when the buttons are first initiated or when the player clicks. I figured that since I was using unity this could be a simple task but I found out that GUIText cannot be rotated so even if I figure out how to rotate the quad that is the background the text won't do anything.

To sum this all up, how can I add a nice flipping effect to these buttons? Do I need to remove the GUIText and if so what can replace them but still keep the buttons looking nice? Is there even an alternative to GUIText?

# Answer
> 1 votes
This is not practical using the current GUI system. Ideally you'd wait for the new GUI system coming in 4.6, which supports animation and a number of other features.

However, if you need to get this working now, don't use the GUI system. Add a textured quad to your scene and interact with it the same way you would a GUI element. The textured quad can be rotated easily.

The easiest way to create the textures for your quads is to use a paint program. Alternatively you can create a custom library for adding textures of individual letters. This can get pretty complicated. There are some existing libraries on the asset store for this purpose already if you'd rather use those.

---
Tags: c#, unity, graphic-effects
---


title: How should I manage states in my game?

text:
# Question
Title: How should I manage states in my game?
I can't understand what design pattern I can take advantage to build an intro screen, help screen, level select screen, game screen, game over screen, altogether.

I can make one in AS3, but the code becomes hugely messy.

That's what I sort of do. I would create a different class for each one but all classes don't share nothing in common, I just separate the classes to short the code in each file. The only parameter I pass on is stage as reference for all of them so that I can place the sprites and assets on the screen. I instantiate the game itself in a separated file and when the player reset the level that class would be re-instantiate or overwrite again. I run garbage collector in each class because there are some events I can't use reference.

Only I understand what I do, but as you can see it's certainly the wrong way since it has became messy and hard to maintain. I learned by trial and error because I couldn't find examples showing how to code with OOP these layers or states(play, select, send score, play again and so on) of the game.

# Answer
Here's what I normally do with my states. It might not be the best way, or even the second best (but remember, the thing that matters is not the architecture of your game code, but the actual end result.). I start with a basic State-class (all code in Pseudo-C++):

```
class State
{
    virtual void Event(Event e);
    virtual void Update(float deltaTime);
    virtual void Render(Renderer renderer); // It's not a good practice to let things render themselves, but that's another thing.
};

```

Then I store the states in somewhere. This might be your game-class, a state manager or something else. I like to use "stacks" for my states, to allow easy transitions to the previous state. So maybe something like this:

```
class StateManager
{
    State GetCurrentState();
    void PushState(State state);
    State PopState();
};

```

Then, code your states (something like this):

```
class IntroState : public State
{
    StateManager Manager;

    IntroState(StateManager manager)
    {
        Manager = manager;
    }

    void Event(Event e)
    {
        if (e.key == START_KEY)
        {
            // Move to the next state.
            Manager.PushState(MainMenuState(Manager));
        }
    }

    void Update(float deltaTime);
    void Render(Renderer renderer);
};

```

Finally in your game loop you would perform something like this:

```
while (Run)
{
    for (Event e : GetEvents())
    {
        Manager.GetCurrentState().Event(e);
    }

    Manager.GetCurrentState().Update(deltaTime);
    Manager.GetCurrentState().Render(renderer);
}

```

The pattern is called **The State Pattern** (Duh?). Your states might need some reference to the manager, and that can be implemented like I did above, or with the usage of the evil singleton or maybe like a service class. The state pattern sometimes might be used with just a simple enum and a switch statement, but it's much easier to maintain classes instead of messy switch and if statements.
> 5 votes

---
Tags: game-design, actionscript-3, design-patterns
---


# Question
Title: How do I add a sprite to an object layer?
I am using **Tiled** to create a map which I am then using for a game written in **Phaser**.

I cannot figure out how to add a Sprite into the **Object layer** using the Tiled editor. I am having to do it with code but that's not ideal as I want to see the sprites in their positions on the map when I edit it.

I know this is very simple but I cannot see how to add/see sprites in Tiled. Is Tiled not able to do this or not designed to do this?

# Answer
> 5 votes
First of all your sprite image needs to be part of a tileset. If your sprites use individual images, you should use Tiled \>= 0.10 so that you can set up a tileset as a "Collection of Images" which you then add images to individually with the + button below the tileset view.

Then create an Object Layer, select the sprite you want to insert in the tileset view and select the "Insert Tile" tool from the tool bar. Then click on the map to add each sprite object. You can hold your mouse button while placing to position them more easily, or select and move them later with the Object Selection tool.

---
Tags: phaser, tiled
---


# Question
Title: How many normals are needed to have a smooth surface?
I'm trying to draw a smooth cloth surface and I have a per-pixel shader. I expect to have a smooth surface but it's not the case. I think the problem comes from my normals.

The image show the surface drawn with multiple triangles. The surface is lit; the white zone are specular reflection.

Here is the way I calculate normals

```
ofVec3f v0(ps[i].pos.x, ps[i].pos.y, ps[i].pos.z);
ofVec3f v3(ps[i+cols+1].pos.x, ps[i+cols+1].pos.y, ps[i+cols+1].pos.z);
ofVec3f v1(ps[i+1].pos.x, ps[i+1].pos.y, ps[i+1].pos.z);
ofVec3f v2(ps[i+cols].pos.x, ps[i+cols].pos.y, ps[i+cols].pos.z);

    ofVec3f n0 = (v1-v0).cross(v3-v0);
    n0.normalize();
    ofVec3f n2 = (v0-v2).cross(v3-v2);
    n2.normalize();
    ofVec3f n3 = (v0-v3).cross(v1-v3);
    n3.normalize();
    ofVec3f n1 = -(v0-v1).cross(v3-v1);
    n1.normalize();

```

Here is the code to draw my surface. It's a 64x64 array of double triangles

```
glBegin(GL_TRIANGLES);

for (int i=0; i<ps.size()-(cols+1); i++) {
//  v0 - v1
//  | \  |
//  v2 - v3

// v0
glNormal3f(n0.x, n0.y, n0.z);
glVertex3f(ps[i].pos.x, ps[i].pos.y, ps[i].pos.z);

//v3
glNormal3f(n3.x, n3.y, n3.z);
glVertex3f(ps[i+cols+1].pos.x, ps[i+cols+1].pos.y, ps[i+cols+1].pos.z);

//v1
glNormal3f(n1.x, n1.y, n1.z);
glVertex3f(ps[i+1].pos.x, ps[i+1].pos.y, ps[i+1].pos.z);

//v0
glNormal3f(n0.x, n0.y, n0.z);
glVertex3f(ps[i].pos.x, ps[i].pos.y, ps[i].pos.z);

//v2
glNormal3f(n2.x, n2.y, n2.z);
glVertex3f(ps[i+cols].pos.x, ps[i+cols].pos.y, ps[i+cols].pos.z);

//v3
glNormal3f(n3.x, n3.y, n3.z);
glVertex3f(ps[i+cols+1].pos.x, ps[i+cols+1].pos.y, ps[i+cols+1].pos.z);

```

I don't know how many normals I need and where to put them: at each vertex, one by face ? four by vertex ? I still have a flat triangulated surface although I have a per pixel glsl shader

Thanks for help.

# Answer
> 3 votes
The way you are computing vertex normals only considers an individual quad and not its neighbours. Thus you get the discontinuities between the somewhat flat quads.

If you want smooth normals, the way to compute them is to consider the gradient of nearby vertices on your grid.

If you've got points on the form

```
a-b-c
| | |
d-e-f
| | |
g-h-i

```

then you want to use the gradient between `b,h` and `d,f` when computing your normal for the vertex `e`. Alternatively, you can compute face normals for each surrounding quad and normalize the average of them to be your vertex normal.

All in all, you need to consider the neighbourhood of your vertices in order to get smooth shading across them. No amount of per-pixel shading will help you if the interpolated quantities are essentially constant.

# Answer
> 0 votes
Smooth shading can be enabled with `glShadeModel(GL_SMOOTH)` which is, however, the default. Your screenshot does look like you have the flat shading set.

---
Tags: opengl, normals
---


# Question
Title: Converting A 3D Rotational Vector Into A 3D Forward Heading Vector
I need to do a raycast which accepts a Vector3D StartPos and a Vector3D EndPos.

I have available to me the characters position and the cameras rotation in 3D vectors.

I need to somehow compute a 'forward heading' from the cameras rotation and apply it to the players position and multiply by some large number to get my EndPos vector however I can't figure out the math behind it, I know I can use sin() and cos() here which is the approach i'd like to take.

```
irr::core::vector3df CamRotation = GetOwner()->GetRotation();
irr::core::vector3df StartPos(GetOwner()->GetPosition().x(), GetOwner()->GetPosition().y(), GetOwner()->GetPosition().z());
irr::core::vector3df EndPos(0, 0, 0);

```

I've experimented around with using sin() and cos() in different combinations throwing in negative signs into places but quite frankly I don't know how to properly use those functions.

# Answer
> 1 votes
You can do the trig functions yourself if you want, but it's a lot easier to use a rotation matrix. In the background it will do the exact same sin/cos stuff, but it's already programmed for you, so why redo it?

I'm not too familiar with Irrlicht (or C++), but adapting some code I found on their forums, it'll probably look something like this:

```
irr::core::vector3df camRotation = GetOwner()->GetRotation();
irr::core::vector3df forward(0, 0, 1);
irr::core::matrix4 m;
m.setRotationDegrees(camRotation);
m.rotateVect(forward);

```

# Answer
> 0 votes
This seems to get the job done, special thanks to a forum member Entity for this answer:

```
core::vector3df(sin(core::degToRad(rot.Y)), -sin(core::degToRad(rot.X)), cos(core::degToRad(rot.Y))).normalize();

```

---
Tags: mathematics, movement, vector, raycasting
---


# Question
Title: How to create normal map from bump map in runtime?
I am using this port of libnoise to generate noise. There are several methods (Noise2D.cs, 462 and 494 line) to output images. Second one, that should give me normal map does not work completely, it outputs this with low intensity (1.0f)

And this with high intensity (\>100);

So i decided to use grayscale and default Bumped Diffuse shader works good, but only in Editor. How should i modify grayscale image for correct normal map? How should i use library in proper way?

# Answer
> 2 votes
You can generate each the normal map, pixel by pixel, by computing the respective the X and Y gradients from the height map using a Sobel operator.

---

Sampling the heightmap with a clamping mode produces an output like such:

Or with a wrapping mode, produces what was shown in your comment: (Including the errors around the border)

---

And for good measure, here's the tool I wrote to generate those images. Using SDL and plain C, I called it "hbm2tnm.c" (Height Bump Map to Tangent Normal Map)

```
#include <stdio.h>
#include <math.h>
#include <SDL/SDL.h>
#ifdef NO_SDL_IMAGE
#define IMG_Load SDL_LoadBMP
#else
#include <SDL/SDL_image.h>
#endif

double extrusion = 2.0;

SDL_Surface* load32(const char* fn) {
    SDL_Surface* p_textureSurface = IMG_Load(fn);
    if (!p_textureSurface) return 0;
    SDL_Surface* p_textureBGRA = SDL_CreateRGBSurface(SDL_SWSURFACE, p_textureSurface->w, p_textureSurface->h, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
    SDL_SetAlpha(p_textureSurface, 0, 0);
    SDL_SetAlpha(p_textureBGRA, 0, 0);
    SDL_BlitSurface(p_textureSurface, 0, p_textureBGRA, 0);
    SDL_FreeSurface(p_textureSurface);
    return p_textureBGRA;
}

double getPixel(SDL_Surface* surf, int wrap, int x, int y) {
    unsigned char* in32 = (unsigned char*)surf->pixels;
    if (x < 0) x = wrap ? (x + surf->w) : 0;
    if (y < 0) y = wrap ? (y + surf->h) : 0;
    if (x >= surf->w) x = wrap ? (x - surf->w) : (surf->w - 1);
    if (y >= surf->h) y = wrap ? (y - surf->h) : (surf->h - 1);
    int idx = x + y * surf->w;
    return (in32[idx * 4 + 0] + in32[idx * 4 + 1] + in32[idx * 4 + 2]) / (256.0 * 3.0);
}

void ComputeGradientMap(SDL_Surface* nmap, SDL_Surface* hmap, int wrap) {
    int x,y;
    unsigned char* out32 = (unsigned char*)nmap->pixels;
    for(y = 0; y < hmap->h; y++) {
        for(x = 0; x < hmap->w; x++) {
            double center = getPixel(hmap, wrap, x, y);
            double up = getPixel(hmap, wrap, x, y - 1);
            double down = getPixel(hmap, wrap, x, y + 1);
            double left = getPixel(hmap, wrap, x - 1, y);
            double right = getPixel(hmap, wrap, x + 1, y);
            double upleft = getPixel(hmap, wrap, x - 1, y - 1);
            double upright = getPixel(hmap, wrap, x + 1, y - 1);
            double downleft = getPixel(hmap, wrap, x - 1, y + 1);
            double downright = getPixel(hmap, wrap, x + 1, y + 1);

            double vert = (down - up) * 2.0 + downright + downleft - upright - upleft;
            double horiz = (right - left) * 2.0 + upright + downright - upleft - downleft;
            double depth = 1.0 / extrusion;
            double scale = 127.0 / sqrt(vert*vert + horiz*horiz + depth*depth);

            unsigned char r = 128 - horiz * scale;
            unsigned char g = 128 + vert * scale;
            unsigned char b = 128 + depth * scale;

            int idx = x + y * nmap->w;
            out32[idx * 4 + 0] = b;
            out32[idx * 4 + 1] = g;
            out32[idx * 4 + 2] = r;
            out32[idx * 4 + 3] = 255;
        }
    }
}

int main(int argc, const char** argv) {
    if (argc <= 1) {
        printf("Usage: %s <input image> [clamp output image] [wrap output image] [extrusion = %.1f]\n", argc ? argv[0] : "hbm2tnm", extrusion);
        return 1;
    }
    const char* out_clamp = "normal_clamp.bmp";
    const char* out_wrap = "normal_wrap.bmp";
    if (argc >= 3) out_clamp = argv[2];
    if (argc >= 4) out_wrap = argv[3];
    if (argc >= 5) extrusion = atof(argv[4]);

    SDL_Surface* hmap = load32(argv[1]);
    if (!hmap) {
        printf("Failed to load: %s\n", argv[1]);
        return 2;
    }
    SDL_Surface* nmap = SDL_CreateRGBSurface(SDL_SWSURFACE, hmap->w, hmap->h, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);

    ComputeGradientMap(nmap, hmap, 1);
    SDL_SaveBMP(nmap, out_wrap);

    ComputeGradientMap(nmap, hmap, 0);
    SDL_SaveBMP(nmap, out_clamp);
    return 0;
}

```

---
Tags: c#, unity
---


# Question
Title: How to progress an entity-component gamestate in a turn-based game?
So far the entity component systems I've used have worked mostly like Java's artemis:

* All data in components
* Stateless independent systems (at least to the degree that they don't require input on initialization) iterating over each entity that contains only the components that particular system is interested in
* All systems process their entities one tick, then the whole thing starts over.

Now I'm trying to apply this to a turn based game for the first time, with tons of events and responses that must occur in a set order relative to eachother, before the game can move on. An example:

Player A receives damage from a sword. In response to this, A's armor kicks in and lowers the damage taken. A's movement speed is also lowered as a result of getting weaker.

* The damage taken is what sets off the whole interaction
* Armor must be computed and applied to the incoming damage before the damage is applied to the player
* Movement speed reduction cannot be applied to a unit until after the damage has actually been dealt, since it is dependent on the final damage amount.

Events can also trigger other events. Reducing sword damage using armor can cause the sword to shatter (this must take place before the damage reduction is completed), which in turn can cause additional events in response to it, essentially a recursive evaluation of events.

All in all, this seem to lead to a few problems:

1. Lots of wasted processing cycles: Most systems (save for things that always run, like rendering) simply doesn't have anything worthwile to do when it's not "their turn" to work, and spend most of the time waiting for the game to enter a valid work-state. This litters every such system with checks that keep growing in size the more states are added to the game.
2. To find out if a system can process entities that is present in the game, they need some way to monitor other unrelated entity/system states (the systaem responsible for dealing damage needs to know if armor has been applied or not). This either muddles the systems with multiple responsibilities, or creates the need for additional systems with no other purpose but to scan the entity collection after each processing cycle and communicate with a set of listeners by telling them when it's okay to do something.

The above two points assume that the systems work on the same set of entities, that end up changing state using flags in their components.

Another way to solve it would be to add/remove components (or create entirely new entities) as a result of a single systems work to progress the games state. This means that whenever a system actually have a matching entity, it knows that it is allowed to process it.

This however make systems responsible for triggering subsequent systems, making it difficult to reason about the programs behaviour since bugs won't show up as the result of a single system interaction. Adding new systems also gets harder since they can't be implemented without knowing exactly how they affect other systems (and previous systems might have to be modified to trigger the states the new system is interested in), kinda defeating the purpose of having separate systems with a single task.

Is this something I'll have to live with? Every single ECS example I've seen have been real time, and it's really easy to see how this one-iteration-per-game-loop works in such cases. And I still need it for rendering, it just seems really unfit for systems that pause most aspects of itself every time something happens.

Is there some design pattern for moving the game state forward that is suitable for this, or should I just move all logic out of the loop and instead trigger it only when needed?

# Answer
Posting the solution I finally settled on, similar to Yakovlev's.

Basically, I ended up using an event system since I found it very intuitive to follow its logic over turns. The system ended up responsible for the in-game units that adhered to turn-based logic (player, monsters, and anything they can interact with), real-time tasks such as rendering and input polling was placed elsewhere.

Systems implement an onEvent method that takes an event and an entity as input, signalling that the entity has received the event. Every system also subscribes to events and entities with a specific set of components. The only point of interaction available to the systems are the entity manager singleton, used to send events to entities and to retrieve components from a specific entity.

When the entity manager receives an event coupled with the entity it is sent to, it places the event at the back of a queue. While there are events in the queue, the foremost event is retrieved and sent to every system that both subscribes to the event and is interested in the component set of the entity receiving the event. Those systems can in turn process the components of the entity, as well as send additional events to the manager.

Example: Player takes damage, so the player entity is sent a damage event. The DamageSystem subscribes to damage events sent to any entity with the health component and has an onEvent(entity, event) method that reduces the health in the entitys component by the amount specified in the event.

This makes it easy to insert an armor system that subscribes to damage events sent to entities with an armor component. Its onEvent method reduces the damage in the event by the armor amount in the component. This means that specifying the order that systems receive events impact game logic, since the armor system must process the damage event before the damage system in order to work.

Sometimes a system has to step outside of the receiving entity however. To continue with my response to Eric Undersander, it would be trivial to add a system that accesses the game map and looks for entities with the FallsDownLaughingComponent within x spaces of the entity receiving damage, and then send a FallDownLaughingEvent to them. This system would have to be scheduled to receive the event after the damage system, if the damage event has not been cancelled at that point, the damage was dealt.

One issue that came up was how to make sure response-events are processed in the order they are sent, given that some responses may spawn additional responses. Example:

The player moves, prompting a movement event being sent to the players entity and picked up by the movement system.

In queue: Movement

If the movement is allowed, the system adjusts the players position. If not (player tried moving into an obstacle), it marks the event as cancelled, causing the entity manager to discard it instead of sending it to subsequent systems. At the end of the list of systems interested in the event is the TurnFinishedSystem, that confirms that the player has spent his turn on moving the character, and that his/her turn is now over. This results in a TurnOver event being sent to the player entity and placed queue.

In queue: TurnOver

Now say that the player stepped on a trap, causing damage. The TrapSystem gets the movement message before the TurnFinishedSystem, so the damage event is sent first. Now the queue instead looks like this:

In queue: Damage, TurnOver

All is fine so far, the damage event will be processed, and then the turn ends. However, what if additional events are sent as a response to the damage? Now the event queue would look like:

In queue: Damage, TurnOver, ResponseToDamage

In other words, the turn would end before any responses to damage were processed.

To solve this I ended up using two methods of sending events: send(event, entity) and respond(event, eventToRespondTo, entity).

Every event keeps a record of previous events in a response chain, and whenever the respond() method is used, the event being responded to (and every event in its response chain) ends up at the head of the chain in the event used to respond with. The intial movement event has no such events. The subsequent damage response has the movement event in its list.

On top of that, a variable-length array is used to contain multiple event queues. Whenever an event is received by the manager, the event is added to a queue at an index in the array that matches the amount of events in the response chain. Thus the initial movement event is added to the queue at \[0\], and the damage, as well as TurnOver events are added to a separate queue at \[1\] since they both were sent as responses to the movement.

When the responses to the damage event are sent, those events will contain both the damage event itself, as well as the movement, putting them in a queue at index \[2\]. As long as index \[n\] has events in its queue, those events will be processed before moving on to \[n-1\]. This gives a processing order of:

Movement -\> Damage\[1\] -\>ResponseToDamage\[2\] -\> \[2\] is empty -\> TurnOver\[1\] -\> \[1\] is empty -\> \[0\] is empty
> 2 votes

# Answer
My advice here is coming from past experience on an RPG project where we used a component system. I will say that I hated working in that gameside code because it was spaghetti code. So I'm not offering much of an answer here, just a perspective:

The logic you describe for handling sword damage to a player... it seems **one** system should be in charge of all of that.

Somewhere, there's a HandleWeaponHit() function. It would access the player entity's ArmorComponent to get the relevant armor. It would access the attacking weapon entity's WeaponComponent to perhaps shatter the weapon. After computing final damage, it would touch the MovementComponent for the player to achieve the speed reduction.

As for wasted processing cycles... HandleWeaponHit() should only be triggered when needed (upon detecting the sword hit).

Maybe the point I'm trying to make is: surely you want a place in code where you can put a breakpoint, hit it, and then proceed to step through all the logic that is supposed to run when a sword hit occurs. In other words, the logic shouldn't be scattered throughout the tick() functions of multiple systems.
> 3 votes

# Answer
It's a year old question but now I'm facing the same trubles with my home made game while studying ECS, thus some necromany. Hopefully it will end up in a discussion or at least few comments.

I\`m not sure if it violates ECS concepts, but what if:

* Add an EventBus to let Systems issue/subscribe to event objects (pure data in fact, but not a component I guess)
* Create Components for each intermediate state

Example:

* UserInputSystem fires an Attack event with *\[DamageDealerEntity, DamageReceiverEntity, Skill/Weapon used info\]*
* CombatSystem is subscribed to it and calculates evasion chance for DamageReceiver. If evasion fails then it triggers Damage event with same parameters
* DamageSystem is subscribed to such event and thus triggered
* DamageSystem uses Strength,BaseWeapon damage, its type etc and writes it to a new IncomingDamageComponent with *\[DamageDealerEntity, FinalOutgoingDamage, DamageType\]* and attach it to the damage receiver Entity/Entities
* DamageSystem fires a OutgoingDamageCalculated
* ArmorSystem is triggered by it, picks up a receiver Entity or searches by this IncomingDamage aspect in Entities to pick up IncomingDamageComponent (last one could be probably better for multiple atacks with spread) and calculates armor and damage applied to it. Optionally triggers events for sword shattering
* ArmorSystems removes IncomingDamageComponent in each entity and replaces it with DamageReceivedComponent with final calculated numbers that will afffect HP and Speed reduction from wounds
* ArmorSystems sends an IncomingDamageCalculated event
* Speed system is subscribed and recalculates the speed
* HealthSystem is subscribed and decreases actual HP
* etc
* Somehow clean up

Pros:

* System trigger each other providing intermediate data for complex chain events
* Decoupling by EventBus

Cons:

* I feel that I mix two ways of passing things: in event parameers and in the temporary Components. it might be a weak place. In theory to keep things homogeneous I could fire just enum events with no data so that Systems would find the implied parameters in the Entity's components by aspect... Not sure if it is Ok though
* Not sure how to know if all the potentially interested SystemsHave processed IncomingDamageCalculated so that it could be cleaned up and let next turn happen. Maybe some kind of checks back in CombatSystem...
> 3 votes

---
Tags: turn-based, entity
---


title: NiftyGUI - Text isn't rendering

text:
# Question
Title: NiftyGUI - Text isn't rendering
I am trying to create a gui with nifty on top of lwjgl. I've already had some problems during the Nifty setup, however now Nifty is set up and running correctly but for text rendering. Here is my xml file:

```
    <?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty-1.4.xsd" xmlns:xsi="http://
www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://niftygui.
sourceforge.net/nifty-1.4.xsd http://nifty-gui.sourceforge.net/nifty-1.4.xsd">
    <screen id="start">
        <layer childLayout="center">
            <panel id="panel" height="25%" width="35%" align="center" valign="center" backgroundColor="#f60f" childLayout="center" visibleToMouse="true">
                <text id="text" font="aurulent-sans-16.fnt" color="#ffff" text="Hello World!"/>
            </panel>
        </layer>
    </screen>
</nifty>

```

and here the respective java class:

```
package niftylwjgl;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.nulldevice.NullSoundDevice;
import de.lessvoid.nifty.renderer.lwjgl.input.LwjglInputSystem;
import de.lessvoid.nifty.renderer.lwjgl.render.LwjglRenderDevice;
import de.lessvoid.nifty.tools.TimeProvider;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

public class NiftyLwjgl {

    private static Nifty nifty;
    private static boolean close;
    private static LwjglInputSystem inSys;

    public static void main(String[] args) throws LWJGLException, Exception {
        init();
        initNifty();
        while (!close) {
            update();
            preRender();
            render();
            postRender();
        }
        destroy();
    }

    private static void init() throws LWJGLException {
        Display.setDisplayMode(Display.getDesktopDisplayMode());
        Display.setFullscreen(true);
        Display.create();

        GL11.glOrtho(0, 1920, 0, 1080, 1, -1);
    }

    private static void initNifty() throws Exception {
        inSys = new LwjglInputSystem();
        inSys.startup();

        nifty = new Nifty(new LwjglRenderDevice(),
                new NullSoundDevice(),
                inSys,
                new TimeProvider());
        nifty.fromXml("xml/main.xml", "start");
        nifty.loadStyleFile("nifty-default-styles.xml");
        nifty.loadControlFile("nifty-default-controls.xml");
    }

    private static void preRender() {
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();

        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        GL11.glEnable(GL11.GL_TEXTURE_2D);
    }

    private static void postRender() {
        GL11.glDisable(GL11.GL_TEXTURE_2D);
    }

    private static void update() {
        if (Display.isCloseRequested()
                || Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)
                || nifty.update()) {
            close = true;
        }
    }

    private static void render() {
        nifty.render(false);
        Display.update();
    }

    private static void destroy() {
        inSys.shutdown();
        Display.destroy();
    }
}

```

Here is a screenshot of the application running: I somehow feel like I'm missing something incredible simple but important, like an glXXXXX call. Any help/suggestions are appreciated.

# Answer
> 1 votes
You're not setting the projection matrix correctly. At the time you call glOrtho() you probably want to have the GL\_PROJECTION matrix mode enabled.

Something like that

```

// set projection matrix
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 1920, 1080, 0, 1, -1);

// set modelview matrix to identity
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();

```

Also note that Nifty assumes the coordinates (0,0) at the top left corner. That's why the third and fourth parameter should be switched.

---
Tags: opengl, java, lwjgl, nifty-gui
---