# Question
Title: How do I represent blended tiles in a mesh/vertex array?
I recently started making a Terraria clone using the LÖVE library, which is based in OpenGL.

---

In Terraria, for each tile, there is a large texture with all possible combinations for merging with neighbouring tiles. They usually only support tiles of the same type, and sometimes other materials, like dirt. As a result, they only need a single vertex array.

---

In Starbound, it seems to be simpler. A tutorial I found notes the use of basic 8x8 blocks, with a few edges drawn if the block is next to a block of a different type.

---

I want to implement a similar mechanic, but I encountered a serious issue. A single vertex array does not allow z-ordering, which I would need.

* My first idea was to use one vertex array for each type of block, but that would eat a lot of memory.
* My second idea was to use the fact that OpenGL vertex array draws primitives in order. I could use some complicated data structure to represent tiles, so I would always know where to place their vertices in the array. However, that would either require moving lots of vertices or lots of memory.

What is the best way to implement this?

# Answer
> 2 votes
I found a way myself.

The key is to have two vertex arrays. In first you store solid blocks. In second you store edges, only if they are visible. Then you simply draw solid blocks first, then edges.

It is easy to add third array to store in-corners.

Vertex arrays look like these (from left: first, second, third array, final result)

Hope this helps somebody!

---
Tags: opengl, performance, tiles, tilemap, love2d
---


title: Difference between Material and Shader

text:
# Question
Title: Difference between Material and Shader
In games, materials often only influence the visual appearance of objects. The visual appearance is effected by shaders. So regarding to terminology is there a difference between materials and shaders? Should you write one shader for one material?

# Answer
> 34 votes
A material is a combination of attributes which describe how a surface of the given material should look like.

Some engines use different shaders for different materials, in which case a material definition could look like this:

```
[Material]
Shader=NormalMappedSpecular.glsl
Texture1=Rock.png
Texture2=RockNormal.png
Texture3=RockSpecular.png

```

Other engines use one shader for all objects (or rather the engines decides what shader to use dependent on the parameters, the capabilities of the GPU and other factors such as distance), in which case a material would look more like this:

```
[Material]
Ambient=0.5
Specularity=0.7
DiffuseMap=Rock.png
NormalMap=RockNormal.png
SpecularMap=RockSpecular.png

```

# Answer
> 11 votes
A **material** specifies how an object responds to light.

There are a couple of common parameters:

* Kd: Diffuse response to light
* Ks: Specular response to light
* Ns: "Shininess"
* map\_Kd: Texture

Now say you have a triangle rendered *with* material `M`. `M` has Kd=(1,0,0) (red diffuse response), Ks=(1,1,1) (white specular response), Ns=25 (specular highlight will be quite sharp and not fuzzed out) and no map\_Kd (no texture).

The job of the **shader** is to use math to take the vertex positions of **triangle**, the position of the light, the material color values, and figure out what color the triangle should appear. A vertex shader does this "shading computation" once at each vertex and interpolates the color across the triangle.

A common operation in a shader to compute the diffuse response at a vertex is:

```
// hlsl
float3 vertexToLight = normalize( lightPos.xyz - vertexPos.xyz ) ;

float3 diffuseColor = max( dot( vertexToLight, vertexNormal ), 0.0 ) * kd * lightColor ;

```

# Answer
> 3 votes
A material is what you apply to geometry to give it a colour and pattern. A texture is a component of a material.

A shader is a small program that allows this material to be rendered at runtime. The nice thing about shaders is that you can do everything from simply rendering the material, to adding dynamic effects like specular highlights and reflections all the way up to extremely clever things such as rendering fake holes through walls where a bullet has hit.

so in answer to your question - yes there is a difference, there is a little overlap too - you could either make a red material or write a shader to render things as red, but both of them also allow you to a lot of things you could not with the other.

and no, you don't need one shader per material. although a material requires a shader to be rendered, you could have one for all you materials if you wanted. they do specific things so if you wanted everything to be shiny for example, you could just write one.

A nice example of shaders is in gears of war. there is one set of materials for the scene, but when you press a button to switch to tactical view, the shaders that are rendering these materials change so things look outlined and generally different. The same thing happens in batman: arkham's 'detective mode'.

# Answer
> 2 votes
Although late, there is a "cheat" which can help you understand better.

A material is everything that is attached to a certain shader for that draw call.

For example, in the above answer, you have this material: \[Material\] Shader=NormalMappedSpecular.glsl Texture1=Rock.png Texture2=RockNormal.png Texture3=RockSpecular.png

which translated that you will be rendering with a shader that does a normal map and a specular computation, and it will use the 3 textures inside that shader.

Later on, you can re-use the same shader, with different other 3 textures (like car, carNormal and carSpecular), you will do a different draw call with a different material, just because you changed the shader parameters.

All in all, a material is everything that uniquely creates a draw call using the same shader with the same parameters (textures, uniforms, attributes).

I hope this helps to better visualize it

---
Tags: shaders, terminology, materials
---


# Question
Title: How do I sort with both depth and y-axis in OpenGL?
Continuing my misadventures in pyOpenGL, I've refactored the whole thing to use 4 buffers:

1. tile vertices - all drawn at the start, probably never modified
2. tile texture co-ords - not modified often (but enables support for animated tiles later)
3. sprite vertices - modified often as sprites move around the map
4. sprite texture co-ords - modified often as sprites animate

My draw loop binds each buffer, and calls `drawArrays()` twice. I have enabled depth testing, and clear the depth buffer on each draw:

```
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH)
...
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

```

For the moment, I've hard-coded the z coordinate for each of the things I'm drawing, just to be sure they're definitely in the right order - grass tiles are at `0.9`, the tree (4 tiles) is set to -1.0 and the sprites are at 0.0. This is what I get:

In a previous attempt to build this engine without openGL, I was using Tkinter canvas images, which ended up very slow. To get the draw order right, I had to sort all the objects by their y-coordinate plus their z-coordinate, because it is all on a 2D plane. I want something similar, here. I don't understand why the grass tiles cause this problem, when they should be drawn right at the back. `GL_DEPTH_TEST` is definitely enabled - if I disable it by commenting out the `glEnable()` call, the sprites are drawn on top of everything (including on top of the trees). I want an illusion of depth by being able to walk behind high-sticking-up objects.

---

I've continued hacking away at this, and I've gotten a little further by modifying my shader:

```
fragment_shader = shaders.compileShader("""
    uniform sampler2D u_image;

    varying vec2 v_texCoords;

    void main()
    {
        vec4 tex = texture2D(u_image, v_texCoords);
        if(tex.a < 1.0)
          discard;
        gl_FragColor = tex; //texture2D(u_image, v_texCoords);
    }
""", GL_FRAGMENT_SHADER)

```

By checking for transparent pixels and throwing them away, I get a lot closer to my goal, however it is still not *quite* right, and I do not know how to fix it.

The wizard is at `z:-0.5`, and the tree trunk is at `z:-0.2`; it *is* doing what I'm telling it to do, just not what I *want* it to do. If I put them on the same z-level, the trunk is drawn over the wizard when he stands in front of the tree, and correctly when he stands behind it:

I don't just want depth sorting, I also want to sort on the *y-axis*. How can I do this in OpenGL?

# Answer
> 4 votes
You'll need

1. An orthogonal Projection Matrix.

In fixed pipeline openGL: `glOrtho(0, screen_width, screen_height, 0, -(1<<16), 1<<16)`
2. A wrapper function similar to: `DrawSprite(int x, int y, int z, Rect texcoords)` This function will add vertices to the vertex buffer you're using - with the exact Z coordinate specified for the whole sprite.
3. Coordinate system that looks like this (e.g. identity matrix for modelview):

4. Alpha testing `glEnable(GL_ALPHA_TEST);` `glAlphaFunc(GL_GREATER, 0.9f);` \- this is to make sure that transparent pixels DO NOT get written to depth buffer.
5. Depth testing `glEnable(GL_DEPTH_TEST);` The default depth function is the one we want.
6. Finally when you draw a sprite you call `DrawSprite(sprite.x, sprite.y, sprite.y, texturecoords_rect)`. As you see, the `sprite.y` coordinate is used as the Z coordinate and corresponds to value written to depth buffer.
7. Sprite coordinates correspond to *feet* of the object.

The RED DOT, is the sprite X, Y coordinate. So the Z value has to correspond to Y coordinate of the RED DOT. Also in this case the tree is a sprite and not part of the tilemap (directly).

Or you could have the red dot be right in the middle (but that doesn't really matter for the correct Z ordering):

No manual sorting is necessary here, all the *sorting* is done using depth testing!

---
Tags: opengl, python
---


title: unity 5.5 - OnMouseClick not fired

text:
# Question
Title: unity 5.5 - OnMouseClick not fired
On the Unity Editor, the `OnMouseClick()` function is fired but in my executable file it does not work. It is rare for it to fire, but it does not fire when the object is clicked. I have tried to:

The method used:

```
public void checkHit()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            if (ammo > 0)
            {
                money++;
                explosion.Play();
                health -= dmg;
            }
        }
    }
}

```
* Set a BoxCollider2D
* Set a BoxCollider

None of these methods have worked so far when opening the game from the executable file.

This is my code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using UnityEngine.SceneManagement;

[RequireComponent(typeof(AudioSource))]

public class SeAI : MonoBehaviour {

    public Image sof;
    public Canvas Game;
    public Canvas GameOver;
    public Canvas WinScreen;
    Vector3 canvasMin;
    Vector3 canvasMax;
    Vector3 randomVec;
    System.Random r;
    public Text ammoTxt;
    public Text moneyTxt;
    public Text outOfAmmo;
    public Text gunDmg;
    public Text seLife;
    public Button addDmg;
    public AudioSource explosion;

    int ammo = 10;
    int money = 0;
    int dmg = 1;
    int health = 250;

    void Start()
    {
        GameOver.enabled = false;
        WinScreen.enabled = false;
        canvasMin = Game.GetComponent<Collider2D>().bounds.min;
        canvasMax = Game.GetComponent<Collider2D>().bounds.max;
        randomVec = new Vector3();
        r = new System.Random();
    }

    void updateScore()
    {
        ammoTxt.text = "AmMo: " + ammo;
        moneyTxt.text = "MoNeY: $" + money;
        gunDmg.text = "Gun Damage: " + dmg;
        se.text = "Se's Health: " + health;
        addDmg.GetComponentInChildren<Text>().text = "Add gun damage: $" + (dmg * 2);
    }

    public void buyAmmo()
    {
        if (money > 1)
        {
            ammo += 6;
            money -= 2;
        }
    }

    public void addGunDamage()
    {
        if(money >= (dmg * 2))
        {
            dmg += 1;
            money -= (dmg * 2);
        }
    }

    public void checkHit()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (ammo > 0)
                {
                    money++;
                    explosion.Play();
                    health -= dmg;
                }
            }
        }
    }

    void checkClicks()
    {

        if (Input.GetMouseButtonUp(0))
        {
            if (ammo >= 1)
            {
                --ammo;
            }
        }
    }

    void checkGameOver()
    {
        if((money <= 1) && (ammo == 0))
        {
            Game.enabled = false;
            WinScreen.enabled = false;
            GameOver.enabled = true;
        }
    }

    void checkWin()
    {
        if(health <= 0)
        {
            Game.enabled = false;
            GameOver.enabled = false;
            WinScreen.enabled = true;
        }
    }

    public void tryAgain()
    {
        SceneManager.LoadScene("Game");
    }

    public void Quit()
    {
        Application.Quit();
    }

    void Update ()
    {

        checkHit();
        updateScore();
        checkClicks();
        checkGameOver();
        checkWin();

        if(ammo < 1)
        {
            outOfAmmo.enabled = true;
        }
        else if(ammo > 0)
        {
            outOfAmmo.enabled = false;
        }

        if(r.Next(0, 30) == 15)
        {
            randomVec.x = r.Next((int)canvasMin.x, (int)canvasMax.x);
            randomVec.y = r.Next((int)canvasMin.y, (int)canvasMax.y);

            gameObject.transform.position = randomVec;
            sof.transform.position = randomVec;
        }

    }
}

