# Question
Title: Explosion animation only rendering last frame
I recently picked up libgdx and I'm obsessed. So far it's been smooth sailing until I've tried to implement an explosion animation based on an event. The game I'm developing is a simple space asteroid shooter, my method currently is checking for a bullet hit on an asteroid, creating a new explosion object, then rendering with that objects coordinates using an iterator. I've read that you have to set runTime to 0 after the animation is finished so the animation will restart. However I'm continually getting only the last frame, and then it disappears because I remove my explosion object based on the animation being finished. So it is being removed on time correctly, however the animation does not start on the right frame. Can anyone give me some insight?

Here is my PlayScreen class which uses a PlayRenderer and a PlayWorld, (PlayRenderer rendering our objects, PlayWorld containing our objects and updating accordingly)

```
public class PlayScreen implements Screen {

    private Game game;

    private PlayWorld world;
    private PlayRenderer renderer;

    private float runTime;

    public PlayScreen(Game game){
        this.game = game;
        world = new PlayWorld(game);
        renderer = new PlayRenderer(world);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        runTime += delta;
        renderer.render(runTime);
        world.update(delta);
    }

```

PlayWorld class which is where I have collision detection contained

```
public class PlayWorld {

    private Game game;

    private Player player;
    private Array<Bullet> bullets;
    private Array<Explosion> explosions;
    private ScrollBackground bg1, bg2;
    private Crater crater1, crater2, crater3, crater4, crater5;
    private float runTime;

    public static float explosionX, explosionY;
    public static boolean shot;

    public PlayWorld(Game game){
        this.game = game;
        initPlayer();
        initBackground();
        initBullets();
        initExplosions();
        initCraters();
        Gdx.input.setInputProcessor(new PlayHandler(player, bullets));
    }

    private void initPlayer(){
        player = new Player(SSGame.GAME_WIDTH / 2 - 19, 500, 38, 34);
    }

    private void initBackground(){
        bg1 = new ScrollBackground(0, 0, 25);
        bg2 = new ScrollBackground(0, -640, 25);
    }

    private void initBullets(){
        bullets = new Array<Bullet>();
    }

    private void initExplosions(){
        explosions = new Array<Explosion>();
    }

    private void initCraters(){
        crater1 = new Crater(50, -36, 31, 36);
        crater2 = new Crater(100, -50, 31, 36);
        crater3 = new Crater(170, -85, 31, 36);
        crater4 = new Crater(250, -125, 31, 36);
        crater5 = new Crater(75, -200, 31, 36);
    }

    public void update(float delta){
        runTime += delta;
        player.update(delta);
        bg1.update(delta);
        bg2.update(delta);
        updateBullets(delta);
        updateCraters(delta);
        updateCollisions(runTime, delta);
        updatePlayerCollisions();
    }

    private void updateBullets(float delta){
        for(Iterator<Bullet> itr = bullets.iterator(); itr.hasNext();){
            Bullet b = itr.next();
            b.update(delta);
            if(b.getY() < -17){
                itr.remove();
            }
        }
    }

    private void updateCraters(float delta){
        crater1.update(delta);
        crater2.update(delta);
        crater3.update(delta);
        crater4.update(delta);
        crater5.update(delta);
    }

    private void updateCollisions(float runTime, float delta){
        for(Iterator<Bullet> itr = bullets.iterator(); itr.hasNext();){
            Bullet b = itr.next();
            if(b.getY() > 0){
                if(b.getRect().overlaps(crater1.getRect())){
                    Explosion e = new Explosion(crater1.getX(), crater1.getY());
                    explosions.add(e);
                    itr.remove();
                    crater1.reset();
                    Bullet.score++;
                }else if(b.getRect().overlaps(crater2.getRect())){
                    Explosion e = new Explosion(crater2.getX(), crater2.getY());
                    explosions.add(e);
                    itr.remove();
                    crater2.reset();
                    Bullet.score++;
                }else if(b.getRect().overlaps(crater3.getRect())){
                    Explosion e = new Explosion(crater3.getX(), crater3.getY());
                    explosions.add(e);
                    itr.remove();
                    crater3.reset();
                    Bullet.score++;
                }else if(b.getRect().overlaps(crater4.getRect())){
                    Explosion e = new Explosion(crater4.getX(), crater4.getY());
                    explosions.add(e);
                    itr.remove();
                    crater4.reset();
                    Bullet.score++;
                }else if(b.getRect().overlaps(crater5.getRect())) {
                    Explosion e = new Explosion(crater5.getX(), crater5.getY());
                    explosions.add(e);
                    itr.remove();
                    crater5.reset();
                    Bullet.score++;
                }
            }
        }
    }

    private void updatePlayerCollisions(){
        if(player.getRect().overlaps(crater1.getRect())){
            game.setScreen(new GameOverScreen(game));
        }else if(player.getRect().overlaps(crater2.getRect())){
            game.setScreen(new GameOverScreen(game));
        }else if(player.getRect().overlaps(crater3.getRect())){
            game.setScreen(new GameOverScreen(game));
        }else if(player.getRect().overlaps(crater4.getRect())){
            game.setScreen(new GameOverScreen(game));
        }else if(player.getRect().overlaps(crater5.getRect())){
            game.setScreen(new GameOverScreen(game));
        }
    }

    public Player getPlayer(){
        return player;
    }

    public ScrollBackground getBg1(){
        return bg1;
    }

    public ScrollBackground getBg2(){
        return bg2;
    }

    public Array<Bullet> getBullets(){
        return bullets;
    }

    public Crater getCrater1(){
        return crater1;
    }

    public Crater getCrater2(){
        return crater2;
    }

    public Crater getCrater3(){
        return crater3;
    }

    public Crater getCrater4(){
        return crater4;
    }

    public Crater getCrater5(){
        return crater5;
    }

    public Array<Explosion> getExplosions(){
        return explosions;
    }

```

And finally my PlayRenderer class which is passed runTime, which is = delta, this is where I believe the issue is, however I cannot figure it out, I've inserted a few print statements so someone may be able to put me on the right path

```
public class PlayRenderer {

    private PlayWorld world;

    //Objects
    private Player player;
    private ScrollBackground bg1, bg2;
    private Array<Bullet> bullets;
    private Array<Explosion> explosions;
    private Crater crater1, crater2, crater3, crater4, crater5;

    //Assets
    private TextureRegion player_texture;
    private TextureRegion background;
    private TextureRegion bullet;
    private TextureRegion crater;
    private Animation explosion;
    private Array<Animation> explosionAnimArray;
    private BitmapFont font;

    private float animTime;

    private OrthographicCamera cam;

    private SpriteBatch batch;

    public PlayRenderer(PlayWorld world){
        this.world = world;
        initEquipment();
        initAssets();
        initObjects();
    }

    private void initEquipment(){
        cam = new OrthographicCamera();
        cam.setToOrtho(true, SSGame.GAME_WIDTH, SSGame.GAME_HEIGHT);
        batch = new SpriteBatch();
        batch.setProjectionMatrix(cam.combined);
    }

    private void initAssets(){
        player_texture = AssetLoader.ship;
        background = AssetLoader.bg;
        bullet = AssetLoader.bullet_basic;
        crater = AssetLoader.crater;
        explosion = AssetLoader.explosion;
        explosionAnimArray = new Array<Animation>();
        font = AssetLoader.font;
    }

    private void initObjects(){
        player = world.getPlayer();
        bg1 = world.getBg1();
        bg2 = world.getBg2();
        bullets = world.getBullets();
        crater1 = world.getCrater1();
        crater2 = world.getCrater2();
        crater3 = world.getCrater3();
        crater4 = world.getCrater4();
        crater5 = world.getCrater5();
        explosions = world.getExplosions();
    }

    public void render(float runTime){
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        renderBackground();
        renderBullets();
        renderPlayer();
        renderCraters();
        renderExplosions(runTime);
        renderFont();
    }

    private void renderPlayer(){
        batch.begin();
        batch.enableBlending();
        batch.draw(player_texture, player.getX(), player.getY());
        batch.end();
    }

    private void renderBackground(){
        batch.begin();
        batch.draw(background, bg1.getX(), bg1.getY());
        batch.draw(background, bg2.getX(), bg2.getY());
        batch.end();
    }

    private void renderBullets(){
        for(Iterator<Bullet> itr = bullets.iterator(); itr.hasNext();){
            Bullet b = itr.next();
            batch.begin();
            batch.draw(bullet, b.getX(), b.getY());
            batch.end();
        }
    }

    private void renderCraters(){
        batch.begin();
        batch.draw(crater, crater1.getX(), crater1.getY());
        batch.draw(crater, crater2.getX(), crater2.getY());
        batch.draw(crater, crater3.getX(), crater3.getY());
        batch.draw(crater, crater4.getX(), crater4.getY());
        batch.draw(crater, crater5.getX(), crater5.getY());
        batch.end();
    }

    public void renderExplosions(float runTime){
        for(Iterator<Explosion> itr = explosions.iterator(); itr.hasNext();){
            Explosion e = itr.next();
            batch.begin();
            batch.draw(explosion.getKeyFrame(runTime), e.getX(), e.getY());
            System.out.println("" + runTime);
            batch.end();
            if(explosion.isAnimationFinished(runTime)){
                runTime = 0;
                System.out.println("RUNTIME: " + runTime);
                itr.remove();
            }
        }

    }

    private void renderFont(){
        batch.begin();
        font.setColor(Color.WHITE);
        font.draw(batch, "" + Bullet.score, 300, 20);
        batch.end();
    }

}

```

Here are my print reports for debugging:

```
MAIN MENU
BEGIN
EXPLOSION
EXPLOSION
1.974246
RUNTIME: 0.0
0.0
1.9911842
RUNTIME: 0.0
EXPLOSION
EXPLOSION
4.626008
RUNTIME: 0.0
0.0
4.6428485
RUNTIME: 0.0
EXPLOSION
7.264123
RUNTIME: 0.0

```

# Answer
The LibGDX Animation class is primarily a container of keyframes (Texture or TextureRegion instances) with some extra logic to pick the correct keyframe given a time and a play mode (normal, loop, ping-pong, etc...)

The important part is that the timer that is used to get a keyframe is not built in to the Animation instance and so there should be a separate timer variable for every running animation. It looks like you might be running with a single animation timer for all your explosions right now.

In your case, since you create a new Explosion instance each time you spawn an explosion, it might be best to put the animation timer float inside the Explosion class and increment all of them by delta time during the update loop.

Something like:

```
Animation explosionAnim = ...;

// In world.update(delta):
for (Explosion explosion : explosions) {
    explosion.animTimer += delta;
    if (explosionAnim.isAnimFinished(explosion.animTimer) {
        // TODO: cleanup 'finished' explosions here...
    }
}

// In renderExplosions():
for (Explosion explosion : explosions) {
    batch.draw(explosionAnim.getKeyFrame(explosion.animTimer), explosion.getX(), explosion.getY());
}

```

Even better (if you have lots of them) would be to Pool the Explosion instances so that you aren't allocating new memory all the time when you create and destroy them... This is a bit more complex (but not all that much) so I'll just link to the LibGDX wiki object pooling example code: https://github.com/libgdx/libgdx/wiki/Memory-management

If all else fails, try updating/drawing a single Animation instance in isolation just to make sure the Animation object is set up correctly and that your timer is behaving as expected.
> 0 votes

---
Tags: libgdx, animation, rendering
---


title: LibGDX - blurred textures when resizing

text:
# Question
Title: LibGDX - blurred textures when resizing
Hi could anyone help me solving the problem of blurred texures? My viewport screen have 800px of height and 480-600px (for different aspect ratios) of width and when I test game on smartphone with bigger screen the textures, buttons and the text are so blurry, even if I use Linear texture filter. How can I get rid of that? What can possibly solve my problems?

# Answer
It's hard to know what's going on without images or code so not sure if this addresses your particular issue or not, but 'Linear' in this context means that OpenGL applies a bilinear filter to the texture when it is sampled.

A bilinear filter is an average of the pixels from the original image around the sample position so you may get slightly blurry result depending on the image's original size and how it is scaled.

If you do not want your textures to be filtered in that way, you should apply the Nearest texture filter mode which just picks whichever pixel from the original image is closest to the requested sample position and draws that instead of trying to be clever about it. (This is what gives games like Minecraft their distinctive 'chunky pixel' look in its textures)

Here's the difference on a small image that has been scaled up:

(nearest neighbor, bilinear, bicubic \[not directly supported in OpenGL\])

Hope that helps!
> 0 votes

---
Tags: android, libgdx, textures
---


title: SDL2: Texture not rendering to screen

text:
# Question
Title: SDL2: Texture not rendering to screen
I'm trying to render a BMP image, but nothing is showing up other than the draw color. I have most of my code in a header file.

\[game.h\]

```
#ifndef __Game__
#define __Game__

#include <string>
#include "SDL.h"

using namespace std;

class Game {
public:
    Game();

    bool init(const char*, int, int, int, int, int);
    bool isRunning();
    void update();
    void render();
    void eventHandle();
    void exit();
    SDL_Texture* getTexture();
    SDL_Texture* loadBMPTexture(const char*);

private:
    SDL_Window* window = NULL;
    SDL_Renderer* renderer = NULL;
    SDL_Texture* texture;

    bool running;
};

Game::Game() {}

bool Game::init(const char* winTitle, int xpos, int ypos, int width, int height, int flags) {
    bool success = true;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "An Error Has Occured", ("SDL_Error:" + ((string)SDL_GetError())).c_str() , NULL);
        bool success = false;
    }
    else {
        window = SDL_CreateWindow(winTitle, xpos, ypos, width, height, flags);
        if (window == NULL) {
            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "An Error Has Occured", ("SDL_Error:" + ((string)SDL_GetError())).c_str(), NULL);
            bool success = false;
        }
        else {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
            if (renderer == NULL) {
                SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "An Error Has Occured", ("SDL_Error:" + ((string)SDL_GetError())).c_str(), NULL);
                bool success = false;
            }
            else
            {
                SDL_Rect srcRect;
                SDL_Rect destRect;
                SDL_Surface* pTempSurface = SDL_LoadBMP("./resources/img4.bmp");
                if (pTempSurface == NULL) {
                    SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "An Error Has Occured", ("SDL_Error:" + ((string)SDL_GetError())).c_str(), NULL);
                }
                SDL_FillRect(pTempSurface,NULL,0xFFFFFFFF);
                SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, pTempSurface);
                SDL_FreeSurface(pTempSurface);

                destRect.x = srcRect.x = 0;
                destRect.y = srcRect.y = 0;

                SDL_QueryTexture(texture,NULL,NULL,&srcRect.w, &srcRect.h);
                cout << srcRect.w << endl;
                int w, h;
                SDL_GetRendererOutputSize(renderer,&w,&h);
                destRect.w = w;
                destRect.h = h;
                cout << w;
                SDL_SetRenderDrawColor(renderer, 255, 255, 0, 0);

                SDL_RenderCopy(renderer, texture, &destRect, &srcRect);

                SDL_RenderPresent(renderer);
                running = true;
            }
        }
    }
    return success;
}

void Game::render() {
    //SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);

    SDL_RenderClear(renderer);

    SDL_RenderPresent(renderer);
}
void Game::eventHandle() {
    SDL_Event e;

    if (SDL_PollEvent(&e)) {
        switch (e.type) {
        case SDL_QUIT:
            running = false;
            break;
        }
    }
}
void Game::exit() {
    SDL_DestroyWindow(window);
    window = NULL;
    SDL_DestroyRenderer(renderer);
    renderer = NULL;
    SDL_Quit();
}

bool Game::isRunning() {
    return running;
}
SDL_Texture* Game::loadBMPTexture(const char* path) {
    SDL_Surface* tempSurface = SDL_LoadBMP(path);
    SDL_Texture* returnTexture = SDL_CreateTextureFromSurface(renderer, tempSurface);
    SDL_FreeSurface(tempSurface);
    return returnTexture;
}
void Game::update() {

}
SDL_Texture* Game::getTexture() {
    return texture;
}

#endif

```

\[main.cpp\]

```
#include "SDL.h"
#include <string>
#include <iostream>
#include "Game.h"
using namespace std;

int SCREEN_WIDTH = 1280;
int SCREEN_HEIGHT = 720;

const Uint8* keystate;
//keystate = SDL_GetKeyboardState(NULL);

Game* game = NULL;

int main(int argc, char* argv[]) {
    game = new Game();

    game->init("Game Title [Confused]",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

    while (game->isRunning()) {
        game->eventHandle();
        game->render();
    }

    game->exit();
    return 0;
}

```

# Answer
> 1 votes
For no apparent reason, you are filling your loaded image with a solid white color using `SDL_FillRect`. Also, you seem to clear the renderer without rerendering the texture. You need to `SDL_RenderCopy` the texture again after clearing the renderer.

---
Tags: textures, rendering, sdl, sdl2
---


# Question
Title: Custom Tile Collision Detection Has Trouble With Edges
So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's-block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it).

The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence: http://i.imgur.com/CACfhIP.gifv

I have narrowed this down to this specific segment of code: (Please note that SPRITE\_WIDTH is 20, which also means 20 pixels)

```
BOOL changePos(Player* player, Level* level, int newX, int newY)
{
    int roundedY;
    int roundedX;

    if (newX <= player->pos.x)
        roundedX = roundDownTo(newX, SPRITE_WIDTH); //round down to a multiple of SPRITE_WIDTH
    else if (newX > player->pos.x)
        roundedX = roundUpTo(newX, SPRITE_WIDTH); //ditto but up

```

The problem seems to be that both parts of the `if...else if...` statement require the equality symbol to work correctly. Meaning that in the provided example, the fall-through glitch will happen to the tile on the left instead if I move the equality symbol to the `else if` portion.

I attempted to fix this issue by adding an `else` clause and removing the equality from the `if...else if...` parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this:

```
BOOL changePos(Player* player, Level* level, int newX, int newY)
{
    int roundedY;
    int roundedX;

    if (newX < player->pos.x)
        roundedX = roundDownTo(newX, SPRITE_WIDTH);
    else if (newX > player->pos.x)
        roundedX = roundUpTo(newX, SPRITE_WIDTH);

    else
        if (newX%SPRITE_WIDTH >= SPRITE_WIDTH / 2)
            roundedX = roundDownTo(newX, SPRITE_WIDTH);
        else
            roundedX = roundUpTo(newX, SPRITE_WIDTH);

```

But this created an even stranger case where the middle part of the tile would cause a fall-through but the edges would work correctly on both the left and the right tile. This can be seen here: http://i.imgur.com/lTaUuzh.gifv

I've been at this all day (literally), I appreciate any help you can provide.

If I have not provided enough information, please let me know and I will do my best to provide it.

# Answer
> 0 votes
My approach was fundamentally flawed. After chancing upon this post I realized that using only a single point and some weird rounding would not work. So, I decided to add four collision points on all four corners of the player. So, I replaced my collision detection code for something that compensates for this.

```
typedef struct tagPlayer
{
    POINT pos;
    POINT collisionPoints[4];
    int jumpHeight;
    unsigned int isJumping : 1;
}Player;

BOOL changePos(Player* player, Level* level, int newX, int newY)
{
    for (int i = 0; i < 4; i++)
    {
        POINT colPoint = player->collisionPoints[i];
        if (colPoint.y + newY >= level->levelHeight || colPoint.y + newY < 0 || newX > level->levelWidth - SPRITE_WIDTH || newX < 0)
            return TRUE;
        int test = roundUpTo(newY - colPoint.y, SPRITE_HEIGHT);
        int test2 = roundUpTo(newX - colPoint.x, SPRITE_WIDTH);
        TileInfo* info = getTileAtPos(level, test, test2);
        if (info->is_collidable)
            return TRUE;
    }
    player->pos.x = newX;
    player->pos.y = newY;
}

```

This works perfectly now. In this example the white dots represent the collision points on the sprite. Notice that collision is now operating correctly. Please note that the collision points I selected were set like this

```
player.collisionPoints[0].x = 0;
player.collisionPoints[0].y = 0;

player.collisionPoints[1].x = 0;
player.collisionPoints[1].y = SPRITE_HEIGHT - 1;

player.collisionPoints[2].x = SPRITE_WIDTH - 1;
player.collisionPoints[2].y = 0;

player.collisionPoints[3].x = SPRITE_WIDTH - 1;
player.collisionPoints[3].y = SPRITE_HEIGHT - 1;

```

`SPRITE_WIDTH` and `SPRITE_HEIGHT` are both equal to 20. The `-1` is to make sure that they are on the correct parts of the sprite for the white dots that represent the collision points. I believe that it would operate just fine without it, but I have not tested that and I have no plans to. I hope this helps anyone else creating custom tile collision in the future.

---
Tags: collision-detection, tiles, c
---


title: Separating game logic and rendering