```

# Answer
> 0 votes
I fixed this issue by adding a Collider2D to the image, then I checked to see if the mouse position was inside of the Collider2D bounds when the image is clicked on. I also had to move the Collider2D to where the image was moving.

Example:

```
public void checkHit(){
    if(Input.GetMouseButtonDown(0)){
        if(sof.transform.GetComponent<Collider2D>().bounds.Contains(Input.mousePosition)){
            //Code here
        }
    }
}

```

# Answer
> 0 votes
if `SeAI` script is enabled and attached to an active gameObject in the scene `Input.GetMouseButtonDown(0)` should work. otherwise it shouldn't.

if `SeAI` script is enabled and attached to an active gameObject in the scene, and also it it a raycast target and no other raycast targets are blocking the raycast to it, then `OnMouseClick` should work. otherwise it shouldn't.

If you must use `OnMouseClick` make sure your game object with SeAI script, has a component which provides the raycast ability and no other (probably invisible) raycasts targets are in front of it.

Note 1 - colliders are also raycast targets.

Note 2 - raycast hits only one target.

---
Tags: unity, c#, bounding-boxes
---


title: LibGdx Tiled Map Rendering Problem

text:
# Question
Title: LibGdx Tiled Map Rendering Problem
I'm trying to study a book to learn LibGDX game engine but I have a problem with rendering tiled maps. I think I wrote the same code that is in the book but I couldn't get the same result.

It's a simple game with a character and a map. When I rendered my character and background, there was no problem.

It's looking like this:

But after I add my tmx map, the screen shows just some part of the game and no map.

I don't know how to fix this and I'm really confused.

The code below are my GameManager and ScreenManager classes. If possible, please figure out what I did wrong.

```
public class GameManager {

 static TiledMap map;
 public static TiledMapRenderer renderer; /////

 //region paddle
 static TextureRegion leftPaddleTexture;
 static TextureRegion rightPaddleTexture;
 static Sprite leftPaddleSprite;
 static Sprite rightPaddleSprite;
 public static final float PADDLE_RESIZE_FACTOR = 700 f;
 public static final float PADDLE_ALPHA = 0.25 f;
 public static final float PADDLE_HORIZ_POS_FACTOR = 0.02 f;
 public static final float PADDLE_VERT_POSITION_FACTOR = 0.01 f;
 //endregion

 static AssetManager assetManager;
 static TextureAtlas texturePack;

 static Bob bob;

 static TextureRegion bobSpriteSheet;

 public static Sprite backgroundSprite;
 public static Texture backgroundTexture;

 public static final float BOB_RESIZE_FACTOR = 400 f;

 public static void loadAssets() {
  assetManager.load(GameConstants.backgroundImage, Texture.class);
  assetManager.load(GameConstants.texturePack, TextureAtlas.class);

  assetManager.setLoader(TiledMap.class, new TmxMapLoader(new InternalFileHandleResolver()));

  assetManager.load(GameConstants.level1, TiledMap.class);

  assetManager.finishLoading();
 }

 public static void initialize(float width, float height) {

  assetManager = new AssetManager();
  loadAssets();

  map = assetManager.get(GameConstants.level1);
  renderer = new OrthogonalTiledMapRenderer(map, GameConstants.unitScale);

  GameScreen.camera.setToOrtho(false, 35, 20);
  GameScreen.camera.update();

  renderer.setView(GameScreen.camera);

  texturePack = assetManager.get(GameConstants.texturePack);

  initializeLeftPaddle(width, height);
  initializeRightPaddle(width, height);

  bob = new Bob();
  bobSpriteSheet = texturePack.findRegion(GameConstants.bobSpriteSheet);
  bob.initialize(width, height, bobSpriteSheet);

  bob.bobSprite = new Sprite(bobSpriteSheet);

  //set the size of the bob
  bob.bobSprite.setSize((walkSheet.getRegionWidth() / ANIMATION_FRAME_SIZE) * (width / BOB_RESIZE_FACTOR),
   walkSheet.getRegionHeight() * (width / BOB_RESIZE_FACTOR));

  bob.bobSprite.setPosition(width / 2 f, 0);

  backgroundTexture = assetManager.get(GameConstants.backgroundImage);
  backgroundSprite = new Sprite(backgroundTexture);

  backgroundSprite.setSize(width, height);

 }

 public static void renderGame(SpriteBatch batch) {
  backgroundSprite.draw(batch);
  bob.update();
  bob.render(batch);
  leftPaddleSprite.draw(batch);
  rightPaddleSprite.draw(batch);

 }

 public static void dispose() {
  assetManager.unload(GameConstants.backgroundImage);
  assetManager.clear();
 }

 public static void initializeLeftPaddle(float width, float height) {
  leftPaddleTexture = texturePack.findRegion(GameConstants.leftPaddleImage);
  leftPaddleSprite = new Sprite(leftPaddleTexture);

  leftPaddleSprite.setSize(leftPaddleSprite.getWidth() * width / PADDLE_RESIZE_FACTOR,
   leftPaddleSprite.getHeight() * width / PADDLE_RESIZE_FACTOR);

  leftPaddleSprite.setPosition(width * PADDLE_HORIZ_POS_FACTOR, height * PADDLE_VERT_POSITION_FACTOR);

  leftPaddleSprite.setAlpha(PADDLE_ALPHA);
 }

 public static void initializeRightPaddle(float width, float height) {
  rightPaddleTexture = texturePack.findRegion(GameConstants.rightPaddleImage);
  rightPaddleSprite = new Sprite(rightPaddleTexture);

  rightPaddleSprite.setSize(rightPaddleSprite.getWidth() * width / PADDLE_RESIZE_FACTOR,
   rightPaddleSprite.getHeight() * width / PADDLE_RESIZE_FACTOR);

  rightPaddleSprite.setPosition(leftPaddleSprite.getX() + leftPaddleSprite.getWidth() + width * PADDLE_HORIZ_POS_FACTOR,
   height * PADDLE_VERT_POSITION_FACTOR);

  rightPaddleSprite.setAlpha(PADDLE_ALPHA);
 }
}

public class GameScreen implements Screen {

 MainGame game;
 SpriteBatch batch;
 public static OrthographicCamera camera;

 public GameScreen(MainGame game) {
  this.game = game;
  float height = Gdx.graphics.getHeight();
  float width = Gdx.graphics.getWidth();

  camera = new OrthographicCamera(width, height);
  camera.setToOrtho(false);

  batch = new SpriteBatch();

  GameManager.initialize(width, height);

  Gdx.input.setInputProcessor(new InputManager(camera));

 }

 @Override
 public void show() {

 }

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

  batch.setProjectionMatrix(camera.combined);

  GameManager.renderer.render();

  batch.begin();
  GameManager.renderGame(batch);
  batch.end();

 }

 @Override
 public void resize(int width, int height) {

 }

 @Override
 public void pause() {

 }

 @Override
 public void resume() {

 }

 @Override
 public void hide() {

 }

 @Override
 public void dispose() {
  batch.dispose();
  GameManager.dispose();

 }
}

```

I also searched on site to find same problem but I couldn't. I hope the community can help and Thank You if you can.

# Answer
> 1 votes
The following code is the problem:

```
GameScreen.camera.setToOrtho(false, 35,20);

```

This basically says - make the screen show only 35 across and 20 vertically of the area. If you use larger numbers, you will see more (zoom out).

# Answer
> 0 votes
Problem is in this line of code:

```
renderer = new OrthogonalTiledMapRenderer(map, GameConstants.unitScale);

```

// it means load the map, set the unit scale to 1/16 (1 unit == 16 pixels)

```
 GameScreen.camera.setToOrtho(false, 35,20);
    GameScreen.camera.update();

```

// create an orthographic camera, shows us 35x20 units of the world

what renderer does, it shows you in pixels so it is showing you that part with that scale 16 pixel is tile width/height in your map and 35,20 is how much map size you want to render at a time.Hope this helps

Here is link to source code for simple platformer:

https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/superkoalio/SuperKoalio.java

---
Tags: java, libgdx
---


# Question
Title: Why does Unity require an EventSystem component for input during a play-test, where input works fine without it in a build?
<sup>*Please be aware that this was initially a question about how to get the input to work. A comment pointed me in the direction of a fix, but only left me with more questions in regards to understanding the problem I was originally having, so I have edited my question to include the initial solution and focus on the question I still have.*</sup>

## The Problem:

Recently, I have moved from using GUIText and GUITexture objects to using the Canvas to display UI elements. In effort to set up a prototype, some external GUI elements were imported, and when the game is **built and run** from my phone, everything works as intended.

*However*, if I simply run the game from inside Unity, input is completely ignored. I originally thought this may have been a response to grabbing *touch screen* input, and expecting it to work on a regular screen with mouse input, but I have since confirmed that it still does not work when using Unity Remote to test the game on my phone.

It has since been pointed out that I was not using an EventSystem, along side my Event Trigger objects. After implementing an EventSystem component, and the default input module supplied by the EventSystem interface, the input works. However, this still leaves me confused. What is the point of enforcing the implementation of the EventSystem, if it only ensures functionality during play test? Why would I want this system in my end build, when I can confirm that the build version functions properly, without it?

Below you will find my setup, contextual to the problem. Click for a zoomed in view, as I have included the component structure of my UICanvas and MainCamera objects, in case it is helpful. In this case, we have a button that increases the max speed, when pressed. Everything works in a build, but nothing works during a play-test.

## Additional Information:

* I have enabled 'show touch input' on my phone, to confirm that the phone is still registering touch input.
* I moved to using the Canvas object after the 'depreciated warning' for using GUIText and GUITexture turned into a 'depreciated error'. *Even if there is a suitable way to still perform these actions with the GUIText and GUITexture objects*, I still wish to persist with using the Canvas. I am also personally curious as to why this issue exists within the Canvas, as it seems lead to obvious cases of severe inefficiency, in a system that seems to have been put together with the sole point of being more efficient.
* I can create manual *OnMouseDown* buttons that will work during play test, however, some GUI elements are more complex and persisting with this sort of solution seems like an incredible waste of time.
* As previously mentioned, I do not have any input issues if I simply build and run the game from my phone. However, this takes considerably more time than a simply debug test, and even without the high efficiency cost, I do not have access inspector-manipulation during my play-test.
* I am using Unity version 5.3.5 personal. Any solution that *does not* include updating Unity will be well preferred. While I have no physical problems updating Unity, in some previous projects updating Unity versions has lead to massive issues that we would prefer to outright avoid, if possible.

## TL;DR:

Unity will not accept input on my input canvas during debug. I literally have to build and run my project each time I want to test input, or create dodgy hacks to provide input from the Inspector. The addition of an EventSystem allows input during debug play-testing, but is not needed for input post-build. Why does Unity act this way, and why do I need an EventSystem entirely for play-test input?

# Answer
Given the consistency in user testing, and the failure to replicate this odd behaviour, I am content with leaving this down to a bug.

If anybody else experiences this problem, rest assured that it does not seem to pose any additional problems. Four months later, and there have not been any apparent side effects in our game, apart from a very confusing initial debug phase.
> 0 votes

---
Tags: unity, touch, interface
---


# Question
Title: Animations with individual images in Phaser.js
So I have this game that I made a while back and I want to port it using Phaser.

The game is made using individual PNG files for all the animation frames, and there are over 100 of them.

From reading through the docs, it seems Phaser only supports spritesheets for animations.

I would like to do something like this :

```
player.sprite.animations.add('idle', ['images/s_snailIdle_0.png', 'images/s_snailIdle_1.png'], 60, true, false);
player.sprite.animations.play('idle');

```

Is there a way to add individual images to a sprite's animation? If not, Is there a way to change the image of a sprite so that I can implement my own animation system?

# Answer
For anyone else in this dilemma, I would recommend these links to you:

https://www.codeandweb.com/texturepacker/tutorials?km\_user-type=developer

https://www.codeandweb.com/texturepacker/download
> 1 votes

# Answer
Since the asker ended up using a texture atlas, for those looking for the relevant code, preload the texture atlas as usual:

```
this.load.atlas('sheet', 'sheet.png', 'sheet.json', null,
    Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);

```

You can then create a new `Sprite`, making sure to reference the atlas.

```
var afterburners = new Phaser.Sprite(game, 0, 15,
    'sheet', 'fire11.png');

```

Then you can switch to a different sprite in that atlas for an animation.

```
afterburners.animations.add('burn',
    ['fire11.png', 'fire14.png', 'fire15.png'],
    15, true);
afterburners.animations.play('burn');

```
> 1 votes

---
Tags: javascript, animation, sprites, phaser, png
---


title: OpenGL texture bleeding

text:
# Question
Title: OpenGL texture bleeding
I am rendering some sprites from a sprite sheet that I generated but as I do, I get a purple haze around the blocks (The purple is coming from the other blocks in the sprite sheet that are next to them)

I thought it might be down to float mathematics not being 100% accurate but from what I can tell there is no problem. Also, it only happens when loading in sprite sheets as this is the only image code that extracts a section of an image in my game.

Has anyone else came across this and know what might be causing it?

Edit: Here is some example code of how the shader gets the sprite position's

Vertex Shader

```
#version 400 core

in vec3 position;
in vec2 textureCoords;
in vec3 normal;

out vData{
    vec2 pass_textureCoords;
    vec3 surfaceNormal;
    vec3 toLightVector;
    vec3 toCameraVector;
    float visibility;
}vertexOut;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;

uniform float useFakeLighting;

uniform float texture_spriteSheetWidth = 1;
uniform float texture_spriteSheetHeight = 1;

uniform float texture_spriteSheet_xOffset;
uniform float texture_spriteSheet_yOffset;

const float density = 0.0035;
const float gradient = 5.0;

void main(void) {
    vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
    vec4 positionRelitiveToCam = viewMatrix * worldPosition;
    gl_Position = projectionMatrix * positionRelitiveToCam;
    vertexOut.pass_textureCoords = vec2((textureCoords.x + texture_spriteSheet_xOffset) / texture_spriteSheetWidth,
        (textureCoords.y + texture_spriteSheet_yOffset) / texture_spriteSheetHeight);

    vec3 actualNormal = normal;
    if (useFakeLighting>0.5) {
        actualNormal = vec3(0.0, 1.0, 0.0);
    }

    vertexOut.surfaceNormal = (transformationMatrix * vec4(actualNormal, 0.0)).xyz;
    vertexOut.toLightVector = lightPosition;// -worldPosition.xyz;
    vertexOut.toCameraVector = (inverse(viewMatrix) * vec4(0.0, 0.0, 0.0, 1.0)).xyz - worldPosition.xyz;

    float distance = length(positionRelitiveToCam.xyz);
    vertexOut.visibility = exp(-pow((distance*density), gradient));
    vertexOut.visibility = clamp(vertexOut.visibility, 0.0, 1.0);
}

```

Fragment Shader

```
#version 400 core

in vData{
    vec2 pass_textureCoords;
    vec3 surfaceNormal;
    vec3 toLightVector;
    vec3 toCameraVector;
    float visibility;
}vertexIn;

out vec4 out_Color;

uniform sampler2D textureSampler;
uniform vec3 lightColour;
uniform float shineDamper;
uniform float reflectivity;
uniform vec3 skyColor;

void main(void) {

    vec3 unitNormal = normalize(vertexIn.surfaceNormal);
    vec3 unitLightVector = normalize(vertexIn.toLightVector);

    float nDotl = dot(unitNormal, unitLightVector);
    float brightness = max(nDotl, 0.2);
    vec3 diffuse = brightness * lightColour;

    vec3 unitVectorToCamera = normalize(vertexIn.toCameraVector);
    vec3 lightDirection = -unitLightVector;
    vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);

    float specularFactor = dot(reflectedLightDirection, unitVectorToCamera);
    specularFactor = max(specularFactor, 0.0);
    float dampedFactor = pow(specularFactor, shineDamper);
    vec3 finalSpecular = dampedFactor * reflectivity * lightColour;

    vec4 textureColour = texture(textureSampler, vertexIn.pass_textureCoords);
    if (textureColour.a<0.5) {
        discard;
    }

    out_Color = vec4(diffuse, textureColour.a) * textureColour + vec4(finalSpecular, textureColour.a);
    //out_Color = mix(vec4(skyColor, 1.0), out_Color, vertexIn.visibility);

}

```

And the relevent part is here

```
vertexOut.pass_textureCoords = vec2((textureCoords.x + texture_spriteSheet_xOffset) / texture_spriteSheetWidth,
        (textureCoords.y + texture_spriteSheet_yOffset) / texture_spriteSheetHeight);

```

Loading Textures Into OpenGL

```
glEnable(GL_TEXTURE_2D);
GLuint id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
textures.push_back(id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &finalBuffer[0]);

glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
float mipMapingAffectivness = 0.4f;
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, mipMapingAffectivness);

glBindTexture(GL_TEXTURE_2D, 0);

```

# Answer
> 4 votes
If I understand correctly, you're using a texture atlas (several sprites in a single texture)? You've got the min and mag filters set to linear, which means it will interpolate between pixels if the texture sampling coordinate isn't exactly in the center of the pixel. That means that near the border, if you aren't careful, you'll get bleed-through from neighboring sprites. There are a few options:

1. Set the min and mag filters to nearest instead of linear.
2. Ensure that when the fragment shader actually samples the textures it never samples less than 1/2 a pixel from any border.
3. Put a 1-pixel border around each sprite that simply repeats the current edge.

---
Tags: opengl, textures
---


# Question
Title: Unity swapping textures not working, weird?
I made two textures for my 3D game character. I can use both of them by dragging them on my player but I want to do the same through code. I searched and found that people are either using:

1) `rend.material.mainTexture = texts [0];`

or

2) `transform.GetComponent<Renderer>().material.mainTexture = texts [0];`

but none of them works for me. I have a mesh renderer attached to my player. I set my code to swap the texture on my player when it reaches a certain amount of points. To debug I attached an empty material to my player and during run time so that I could see the texture on it but the swap didn't take place. The first texture is in texts\[0\] and the second one is in texts\[1\].

This is my code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class swaptexture : MonoBehaviour {

    public Texture[] texts;
    public gemlife g;

    // Use this for initialization
    void Start () {

        transform.GetComponent<Renderer> ().material.mainTexture = texts [0];
    }

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

        if (g.ratio >= 0.96f)
            transform.GetComponent<Renderer> ().material.mainTexture = texts [1];
    }
}

```

# Answer
I think there is a problem with your `g.ratio >= 0.96f` condition. In my opinion the code is working fine, you might have to check if the condition is met or not.

```
public Texture[] tex;

float timer = 0;
// Use this for initialization
void Start ()
{
    transform.GetComponent<Renderer>().material.mainTexture = tex[0];
}

// Update is called once per frame
void Update ()
{
    if (timer >= 1)
    {
        transform.GetComponent<Renderer>().material.mainTexture = tex[1];
        //timer = 0;
    }

    timer += Time.deltaTime;
}

```
> 1 votes

---
Tags: unity, c#, textures, unityscript, rendertexture
---


# Question
Title: How to find the nearest object from another, in a non tile based game where obstacles are present?
The nearest object means the path from the initial position to this object is shorter than the path from initial position to any other object. The path is the smallest number of pixels this object must move to reach the target object while making sure that it does not collide with any obstacle.

Like in this example below, consider that object A has to determine which object is closer, object B or object C. The pink rectangle is an obstacle. Now if we consider the euclidean distance, object B will be closer but due to the presence of an obstacle euclidean distance will give false answers.

Another solution would be to find the distance using some pathfinding algorithm (like A\*), which will give the correct solution, but will be slower than simply calculating euclidean distance.

The ideal solution should give the answer as an object the path to which is no more than 10% larger than to the nearest object. And it should take no more than 10 millisecond on a modestly powered computer to find the nearest object for 1000 different objects on a map that has upto 1000 obstacles of different sizes and the map is no larger than 1000\*1000 pixels (like in the image above the nearest object for A is C, for B it is A and for C it is A). Also it should not take more than 50 MB of RAM (excluding the size of RAM used to store the coordinates of objects and obstacles and their sizes).

And the map is dynamic. The solution need not return the path between the objects, it need to only find the nearest object.

What will be the ideal solution of this problem?

# Answer
> 2 votes
Considering the settings described in the question with a map limited to 1000^2 in size, that constantly changes, you can draw the obstacles on a bit array and then run A\* where `h(n)` is the path length until node `n` and `g(n)` is the distance in pixels.