text:
# Question
Title: Separating game logic and rendering
I know this has been asked before but I would like some things cleared up.

I understand that game logic and rendering should be separated but my problem is more or less how? For instance, should the renderer get ALL info from the sprite/object and use that to draw? Also should the renderer be a seperate class or member function. If it's a separate class should it be able to get the necessary info via public functions or should it be a friend of the class to draw it?

Also some clarification as to what the main object should contain, e.g, is it okay for the main class to have other sprites, shapes, fonts, and effect data? Or, should the renderer somehow contain or produce that data?

I'm asking this because I'm making a menu list class in SFML. And, although it technically works, I'm confused because it's implemented in a way that is considered by many to be bad. Thus, I would like to know as to how to implement it and fix it correctly because I have currently blended both the logic and rendering together.

```
class MenuList {
    private:
        bool m_visibility{ true };
        std::vector<std::pair<MenuItem, sf::Text>> m_items;
        sf::RenderWindow& m_window;
        SEL::EventManager& m_manager;
        sf::Font m_font;

        sf::RectangleShape m_highlighter;
        sf::Color m_highlightColor;

        sf::RectangleShape m_box;

        size_t m_size{ 0 };
        size_t m_rowSpacing;

        static const uint16_t indent;
    public:
        MenuList(sf::RenderWindow& window, SEL::EventManager& manager);
        ~MenuList();
        // get a certain option, no range checking
        MenuItem& operator[](size_t index);

        // get a certain option, with range checking
        // will report an error to the console if range is out of bounds
        MenuItem& getOption(size_t index);

        // update the menu
        void Update();

        // set the visibility of the menu
        void setVisibility(bool value);

        // get the visibility of the menu
        bool getVisibility() const;

        // add another option
        void addOption(const MenuItem& item);

        // add multiple options via a list { }
        void addOption(std::initializer_list<MenuItem> items);

        // remove an options index
        void removeOption(size_t index);

        // remove an option by name
        void removeOption(const sf::String& name);

        // resize the amount of submenus
        void resize(size_t size);

        // get the local position of the menubox
        sf::FloatRect getLocalBounds();

        // set the amount of spacing between each menu in pixels
        void setRowSpacing(size_t rowSpacing);

        // get the amount of spacing is in between each menu in pixels
        size_t getRowSpacing() const;

        //void addSeperator(size_t index, sf::PrimitiveType Type = sf::PrimitiveType::LinesStrip);

        // get the amount of sub menus
        size_t getMenuCount() const noexcept;

        // get the position of the menu, the top left
        const sf::Vector2f& getPosition() const noexcept;

        // move the menu to a completely new position, overides the previous position
        void setPosition(float x, float y);

        // move the menu to a completely new position, overides the previous position
        void setPosition(const sf::Vector2f& pos);

        void setOutlineThickness(size_t thickness);

        size_t getOutlineThickness() const;

        // reset the menu such as the size, menus, and box
        void reset();
    };

```

# Answer
The idea is simple. You need to have a way to define an object on the screen. It should contain the information for the rendering (like textures, effects, etc.) and for the game logic (velocity, acceleration, etc.). The main game logic shouldn't touch the rendering parts and vice-versa. There are variables, which needs to be used by both systems (like the position of the object).

Your main class should not contain anything. Each part of the game should be isolated from each other. Sometimes a messaging system is used to let these parts communicate with each other.

In the updater method you should update the game logic variables. Move the character, do the path finding, etc. In the rendering method you need to use the textures and effects to render the character on the screen.
> 3 votes

# Answer
EDIT: @Bálint made a great point about my answer. This works best for 2D rendering frameworks (SDL, XNA, etc) and less so with working directly with things like DirectX/OpenGL, which require a much closer coupling of the WHAT, WHERE, and HOW that I list below.

Here is the paradigm I follow with how I organize my classes and what responsibilities each has:

* Renderer class
    + Static class that can be called by anyone
    + Has Render() method that given a texture and a set of parameters, will render the texture (X & Y coordinates, rotation, etc)
* Texture classes
    + WHAT you want to render (EX: The actual image data for a tree)
    + Has Render() method that will render the texture given a set of parameters (X & Y coordinates, rotation, etc)
* Sprite classes
    + Contains the Texture you wish to render for the Sprite
    + WHERE and HOW you want to render that texture (EX: The X & Y locations, rotation, etc)
    + Has Update() method to update the sprite's WHERE and HOW
    + Has Render() method to render the texture using the WHERE and HOW stored in the sprite

Here's an example of what your typical frame would look like:

* Sprite-\>Update()

.. .. ..
* Sprite-\>Render()

+ Texture-\>Render(this-\>x, this-\>y, this-\>rotation)
        - Renderer-\>Render(this-\>texture, x, y, rotation)

Although some might view this as over complication, it helps separate out the logic and responsibilities of each class:

* Renderer knows how to render things given to it
* Texture knows how to render itself given location parameters
* Sprite knows how to update its state and how to render its texture using its state
> 0 votes

---
Tags: game-design, architecture, rendering, graphics-programming
---


# Question
Title: experience/level growth system formula based on a plot chart, what kind of equation suits this one?
Hi I am trying to build a experience/level growth system based on the following plot chart, however I can't think of a proper formula or equation to this chart. Can anyone lend me a hand, please? The x-axis grow significant bigger very fast but the y-axis grow very slow after it reaches 200.

I have tried `log` and `power` function but can't make it work. What kind of equation should I use to make it conform to this chart?

# Answer
I can't resist a good formula puzzle. Here's one with a decent fit, though it's less elegant than I'd like...

```
float PowerCurveValueAt(float x)
{
    // Compute a root function with a steep rise in the low range.
    float low = pow(x, 0.55f);

    // Compute a second root function that's shallower in the high range.
    float high = 5f * pow(y, 0.2f);

    // Compute a blend factor that smoothly transitions between low & high.
    float blend = 1.0f / (x/30000f + 1);

    // Blend the two together, and scale to the desired output range.
    return 1.28f * lerp(high, low, blend);
}

```

This formula is a bit neater, though it's slightly steeper at the far end...

```
float LogCurveValueAt(float x)
{
     return 6.66f * log(pow((x+300f)/500f, 8f));
}

```
> 5 votes

# Answer
DMGregory did good work at approximating the curve you posted as closely as possible.

But to provide a more general and more widely applicable answer:

* When you want fast growth at first which then gets slower but never caps, use`y = sqrt(x)`
* When you want to approach a constant cap value `c` but never reach it, use `y = c - c / x`
* When you really want the hard cap, but the latter function has too fast growth in the beginning but then plateaus too fast, you can substitute `x` with a square-root function (`c - c / sqrt(x)`) or even logarithmic function (`c - c / log(x)`).

I personally find a spreadsheet application like Excel very useful in trying out my formulas and quickly plotting them into a diagram. When you want to get really serious about designing and plotting your game formulas, you might want to give Wolfram Mathematica a try.
> 2 votes

---
Tags: mathematics
---


# Question
Title: What is the term for a 3x3 tile set used to create larger areas?
What is the pattern/design name of using a 3x3 tileset (usually in a tiled 2D game) that can be used to create larger areas of itself. For example, these:

(Image source)

I thought it was a "9 tree" or something like that but cannot find it, it is perhaps an uncommon reference.

# Answer
A name that will give you actual results in Google is **9-slice**.

Another way to call it and ask Google about it is **9-patch**.

As per this chat discussion, **9-pane** seems to also be used, but the almighty Google will not show you what you need, unless you're into windows or something.

---

Thanks to Kevin and Josh in chat for that.
> 39 votes

# Answer
I'd disagree with the accepted answer here.

I'd call this an **autotile**, and *not* a 9-slice

"**9-Slice**" (or 9-patch) is usually used to refer to a system where the content creator slices the image along 4 lines (not necessarily equally-spaced tiles). When rendering a rectangle, the corner slices are displayed at their native size, and the edges/center are stretched (not repeated) to cover the gap.

This is the sense in which Flash, Illustrator, Unity, etc. use the term, so there seems to be good consensus that 9-slice means stretching, not repeating. This is usually used for scaling UI elements like message windows & buttons - and a Google image search turns up this usage almost exclusively.

Image from Adobe docs on 9-slice scaling

Image from the game{closure} docs on 9-slice options

The term I'm more familiar with to describe a set of tiles that can cover an area of any shape or size is "**Autotile**" (especially in the context of a system that works out/constructs the right tile permutation to use based on adjacency rules, so a level designer doesn't have to hand-pick each tile)

This terminology seems to have been popularized by RPGMaker, which has used a couple of variants on this idea over its generations.

An image search for autotile shows results which seem much closer to what the question describes, and other posts on GameDev.StackExchange describe this as "autotiling" as well.

Image from the docs for the Rotorz Tile System for Unity
> 66 votes

# Answer
There are some other names; Wang tiles (dominoes), aperiodic tiling

https://en.wikipedia.org/wiki/Wang\_tile

Also known as tile sets with map editors.
> -1 votes

---
Tags: 2d, tiles, terminology
---