You can use a low res representation 250^2 / 100^2 if you can afford to lost a little bit of accuracy.

https://en.wikipedia.org/wiki/A\*\_search\_algorithm

---
Tags: path-finding
---


# Question
Title: How to start an animation just once on an event in libGDX
I am trying to show an explosion animation which i created using a few textureregions and created Animation `missileblastAnimation` from those textureregion like this -- \>

```
 TextureRegion[] explosion = { explodemissile1, explodemissile2, explodemissile3, explodemissile4, explodemissile5,
                 explodemissile6, explodemissile7,explodemissile8, explodemissile9, explodemissile10, explodemissile11,
                 explodemissile12, explodemissile13, explodemissile14,explodemissile15, explodemissile16, explodemissile17,
                 explodemissile18};
        missileblastAnimation = new Animation(0.1f, explosion);
        missileblastAnimation.setPlayMode(Animation.NORMAL);

```

I have this following code in the `render` method -- \>
Note:- **`explosionstarted`** is set to true when missile hits the ground

```
  if(explosionstarted){//check if the missile hits the ground to start explosion animation
       batcher.draw(AssetLoader.missileblastAnimation.getKeyFrame(runTime),
                              100, 300-102, 50, 102);
      if(AssetLoader.missileblastAnimation.isAnimationFinished(runTime)){
     // i found that isAnimationFinished tells if animation is finished or not but i still cant understand the passing runTime thing
          explosionstarted = false; //reset the boolean to make the animation stop drawing
        }
    }

```

Problem is the animation is not playing as it should i.e sometimes it plays too much fast . sometimes it skips first few frames and jumps to ending frames.
What is the right way to do this?
Is there any other way i can check if the animation is completed ?

# Answer
Before you start your animation you need to set the runTime to 0, and then add the delta value while the animation is running. The animation class uses the runTime variable to figure out which frame to return based on the frame duration you specify when you initiate the class.
> 2 votes

# Answer
Best way I know of:

```
if (!animation.isAnimationFinished(timeElapsed)) {
   batch.draw(animation.getKeyFrame(timeElapsed), this.getX(), this.getY());
}

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: How would I determine whether or not to render the player over or behind a tree in a 2d top down game?
In games like Factorio, you might notice that when the player is at a certain coordinate relative to the tree, it renders in front of the player, thereby giving the effect that the player is behind the tree. My question is, how is this accomplished?

Here are some examples: Behind a telephone pole:  In front of one:

# Answer
> 0 votes
This effect is usually accomplished through sorting the draw order along an axis. In this case, the Y axis. Objects with the lower Y value (higher up on the screen) are drawn first. Objects drawn with a higher Y value are then drawn, overlapping the objects drawn earlier.

In this example, the X value is unimportant;

On the left, the orange box is drawn first because it's y is less than the y of the green box.

On the right, the orange box has now moved down 10 units on the y axis and is now drawn after the green box because it's y is greater than that of the green box.

---
Tags: 2d, rendering, tiles
---


title: Changing rendering in UE4

text:
# Question
Title: Changing rendering in UE4
Is it possible to have Ue4 render the graphics with a black line around everything similar to a cell shaded style, or would that require models specifically prepared for that purpose?

# Answer
There's a great post here about achieving a similar effect: http://www.michalorzelek.com/blog/tutorial-creating-outline-effect-around-objects/

The general steps involved are to create a depth map and then create a material that utilizes that depth information to perform edge-detection on your geometry. This is not an extremely simple thing to do, but it is possible.
> 2 votes

---
Tags: rendering, unreal-4
---


# Question
Title: Could I use Perlin Noise to generate a random musical melody?
Wouod it be possible to use a perlin noise function that generated random musical melodies? It would need parameters directing range and key changes. If so, with what platform/language?

# Answer
You could, but you probably shouldn't. A simple system will likely have too much random variation to sound pleasing.

There is extensive research into algorithmic/procedural generation of music and I recommend you search for some of it.

Specifically you might look into Markov Chains and some of the work being done with neural networks.
> 1 votes

---
Tags: procedural-generation, random, perlin-noise, music
---


# Question
Title: How do I run code for a period of time and then return to normal behavior?
i wanna run a code for my special power for five seconds only and then return to my normal working. when that power activates i am changing my player's material and i wanna return to my old material after those five secs are over. this is the code i tried:

```
void Start () {

        transform.GetComponent<Renderer> ().material.mainTexture = texts [0];
    }

    void Update () {

        if (condition) {
            for (int t1 = 0; t1 < 5; t1 += (int)Time.deltaTime) {
                transform.GetComponent<Renderer> ().material = mats [0];
            }
            transform.GetComponent<Renderer> ().material.mainTexture = texts [0];
        }
    }

```

this code breaks the game i think because unity is freezing when the condition is being met.

# Answer
Yes, this code freezes the game, because it is an infinite loop. You seem to have two misconceptions which seem to have lead you to writing this code:

1. Unity processes each `Update`-method in an independent threat of execution. That's wrong! While an `Update` method is being executed, nothing else happens in the engine. So it is important that your `Update` methods (as well as any other message handlers) return quickly.
2. When an `Update` method takes a while, `Time.deltaTime` increases. Also wrong! It gives you the time in seconds it took to complete *the last* frame, so it will only change between `Update`'s.

Casting `Time.deltaTime` to `int` will round it down. `Time.deltaTime` only changes between `Update`'s and will almost always be far lower than `1.0`. that means `0` gets added to `t1` over and over again. This for-loop will loop forever and not let Unity do anything else. If you want Unity to be able to resume the normal gameplay while the special power is active, you need to return the program's execution flow back to the engine by leaving your `Update` method.

There are several patterns you could use to implement this.

## Temporary component

You could implement your special effect as a `Component` which you add to the gameObject when the special effect is activated. Program the component to automatically remove itself when the effect time is over. You can do that by taking the time it was created and having the update-method check if the time has elapsed.

```
public class ActiveSpecialPower : MonoBehaviour {

    private float startTime;
    private static readonly float POWER_DURATION_IN_SECONDS = 5.0f;

    void Start() {
          startTime = Time.time;
          // code which happens on activation of the special power
    }

    void Update () {
        if (Time.time > startTime + POWER_DURATION_IN_SECONDS) {
             // code which happens on deactivation of special power
             Destroy(this);
        }
    }
}

```

Code for activating the special power:

```
gameObject.AddComponent<ActiveSpecialPower>();

```

Code for checking if special power is currently active:

```
if(gameObject.GetComponent<ActiveSpecialPower>() != null) {

```

## Permanent Component

Or you could have your `SpecialPower` component permanently on your player game object and have a method to activate it:

```
public class SpecialPower : MonoBehaviour {

    public float remainingTime;
    private static readonly float POWER_DURATION_IN_SECONDS = 5.0f;

    public void Activate() {
          // code which happens on activation of the special power
          remainingTime = POWER_DURATION_IN_SECONDS;
    }

    void Update () {
        if (remainingTime > 0.0f) {
           // code which happens every update while the power is active
           remainingTime -= Time.deltaTime;
           if (remainingTime <= 0.0f) {
                // code which happens on deactivation of special power
           }
        }
    }
}

```

Code for activating the special power:

```
gameObject.GetComponent<SpecialPower>().Activate();

```

Code for checking if special power is currently active:

```
if(gameObject.GetComponent<SpecialPower>().remainingTime > 0.0f) {

```

## Coroutine

Another option is to implement your special effect as a Coroutine. A coroutine can use the construct `yield return WaitForSeconds(n)` to return the program flow back to the engine and continue it after the given time has passed. Such a coroutine-method could look like this:

```
private IEnumerator ActivateSpecialPowerCoroutine() {
    // code which happens on start of special power
    yield return new WaitForSeconds(POWER_DURATION_IN_SECONDS);
    // code which happens on end of special power
}

```

Code for activating the special power:

```
StartCoroutine(ActivateSpecialPowerCoroutine());

```

Unfortunately there is no good way to check if a coroutine is currently being executed.
> 6 votes

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


title: Ball jumping algorithm

text:
# Question
Title: Ball jumping algorithm
I'm still starting out anf i'm making a 2d game where a ball which jumps through different blocks. The ball jumps a fixed height when i place the blocks that the ball should dodge i place them randomly so let's say 0 4 8 11 17 so the distance between two blocks is not always the same my problem is that i cant find a way to do algorithm for a systematic way to determine how hard is this level so if i made a sequence 0 6 11 19 21 i try it to see how difficult is it.. i want a way so that the blocks positions are determined in a way where i could know how difficult it is and that it is possible to pass this level. It is know the height the ball reaches as well as the time he ball moves in the x-direction as well as the time it takes to jump and get back to its original position..

# Answer
> 1 votes
I have a suggestion.

Design short segments of block configurations (maybe a sequence of 4 to 10 blocks). Make several configurations (maybe 30) and play with them in game until you are clear on which configurations provide the most challenging arrangement and which the least (you'll probably have some idea as you design them). As you play, you'll start to see what makes the arrangements the most challenging. This may give you an idea of how to programmatically generate hard levels. But I think a more design oriented approach would work well.

So after you have your sequences made you can rank them by difficulty or just categorize them into 5 difficulty levels. Now you have the building blocks to intelligently and programmatically construct levels of specified difficulty. An easy level may randomly assemble 15 sequences of block arrangements from the 1,2, and 3 level difficulty group. A hard level would grab only from the level 12,13,14 groups.

This is a modular approach gives you design control. It can be your genius that develops a specific challenging arrangement. The player may begins to recognize this arrangement and learn the correct sequence of inputs to clear that segment. That is an advantage in my view. Players like to feel like they are learning and mastering the game. If you just have the code generate everything randomly, they may come across a sequence that makes their heart race and palms sweat and they may fail it, but be eager to try thy sequence again, but because it was made randomly, they may never ever see it again. In that moment they will wish that you had made the levels modular so they could master that sequence. This is just my opinion of course. But as a designer, won't you want to be responsible for specific devilish and devious block sequences? It will give your levels character, even if the order or frequency of the block sequences is left to a randomizer in your code.

# Answer
> 0 votes
If I did not understand your problem wrongly, you want a method to generate a level(blocks' position) based on the difficulty - by level or user selection.

Splitting the answer into two parts:

1. In order to determine if a level can possibly be completed, it is just simple calculation of values you already have. Two blocks cannot be so close to each other that an immediate just after landing from the previous jump(due to a block) cannot clear the next block. And if a jump can clear multiple blocks, there cannot be more blocks together than what a single jump can clear.
2. The difficulty of a reaction game like what you described is affected by two factors - distance between two blocks and randomness of the pattern of jump required to clear the blocks. So if you want to generate the levels randomly instead of a fixed design, the decreasing the average distance between each blocks while increasing the range of distance between each block will generally make each level harder.

If you want more details than what I have provided, I suggest you try what I have suggested and ask a more specific question about which parts you could not get.

---
Tags: unity, game-design, algorithm, game-mechanics, jumping
---


# Question
Title: LibGDX - Rectangle Collision and Response
I've been using LibGDX for the past few weeks and I have some problems that I need help on. What I need help on is understanding how to use LibGDX `Rectangle` class for a platformer.

I found this project on github that seems to be useful.

https://github.com/obviam/star-assault-reboot

I was able to wrap my mind around how this game worked for the most part.

The only thing I can't understand, which is the most essential part of the game, is how the collision detection and response works.

In the project, the `BobController` class holds the everything that's used to detect collision.

https://github.com/obviam/star-assault-reboot/blob/master/core/src/net/obviam/starassault/controller/BobController.java

I tried going to the website linked in the github project for answers, but it seems to be empty.

Maybe I'm just dumb, but I can't wrap my mind how this works. Even with the comments provided in the project, I still don't understand.

Can someone explain in greater detail how this class handles collision detection and response using the LibGDX Rectangle class.

**EDIT**:

This is the specific function that I don't understand:

```
/** Collision checking **/
private void checkCollisionWithBlocks(float delta) {
    // scale velocity to frame units
    bob.getVelocity().scl(delta);

    // Obtain the rectangle from the pool instead of instantiating it
    Rectangle bobRect = rectPool.obtain();
    // set the rectangle to bob's bounding box
    bobRect.set(bob.getBounds().x, bob.getBounds().y, bob.getBounds().width, bob.getBounds().height);

    // we first check the movement on the horizontal X axis
    int startX, endX;
    int startY = (int) bob.getBounds().y;
    int endY = (int) (bob.getBounds().y + bob.getBounds().height);
    // if Bob is heading left then we check if he collides with the block on his left
    // we check the block on his right otherwise
    if (bob.getVelocity().x < 0) {
        startX = endX = (int) Math.floor(bob.getBounds().x + bob.getVelocity().x);
    } else {
        startX = endX = (int) Math.floor(bob.getBounds().x + bob.getBounds().width + bob.getVelocity().x);
    }

    // get the block(s) bob can collide with
    populateCollidableBlocks(startX, startY, endX, endY);

    // simulate bob's movement on the X
    bobRect.x += bob.getVelocity().x;

    // clear collision boxes in world
    world.getCollisionRects().clear();

    // if bob collides, make his horizontal velocity 0
    for (Block block : collidable) {
        if (block == null) continue;
        if (bobRect.overlaps(block.getBounds())) {
            bob.getVelocity().x = 0;
            world.getCollisionRects().add(block.getBounds());
            break;
        }
    }

    // reset the x position of the collision box
    bobRect.x = bob.getPosition().x;

    // the same thing but on the vertical Y axis
    startX = (int) bob.getBounds().x;
    endX = (int) (bob.getBounds().x + bob.getBounds().width);
    if (bob.getVelocity().y < 0) {
        startY = endY = (int) Math.floor(bob.getBounds().y + bob.getVelocity().y);
    } else {
        startY = endY = (int) Math.floor(bob.getBounds().y + bob.getBounds().height + bob.getVelocity().y);
    }

    populateCollidableBlocks(startX, startY, endX, endY);

    bobRect.y += bob.getVelocity().y;

    for (Block block : collidable) {
        if (block == null) continue;
        if (bobRect.overlaps(block.getBounds())) {
            if (bob.getVelocity().y < 0) {
                grounded = true;
            }
            bob.getVelocity().y = 0;
            world.getCollisionRects().add(block.getBounds());
            break;
        }
    }
    // reset the collision box's position on Y
    bobRect.y = bob.getPosition().y;

    // update Bob's position
    bob.getPosition().add(bob.getVelocity());
    bob.getBounds().x = bob.getPosition().x;
    bob.getBounds().y = bob.getPosition().y;

    // un-scale velocity (not in frame time)
    bob.getVelocity().scl(1 / delta);

    }

```

# Answer
Detecting a collision between two rectangles is relatively straightforward- if they overlap, they collide. libGDX provides this as part of the `Rectangle.overlap()` method:

public boolean overlaps (Rectangle r) { return x \< r.x + r.width && x + width \> r.x && y \< r.y + r.height && y + height \> r.y; }

You can find the source here. What this algorithm does is say "If my x coordinate is greater than the other rectangle's x coordinate and less than its x coordinate + its width, then we overlap on the X axis." The same is done for the Y axis. If the rectangles overlap on both axis, then we consider it to be a collision.

The tricky part is figuring out what to do once the collision has been detected. If we detect it by seeing the overlap, that means Bob (our actor) has embedded himself in the wall (which clearly shouldn't happen). We can solve this by doing one of two things: A) We push him back out of the wall before we render, or B) Before we move him we simulate his movement to see if he would collide. The code you reference opts for the latter.

The algorithm has been further optimized to only check for collisions near Bob, instead of checking to see if he has collided with every tile in the game (which gets to be very expensive, especially when you have multiple things moving around besides Bob which require collision checks).

Hopefully that makes sense.
> 2 votes

---
Tags: libgdx, collision-detection, collision-resolution
---


title: How can I clean this if Statement up?

text:
# Question
Title: How can I clean this if Statement up?
I am busy working on a full solo project with no assistance from tutorials or guides. But I have created a monstrosity of an If statement. How could I clean this up and save on memory since I'm calling this in my Update() method and the game is for android?

the hp1 to hp5 are images used as health bars on the hud, I need to deactivate the ones that are not in use when the hp value decreases.

```
if(hp >= 81)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = true;
        hp4.enabled = true;
        hp5.enabled = true;
    }
    else if(hp >= 61)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = true;
        hp4.enabled = true;
        hp5.enabled = false;
    }
    else if(hp >= 41)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = true;
        hp4.enabled = false;
        hp5.enabled = false;
    }
    else if (hp >= 21)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = false;
        hp4.enabled = false;
        hp5.enabled = false;
    }
    else if (hp >= 1)
    {
        hp1.enabled = true;
        hp2.enabled = false;
        hp3.enabled = false;
        hp4.enabled = false;
        hp5.enabled = false;
    }
    else if(hp < 1)
    {
        hp1.enabled = false;
        hp2.enabled = false;
        hp3.enabled = false;
        hp4.enabled = false;
        hp5.enabled = false;
    }

```

# Answer
Making it more efficient (saving CPU cycles) will be a matter of making sure you only call this chunk of code when `hp` changes. That being said, you can easily simplify this to five lines of code:

```
hp1.enabled = hp >= 1;
hp2.enabled = hp >= 21;
hp3.enabled = hp >= 41;
hp4.enabled = hp >= 61;
hp5.enabled = hp >= 81;

```

If you want to make it easier to maintain, you can put your hp bars in an array and loop over them (see the pseudocode below):

```
int healthInterval = 20;
for(int i = 0; i < bars.length; i++) {
    bars[i].enabled = hp >= 1 + healthInterval * i;
}

```

\[Edit\]: I suppose the latter *might* take up more memory, but it will be negligible, and this method is the first step towards having dynamic health bars which you can give different numbers of bars and different amounts of HP per bar without re-writing your code.
> 2 votes

# Answer
Instead of setting each booleans' value in the if statements, you should set all of them to true, then only change the booleans, which need to be false.

```
hp1.enabled = true;
hp2.enabled = true;
hp3.enabled = true;
hp4.enabled = true;
hp5.enabled = true;

if(hp >= 61)
{
    hp5.enabled = false;
}
else if(hp >= 41)
{
    hp4.enabled = false;
    hp5.enabled = false;
}
else if (hp >= 21)
{
    hp3.enabled = false;
    hp4.enabled = false;
    hp5.enabled = false;
}
else if (hp >= 1)
{
    hp2.enabled = false;
    hp3.enabled = false;
    hp4.enabled = false;
    hp5.enabled = false;
}
else if(hp < 1)
{
    hp1.enabled = false;
    hp2.enabled = false;
    hp3.enabled = false;
    hp4.enabled = false;
    hp5.enabled = false;
}

```

Second: Currently, `hp5.enabled` is false, when `hp` is either

* smaller than 1
* more than or equal to 1
* more than or equal to 21
* more than or equal to 41
* more than or equal to 61

So it is pretty much when `hp` is smaller than 81

`hp4.enabled` is false, when hp is

* smaller than 1
* more than or equal to 1
* more than or equal to 21
* more than or equal to 41

or in short, when `hp` is less than 61. You can do this to every boolean, and you get the following

```
hp1.enabled = true;
hp2.enabled = true;
hp3.enabled = true;
hp4.enabled = true;
hp5.enabled = true;

if (hp < 1) {
    hp1.enabled = false;
}

if (hp < 21) {
    hp2.enabled = false;
}

if (hp < 41) {
    hp3.enabled = false;
}

if (hp < 61) {
    hp4.enabled = false;
}

if (hp < 81) {
    hp5.enabled = false;
}

```
> 0 votes

# Answer
Why don't you create an two-dimensional array that stores the health it needs to be to be on(index 0) and the hp object itself(index 1). Then you can write code something like this:

C# is one of the few languages I dont fully know, but in basic programming syntax...

```
foreach(miniArray in biggerArray){
if(hp >= miniArray[0]){
miniArray[0].enable = true;
}
else{
miniArray[0].enable = false;
}
}

```

You will have to change this code up a bit because its not actually c#, but basic logic is correct.
> -3 votes

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


# Question
Title: LibGDX keep camera within bounds of TiledMap
I have a simple TiledMap which I can render fine. I have a player hopping (with Box2D) around and my camera follows the player around:

```
cam.position.set(
    player.position().x * Game.PPM + Game.V_WIDTH / 4,
    player.position().y * Game.PPM,
    0
);
cam.update();

```

However, the camera will move "off" the TiledMap. How could I keep my camera on the TiledMap, so when I near the edges of my map, the camera stops scrolling and the player moves towards the edge of the camera?

# Answer
Alright, so you're working with two rectangles here. A larger static one (the map) and a smaller moving one (the camera) inside of it. What you want is to not let the bounds of the smaller rectangle move outside the inner bounds of the larger rectangle.

```
// These values likely need to be scaled according to your world coordinates.
// The left boundary of the map (x)
int mapLeft = 0;
// The right boundary of the map (x + width)
int mapRight = 0 + map.getWidth();
// The bottom boundary of the map (y)
int mapBottom = 0;
// The top boundary of the map (y + height)
int mapTop = 0 + map.getHeight();
// The camera dimensions, halved
float cameraHalfWidth = cam.viewportWidth * .5f;
float cameraHalfHeight = cam.viewportHeight * .5f;

// Move camera after player as normal

float cameraLeft = cam.position.x - cameraHalfWidth;
float cameraRight = cam.position.x + cameraHalfWidth;
float cameraBottom = cam.position.y - cameraHalfHeight;
float cameraTop = cam.position.y + cameraHalfHeight;