# Question
Title: Polygon movement towards certain point libGDX
I recently started using the Polygons but I'm have struggle as I'm trying to make a Polygon move towards the center of my screen, although I don't know how. Here's the code I have(**What I'm trying to accomplish here is to make the balls spawn randomly by every side of the screen and make them go towards the middle of the screen to collide against a square**):

```
public class Game extends com.badlogic.gdx.Game implements Screen{

private SpriteBatch batch;
private Texture Ball;
private Texture Up;
private OrthographicCamera cam;
private int score;
private String showScore;
private BitmapFont scoreFont;
private Sprite upSprite;

private Polygon square;

private Array<Polygon> balls1;
private Array<Polygon> balls2;
private Array<Polygon> balls3;
private Array<Polygon> balls4;

private Polygon ball1 = new Polygon();
private Polygon ball2 = new Polygon();
private Polygon ball3 = new Polygon();
private Polygon ball4 = new Polygon();

@Override
public void create(){

    batch = new SpriteBatch();

    Ball = new Texture("energyball.png");
    Up = new Texture("up.png");

    upSprite = new Sprite(Up);

    upSprite.setOriginCenter();
    upSprite.setX(615);
    upSprite.setY(340);
    upSprite.setRegionWidth(64);
    upSprite.setRegionHeight(64);

    square = new Polygon(new float[] {
            upSprite.getX(), upSprite.getY(),
            upSprite.getX(), upSprite.getY() + upSprite.getHeight(),
            upSprite.getX() + upSprite.getWidth(), upSprite.getY() + upSprite.getY(),
            upSprite.getX() + upSprite.getWidth(), upSprite.getY()
    });

    cam = new OrthographicCamera();
    cam.setToOrtho(false, 1280, 720);

    upSprite.setPosition(upSprite.getX(), upSprite.getY());

    square.setOrigin(upSprite.getX(), upSprite.getY());

    // calls the functions to spawn balls randomly
    balls1 = new Array<Polygon>();

    balls2 = new Array<Polygon>();

    balls3 = new Array<Polygon>();

    balls4 = new Array<Polygon>();

    score();

    //if the screen is touched sprite rotates 90 degrees clockwise
    Gdx.input.setInputProcessor(new InputAdapter() {

        @Override
        public boolean touchDown(int x, int y, int pointer, int button) {

            return true;
        }

        @Override
        public boolean touchUp(int x, int y, int pointer, int button) {

            upSprite.rotate(-90);
            square.rotate(-90f);
            return true;
        }
    });

}

//shows score
private void score() {

    score = -4;
    showScore = "Score: 0";
    scoreFont = new BitmapFont();

}

//creates the balls and sets their position as well as the random timer for each
private void spawnBalls1() {

    ball1.setPosition(MathUtils.random(639, 641), 720);
    ball1.setScale(32, 32);
    balls1.add(ball1);
    lastDropTime = TimeUtils.nanoTime();

}

private void spawnBalls2() {

    ball2.setPosition(0, MathUtils.random(359, 361));
    ball2.setScale(32, 32);
    balls2.add(ball2);
    lastDropTime = TimeUtils.nanoTime();
}

private void spawnBalls3() {

    ball3.setPosition(MathUtils.random(639, 641), 0);
    ball3.setScale(32, 32);
    balls3.add(ball3);
    lastDropTime = TimeUtils.nanoTime();
}

private void spawnBalls4() {

    ball4.setPosition(1280, MathUtils.random(359, 361));
    ball4.setScale(32, 32);
    balls4.add(ball4);
    lastDropTime = TimeUtils.nanoTime();
}

@Override
public void render() {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    cam.update();

    //draws the game itself as well as the balls on the screen
    batch.setProjectionMatrix(cam.combined);
    batch.begin();

    upSprite.draw(batch);

    //draws the balls
    for (Polygon ball1 : balls1) {

        batch.draw(Ball, ball1.getX(), ball1.getY());
    }

    for (Polygon ball2 : balls2) {

        batch.draw(Ball, ball2.getX(), ball2.getY());
    }

    for (Polygon ball3 : balls3) {

        batch.draw(Ball, ball3.getX(), ball3.getY());
    }

    for (Polygon ball4 : balls4) {

        batch.draw(Ball, ball4.getX(), ball4.getY());
    }

    scoreFont.setColor(1, 1, 1, 1);
    scoreFont.draw(batch, showScore, 25, 100);

    batch.end();

    // if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place
        if (TimeUtils.nanoTime() - lastDropTime > 1000000000) {

            switch (MathUtils.random(4)) {

                case 0:
                    spawnBalls1();
                    break;

                case 1:
                    spawnBalls2();
                    break;

                case 2:
                    spawnBalls3();
                    break;

                case 3:
                    spawnBalls4();
                    break;
            }
        }
    Iterator<Polygon> iter1 = balls1.iterator();
    while(iter1.hasNext()) {

        Polygon balls1 = iter1.next();
        balls1.getY() -= 350 * Gdx.graphics.getDeltaTime();
        if (Intersector.overlapConvexPolygons(balls1, square)) {

            score++;
            showScore = "Score: " + score;
            iter1.remove();
        }

    }

    Iterator<Polygon> iter2 = balls2.iterator();
    while (iter2.hasNext()) {

        Polygon balls2 = iter2.next();
        balls2.x += 550 * Gdx.graphics.getDeltaTime();
        if (Intersector.overlapConvexPolygons(balls2, square)) {
            score++;
            showScore = "Score: " + score;
            iter2.remove();
        }

    }

    Iterator<Polygon> iter3 = balls3.iterator();
    while(iter3.hasNext()) {

        Polygon balls3 = iter3.next();
        balls3.y += 350 * Gdx.graphics.getDeltaTime();
        if (Intersector.overlapConvexPolygons(balls3, square)) {

            score++;
            showScore = "Score: " + score;
            iter3.remove();
        }
    }

    Iterator<Polygon> iter4 = balls4.iterator();
    while(iter4.hasNext()) {

        Polygon balls4 = iter4.next();
        balls4.x -= 550 * Gdx.graphics.getDeltaTime();
        if (Intersector.overlapConvexPolygons(balls4, square)) {

            score++;
            showScore = "Score: " + score;
            iter4.remove();
        }

    }

}

```

And I'm getting an error here:

```
balls1.y -= 350 * Gdx.graphics.getDeltaTime();

balls2.x += 550 * Gdx.graphics.getDeltaTime();

balls3.y += 350 * Gdx.graphics.getDeltaTime();

balls4.x -= 550 * Gdx.graphics.getDeltaTime();

```

**Basically move this ball to the square**

Any help would be gladly appreciated.

# Answer
> error: y has private access in Polygon

This simply means, that the `y` field is private in the Polygon class. Instead of trying to use `balls1.y` to reach that variable, use `setPosition(float x, float y)`, `getX()` and `getY()`
> 2 votes

---
Tags: libgdx, android, collision-detection
---


title: How to make a sword swing effect

text:
# Question
Title: How to make a sword swing effect
I'm working on a 2d java game on Slick engine and I always wondered how to make swing effects when striking with a sword? How to code something like this what's in the game Hollow Fear? Example from YouTube here.

(Image source)

# Answer
You've got two simple options:

Generate particles based on the velocity of the sword in the form of motion lines

Draw up sprites and iterate through these using frames (couple of examples at http://www.spriters-resource.com/genesis\_32x\_scd/shinobi3/sheet/20808/)
> 1 votes

---
Tags: java, 2d, slick, graphic-effects
---


# Question
Title: Unable to remove class information in serialized json file using libgdx
I am encountering a problem in serializing an array of objects to json file. Please let me know where I'm making the mistake.

Object to be serialized :

```
package components;

public class UserGameInfo {
private int level;
private boolean isLocked;

public UserGameInfo() {

}

public UserGameInfo(final int level, final boolean isLocked) {
    this.level = level;
    this.isLocked = isLocked;
}
public int getLevel() {
    return level;
}
public void setLevel(int level) {
    this.level = level;
}
public boolean isLocked() {
    return isLocked;
}
public void setLocked(boolean isLocked) {
    this.isLocked = isLocked;
}
}

```

Object definitions:

```
  public class LevelsInfoFileReader {
  private Json fileJson;
  private Logger logger;
  private Array<LevelObjects> levelObjectsList;
  private Array<UserGameInfo> userGameObjectsList;
  ....
  }

```

Code for serializing the object :

```
    //write to the file
    try {
        FileHandle newFile = Gdx.files.local(userInfoFilePath);
        fileJson.toJson(userGameObjectsList, Array.class, UserGameInfo.class, newFile);
        System.out.println(fileJson.prettyPrint(userGameObjectsList));
    } catch (final Exception e) {
        logger.error("Could not save user data to the filepath", e);
    }

```

**1st approach :**

File contents after serialization : \[{level:1},{level:2},{level:3,isLocked:true},{level:4,isLocked:true},{level:5,isLocked:true},{level:6,isLocked:true},{level:7,isLocked:true},{level:8,isLocked:true},{level:9,isLocked:true},{level:10,isLocked:true}\]

The problem here is that, though no class information is displayed, the boolean variable is not shown for level1 and level2 in the serialized json file. However, I put a debug point and checked the array object before serialization. It does contain the list properly as shown int the attached snapshot **2nd approach** The second approach I tried was with pretty print. However, the class information of the array elements is also displayed in the .json file :

Following is the .json file content :

```
[
{
class: components.UserGameInfo
level: 1
}
{
class: components.UserGameInfo
level: 2
}
{
class: components.UserGameInfo
level: 3
isLocked: true
}
]

```

**My final expected output is :**

```
[
{
"level": 1,
isLocked : false
}
{
"level": 2.
isLocked : false
}
{
"level": 3,
isLocked: true
}
]

```

# Answer
1. to remove class information, use fileJson.setTypeName(null)
2. to display all infomation including default value (in your case "false" is default of boolean), use fileJson.setUsePrototypes(false);

see more in documents
> 4 votes

---
Tags: java, libgdx, serialization, json
---


title: Animating isometric sprites

text:
# Question
Title: Animating isometric sprites
I'm having trouble coming up with a way to animate these 2D isometric sprites. The sprites are stored like this:

```
(Game Folder Root)/Assets/Sprites/(Sprite Name)/(Sprite Animation)/(Sprite Direction)/(Frame Number).png

```

So for example,

```
/Assets/Sprites/Worker/Stand/North-East/01.png

```

Sprite sheets aren't really viable for this type of animation. The example stand animation is 61 frames. 61 frames for all 8 directions alone is huge, but there's more then just a standing animation for each sprite. Creating an sf::Texture for every image and every frame seems like it will take up a lot of memory and be hard to keep track of that many images. Unloading the image and loading the next one every single frame seems like it will do a lot of unnecessary work. What's the best way to handle this?

The reason I am not using a sprite sheet is because these sprites are hi-res images with many animations which all have a large quantity of frames. The resulting sprite sheet would be massive. In case you're wondering, here was my implementation of creating animated sprites.

```
// Animation class declaration
class Animation
{
public:
        Animation(std::string path, int frames);
        ~Animation();
        void nextFrame();
        void gotoStart();
        bool loadFrames();
        sf::Texture& getActiveFrame();

private:
        int frameCount;
        std::string pathToAnimation;
        int currentFrame;
        sf::Texture frame[];
};

// Animation class implementation
Animation::Animation(std::string path, int frames)
{
        pathToAnimation = path;
        frameCount = frames;
}

Animation::~Animation()
{
        // destructor
}

void Animation::nextFrame()
{
        if(currentFrame < frameCount)
        {
            currentFrame = 1;
        }
        else
            currentFrame += 1;
}

void Animation::gotoStart()
{
        currentFrame = 1;
}

bool Animation::loadFrames()
{
        for(int i = 01; i < frameCount; i++)
        {
            if(!frame[i].loadFromFile(pathToAnimation + std::to_string(i) + ".jpg")) return false;
        }
        return true;
}

sf::Texture& Animation::getActiveFrame()
{
    return frame[currentFrame];
}

// Actor class declaration
class Actor
{
public:
        Actor();
        ~Actor();
        void setActiveAnimation(std::shared_ptr<Animation> anim);
        void draw(sf::RenderWindow& win);

private:
        sf::Sprite sprite;
        std::shared_ptr<Animation> activeAnimation;
};

// Actor class implementation
Actor::Actor()
{
    // constructor
}

Actor::~Actor()
{
    // destructor
}

void Actor::setActiveAnimation(std::shared_ptr<Animation> anim)
{
    activeAnimation = anim;
    activeAnimation->gotoStart();
}

void Actor::draw(sf::RenderWindow& win)
{
    sprite.setTexture(activeAnimation->getActiveFrame());
    win.draw(sprite);
    activeAnimation->nextFrame();
}

```

It's still not 100% where I'd like it to be but it's working and it's pretty easy to use.

# Answer
You would not want to load/unload a texture after each frame. This is because it would involve accessing the hard drive each time. This takes a very long time compared to accessing memory and you would certainly see a slow down in rendering. So what you want to do is to load all of the textures into memory.

If we have 60, 32x32, rgba8 textures for each 8 directions, this is about 2MB. So we can see that it really isn't that much memory.

(You could just keep each texture in memory and swap around, but the following is the more "correct" way to do it)

I believe you are using SFML, I haven't used it personally but after searching there is a class you can use just for this purpose, an sf::Sprite. This is just the same as rendering an sf::Texture, however you need to pass it a texture to start with. What's the difference? Well you need to pass this sprite a rectangle in the texture to use. So you say this sprite will use this part of the texture.

This is better because we can make one big texture with all of our sprites on and reference each sprite individually. It means we do not have to swap textures after each frame (this is expensive for the GPU to do).

Of course this means that you will have to add all of your separate sprites into one texture before you load them. It also means that you need to know the rectangle that each sprite occupies. After a quick google search you could use this SpriteSheetPacker; it outputs a final texture and a .txt file that gives you where each sprite is located.
> 2 votes

# Answer
Rather than loading and unloading the textures on a per-frame basis, one possibility would be to load all the frames for a certain animation at once. For example, if you're about to play the attack animation, load all the frames for the attack animation(s) into memory if they aren't already there (checking whether the animation already exists in memory would have to be managed by a texture manager or some similar construct).

Another (probably better) option would be to combine all frames for a specific animation into a single animation-specific spritesheets, which is what Jeff Vogel from Spiderweb Software does for his 2D isometric RPG games. For example, you might combine all the defense animation frames (for all directions) into a single spritesheet, all the running frames (for all directions) into a single spritesheet, etc. Jeff's code is proprietary so I'm not sure how he handles the loading and unloading of the sprite sheets, but his games have good performance, and this approach strikes a good middle ground between having a single colossal spritesheet and having tons of single frames.
> 1 votes

---
Tags: c++, animation, sprites, sfml
---


# Question
Title: Why can't I get a bool packed and aligned into a D3D constant buffer?
Alright, I'm having a hard time getting a bool packed and aligned into a hlsl constant buffer and I'm not sure why.

Here is the buffer in hlsl

```
cbuffer MaterialBuffer : register(b1) {
    float3 materialDiffuseAlbedo;
    float  materialSpecularExponent;
    float3 materialSpecularAlbedo;
    bool isTextured;
};

```

And here it is in c++

```
struct GeometryBufferPass_MaterialBuffer {
    XMFLOAT3 diffuse;
    float specularExponent;
    XMFLOAT3 specular;
    bool isTextured;
};

```

I've tried moving the bool and padding the struct in all kinds of ways with no luck. What is the correct way to do this?

# Answer
> 9 votes
For efficiency, constant buffers will be mapped such that values do not straddle GPU registers. Each register is four floats in size (16 bytes) so constant buffer structures must be a multiple thereof on the GPU. Your C++ structure should be padded accordingly if you want to use it as a convenience for mapping data (this, note, doesn't always scale well).

Your issue, then, is that an HLSL boolean is four bytes, but one byte on the CPU side (in your specific implementation). This causes your C++ structure to not align properly: the significant bit of a boolean value (the 0 or 1 that matters) is going to be stored in the least-signficant byte of the value, and since the sizes don't agree the location of that byte in memory will differ in the CPU and GPU versions of the structure.

Manually inserting the appropriate padding and ensuring proper 16-byte alignment, or just using an appropriately-sized type, like an integer, should fix the issue. This thread may also be of use to you as it contains a more in-depth discussion of roughly the same problem.

# Answer
> 4 votes
Alright, did some reading and noticed that a hlsl bool is essentially a 32 bit integer. So I just used an int in the c++ struct to solve my problem.

```
struct GeometryBufferPass_MaterialBuffer {
    XMFLOAT3 diffuse;
    float specularExponent;
    XMFLOAT3 specular;
    int isTextured;
};

```

# Answer
> 0 votes
float, bool and int do not necessary line up for endian particularly for multiple items.

Switching to int or float works in some of the examples listed here as its aligned between XMFLOAT3 items so are referenced correctly. However if you need to declare an array or several items in the structure for int, float (none XM types) then you will likely find that GPU values don't match the values in set in the CPU structure.

I certainly did when adding an array of type int to be used for lighting type.

The easiest way I found is to stick to XM types that align by 16, which may require wasted elements / bytes but sorts the endian for you. E.G XMINT4 and just used the first element .x for your value, or if you have the need then use the other elements for another purpose but means poor naming (make sure to comment). Note: XMINT2 array will also be out of logical order

---
Tags: directx, hlsl, data-structure
---


# Question
Title: Where to cast light/shadows in a 2.5D view?
I'm working on a tile-based 2D pseudo top-down/side-on game very much in the graphical style of Prison Archiect. More specifically, I'm referencing their style of drawing wall tiles where you can see the south, east and west sides of the wall at once. Here's an example from my engine:

I'm also working on a pixel-based (i.e. not tile-based) lighting and shadows implementation. I'm currently struggling with trying to decide how/where to project from a light source on intersections with these wall tiles.

I can't decide where on these tiles should occlude light cast out by light sources. If the red highlighted areas are the "top" of the wall, and the blue highlighted areas are the "side" of the wall, I believe I have two options:

**A) Only occlude light from the "top" of the wall**

It's worth mentioning that I also plan to use UV-mapping so that only the walls facing the light source will be illuminated, rather than the pre-shaded tiles I'm using as an example. However, that would mean that the tiles adjacent to a wall in shadow may be lit and I don't think this would look quite right. Alternatively...

**B) Occlude light from the entirety of the wall tile**

This seems more realistic for the ground tiles but does not let me easily illuminate the wall "sides".

I'm not really happy with either solution so my question is: **is there another alternative which will give more realistic shadow-casting in a 2.5D view?** I'd also rather keep the sides of the walls visible rather than use a top-down only perspective as I feel this would force the rest of the art into a top-down perspective, rather than pseudo side-on.

# Answer
> 11 votes
Going to try and doodle up what I mean here as soon as I finish typing this, but:

**What about merging the two?**

Use the second (occlude by base) for everything that *isn't* a wall and the first (occlude by tops) for lighting the walls?

You actually did this by accident in your second example, with the wall that goes off the bottom of the image. Extending this to the remaining walls won't be perfect, but it would allow some lighting of the walls that will look pretty decent.

# Answer
> 1 votes
I won't be able to make an image for you, but one trick you could do to figure out if a piece of wall should light up is to take advantage of the 'alpha' channel for determining the direction the pixel is facing, as opposed to the opacity of the pixel.

You could then determine whether the pixel should be lit between the light source and the facing of the wall pixel (alpha value). **Flat Shading** in 3d rendering is a cheap and effective method that usually uses a similar algorithm using the normal of the plane and the light source's position/color. In your case, the normal is interpreted from the alpha, but you could use a similar algorithm, resulting in very 3D lighting for a 2D game (*which is probably overkill but still cool, in my opinion*)

```
//some psuedocode of the important parts
Vector2 lightPosition;
Vector2 pixelPosition;

Vector2 lightDirection = lightPosition - pixelPosition;
Vector2 normalDirection = //(translate into a rotation Vector)

lightDirection.normalize();
normalDirection.normalize();
angleBetweenLightAndNormal = dotProduct(normalDirection, lightDirection);
//determine from the angle whether the normal should be lit or not

```

You could scale a value of 0.00 to be facing `down` (*or whatever direction you prefer*) and the value of 1.00 to also be `down`, as if the direction had rotated 360 degrees. This means the value of `up` is 0.50

If you plan on including the top of walls or the ground you may even scale it a few values short, and keep specific reserved values to mean `top` or `ground`.

In fact, if you needed it to be as simple as possible:

```
//0.00 = down
//0.10 = left
//0.20 = right
//0.30 = up

//0.40 = floor
//0.50 = top of wall

```

which then leaves plenty more values for other situations.

---

The drawback is that you are taking over the `alpha` channel, which generally relates to opacity. This means both that your engine may take some modifying to ignore alpha, and, if you *do* need an alpha channel, you can't do this method directly.

You could create a new image with only lighting information instead. The nice thing about creating a new image with lighting information is that your RGB values can fully translate into a 3-directional rotation for the normal that pixel is facing, and the alpha could be the "height" of the pixel (*as if it were in 3D space*)

# Answer
> 0 votes
I don't want to take anything away from @Draco18s' answer, but I went with his suggestion (combining the two) and ended up putting together a demonstration video on how it's done (for those interested) at https://www.youtube.com/watch?v=Cabl0LMmlgY

In addition to the quick sketch that he added, I ended up using normal maps on each "face" of the wall so that if there was any "bleed over" light, the angle of incidence means that it isn't illuminated.

---
Tags: 2d, tiles, lighting, shadows, 2.5d
---


# Question
Title: How can I handle fighting game collisions for complex animations?
Imagine that I have an animation like this.

As you can see, this attack hits in three horizontal places. The opponent facing this player could be hit mid and low (standing or crouching).

The same goes for this move:

If the opponent is crouching, standing or in air it gets hit because the fire circle hits all areas (low, mid and high)

How can I handle hit detection with this sort of animation?

# Answer
The way fighting games work is with attack and collision boxes *per frame*. This way there is not a high/mid/low hit per se, a high-kick could for example hit a jumping character.

In Street Fighter this looks like this:

The hit is scored if a red box hits a opponents blue box. Red being the attack box and blue hit boxes

In your example each frame of animation would define the red boxes, where a hit should be scored. In the 2nd animation- the flaming circle, you could remove hit boxes from that character rendering him invulnerable during that attack.

Sometimes there are additional block boxes, those nullify a hit. A character could for example be hit from the back but have a block up when hit from the front.

So: add hit and collision boxes to your anination information and check against those.
> 6 votes

---
Tags: 2d, collision-detection, fighting-game
---


# Question
Title: How can I create a car mod for GTA: Vice City?
I am a player of GTA games. I want to create my own car for GTA: Vice City. How do I create a mod that adds a new car to the game?

# Answer
> 4 votes
To make a totally new car, you'll first have to model it in 3D in a modelling program. Blender is a reasonable freely-available modelling tool.

Once you've got the model, you need to export it into the `.dff` file format used by Vice City. This plugin can export from Blender to `.dff`; you can find plenty of other `.dff` exporters for other modelling tools as well if you search around.

The G-IMG tool can be used to edit GTA's archive files and install your custom `.dff` (and associated `.txd`). The `.dff` and `.txd` files exported for the car are the basics needed to get the car in game; the rest allows you to customize and tweak the car.

The CFG Studio tool can be used to install any custom `handling.cfg` (which is just a text file) parameters for your car. This car editor can also edit handling and color files for your car.

This guide covers the basic steps in more detail.

---
Tags: modding
---


# Question
Title: Change the alpha blending color of scaled textures
It looks like semitransparent pixels are blended with while color when textures are drawn scaled. It is very noticeable and looks ugly when textures are drawn on dark background.

```
public class SomeScreen implements Screen {
    private TextureRegion textureRegion;

    @Override
    public void show() {
        // Loading texture
        Texture texture = new Texture(Gdx.files.internal("texture.png"), true);
        // Setting filter to "linear"
        texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
        // Getting the region
        textureRegion = new TextureRegion(texture, 0, 0, 64, 64);
    }

    @Override
    public void render(float delta) {
        // Clearing screen
        Gdx.gl.glClearColor(0.09f, 0.09f, 0.09f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Drawing textureRegion
        Game.instance.batch.begin();
        Game.instance.batch.draw(textureRegion, 100f, 100f, 256f, 256f); // Actual texture region size is 64x64px
        Game.instance.batch.end();
    }
}

```

I need to get rid of that white noise around the shape, bud don't know how.

Source image:

Draw results:

# Answer
> 0 votes
This colour usually comes from the texture itself. When using alpha transparency, even fully transparent texels still have an RGB colour, though it's usually unseen. Because we don't see it, image editors and compression tools can be inconsistent in how they handle these areas - filling them with white, black, or streaked-out copies of adjacent texels to improve predictability for compression.

The most reliable way I've found to control this is to use TGA (Targa) files for intermediate texture storage (before converting to GPU compressed formats like DXT-5 etc. when generating an executable build). Targa files don't assume that the alpha channel is transparency, so you can export arbitrary RGBA data without a compressor second-guessing what the 0-alpha texels should look like.

If you're using Photoshop or a similar tool, you'll want to create an alpha mask from the transparency of your texture, and store it as a new alpha channel. Then go back to the RGB colour planes, and paint a border behind any transparent edges of your texture, matching the colours of adjacent texels. This way you can ensure any blending with these texels during mipmapping or texture filtering won't distort the RGB result away from the colour specified by the non-fully-transparent texels in the vicinity.

When working on the Wii, I set up a Photoshop script to automatically bleed out colours into transparent regions like this by repeatedly duplicating, blurring, and merging layers (keeping the original on top), and used that as part of my standard export flow.

Note that you can also get similar artifacts if you're using a compressed texture format like DXT-1, which supports only 1-bit transparency, using transparent black as its blending colour. That doesn't appear to be the problem you're encountering here, but this can be worked around too by treating the texture as having pre-multiplied alpha, so the dark fade at the edges gets used as the normal feathering-out of the blending equation, without doubling-up the effect.

---
Tags: libgdx, spritebatch, transparency, alpha-blending
---


# Question
Title: Simple 2D Platformer Collision Detection?
I'm relatively new to programming and I am attempting to write a 2d platformer in C++ using the SFML library.

The structure of my code is that I have a Stage class which contains a vector of sf::RectangleShape 's (the stage platforms). I have a method in the stage class to check for the collision between a player's hitbox and the stage as follows:

```
bool Stage::checkForStageCollisions(sf::RectangleShape player)
{
    for (unsigned int i = 0; i < collidableObjects.size(); i++)
    {
        if (player.getGlobalBounds().intersects(collidableObjects[i].getGlobalBounds()))
        {
            return true;
        }
    }
    return false;
}

```

Then in my player class I can perform logic based on whether there was a collision. The problem is that I need to know which object the player collided with to move them to the appropriate spot. Am i going about this the wrong way? Any help would be appreciated. Thank you!

# Answer
You are totally on target. One approach would be to return an integer which is the index of which one you hit, and a "special value" if nothing was hit. So:

```
int Stage::checkForStageCollisions(sf::RectangleShape player)
{
    ...
            return i;
    ...
    return -1;
}

```

Elsewhere you could say, `if(checkResult >= 0) [something was hit]`. Or do something with the checkResult which is the index of the rectangle that was hit.

If there's several rectangles per "thing you might hit" you'll need more lists or something to convert from that index to the value you actually care about.

Hope that helps.
> 2 votes

---
Tags: c++, platformer, sfml
---


# Question
Title: Do game-theoretic considerations stand in the way of this market-based game-mechanic achieving its goals?
**Mechanic**

The mechanic is called "market manipulation" and is supposed to work like this:

* Players can enter the London Stock Exchange (LSE)
* LSE displays the stock prices of 8 to 10 companies and derivatives. This number is relatively small to ensure that players will collide in their efforts to manipulate the market in their favor. The prices are calculated based on
    + real world prices of these companies and derivatives (in real time)
    + any market manipulations that were conducted by the players
    + any market corrections of the system
* Players can buy and sell shares with cash, a resource in the game, at current in-game market value
* Players can manipulate the market, i.e. let the price of a share either rise or fall, by some amount, over a certain period of time. Manipulating the market requires spending certain in-game resources and is therefore limited.
* The system continuously corrects market manipulations by letting the in-game prices converge towards their real world counterparts at a rate of 2% of the difference between the two per hour. Because of this market correction mechanism, pushing up prices (and screwing down prices) becomes increasingly difficult the higher (lower) the price already is.

**Goals**

* Players are supposed to collide (and have incentives to collide) in their efforts to manipulate the market in their favor, especially when it comes to manipulation efforts by different groups.
* Prices should not resolve around any equilibrium points. The more variance the better.
* Band-wagoning should always involve risk (recognizing that prices start rising should not be a sure sign that they will keep rising so that everybody can make easy profits even when they don't manipulate the market themselves)

**Question**

**Are there any game-theoretic considerations that prevent the mechanic from achieving these goals?**

# Answer
I'd start by asking where the conflict between players is supposed to come from. At a glance, I see only two potential sources for it:

* **Incomplete information**, a.k.a. "Who the *bleep* is driving this stock down when I'm trying to drive it up?" Unfortunately, while this can easily generate plenty of heated forum posts aimed at *those idiot n00bs*, it seems unlikely to lead to any sort of organized conflict.
* **Freeloaders** letting others manipulate the market and just taking the benefit without the cost. Alas, I don't see much that the non-freeloading players can *do* about it in your game, except maybe try to make their manipulations unpredictable.

I'd suggest trying to figure out what in your game would seem likely to make the players divide into opposing factions. If you can't find anything like that, you may want to add some.

Of course, another option would be to just implement it, let people playtest it and see what happens. It's hard to predict emergent game dynamics, and sometimes even seemingly trivial games may become interesting once you add actual human players into the mix.
> 2 votes

# Answer
Whether you let the in-game price converge to the real world prices by 2% per hour or some other system, the knowledge that they somehow will converge gives players a lot of certainty about the development of the stock market. If you want the recognition of rising prices to leave uncertainty about whether they will continue to climb, I would be very careful in offering tools to manipulate the market that have a predictable effect after they've been initiated. To maintain the uncertainty of the real stock market, you will have to avoid the in-game market lagging behind.

As far as bandwagoning goes, it depends on what a player's objective is. If the goal is to make money, nothing will stop me from getting on board with the same shares the strongest player bought, knowing he will devote his resources to driving these prices up. If the goal is to outwit other players, there already is a lot of feedback discouraging this play, even with complete information. Buying shares from the same company reduces incentive for people to drive the price up, since that would be advantageous to their opponents, and increases incentive for competitors to bring the price down. The only non-speculative way to determine whether this feedback works, is through playtesting.
> 1 votes

# Answer
I don't understand how players will be able to do any form of in-game market manipulations when your data is feed from the real LSE. The real market will do all the manipulations. Your game will just mimic the real market.

I would recommend to create your own market. Like World of Warcraft Auction House or Eve Online.

A stock exchange "simulation" system. Good luck with that.
> 0 votes

# Answer
One thing that might lead to a natural conflict in this kind of a game is to allow the players to "cash in" shares they own of the various companies for items/doodads/prizes of some kind that they want and the player can collect/show off. That way, a player will want to get the shares of a company they own part of as high as possible, then sell off at "the right time" and cash in for whatever the prize doodads are. You might artificially limit the number of companies they can own, which would lead to them trying to find a deal by buying a company that is cheap and trying to drive up the price before selling it off. It would not be in the interest of a player to buy into a company that is already expensive, since that would limit their ability to convert game credits/dollars/gold/whatever into permanent prize doodads. What they want is the least game credits spent to buy the most percentage of a company's stock, which they can then sell off and keep some stuff to brag about on the game forum. By adding a permanent, player-centric prize to the game and controlling the rate at which they can gain in-game credits, you could create sort of a stock market-based multiplayer online monopoly like game.
> 0 votes

---
Tags: game-design, game-theory
---


# Question
Title: What's the economical design difference for a global auction house or seperate auction traders?
I'm playing *The Elder Scrolls: Tamriel Unlimited* and there we have local auction houses. (Thy don't have auctions, but I keep the term to not get confused in the following text.)

I can see the advantage that guilds (who own these AHs) can set up their own little economy, which is a nice feature.

On the other side I always have to check several guild traders to see which one offers my searched item for the lowest price.

On the forums, people are discussing heavily whether a global auction house should be introduced or not. This may have pros and cons, too, but I'm not too involved in this game design to really set up a mind for that.

Backers argument that an global AH leads to a more regulated market, easier to use and a seller will reach a broader audience (reads: When you put in an item, you can be sure that there may be a buyer.)

On the other hand critics say that this will make only *really* useful items get a massive increased price and common used items will drop their prices to their normal selling price.

But are these concerns really true? Would the introduction of a global AH really have such a big impact on the game's economy? And if yes, will they more tend to even the prices or really make most of the items useless for selling?

You could also ask vice-versa: If a game already has global AH, what would the impact be if they replaced it with local auction houses?

**What is the difference for the game's and players' economy if you introduce a global or local auction house system?**

*For clarification: I do ask this for the matter of The Elder Scrolls: Tamriel Unlimited. But you can also subject this to other games. (This should be more a theoretical question for a developer's decision.)*

# Answer
This basically boils down to basic economic theory, more specifically the concept of market transparency.

When someone wants to buy or sell a fungible good (like most items in a common MMO game), they will look for the best available offer on the market and take it. In order to find this offer, they need to obtain full market transparency by looking at all places where the good can be offered.

By centralizing all offers in one place, you make it much easier for players to obtain market transparency. By spreading out the offers over many places you make it harder for players to obtain market transparency, but not impossible.

Those who are eager enough to put in the effort to obtain a better market transparency than others can make a profit by buying cheap in one market and selling high in another. But their activity will balance out the markets so that certain items will be worth almost the same in all markets.

So in the end having multiple separate auction house is just one thing: **a bad user interface**. It adds nothing to your game except forcing players to travel around and check all the different auction houses until they found the deal they want.

However, it can get interesting when you add **locality** to the equation, e.g. what if there is a cost for traveling between auction houses? Or what if some markets are unavailable to certain players because of their current game progress? In that case players might take suboptimal deals to avoid the cost (in time and/or resources) of traveling to a remote location. Under this condition prices could have regional variations. This means players who are willing to take the travel-cost others won't for an opportunity to buy low in one place and sell high in another will have the opportunity for a considerable profit margin. This can add an interesting additional trade component to your game when done well.

But keep in mind that adding cost for changing markets means that you need to remove three features which are very popular with players:

1. fast and cheap travel
2. fast and cheap item transfer between characters
3. large inventories

This won't just affect the trading component but also many other aspects of your game. Think carefully if this is worth it.
> 12 votes

# Answer
*Nickson104* already wrote a pretty nice summary in his comment.

I've been playing the game since early beta and I prefer the small AHs, so this might be a bit subjective, but overall the most important points have been mentioned already:

* A global AH makes it far easier for players to find the item they want at the cheapest price (which they usually want as well).
* A global AH makes grants a far bigger reach to single offers, so sellers will sell their wares faster as well.

However, both points have their downsides as well:

* With only one big auction house, it's far easier to find the cheapest or best offer, so sellers will actually have a harder time getting their asking price and underbidding would be even more common.
* At the same time, rare items will be sold a lot faster (due to bigger audience seeing the listing), which at the same time will raise prices for those.

---

Of course this is all but proven, but there are actually games out there I've played, which show this exactly. Take *Guild Wars 2* as an example:

* As a player it's almost impossible to sell common wares in a reasonable time. For some crafting materials you can't even use the AH's feature "suggest a price", because it would undercut the minimum asking price (which is fixed to the price NPCs will buy the stuff for).
* At the same time rare items (like legendary weapons) are very expensive and still raise in price, since there's constantly new money pumped into the economy and it's easy for players to find some demand, even for ridiculous prices. It's essentially a slow and steady inflation and there's hardly anything you can do to counter that (except adding massive money sinks, which in the end just promote even higher asking prices).

---

Now looking at a small scale "auction house landscape" like what *The Elder Scrolls Online* (or *Eve Online*) offers, you'll quickly see that it's definitely harder to find the best price for some specific item you want. The market is partially intransparent, but not in an unfair way. If you invest the little extra time, you can compare prices to save money or make some more money. It might be less convenient, but at the same time I consider it the far superior (and more realistic) system, especially considering those games are still called *MMO**RPG***.
> 10 votes

# Answer
Keeping in mind that in a perfect market, one has to know everything about the market (this includes of course price and quantities available):

With a local market:

* More chances to get ripped off (because you don't know all the prices)
* More possibilities to rip others off (because they don't know all the prices)
* More chances for a local monopoly (because the market is reaching a smaller amount of players)
* Much harder to implement a global monopoly (because you have to travel more to achieve it)
* More gameplay possibilities (some will arise as pure traders: buy low somewhere, sell for a profit somewhere else)

With a global market (it's the total opposite):

* Less chances to get ripped off (because the price you see is truly the lowest)
* Less possibilities to rip others off (because putting in a high price will get your offer bumped down by better offers)
* One (or a small group) can decide to try and buy out a single type of item and resell higher for a profit, just to create inflation (see this as a kind of monopoly over an item)

Now you have to keep some things in mind:

* With a local market, how easy or hard is it to carry goods from a local market to another market?
* With a local market, How easy or hard is it to know the prices of a remote local market?
* How easy or hard is it to *produce* goods?

About your concerns:

> Backers argument that an global AH leads to a more regulated market, easier to use and a seller will reach a broader audience.

This is true (thanks to market transparency).

> On the other hand critics say that this will make only really useful items get a massive increased price and common used items will drop their prices to their normal selling price.

This issue will rise if there is not way to *produce* useful items. This is due to the laws of the market: if there is an increase in the price, more producers will get on the market, and they'll all fight for the best price, which will make the price come down, until it reaches again a "stable" price.

So; what is better?

It all comes down to the implementation and the design.

EVE Online uses local markets but gives users ability to see the prices easily on other local markets via user-developed tools; in EO, you can "easily" produce goods that would net you a profit, you can travel "easily" to other local markets and you can carry stuff "easily" from a local market to another. IMHO, their implementation is GREAT!

Rappelz used to have local auction houses and local personal-store, but a high/infinite cost of producing goods, and a high cost of travelling from local market to local market. They eventually changed everything for a global market and it's been soo much of a plain reliever.
> 4 votes

# Answer
Like most things in game design, this comes down to game designer priorities and intentions.

The primary thing a global auction house does is eliminate the need to actually move goods. Therefore, the most interesting impact to game play by using localized auction houses to me is that it could be a way to facilitate a trading/merchant game as part of the overall game world. Imagine if you have an RPG with local trading houses. You also have localized resource clusters and travel requires time. You could create specialized upgrade paths for PCs to gain large-capacity cargo vehicles like caravans or ships. Maybe make other upgrade paths for different PCs that allow them to act like pirates or bandits. In this instance, you could have a dedicated game where certain players specialize in moving goods from one location to another, taking advantage of price differences.

On the other hand, if travel is nearly instantaneous (as it is in many MMORPGs for top level players), a global auction house would seem to make a lot more sense. As stated above, it would increase market transparency and let players spend less time buying and selling and more time on whatever you want them to be focused on.

It really boils down to what you want the game to be about and how much time you want players to be spending on the buying and selling aspect.
> 0 votes

---
Tags: game-design, game-mechanics, economy, game-theory
---


# Question
Title: How to create animation using sprite sheet in C++ and SFML 2.0?
I was wondering how do animation using a sprite sheet. I have a sprite sheet and the size is height:400 width:601

The code I am using is:

```
#include<SFML/Graphics.hpp>
#include<iostream>
#include <string>
int main() {

sf::RenderWindow Window;
Window.create(sf::VideoMode(980, 760), "Game Engine");
sf::Texture Ptexture;
sf::Sprite playerImage;
if (!Ptexture.loadFromFile("spritesheetIdle.png")) {
    std::cout << "error file not found\n";
}
playerImage.setTexture(Ptexture);
while (Window.isOpen()) {
    sf::Event Event;
    while (Window.pollEvent(Event))     {
            switch (Event.type)
            {
            case sf::Event::Closed:
                Window.close();
                break;

            }
                }
    Window.draw(playerImage);
    Window.display();
            }

        }

```

If you could then can you please try to explain me about `sf:IntRect()` too?

# Answer
> 1 votes
First off, I would suggest using power of two dimensions for your texture, it's not required, but more efficient.

`sf::Sprite` has a function "`void setTextureRect(const sf::IntRect& rectangle)`" which you can use to specify a sub-rectangle of the texture that sprite will display.

`sf::IntRect` has a few options to be created, generally it wants the coordinates for the top left corner and the width and height - IntRect is a typedef for `sf::Rect<int>`.

So if the first frame of your animation starts at 0,0 and your sprite is 64px by 32px, you could write

```
playerImage.setTextureRect(sf::IntRect(0, 0, 64, 32));

```

Between your event pulling and rendering, you could have "update" logic which changes the texture based on whatever conditions you'd like.

\*Edit: fixed code segments. Also - SFML has *great* documentation, check it out: http://www.sfml-dev.org/documentation/2.0/classsf\_1\_1Sprite.php http://www.sfml-dev.org/documentation/2.0/classsf\_1\_1Rect.php

---
Tags: c++, sfml, visual-studio
---


title: Entity System and "composite" entities

text:
# Question
Title: Entity System and "composite" entities
I'm new to the Entity Component System pattern and there's something I cannot figure out. Let's say I have the following entity:

```
Player: {
    Components: [
        Position: {
            x: 0,
            y: 0
        },
        Health: {
            max: 100,
            current: 50
        },
        Sprites: { ... }
    }
}

```

When I render an entity that has a Health component I also would like to render a health bar above that entity. Do I treat the health bar as a new entity and attach it to the Player i.e., the Player becomes a composite of entities; or it \[the Health bar\] should be part of the Health component, in which case how would it be rendered / created?

To illustrate what I'm trying to say:

```
Player: {
    ChildEntities: [
        Character: {
            Components: [
                Position: { x:parent.x, y:parent.y },
                Sprites: { parent... }
            ]
        },
        HealthBar: {
            Components: [
                Position: { x:parent.x, y:parent.y },
                Health: { max:parent.max, current:parent.current }
            ]
        }
    ],
    Components: [
        Position: {
            x: 0,
            y: 0
        },
        Health: {
            max: 100,
            current: 50
        }
    }
}

```

Is there an idiomatic / preferred way of doing this? Thanks.

# Answer
You are possibly conflating two separate things. I'll explain them below, but first I'll strongly note that you should spend some time playing around with existing game engines and get a sense for how they solve problems *before* trying to write your own game/engine from scratch.

**Transform Hierarchies**

Most engines have some form of hierarchy of transforms, aka a scene graph. In this case, a "child entity" would store its position relative to that of its parent. In this way, complex game objects made up of multiple sub-objects can move around in the world in a unified way.

In this case, you might attach the health bar object to the player object but give the health bar a (relative) position of `[0,+10]` so it float over the character's head.

Such a hierarchy is almost exactly what you have with your `Player` / `ChildEntities`.

**Observers**

The other useful concept is that of an observer for a component or an object. This essentially means that object A is able to see and inspect another object B's properties.

In this case, your health bar object wouldn't have it's own `health` component but would instead have a property that denotes which `health` component to observe.

Exactly how observing works is it's own topic. You could just store a handle/reference and manually query properties, or use an event system, or use a reactive flow, or allow all three and select on a case-by-case basis.

Regarding binding the observers, doing this right is somewhat tricky. You could have the health bar contain the component/logic to observe the character, or you could have the character contain the logic to attach the health bar as an observer, or you could have a third-party controller that makes these decisions. Again, in the real world, you'll probably have all three approaches used throughout your code selected on a case-by-case basis.
> 2 votes

# Answer
Here's one way to go about it.

Let's make the HealthBar its own entity and take advantage of the fact that entities can reference the same component instances.

So instead of setting up a parent/child relationship between the Player and HealthBar, we'll have them share components, in this case, the Position and Health components as seen below:

```
// create the position and health components
var pos = {x: 0, y:0};
var health = {max: 100, current: 50};

// create player entity, referencing position and health components
var Player = {
   Components:[
       Position: pos,
       Health: health,
       Sprites: {...},
       ...            // other components that define a player entity
   ]
}

// create healthbar enitity, referencing position and health components
var HealthBar = {
   Components:[
       Position: pos,
       Health: health,
       Sprites: {...},
       ...            // other components that define a healthbar entity
   ]
}

```

With this setup, whenever the player entity takes damage there will be a system in place to update the health component accordingly. Since the health bar has a reference to the same health component it can later use that information to update its state before its rendered.

I will admit that I'm making something of an assumption about your sprites. Most graphic APIs I've come across have some kind of scene-graph where Sprites are containers that have their own coordinate space. So while two Sprites may have the same position, their contents (which can be other Sprites) can be positioned relative to the origin of that container Sprite. So, in this case, the position component is shared between the two entities so that when the Player's position is updated the HealthBar's position is updated as well but the graphic that makes up the healthbar will be positioned within its sprite container so that it does not obscure the player sprite.
> 0 votes

---
Tags: entity-system, design-patterns, entity-component, entity
---


# Question
Title: How is a DirectX Adapter Different from a Device?
I'm relatively new to DirectX programming, and this is one of the more confusing issues I've encountered to date. According to the MSDN Documentation for DirectX 11:

> "A device is used to create resources and to enumerate the capabilities of a display adapter."

and from the MSDN Documentation for DirectX 9:

> "An adapter is a physical piece of hardware. Note that the graphics card might contain more than a single adapter, as is the case with a dual-headed display. "

From my neophyte perspective, these two concepts seem to overlap a fair amount. Am I correct in understanding that a device is an abstraction/encapsulation of a single adapter, which in turn is a software abstraction of a particular graphics card in the system?

# Answer
> 2 votes
The adapter is the physical (or emulated) device and is part of the DXGI api. These adapters are used in multiple APIs (D3D and D2D for example). The device is an abstraction on that that exposes APIs for creation of buffers and performing work in Direct3D. The device is basically what you work with and the adapter is what the device works with.

# Answer
> 1 votes
Yes. Adapters are your video cards (you can also create a software adapter).

First create a DXGIFactory https://msdn.microsoft.com/en-us/library/windows/desktop/dn268307(v=vs.85).aspx

Then query adapters on the device https://msdn.microsoft.com/en-us/library/windows/desktop/ff471336(v=vs.85).aspx

and last create your device with the adapter your prefer https://msdn.microsoft.com/en-us/library/windows/desktop/ff476082(v=vs.85).aspx

You can also query backwards from your device to see what adapter you have:

```
IDXGIAdapter * pDXGIAdapter = nullptr;
hr = pDXGIDevice->GetAdapter( &pDXGIAdapter );

```

---
Tags: directx
---


# Question
Title: Can I use the free version of Construct 2 on Gamejolt?
According to Scirra's website, I am not permitted to use the free version of Construct 2 for commercial purposes. If I host a game I created with the free version of Construct 2 on Gamejolt where I can earn money on the game, am I violating Scirra's terms?

# Answer
> 2 votes
**I am not a lawyer**, but that sounds like "commercial purposes" to me.

However, the best option in this case is to **consult a lawyer**.

# Answer
> 2 votes
From Licensing Agreement:

> The Free Edition is permitted for use by anyone for non commercial use. Commercial use counts as but is not limited to: use within any business (other than limited testing for suitability), generating advertising revenue, selling or licensing generated content or intention or capability to generate revenue.

From official Scirra tutorial page

> By default, games uploaded to Game Jolt have ad revenue sharing enabled, which may pose a problem for Free Edition users, who are not allowed to earn money from their games. Fortunately, Game Jolt recently introduced an option to disable ads for your games. Thanks to this, Free Edition users can feel free to publish their creations on Game Jolt. To disable ads, upload your game and go to its dashboard. Then, go to Settings and switch Show ads? to Off.

---
Tags: licensing, construct-2
---


# Question
Title: How should I control leveling up in a knowledge/skill testing game?
I have developed a game that tests the knowledge and skills in a series of short quiz-like games. Players have to move from Level 1 to Level 16 (with Level 4, 8 and 12 as major milestones~BANDS). The Difficulty level of game/questions increases at each level. The level progression is currently based on 'POINTS'. Points in turn are based on Correct responses, faster responses, Wins, Completion etc. Points continue to increase for a user irrespective of Win / Loss (the duration of completing the levels varies) The challenge I foresee is 'every user can progress to Level 16' if he keeps on playing the game long enough (irrespective of whether he has acquired the skill/knowledge for the next level).

I am looking for a simple to understand progression rule(s) that would make lower-skilled players remain longer in that BAND before progressing to the next level and BAND. What are some best practices in Level progression that I can refer to for overcoming this issue.

Thanks,

# Answer
The rule of thumb of designing difficulty curves is that you want to let the players progress as soon as they have demonstrated that they possess the necessary skills for the next level.

A large number of games with a low score does not demonstrate skill (rather the opposite, in fact). A single high score in a single game might be an indicator of skill, or just that the player got lucky (this depends on your game). But a true demonstration of skill is when the player reaches a *consistently* good performance over multiple consecutive games.

So you might want to look at the players average performance in the past X challenges and have them progress when you deem it good enough to be ready for the next difficulty level. For example, instead of progressing the player to level 10 when they got 1000 points in total, have them progress when they got 100 points in the past 10 challenges they played.

A real world analogue might be professional sports. A team doesn't advance to the next league when they won X games during their whole history or when they win one game extraordinarily high. They only advance when they win enough games during one season.
> 1 votes

---
Tags: android
---


# Question
Title: Algorithm for spacing points out among a line
I'm writing an angled tile system, and my implementation is to have a starting height and an ending height inside the tile.

Like so:

The starting and ending height allow me to get the length of the angle and the angle in degrees using atan2.

For collision against the angled tiles I give the tiles a collection of points along the line, and as a bounding box intersects any of a tile's slope points it will move the box's y position to that point.

This implementation works fine for 45 degree tiles, however with other degrees I don't know how to create the points on the line.

What algorithm could I use to space the points out along the line when they are not in a perfect 1 to 1 ratio angle? (e.g. 17 degrees instead of a nice 45 degrees)

EDIT: Here's a way to interpret my question perhaps more academically:

Given a length of a line and its angle, and an arbitrary number of points, find an algorithm that will space the points out among the line that will as closely resemble the angle.

# Answer
> 1 votes
My solution, using the Brensenham algorithm as suggested by Sam Hocevar:

```
public static Point[] brensenham(Point p1, Point p2) {
        final ArrayList<Point> points = new ArrayList<Point>();

        // BRENSENHAM the line across
        final int dx =  abs(p2.x-p1.x), sx = p1.x<p2.x ? 1 : -1;
        final int dy = -abs(p2.y-p1.y), sy = p1.y<p2.y ? 1 : -1;
        int err = dx+dy, e2; /* error value e_xy */

        while(true){
            points.add(new Point(p1.x, p1.y));
            if (p1.x==p2.x && p1.y==p2.y) break;
            e2 = 2*err;
            if (e2 >= dy) { err += dy; p1.x += sx; } /* e_xy+e_x > 0 */
            if (e2 <= dx) { err += dx; p1.y += sy; } /* e_xy+e_y < 0 */
        }

        return points.toArray(new Point[points.size()]);
    }

```

This returns a PERFECTLY spaced out line of points, with the perfect number of points in integer coordinates that most similates the original angle between the starting points.

Hope this can help anyone else, it made for a very easy angled tile system!

# Answer
> 0 votes
To space points on a line can be done several ways.

Where the line is defined with

```
x1 = ?  // line start
y1 = ?
x2 = ?  // line end
y2 = ?

```

To get a point on the line via a fraction of the line length

```
pointAt = ? // 0 to 1 are on the line
            // less than 0 is before the line greater than 1 is after the line

px = (x2-x1) * pointAt + x1;
py = (y2-y1) * pointAt + y1;

```

To get a point a set distance along the line get the normalized vector of the line

```
distOnLine = ?
nx = x2-x1
ny = y2-y1
lengthOfLine = sqrt(nx * nx + ny * ny)
if(lengthOfLine > 0){ // make sure the line has length
   nx /= lengthOfLine // normalise the vector
   ny /= lengthOfLine
   px = x1 + nx * distOnLine
   py = y1 + ny * distOnLine
}

```

To get points on the line a specific x coordinates find the slope of the line in terms of x

```
findPointForX = ?
if(x1 !== x2){ // make sure the line is not vertical
    slope = (y2-y1)/(x2-x1)
    px = findPointForX
    py = (findPointForX - x1) * slope + y1
}

```

For y just swap x for y in the above

Think that covers most of the situations. If you want to divide a line into equal segments use the first method and set the fraction as multiples of 1/steps.

If you want a point on a line at an angle

```
distOnLine = ? // where on the line in pixels
x1 = ?  // the line start
y1 = ?
angle = ?  // the angle in radians

px = cos(angle) * distOnLine + x1
py = sin(angle) * distOnLine + y1

```

To convert to radians from deg

```
rad = deg / (180 / PI) // where PI is 3.1415....

```

---
Tags: angles, trigonometry, tiles
---