// Horizontal axis
if(map.getWidth() < cam.viewportWidth)
{
    cam.position.x = mapRight / 2;
}
else if(cameraLeft <= mapLeft)
{
    cam.position.x = mapLeft + cameraHalfWidth;
}
else if(cameraRight >= mapRight)
{
    cam.position.x = mapRight - cameraHalfWidth;
}

// Vertical axis
if(map.getHeight() < cam.viewportHeight)
{
    cam.position.y = mapTop / 2;
}
else if(cameraBottom <= mapBottom)
{
    cam.position.y = mapBottom + cameraHalfHeight;
}
else if(cameraTop >= mapTop)
{
    cam.position.y = mapTop - cameraHalfHeight;
}

```

So the logic is pretty simple. Keep the small box inside the larger box. Once you understand that idea feel free to collapse that code down. You could even move it into a series of nested Min/Max statements in your camera position tracking if you'd prefer.
> 14 votes

# Answer
You can easily clamp the camera position to the map boundaries like this:

```
camera.position.x = MathUtils.clamp(camera.position.x, camViewportHalfX, mapWidth - camViewportHalfX);
camera.position.y = MathUtils.clamp(camera.position.y, camViewportHalfY, mapHeight - camViewportHalfY);

```
> 7 votes

# Answer
To move `Camera` in `TiledMap` bounds, `OrthogonalTiledMapRenderer` was used.

I have also noticed it behaves unexpectedly: while `Camera` reaches map bounds, tiled map, like by inertia, moves some pixels too far (it depends on the velocity of the swipe).

**As a solution**, on each `Camera` movement, `Camera` is forcibly put in map bounds. See `putInMapBounds()` method.

To avoid glitches in `TiledMap` rendering, used `Math.min(float, float)`.

Use this listener to handle your `Camera`:

```
/**
 * @author Gram <gram7gram@gmail.com>
 */
public class CameraListener extends InputAdapter {

    private final UIStage stage;
    private final Camera camera;
    private final Vector3 curr;
    private final Vector3 last;
    private final Vector3 delta;
    private final int mapWidth;
    private final int mapHeight;

    public CameraListener(UIStage stage) {
        this.stage = stage;
        this.camera = stage.getViewport().getCamera();

        curr = new Vector3();
        last = new Vector3(-1, -1, -1);
        delta = new Vector3();

        TiledMapTileLayer layer = stage.getLevel().getMap().getFirstLayer();
        mapWidth = layer.getWidth() * DDGame.TILE_HEIGHT;
        mapHeight = layer.getHeight() * DDGame.TILE_HEIGHT;
    }

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

        camera.unproject(curr.set(x, y, 0));

        if (!(last.x == -1 && last.y == -1 && last.z == -1)) {
            camera.unproject(delta.set(last.x, last.y, 0));
            delta.sub(curr);
            camera.translate(Math.min(delta.x, 5), Math.min(delta.y, 5), 0);
            if (isInMapBounds()) {
                stage.moveBy(Math.min(delta.x, 5), Math.min(delta.y, 5));
            }
        }

        last.set(x, y, 0);

        putInMapBounds();

        return false;
    }

    private boolean isInMapBounds() {

        return camera.position.x >= camera.viewportWidth / 2f
                && camera.position.x <= mapWidth - camera.viewportWidth / 2f
                && camera.position.y >= camera.viewportHeight / 2f
                && camera.position.y <= mapHeight - camera.viewportHeight / 2f;

    }

    private void putInMapBounds() {

        if (camera.position.x < camera.viewportWidth / 2f)
            camera.position.x = camera.viewportWidth / 2f;
        else if (camera.position.x > mapWidth - camera.viewportWidth / 2f)
            camera.position.x = mapWidth - camera.viewportWidth / 2f;

        if (camera.position.y < camera.viewportHeight / 2f)
            camera.position.y = camera.viewportHeight / 2f;
        else if (camera.position.y > mapHeight - camera.viewportHeight / 2f)
            camera.position.y = mapHeight - camera.viewportHeight / 2f;

        stage.moveTo(
                camera.position.x,
                camera.position.y);

    }

    @Override
    public boolean touchUp(int x, int y, int pointer, int button) {
        last.set(-1, -1, -1);
        Log.info("Camera at " + camera.position.x + ":" + camera.position.y);
        return false;
    }
}

```
> 0 votes

# Answer
If you have the zoom factor to take care of, I found this to work much better:

```
public void fixBounds() {
    float scaledViewportWidthHalfExtent = viewportWidth * zoom * 0.5f;
    float scaledViewportHeightHalfExtent = viewportHeight * zoom * 0.5f;

    // Horizontal
    if (position.x < scaledViewportWidthHalfExtent)
        position.x = scaledViewportWidthHalfExtent;
    else if (position.x > xmax - scaledViewportWidthHalfExtent)
        position.x = xmax - scaledViewportWidthHalfExtent;

    // Vertical
    if (position.y < scaledViewportHeightHalfExtent)
        position.y = scaledViewportHeightHalfExtent;
    else if (position.y > ymax - scaledViewportHeightHalfExtent)
        position.y = ymax - scaledViewportHeightHalfExtent;
}

```
> 0 votes

---
Tags: libgdx, camera, tilemap
---


# Question
Title: How to make Lists (and Arrays) in Unity only take GameObjects of a certain "type"
If I were coding in generic C# I can create a list that only stores a certain type of object. If I accidentally try to add anything other than that type to the list I will be promptly told and can fix the problem quickly.

```
List<Foo> my_list = new List<Foo>();
my_list.Add(Bar) //Error

```

However because I'm using Unity my script needs to be attached to a GameObject, and that needs to be stored in the List.

```
List<GameObject> my_list = new List<GameObject>();
GameObject Foo = new GameObject; Foo.AddComponent<Foo>();
GameObject Bar = new GameObject; Bar.AddComponent<Bar>();
my_list.Add(Foo) //Fine
my_list.Add(Bar) //Works, but I don't want it to

```

I only want the list to store "Foo" GameObjects (GameObjects with the Foo component), however there is nothing to stop me accidentally storing any type of GameObject, which could (and already has) caused me hours scratching my head trying to debug the problem.

Is there a way to subtype a GameObject so that it has the effect of `List<GameObject(Foo)> my_list`? Is there a way to do it with arrays too?

# Answer
> 3 votes
If you only want to store `GameObject` types that contain a specific `Component` element, the easiest solution is to use the specific `Component` for the list type.

The base `Component` class contains a reference to the "host `GameObject`". Limiting your list to the specific `Component` will still give you access to each respective `GameObject`.

---

The below script is an example of how you would manage this for the generic `Collider` class. I have included a method specifically for adding the element, which will return a `bool` to confirm if a `Collider` was actually found on the `GameObject`, and a method specifically for directly retrieving the required `GameObject` based off an index in the list.

```
///<summary>A list of generic collider types, populated through the inspector.</summary>
public List<Collider> colliders;

///<summary>Adds a collider reference to the list, using the host game object.</summary>
///<param name="targetGameObject">The game object to reference the collider from./<param>
///<returns>True, if the game object contained a collider, else returns false.</returns>
public bool AddGameObjectToList(GameObject targetGameObject)
{
    Collider targetCollider = GameObject.GetComponent<Collider>();

    if(targetCollider == null)
    {
        return false;
    }
    else
    {
         colliders.Add(target collider);
        return true;
    }
}

<summary>Provides direct reference to the game object of a certain element in the list.</summary>
///<param name="index">The index pointer to the collider holding the desired game object.<param>
///<returns>The game object associated with the provided index in the component list.</returns>
public GameObject GetGameObject(int index)
{
    return colliders[index].GameObject;
}

```

For bonus points, you could turn this into a basic class, using generics. Using a generic that is *based* in the `Component` class allows you to create instances on the fly to represent *any* component; all components inherit from `Component`.

# Answer
> 0 votes
1. Make Behaviour for each type. i.e. foo.cs, bar.cs etc
2. Create your desired type of list. i.e List foolist
3. now if you try to add bar instance to foo then it will give an error.

```
public Transform fooObjects;
List<Foo> fooList;
Bar b;
// Use this for initialization
void Awake ()
{
    fooList = new List<Foo>();
    foreach (Transform item in fooObjects)
    {
        Foo f = item.gameObject.GetComponent<Foo>();
        if(f != null)
        {
            fooList.Add(f);
        }
        else
        {
            Debug.Log("There are some object which is not FOO");
        }
   }
   b = new Bar();
}

void OnEnable ()
{
    foreach (var item in fooList)
    {
        item.gameObject.transform.name = "THIS IS FOO";
    }
fooList.Add(b); // this will throw an error in the debug window.
}

```

I hope that helps. If its not enough please give a comment here. Thanks

---
Tags: unity, gameobject, monobehaviour
---


title: Reading a word list into an array

text:
# Question
Title: Reading a word list into an array
I am making a simple hangman game, I have a small list of words in a .txt file separated by new lines. I put the word list into the assets folder. How can I find the path to the word list so I can use:

```
string[] wordlist = System.IO.File.ReadAllLines("pathToFile");

```

Or is there another solution of converting the word list into a string array?

# Answer
> 0 votes
Use the Streamreader to load in the text in unity or set it as a text asset and parse it directly. This forum post should help give you an idea of what to do:

https://forum.unity3d.com/threads/read-from-textasset-line-by-line.327422/

# Answer
> 2 votes
I have little experience with Unity, but it appears as though you can use `Application.dataPath` to obtain the correct path.

Here it is at the API.

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


title: Text-based hold 'em game in C using TCP

text:
# Question
Title: Text-based hold 'em game in C using TCP
So I'm trying to create a simple text input Texas Hold 'Em game that can be played in a Terminal between multiple computer. (Disturbing lack of hold 'em games that don't require Facebook integration or a million ads or micro transactions :c )

With my current knowledge I can create the TCP Server and Connect some clients, but I'm not sure how to proceed from here. How can I communicate between the clients and server turn by turn using text input effectively? My vague idea of what to do is

1. Accept clients, store FD in Array
2. Loop through Id's sending them 2 cards each
3. Create thread with a game info struct, that reads users text input
4. Wait for thread to finish and return value will be the players move
5. Update game info, and move repeat step 3-4 for all Clients
6. Break whenever only 1 player is left, or all bettings phases are over then repeat

This outline makes sense in the server, but I'm not sure how to construct the client to not do anything until it gets prompted by the thread creation in the main server while loop. If anyone has any advice or links to helpful articles or example code I would really appreciate it thanks so much!!

# Answer
> 1 votes
You might want to look up on finite state machines.

The basic idea is that your client can be in one of many different states in which it behaves differently towards both the user and the server.

1. **Player's turn** state
    * Show the player which options they have (raise, fold, check...)
    * Wait for input from the player
    * When the player made a decision what to do, send that decision to the server and go to "Waiting for confirmation" state.
2. **Waiting for confirmation** state
    * Don't accept player input
    * Show some progress indicator to the player
    * Listen to the server and wait for a response
    * When the server rejects the action, go back to *Player's turn*
    * When the server confirms the action, go to *Not player's turn* state
3. **Not player's turn** state
    * Don't accept player input
    * Listen to the server for messages
    * When the server sends a message about an action performed by another player ("player 2 raised by 12". "player 3 folded" ...) or about other events which happen in the game ("turn-card revealed: king of spades"), report that to the player.
    * When the server sends a message that it's the player's turn again, go to *Player's turn* state.
    * When the server sends a message that the game has concluded, switch to *Game Over* state.
4. **Game Over** state
    * Tell the player who won the game
    * Wait for input if they want to join another game or quit

Each state should be implemented as a series of functions for handling user input, network input and UI drawing. When it's time to call one of these functions, check in which state the client currently is and call the appropriate function.

---
Tags: networking, c, poker
---


# Question
Title: Increase event trigger chance the closer two numbers are
I have two numbers, one steadily increasing, the other is fixed. I'm trying to increase the likelihood of triggering an event as the increasing number gets closer to and surpasses the fixed number.

The chance shouldn't get to 100% no matter how far beyond the increasing number gets, but stop increasing at some point. (if this point is easily adjustable, all the better).

Thanks a bunch for any help as math is not my strong suit.

# Answer
> 1 votes
A very quick solution :

If you set the following terms

* currentValue = the increasing variable, going from minValue to maxValue (and possibily more)
* minValue = start value of the increasing one
* maxValue = your "fixed value"
* minPercent = the minimum % of chance for the trigger (for example 0.25)
* maxPercent = the maximum % of chance for the trigger (for example 0.95)

then the following pseudo code returns a trigger chance that grows linearly from 0.25 to 0.95 and then stay at this value

```
if (currentValue <= maxValue)
   // how much are we from the min value (0) to the max value (1)
   float ratio = (currentValue-minValue)/(maxValue - minValue);
   result = MinPercent + ratio*(maxPercent - minPercent)
else
    result = maxPercent
endif

```

---
Tags: mathematics, javascript
---


title: Low-poly heightmap

text:
# Question
Title: Low-poly heightmap
I want to transform a 'normal' heigthmap into something like this:

Starting from a normal grayscale heightmap like this:

I looked into Voronoi, but I cant find a way of how to tranform the grayscale map to fit the upper images style.

How to get getting this result?

# Answer
> 1 votes
You can do this with 3ds Max.

---

1. Create a plane.
2. Subdivide it in to a lot of segments.
3. Select ***Displace***.
4. Select your heightmap.
5. Select ***Create*** -\> ***Splines*** -\> ***Section***.
6. Create a bunch of these "sections"; one for every height.
7. Convert all your "sections" to "Editable Splines"
8. Select ***Create*** -\> ***Compound Objects*** -\> ***Terrain***.

---

Fur further explanation, here is a YouTube video, which explains more.

---
Tags: textures, blending, low-poly
---


# Question
Title: libGDX - Drawing polygon with texture gives weird lines
I have a hexagon-shaped polygon. I want to put a part of a rectangular image onto it (a part because it's a hexagon, not a rectangle). I tried to do this using PolygonRegion, but it gives a weird and flipped result. Also when I have multiple hexagons, the texture is only on the first hexagon, and on the others, only the weird lines are visible. I use libGDX with the Game and Screen classes. I'd also like to know what this error/effect is called.

My questions:

1. How do I make the texture scale to the size of the hexagon?
2. How do I not flip the texture?

My (altered) code "GameScreen":

```
class GameScreen implements Screen {

private OrthographicCamera cam;
private PolygonSpriteBatch pSB;
private Hexagon hexagon1, hexagon2;
public final int HEXAGON_WIDTH = 100;
public final int HEXAGON_HEIGHT = (int) (HEXAGON_WIDTH / (Math.sqrt(3) / 2));
//Ratio of width and height of a regular hexagon.

GameScreen() {
    this.cam = new OrthographicCamera(800, 800);
    cam.setToOrtho(true);
    cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
    cam.update();

    hexagon1 = new Hexagon(new Vector2(0, 0));
    hexagon2 = new Hexagon(new Vector2(HEXAGON_WIDTH + 2, 0));

    pSB = new PolygonSpriteBatch();
}

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

    cam.update();
    pSB.setProjectionMatrix(cam.combined);

    pSB.begin();
    hexagon1.draw(pSB);
    hexagon2.draw(pSB);
    pSB.end();
}
}

```

Class Hexagon

```
class Hexagon {

    private PolygonSprite sprite;
    private Vector2 pos;

    Hexagon(Vector2 pos) {
        this.pos = pos;
        this.sprite = createPolygonSprite();
    }

    private PolygonSprite createPolygonSprite() {

        int hexWidth = GameScreen.HEXAGON_WIDTH;
        int hexHeight = GameScreen.HEXAGON_HEIGHT;

        float[] vertices = {
            pos.x + hexWidth / 2, pos.y,
            pos.x + hexWidth, pos.y + hexHeight * .25f,
            pos.x + hexWidth, pos.y + hexHeight * .75f,
            pos.x + hexWidth / 2, pos.y + hexHeight,
            pos.x, pos.y + hexHeight * .75f,
            pos.x, pos.y + hexHeight * .25f
        };

        PolygonRegion polygonRegion = new PolygonRegion(
            new TextureRegion(new Texture(Gdx.files.internal("badlogic.jpg")),
            vertices,
            new EarClippingTriangulator().computeTriangles(vertices).toArray());
        PolygonSprite polygonSprite = new PolygonSprite(polygonRegion);
        polygonSprite.setOrigin(pos.x + width / 2, pos.y + height / 2);
        return polygonSprite;
    }

    void draw(PolygonSpriteBatch pSB) {
        this.sprite.draw(pSB);
    }
}

```

The result (using similar code as written above but with more hexagons and other things):

What I expected to see (instead of the above picture): I expected to see the image not flipped and on every hexagon. The image should have been of such a size that all the hexagon space is filled (that of course means you can't see the corners of the image, but that's what I want). **The image should be displayed on each hexagon, so it should start drawing on each hexagon. The image should scale to the size of the hexagon.**

# Answer
I figured all three problems out after some time: flipping the texture, putting the texture on every hexagon, and scaling the texture to the size of the hexagon.

To flip the "texture":

```
Texture texture = new Texture(Gdx.files.internal("badlogic.jpg");
TextureRegion textureRegion = new TextureRegion(texture);`
textureRegion.flip(false, true); //Flipping the texture region around the y axis
PolygonRegion polyRegion = new PolygonRegion(
    textureRegion,
    vertices,
    new EarClippingTriangulator().computeTriangles(vertices).toArray()
);`

```

Even though multiple hexagons are present, the texture only seemed to be drawn once. That is because you shouldn't add the starting position to every vertex, but instead set the position of the whole sprite using. (example is shown further down).

To make the texture "scale" to the size of the hexagon, you have to scale the PolygonRegion down to the size of the texture by changing the vertices. After that, set the width and height of the hexagon using `sprite.setBounds(x, y, width, height);` So for this case that would be:

```
float texHeight = texture.getHeight();
float texDrawWidth = texHeight * ((float) Math.sqrt(3) / 2);
  //Ratio between width and height of regular hexagon

float[] vertices = {
        texDrawWidth / 2, 0,
        texDrawWidth , texHeight * .25f,
        texDrawWidth , texHeight * .75f,
        texDrawWidth / 2, texHeight,
        0, texHeight * .75f,
        0, texHeight * .25f};

```

Then after creating the `PolygonSprite` use

```
sprite.setBounds(pos.x, pos.y, hexHeight, hexHeight);

```

Result:

**I do not understand why setting the width and height of the sprite both equal to the desired height of the hexagon is correct, but it is the only thing that works.**
> 0 votes

# Answer
You need to set the texture's `TextureWrap` to `Repeat`

```
setWrap(Repeat, Repeat);

```
> 1 votes

---
Tags: java, libgdx
---


title: Using Lazer with a Quadtree

text:
# Question
Title: Using Lazer with a Quadtree
I have a quadtree implementation that works well with what I need for handling collisions between enemies, projectiles, and heroes.

However, most of these types of entities are pointbased, with varying radius but that's about it.

I have a weapon idea for lazer or ray weapon that's essentially a line. How does something like that fit in to working with something like a quadtree? Normally when we have a quadtree, we are essentially letting that data structure handle point masses to figure out which subset of objects we need. How then might we handle something like a line?

The dumb way to do it is to just query the enemies and do something like a circle line intersection test on all the enemy objects. This is obviously not efficient especially when we already have a quadtree.

One idea i have are to just put some dummy projectile object along the line and submit those to the quadtree. Then if we get any returned objects from those dummies, then we can use the circle line intersection test on it.

Any ideas pertaining to how to use ray weapon that requires some line intersection test with a quadtree would be appreciated. Thanks.

# Answer
you could something like the following, that would at least limit the enemy-ray tests to quads that only intersect the line:

```
void process_sub_quads(Quad q,Ray r) {
    for(int sq=0; sq<4; ++sq) { // query sub quads
        Quad sub_quad = q.sub_quad(sq)
        if(ray_box_intersection(r,sub_quad)) {
            if(sub_quad == lowest_quad) {
                // test ray against enemies, perform appropriate actions
            } else {
                process_sub_quads(sub_quad,r);
            }
        }
    }
}

if(ray_box_intersection(r,top_quad)) {
    process_sub_quads(top_quad,ray);
}

```
> 1 votes

---
Tags: collision-detection, quadtree
---


title: Direct3D 11. GenerateMips not work

text:
# Question
Title: Direct3D 11. GenerateMips not work
I try use this

```
D3D11_TEXTURE2D_DESC desc{};
desc.Width  =   texture->width;
desc.Height =   texture->height;
desc.SampleDesc.Count   =   1;
desc.Format =   DXGI_FORMAT_R8G8B8A8_UNORM;
desc.BindFlags  =   D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
desc.MiscFlags  =   D3D11_RESOURCE_MISC_GENERATE_MIPS;
desc.ArraySize  =   1;
desc.MipLevels  =   1;
desc.Usage  =   D3D11_USAGE_DEFAULT;

D3D11_SUBRESOURCE_DATA initData = {};
initData.pSysMem     =  data32; // unsigned int image buffer
initData.SysMemPitch =  texture->width * 4;
initData.SysMemSlicePitch = texture->width * texture->height * 4;

D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {};
SRVDesc.Format = desc.Format;
SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = -1;

this->m_d3d11Device->CreateTexture2D( &desc, initData, &this->m_texture2d );
this->m_d3d11Device->CreateShaderResourceView( this->m_texture2d, &SRVDesc, &this->textureResView );
this->m_d3d11DevCon->UpdateSubresource( this->m_texture2d, 0, 0, data32, initData.SysMemPitch, initData.SysMemSlicePitch );
this->m_d3d11DevCon->GenerateMips( this->textureResView );

```

No effect.

# Answer
```
desc.MipLevels  =   1;

```

You asked for the texture to be created with only one mip level, so the texture was created with only one mip level.

From the documentation:

> The maximum number of mipmap levels in the texture. ..... 0 to generate a full set of subtextures.

So you almost definitely want to set this to 0 instead.

```
D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {};
SRVDesc.Format = desc.Format;
SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = -1;

```

This isn't actually necessary for the simple case where your SRV accesses the entire texture; again, reading the documentation:

> Set this parameter to NULL to create a view that accesses the entire resource (using the format the resource was created with).

You're creating the texture with initial data so you don't need this either:

```
this->m_d3d11DevCon->UpdateSubresource( this->m_texture2d, 0, 0, data32, initData.SysMemPitch, initData.SysMemSlicePitch );

```

Simplify your code, get rid of stuff you don't need, make sure that you ask for what you actually want, then it should work (and if it doesn't it will be easier for you to troubleshoot because there's less irrelevant code to distract you).
> 2 votes

---
Tags: directx, directx11, mipmaps
---


title: What to do with unused vertices?

text:
# Question
Title: What to do with unused vertices?
Imagine yourself a vertex array in OpenGL representing blocks in a platform game.

But some vertices may be not used.

The environment is dynamic, so there always some vertex may suddenly become invisible.

What is the best way to make them not draw? Graphic cards are complicated and it's hard to predict what is best approach.

Few best ways I can think of:

1. delete and move all vertices after deleted one to fill freed space (sounds extremely inefficient)
2. set positions to 0
3. set transparency to maximum

I could of course benchmark, but what on my computer works faster doesn't have to on other.

# Answer
**Just don't draw them**.

For example, if you have 3 quads in a buffer, and you only wish to draw quads 0 and 2:

```
glDrawArrays (GL_QUADS, 0, 4);
glDrawArrays (GL_QUADS, 8, 4);

```

There's no rule saying that you must draw the entire buffer: glDrawArrays has *first* and *count* parameters for a reason - to allow you to select a subrange of the buffer to draw.

Of course, that means doing multiple draw calls, but that's a tradeoff versus the complexity and overhead of modifying a buffer.

As an alternative to multiple draw calls, you could look at glMultiDrawArrays (which may be more efficient, although some drivers may implement it as a loop over multiple glDrawArrays calls), or indexing: keep the vertex buffer static but build a dynamic index buffer. Because indices are much smaller than vertices, this can often be done much more efficiently.
> 1 votes

---
Tags: opengl, performance, vertex, vertex-arrays
---


# Question
Title: Implementing a glowing effect on 3D objects with Direct3D 11
I'm interested in implementing a glowing effect on some 3D objects. More specifically, I want to make a star that has a sort of halo around it, as it can be seen in the photo:

I've seen on Rastertek the 2D implementation, but I have no idea how it could be done in 3D. I've also read about HDR and bloom effects, but I'm not sure if those would apply here. What Direct3D 11 techniques should I use?

# Answer
You can do this by using the geometry shader to extrude faces from the sphere to face the camera and then use a pixel shader to create a nice glow, this is how I've done it in the past, I'm going to copypaste most of my answer from an earlier question about glow shader and go on a dig for my old shader files.

**Geometry Shaders**

A geometry shader is a part of the graphics pipeline similar to the pixel(fragment) & vertex-shaders. Unlike those two though the geometry shader operates once on each primitive, a primitive being triangles lines or points.

The geometry shader doesn't just use primitives as input it can also output up to a defined max of new primitives, this is the true power of a geomotry shader, it can be used to cull primitives and/or expand them.

**Edge Detection**

I said earlier that the geometry shader works on primitives such as triangles lines or points, this was not a definite list and there is one primitive that is of particular intrest to us:

The Triangle adjecant

The triangle adjecant provides not only data for the triangle but for all neighbouring triangles. If the main triangle faces the camera and an adjecant triangle does not then the triangle lies on the edge and we can proceed.

To check if a triangle is backfacing calculate it's normal and dot product it with the cameras normal. I'll leave the details of the calculation as an exercise to the reader, it's not hard.

**Face Extrusion**

Now we come to the tricky part, start by drawing a line from the camera to an arbitrary point on the edge and use the cross product of this line and the edge to get the direction of where to extrude the new face, we'll call this *e*, make sure to normalize it.

Create two new points *x* distance from the edge points in the direction of *e*, *x* here being a glow amount. From these two new points and the edge we can output a new face in the geometry shader and create a glow around the object.

**But wait!**

This will only work if the edge is completly straight or concave\*, if the edge is convex we'll have a gap.

To solve this first project the edge point normals on the vector *e* this creates two new vectors *n1* and *n2*, make sure to normalize these too.

Like before create two new points *x* distance from the edge points in the direction of *n1* and *n2* and create new faces from these points, this will create a more robust glow.

**Pixel Shader**

I'll leave creation of the pixelshader as an excercise to the reader for now.
> 2 votes

---
Tags: c++, rendering, directx11, hlsl, graphic-effects
---


# Question
Title: How can I create a button with an image in libGDX?
I am new to LibGDX. I am trying to develop a game for Android (so it will support different screen sizes), but I don't know how to put a button with an image. I tried ImageButton but I can't resize it. I have put TextButtons in my app and it works and resizes fine too.

Any suggestions ?

# Answer
> 5 votes
You have the freedom to create your own button class, attach to it a sprite, make some methods to handle input and you're good to go.

```
public class SimpleButton {

    private Sprite skin;

    public SimpleButton(Texture texture, float x, float y, float width, float height) {
        skin = new Sprite(texture); // your image
        skin.setPosition(x, y);
        skin.setSize(width, height);
    }

    public void update (SpriteBatch batch, float input_x, float input_y) {
        checkIfClicked(input_x, input_y);
        skin.draw(batch); // draw the button
    }

    private void checkIfClicked (float ix, float iy) {
        if (ix > skin.getX() && ix < skin.getX() + skin.getWidth()) {
            if (iy > skin.getY() && iy < skin.getY() + skin.getHeight()) {
                // the button was clicked, perform an action
                System.out.println("Button clicked !");
            }
        }
    }

}

```

For the **screen size issue** you could use percentage of the screen size:

```
public float convertToPercents_width (float p) {
    return Gdx.graphics.getWidth()*p/100;
}

public float convertToPercents_height (float p) {
    return Gdx.graphics.getHeight()*p/100;
}

```

# Answer
> 2 votes
follow the steps:

**create a atlas:**

```
atlasUiPadrao = new TextureAtlas("ui/uiPadrao.pack");

```

(how to pack: put png images in a folder and compress with libgdx texturepack).

**create a skin:**

```
skinPadrao = new Skin(atlasUiPadrao);

```

**create a style: ImageButtonStyle:**

```
fireButtonStyle = new ImageButtonStyle();  //Instaciate
fireButtonStyle.up = skinPadrao.getDrawable("uFireUpI");  //Set image for not pressed button
fireButtonStyle.down = skinPadrao.getDrawable("uFireDownI");  //Set image for pressed
fireButtonStyle.over = skinPadrao.getDrawable("uFireOverI");  //set image for mouse over
fireButtonStyle.pressedOffsetX = 1;
fireButtonStyle.pressedOffsetY = -1;

```

**now you can create button in Screen file**

```
ImageButton item1Button = new ImageButton(Assets.fireButtonStyle);

```

for every size screen, you have to define what image will be displayed

# Answer
> 2 votes
I use scene2d library for making UI elements in the screen like button,Text ,Image etc.

The final result looks something like this:

* Create a class start that extends the Game class and call setScreen function to set screen to main menu
* MainMenu Class implements screen.It have stage that contains buttons that also have on/off state ,An input listener is added to button to handle touch inputs

> You can find button.pack and new.fnt files from here

**Start Class**

```
public class Start extends Game{
    public OrthographicCamera camera;
    public SpriteBatch batch;
    public BitmapFont font;

    @Override
    public void create() {

        camera=new OrthographicCamera(Constants.width,Constants.width*Constants.aspectRatio);
        batch=new SpriteBatch();

        setScreen(new MainMenu(this));

    }

}

```

**MainMenu Class**

```
public class MainMenu implements Screen{
        Start game;
         private Stage stage; //** stage holds the Button **//
            private BitmapFont font;
            private TextureAtlas buttonsAtlas; //** image of buttons **//
            private Skin buttonSkin; //** images are used as skins of the button **//
            private TextButton button;

public MainMenu(Start game)
{
    this.game=game;

}

        @Override
        public void show() {

        buttonsAtlas = new TextureAtlas("img/button/button.pack"); //**button atlas image **//
        buttonSkin = new Skin();
        buttonSkin.addRegions(buttonsAtlas); //** skins for on and off **//
        font = new BitmapFont(Gdx.files.internal("font/new.fnt"),false); //** font **//

        stage = new Stage();        //** window is stage **//
        stage.clear();
        Gdx.input.setInputProcessor(stage); //** stage is responsive **//

        TextButtonStyle style = new TextButtonStyle(); //** Button properties **//
        style.up = buttonSkin.getDrawable("buttonOff");
        style.down = buttonSkin.getDrawable("buttonOn");

        style.font = font;

        button = new TextButton("START", style);
        //** Button text and style **//
        button.setHeight(Gdx.graphics.getHeight()/3); //** Button Height **//
        button.setWidth(Gdx.graphics.getWidth()/4); //** Button Width **//

        button.setPosition(Gdx.graphics.getWidth()/2-button.getWidth()/2, Gdx.graphics.getHeight());

        button.addListener(new InputListener() {
            public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                    Gdx.app.log("my app", "Pressed"); //** Usually used to start Game, etc. **//

                    // TODO Auto-generated method stub

                    return true;

            }

            public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                    Gdx.app.log("my app", "Rggggggeleased");

              ///and level
                    game.setScreen(new MyNextScreen(game));

                    dispose();

            }
        });

        MoveToAction moveAction = new MoveToAction();//Add dynamic movement effects to button
        moveAction.setPosition(Gdx.graphics.getWidth()/2-button.getWidth()/2, Gdx.graphics.getHeight()/2+ Gdx.graphics.getHeight()/6);
        moveAction.setDuration(.5f);
        button.addAction(moveAction);

        stage.addActor(button);

    }
    @Override
    public void render(float delta) {
        // TODO Auto-generated method stub
         Gdx.gl.glClearColor(1, 1, 1, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            stage.act();
         game.batch.begin();
            stage.draw();
           game.batch.end();

    }

    @Override
    public void resize(int width, int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void pause() {
        // TODO Auto-generated method stub

    }

    @Override
    public void resume() {
        // TODO Auto-generated method stub

    }

    @Override
    public void hide() {
        // TODO Auto-generated method stub

    }

    @Override
    public void dispose() {
        // TODO Auto-generated method stub

    }

}

```

# Answer
> 0 votes
I have created an introduction tutorial to create Button, ImageButton and TextButton on LibGDX here: https://libgdx.info/buttons-scene2d/

Take a look and let me know if you have questions.

---
Tags: libgdx, gui
---