# Question
Title: Box falls extremely slow? (~1 pixel per second)
As the title says I have a problem where my box2d bodies falls extremely slow.

Around 1 pixel per second.

---

My world is stepped like this `world.Step(1 / 60.0f, 8, 3);`, each frame.

The way I update my `sf::RectangleShape` to match the `b2Body` position is like this :

*(Called every frame)*

```
sfmlShape.setPosition(getBody()->GetPosition().x / b2Meter, getBody()->GetPosition().y / b2Meter);

```

---

Not sure what else is needed to fix this problem, so here's some other stuff that might be the problem :

> **b2Body values :**
>
> `friction = 1.0f`
>
> `density = 0.3f`
>
> `body type = dynamic`

---

The `b2PolygonShape` is set up like this : `boxShape.SetAsBox(size.x / 2.0f, size.y / 2.0f);`

And the size of the actual `sf::RectangleShape` is set up like this :

```
sfmlShape.setSize(sf::Vector2f(size.x, size.y));

```

---

And lastly : `b2Meter` is a macro :

```
#define b2Meter 30.0f

```

# Answer
I believe the issue is your update loop - you are updating a 1/60th of a second, but as fast as you can. The is interrupted by the event handler, which will make it jittery.

Somehow you need to change your loop to only update if 1/60th of a second has passed, or by actually passing the real delta time in. I believe bullet would prefer a fixed update, but you actually need that update to be a bit more realistic, and not full tilt.

Where is there a gate to how fast the outer while loop runs in the following code? You are updating physics 1/60th of a second but at what rate? how often? how fast? Does display always take the same amount of tim? No - same as the event handling, so the movement of the physics objects via step(1/60) is inconsistent.

```
while (window.isOpen())
{
    sf::Event e;
    while (window.pollEvent(e))
    {
        if (e.type == sf::Event::Closed)
            window.close();

        if (e.type == sf::Event::KeyPressed)
        {
            if (e.key.code == sf::Keyboard::Space)
                box.getBody()->ApplyForce(b2Vec2(0, -100000), b2Vec2(0, -10000));
        }
    }

    // Logic
    world.Step(1.0f / 60.0f, 8, 3);
    // Update all entities in the game
    box.update(window.isOpen());
    // Drawing
    window.clear();
    window.draw(*box.getSfShape());
    window.setView(view);
    window.display();
}

```

Instead you need some kind of loop like this:

```
time_step_accumulator = 0;
previous_time = get_current_time();
while ( true )
{
   while ( pollEvents )
   {
      // handle events
   }

   current_time = get_current_time();
   delta_time = current_time - previous_time;
   previous_time = current_time; // for next frame

   time_step_accumulator += delta_time;

   while ( time_step_accumulator > 1/60th )
   {
      step_physics( 1/60th):
      time_step_accumulator -= 1/60th;
   }

   display();

}

```

This will only do steps when enough time has passed to perform them, and only as many as are needed (in the case of a long lag).
> 1 votes

---
Tags: c++, physics, box2d
---


# Question
Title: How do I increase the speed of an object after it spawns?
I'm trying to increase the speed of a game object based on the wave it spawns in. How would I go about doing this?

```
public class GameController:MonoBehaviour{
     public GameObject hazard;
     public Vector3 hazard_values;
     public int min_asteroids;
     public int max_asteroids;
     private int hazard_count;
     public float spawn_wait;
     public float start_wait;
     public float wave_wait;
     private int wave_count = 0;
     public Text score_text;
     private int score;
     public Text restart;
     public Text game_over_text;
     private bool game_over;
     private bool new_game;
     private float new_speed = 1f;

     void Start(){
         game_over = false;
         new_game = false;
         restart.text = "";
         game_over_text.text = "";
         score = 0;
         updateScore();
         StartCoroutine(asteroidWaves());
     }

     void Update(){
         if(new_game){
             if(Input.GetKeyDown(KeyCode.Return)){
                 Application.LoadLevel(Application.loadedLevel);
             }
         }
     }

     IEnumerator asteroidWaves(){
         yield return new WaitForSeconds(start_wait);
         while(true){
             wave_count += 1;
             AsteroidMover asteroid = GetComponent<AsteroidMover>();
             if(asteroid != null){
                 if(wave_count > 1){
                     min_asteroids *= wave_count;
                     max_asteroids += min_asteroids;
                     asteroid.increaseSpeed(new_speed);
                 }
             }
             if(asteroid == null){
                 Debug.Log ("Meh");
             }

             hazard_count = Random.Range(min_asteroids, max_asteroids);
             for(int i = 0; i < hazard_count; i++){
                 Vector3 hazard_position = new Vector3(Random.Range(-hazard_values.x, hazard_values.x), hazard_values.y, hazard_values.z);
                 Quaternion hazard_rotation = Quaternion.identity;
                 Instantiate(hazard, hazard_position, hazard_rotation);
                 yield return new WaitForSeconds(spawn_wait);
             }
             yield return new WaitForSeconds(wave_wait);
             if(game_over){
                 restart.text = "Press 'Enter' to start a new game.";
                 new_game = true;
                 break;
             }
         }
     }

     public void addScore(int new_score){
         score += new_score;
         updateScore();
     }

     void updateScore(){
         score_text.text = "SCORE: " +score;
     }

     public void gameOver(){
         game_over_text.text = "Game Over";
         game_over = true;
     }
 }

         public class AsteroidMover:MonoBehaviour{
             private Rigidbody asteroid;
             public float speed;

             void Start(){
                 asteroid = GetComponent<Rigidbody>();
                 asteroid.velocity = transform.forward * speed;
             }

             public void increaseSpeed(float new_speed){
                 speed += (new_speed + 0.5f);
                 Debug.Log (speed);
             }
         }

```

To better clarify what I'm trying to do, the feature I'm trying to make work is alot like the falling blocks of Tetris. On the first level, the blocks fall at a predetermined speed. When the player beats the level, the blocks fall at a faster speed. This is exactly what I am trying to accomplish. When my game starts, the hazards(asteroids) fall at a predetermined speed. When the player reaches the next wave, the asteroids need to fall at a faster speed.

# Answer
Put it in the Monobehaviour.Update() method:

```
void Update()
{
   Speed += Rate * Time.elapsed;
}

```
> 2 votes

# Answer
As far as I can understand, I'm summarizing it. You have Asteroids (hazards) having AsteroidMover script attached? and you are accessing AsteroidMover in GameController to increase the speed. But it makes no difference in speed? If this is the case then modify you both classes in the way I'm giving or simply replace it.

```
public class AsteroidMover:MonoBehaviour{
    private Rigidbody asteroid;
    public float speed = 1;

    void Start(){
        asteroid = GetComponent<Rigidbody>();
        asteroid.velocity = transform.forward * speed;
    }

    public void increaseSpeed(float factor){
        speed += (0.5f * factor);
        asteroid.velocity = Vector3.Zero;
        asteroid.velocity = transform.forward * speed;
        Debug.Log(speed);
    }
}

public class GameController:MonoBehaviour{
    public GameObject hazard;
    public Vector3 hazard_values;
    public int min_asteroids;
    public int max_asteroids;
    private int hazard_count;
    public float spawn_wait;
    public float start_wait;
    public float wave_wait;
    private float wave_count = 0;
    public Text score_text;
    private int score;
    public Text restart;
    public Text game_over_text;
    private bool game_over;
    private bool new_game;
    //public AsteroidMover asteroid_mover;

    void Start(){
        game_over = false;
        new_game = false;
        restart.text = "";
        game_over_text.text = "";
        score = 0;
        updateScore();
        StartCoroutine(asteroidWaves());
    }

    void Update(){
        if(new_game){
            if(Input.GetKeyDown(KeyCode.Return)){
                Application.LoadLevel(Application.loadedLevel);
            }
        }
    }

    IEnumerator asteroidWaves(){
        yield return new WaitForSeconds(start_wait);
        while(true){
            wave_count += 1;
            if(wave_count > 1){
                min_asteroids *= wave_count;
                max_asteroids += min_asteroids;
                //asteroid_mover.increaseSpeed();
            }

            hazard_count = Random.Range(min_asteroids, max_asteroids);
            for(int i = 0; i < hazard_count; i++){
                Vector3 hazard_position = new Vector3(Random.Range(-hazard_values.x, hazard_values.x), hazard_values.y, hazard_values.z);
                Quaternion hazard_rotation = Quaternion.identity;
                GameObject asteroid = Instantiate(hazard, hazard_position, hazard_rotation) as GameObject;
                asteroid.GetComponent<AsteroidMover>().increaseSpeed(wave_count);
                yield return new WaitForSeconds(spawn_wait);
            }
            yield return new WaitForSeconds(wave_wait);
            if(game_over){
                restart.text = "Press 'Enter' to start a new game.";
                new_game = true;
                break;
            }
        }
    }

    public void addScore(int new_score){
        score += new_score;
        updateScore();
    }

    void updateScore(){
        score_text.text = "SCORE: " +score;
    }

    public void gameOver(){
        game_over_text.text = "Game Over";
        game_over = true;
    }
}

```
> 0 votes

# Answer
Inside your "AsteroidMover" script, add following lines:

```
    void FixedUpdate()
    {
        increaseSpeed();
        asteroid.velocity = transform.forward * speed;
    }

```
> 0 votes

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


# Question
Title: How to find connected groups in a 2D grid of tiles
Firstly, my English is very bad, sorry for this. That's why I showed my problem with a picture.

```
Block[,] sameTiles = new Block[
  WorldController.Instance.World.Width,
  WorldController.Instance.World.Height];

```

`sameTiles` keeps the same side-by-side green blocks. My problem is, I need to detect and separate the shapes made of connected blocks so I can access each shape separately. For example, putting each group on a layer of a 3D array:

```
Block[,,] differentTiles = new Block[
  100,
  WorldController.Instance.World.Width,
  WorldController.Instance.World.Height];

```

(100 connected shapes are supported at max)

```
Block[
  ShapeNumber,
  X Coord,
  Y Cood].

```

Here is my picture, I need to search this array and detect the four shapes of connected green blocks, storing them separately. Picture:

# Answer
> 1 votes
I'm interpreting your problem as follows - please update the question if I've gotten any details incorrect:

1. We are given a grid (world) of size world.Width & world.Height filled with coloured blocks.
2. We want to search this grid to find every group of two or more green blocks connected along their edges (polyominos)
3. We want to store these groups in a structure that lets us quickly identify all the blocks associated with each distinct group.

I'm choosing to reject the form of output described in your question, a 3D array, because this will tend to waste a lot of space and isn't very efficient to iterate over.

Instead, I'd recommend a list of groups, where each group is a list of blocks. There are more compressed formats still, but this hits a nice trade-off of efficiency & ease of use. (I assume each block knows its location in the world - If not, the list can store the coordinates of each block instead of the block itself)

In my example I'll create new lists as needed, but for performance you can modify this to re-use the lists in a pool if you find it's causing excess garbage.

```
public List<List<Block>> FindConnectedGroups(World world, BlockColor matchColor)
{
    var groups = new List<List<Block>>();

    // Search the world grid for pairs of connected blocks.
    for(int x = 0; x < world.Width; x++)
    {
       for(int y = 0; y < world.Height; y++)
       {
           var block = world.GetBlock(x, y);

           // Skip blocks we've already grouped.
           // If you don't want to add a visited field to every block,
           // you can accomplish this with a parallel array instead.
           if(block.visited)
               continue;

           // Remove this check if you want to find groups of any color.
           if(block.color == matchColor)
           {
               // Every group of 2+ blocks has a block to the right or below another,
               // so by checking just these two directions we don't exclude any.
               if(x > 0)
               {
                   var neighbor = world.GetBlock(x - 1, y);
                   if(neighbor.color == block.color)
                   {
                      var group = new List<Block>();
                      PopulateGroup(world, group, block);
                      groups.Add(group);
                      continue;
                   }
               }
               if(y > 0)
               {
                   var neighbor = world.GetBlock(x, y - 1);
                   if(neighbor.color == block.color)
                   {
                      var group = new List<Block>();
                      PopulateGroup(world, group, block);
                      groups.Add(group);
                   }
               }
           }
       }
    }

    // Set all tiles back to unvisited for the next use.
    world.ClearVisitedFlags();

    return groups;
}

// Recursively find connected blocks (depth-first search)
void PopulateGroup(World world, List<Block> group, block)
{
    group.Add(block);
    block.visited = true;

    // Check all four neighbors and recurse on them if needed:
    if(block.x > 0)
    {
        var neighbor = world.GetBlock(block.x - 1, block.y);
        if(neighbor.color == block.color && neighbour.visited == false)
            PopulateGroup(world, group, neighbor);
    }
    if(block.x < world.Width - 1)
    {
        var neighbor = world.GetBlock(block.x + 1, block.y);
        if(neighbor.color == block.color && neighbour.visited == false)
            PopulateGroup(world, group, neighbor);
    }
    if(block.y > 0)
    {
        var neighbor = world.GetBlock(block.x, block.y - 1);
        if(neighbor.color == block.color && neighbour.visited == false)
            PopulateGroup(world, group, neighbor);
    }
    if(block.y < world.Height - 1)
    {
        var neighbor = world.GetBlock(block.x, block.y + 1);
        if(neighbor.color == block.color && neighbour.visited == false)
            PopulateGroup(world, group, neighbor);
    }
}

```

**Edit:** Added the step to clear visited flags once we're done, so that a subsequent call doesn't skip all the groups we found this time. You can also use a number that's incremented with each FindConnectedGroups() call instead of a boolean and avoid clearing, as long as you never keep a world around for more than Int32.MaxValue calls. ;)

---
Tags: unity, c#, 2d
---


title: How to make a "Camera" in Java

text:
# Question
Title: How to make a "Camera" in Java
I need some help with getting my camera to work in java for a game that I am making. The problem is is that I've never made a camera in a game before and this is my first time trying to make one in a game, but whenever I test it to see if it works, the screen doesn't center on the player. I've tried many times and checked a couple of resources online but I still haven't figured it out. The code is here:

Camera.class:

```
public class Camera {

private float playerX, playerY;
private float mapX, mapY;
private float offsetMaxX = mapX - Main.WIDTH;
private float offsetMaxY = mapY - Main.HEIGHT;
private float offsetMinX = 0;
private float offsetMinY = 0;
private float camX;
private float camY;

public Camera (float playerX, float playerY, float mapX, float mapY) {
    super ();
    this.playerX = playerX;
    this.playerY = playerY;
    this.mapX = mapX;
    this.mapY = mapY;
    update();
}

public Camera () {

}

public void update (){
    camX = playerX - Main.WIDTH / 2;
    camY = playerY - Main.HEIGHT / 2;
    if (camX > offsetMaxX) {
        camX = offsetMaxX;
    } else if (camX < offsetMinX) {
        camX = offsetMinX;
    }
}

public float getCamX() {
    return camX;
}

public float getCamY() {
    return camY;
}

public float getMapX() {
    return mapX;
}

public float getMapY() {
    return mapY;
}

public float getPlayerY() {
    return playerY;
}

public float getPlayerX() {
    return playerX;
}

```

}

and my main class is here:

public class Game extends BasicGameState {

```
// Player variables
public SpriteSheet playerSS = null;
protected InputHandler inputHandler;
public float playerX = Main.WIDTH/2, playerY = Main.HEIGHT/2;
private Animation sprite, runningAnimationLEFT, runningAnimationRIGHT, runningAnimationUP, runningAnimationDOWN;
private Animation standLEFT, standRIGHT, standUP, standDOWN; //THIS IS TO PREVENT ANIMATIONS FROM CONTINUING AFTER THE PLAYER STOPS
private int duration = 300;
public boolean isMoving, isLeft, isRight, isUp, isDown;

//Map
private Image testMap; //This is a test map
private float mapX = 0, mapY = 0;

//Camera
public Camera camera;

public Game (int stateID) {}

@Override
public int getID() {
    return Main.game; //GAMESTATE = 1
}

@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    playerSS = new SpriteSheet("res/characters/player_sprite_sheet.png", 50, 75);
    testMap = new Image ("res/grassMap.png");
    camera = new Camera();

    // ANIMATIONS
    runningAnimationDOWN = new Animation();
    runningAnimationDOWN.setAutoUpdate(true);
    runningAnimationDOWN.addFrame(playerSS.getSprite(1, 0), duration);
    runningAnimationDOWN.addFrame(playerSS.getSprite(0, 0), duration);
    runningAnimationDOWN.addFrame(playerSS.getSprite(2, 0), duration);

    runningAnimationLEFT = new Animation();
    runningAnimationLEFT.setAutoUpdate(true);
    runningAnimationLEFT.addFrame(playerSS.getSprite(1, 1), duration);
    runningAnimationLEFT.addFrame(playerSS.getSprite(0, 1), duration);
    runningAnimationLEFT.addFrame(playerSS.getSprite(2, 1), duration);

    runningAnimationRIGHT = new Animation();
    runningAnimationRIGHT.setAutoUpdate(true);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(1, 2), duration);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(0, 2), duration);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(2, 2), duration);

    runningAnimationUP = new Animation();
    runningAnimationUP.setAutoUpdate(true);
    runningAnimationUP.addFrame(playerSS.getSprite(1, 3), duration);
    runningAnimationUP.addFrame(playerSS.getSprite(0, 3), duration);
    runningAnimationUP.addFrame(playerSS.getSprite(2, 3), duration);

    standDOWN = new Animation();
    standDOWN.setAutoUpdate(true);
    standDOWN.addFrame(playerSS.getSprite(1, 0), duration);

    standLEFT = new Animation();
    standLEFT.setAutoUpdate(true);
    standLEFT.addFrame(playerSS.getSprite(1, 1), duration);

    standRIGHT = new Animation();
    standRIGHT.setAutoUpdate(true);
    standRIGHT.addFrame(playerSS.getSprite(1, 2), duration);

    standUP = new Animation();
    standUP.setAutoUpdate(true);
    standUP.addFrame(playerSS.getSprite(1, 3), duration);

    sprite = standDOWN;
}

@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
    inputHandler.updateKeyboardRelay(gameContainer);
    isMoving = false;

    if (inputHandler.keyUP) {
        isUp = true;
        isDown = false;
        isLeft = false;
        isRight = false;
        isMoving = true;
        playerY -= delta * 0.1f;
    } else if (inputHandler.keyDOWN) {
        isDown = true;
        isUp = false;
        isLeft = false;
        isRight = false;
        isMoving = true;
        playerY += delta * 0.1f;
    } else if (inputHandler.keyLEFT) {
        isLeft = true;
        isUp = false;
        isDown = false;
        isRight = false;
        isMoving = true;
        playerX -= delta * 0.1f;
    } else if (inputHandler.keyRIGHT) {
        isRight = true;
        isUp = false;
        isDown = false;
        isLeft = false;
        isMoving = true;
        playerX += delta * 0.1f;
    }

    if (isMoving) {
        if (inputHandler.keyUP) {
            sprite = runningAnimationUP;
            sprite.update(delta);
        } else if (inputHandler.keyDOWN) {
            sprite = runningAnimationDOWN;
            sprite.update(delta);
        } else if (inputHandler.keyLEFT) {
            sprite = runningAnimationLEFT;
            sprite.update(delta);
        } else if (inputHandler.keyRIGHT) {
            sprite = runningAnimationRIGHT;
            sprite.update(delta);
        }
    } else {
        if (isDown) {
            sprite = standDOWN;
            sprite.update(delta);
        } else if (isUp) {
            sprite = standUP;
            sprite.update(delta);
        } else if (isLeft) {
            sprite = standLEFT;
            sprite.update(delta);
        } else if (isRight) {
            sprite = standRIGHT;
            sprite.update(delta);
        }
    }
}

@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
    testMap.draw(mapX, mapY);

    graphics.translate(camera.getCamX(), camera.getCamY());
    sprite.draw(playerX, playerY);
    graphics.translate(-camera.getCamX(), -camera.getCamY());

    graphics.drawString("Player X: " + playerX, 400, 400);
    graphics.drawString("Player Y: " + playerY, 400, 380);

}

```

}

Any help with getting the camera to function properly would be very helpful :)

# Answer
I was able to figure out how to get the whole "camera" to work through the question I posed and subsequently answered on stackoverflow: https://stackoverflow.com/questions/34385383/having-the-camera-positioning-on-the-player-in-java
> 1 votes

# Answer
I am unfamiliar with slick, but given that your camera has no dependencies on it, I believe you are missing the update call to the camera. You never move the camera to where the player is, so it can not be centered on the player.

Maybe this works in the end of your Game class' Update method:

```
camera.playerX = playerX;
camera.playerY = playerY;
camera.update();

```
> 0 votes

---
Tags: java, software-engineering, graphics-programming, slick
---


# Question
Title: Is It Better To Generate A Pre-Generated Map or A Randomly Generated Map When Using Tile Properties?
So I am contemplating whether or not to add a Pre-Generated Map or a randomly generated map into my game. But I also need to add Tile properties into the map (i.e. so that water tiles aren't being walked on by the player, etc.). Which way is better, to add tile properties to an existing image file or to add tile properties to a randomly generated map?

I want to make it so that I can add Tile properties to a pre-generated map as I already have one ready to go, but is it even possible to add tile properties to a pre-generated map?

I am using Java and the Slick2D gaming engine.

# Answer
> 0 votes
I think your question is not very clear and actually brings many mini-questions in one (what you should avoid doing in this website).

That said, I will address very briefly some points:

> is it even possible to add tile properties to a pre-generated map?

Yes, it certainly is. Once you generate the map, for each tile you can just pull a bunch of information related to the tile type in question. For example, suppose you generate a 10x10 map, where the rows are identified by letters and columns by numbers. So, when you randomly define cell A1, it ends up being "water".

Then, you just have to import the values for that cell from a list or array of tile types that has a format similar to the following (in this case, water is the first row):

```
type; walkable; food;
water; 0; 10;
grass; 1; 5;
rocky; 1; 0;

```

If B1 is randomly determined to be a "rocky" type, again you identify which row in the above list/array corresponds to "rocky" and imports that row into the new tile.

> Is It Better To Generate A Pre-Generated Map or A Randomly Generated Map When Using Tile Properties?

Now that's an entirely opinion-based question. Specially because we know nothing about your game. So, it's utterly impossible to give you clues on that. However, what I can do is tell that it's fairly and equally easy to assign properties to tiles in either case.

So, no, your choice between pre-generated and randomly generated maps shouldn't have anything to do with assigning properties to each tile.

Choosing if you are going to use pre-generated maps or randomly generated maps is a game-feature decision. It's a higher-level game design decision that you should make beforehand mostly on the basis of what you want your game to be like and offer to players.

---
Tags: java, software-engineering, slick
---


# Question
Title: Screenshot always returning as a white image on iOS using robovm and libgdx
I am trying to take a screenshot for sharing on social media. This code works on my Desktop project, but when I use it on iOS it always shows up as a white image, I am using the standard libgdx code for the screenshot factory, any suggestions?

```
public class ScreenShotFactory
{
public static void SaveScreenshot()
{
    try
    {
        Gdx.files.local("shot.png").delete();
        FileHandle fh;
        do
        {
            fh = new FileHandle(Gdx.files.getLocalStoragePath() + "shot.png");
        }
        while (fh.exists());

        Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);

        PixmapIO.writePNG(fh, pixmap);

        pixmap.dispose();
    }

    catch (Exception e)
    {
    }
}

private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown)
{
    final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

    if (yDown)
    {
        // Flip the pixmap upside downx
        ByteBuffer pixels = pixmap.getPixels();
        int numBytes = w * h * 4;
        byte[] lines = new byte[numBytes];
        int numBytesPerLine = w * 4;
        for (int i = 0; i < h; i++) {
            pixels.position((h - i - 1) * numBytesPerLine);
            pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
        }
        pixels.clear();
        pixels.put(lines);
        pixels.clear();
    }
    Logger.Log("ScreenShot Taken!");
    return pixmap;
 }
}

```

# Answer
This post is related and offers a solution

The solution is to do the screenshot in iOS specific code:

```
public byte[] takeScreenshot(){
UIImage newImage;
UIGraphics.beginImageContext(new CGSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
application.getUIViewController().getView().drawViewHierarchy(
      new CGRect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) , true);
newImage = UIGraphics.getImageFromCurrentImageContext();
UIGraphics.endImageContext();

NSData data = newImage.toJPEGData(.6);
newImage.dispose();

return data.getBytes();
}

```

only problem is converting the returned data to a pixmap, which I havent figured out yet(because I dont know the format toJPEGData writes in)
> 1 votes

---
Tags: libgdx, ios, screenshot
---


# Question
Title: Why transform.find() does not need actual object[unity]
I m new to unity and C#.

I suspect that transform.find() function below does not need actual object reference like

> player.transform.find()

because it transform find is already applied to the gameObject the script is attached to? Am I right? Why transform.find() does not have any game object in front of it?

public class PlayerControl : MonoBehaviour{

```
private Transform groundCheck ;

void Awake()
{
    groundCheck = transform.Find("groundCheck");
}

```

# Answer
> 1 votes
`transform` is the instance of `Transform` which is a public attribute of `GameObject`. That is why we don't need it. But you can use `gameObject.transform.Find("groundCheck");` though. Similarly `gameObject` is the instance of `GameObject` representing the `GameObject` in which this script is attached.

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


# Question
Title: Cocos2D - How to move sprite on the X axis, using the accelerometer
I'm trying to make a vertical shooter, using Cocos2D and a few tutorials. Unfortunately, most tutorials only show how to make an horizontal shooter.

Still, I tried to adapt the code from a horizontal shooter to a vertical one, but am having a few problems. Mainly, my ship keeps moving right, even when the iPhone is sitting perfectly still.

Seeing as I'm a beginner, I'm having trouble pinpointing the exact issue and I'd love if anyone could help me.

Here's my accelerometer method:

```
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    define kFilteringFactor 0.1

    define kRestAccelX -0.6

    define kShipMaxPointsPerSec (winSize.width*0.5)

    define kMaxDiffX 0.2

    UIAccelerationValue rollingX;

    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));

    float accelX = acceleration.x - rollingX;

    CGSize winSize = [CCDirector sharedDirector].winSize;

    float accelDiff = accelX - kRestAccelX;
    float accelFraction = accelDiff / kMaxDiffX;
    float pointsPerSec = kShipMaxPointsPerSec * accelFraction;

    _shipPointsPerSecX = pointsPerSec;

}

```

And my update method:

```
-(void)update:(ccTime)dt {

    CGSize winSize = [CCDirector sharedDirector].winSize;
    float maxX = winSize.width - _ship.contentSize.width/2;
    float minX = _ship.contentSize.width/2;

    float newX = _ship.position.x + (_shipPointsPerSecX * dt);
    newX = MIN(MAX(newX, minX), maxX);
    _ship.position = ccp(newX, _ship.position.y);

}

```

What could be causing this?

# Answer
You don't really need this much code to do sliding across the ground.

Try simply:

```
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
     _shipPointsPerSecX = acceleration.x * 10;
}

```

To get the ship to accelerate and decelerate you could try

```
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
     float targetSpeed = acceleration.x * 10;
     _shipPointsPerSecX = (_shipPointsPerSecX * .8f) + (targetSpeed * .2f);
}

```

But this isn't really accurate, a more realistic response might involve sliding towards the target value:

```
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    float targetSpeed = acceleration.x * 10;
    if(_shipPointsPerSecX < targetSpeed) {
        _shipPointsPerSecX = MIN(_shipPointsPerSecX + 2, targetSpeed);
    } else {
        _shipPointsPerSecX = MAX(_shipPointsPerSecX - 2, targetSpeed);
    }
}

```
> 3 votes

# Answer
Move the sprite from top to bottom and left to right using Accelerometer:

```
CCScene* PhysicsGame::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();

    // 'layer' is an autorelease object
    PhysicsGame *layer = PhysicsGame::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool PhysicsGame::init()
{

    // 1. super init first
    if ( !CCLayer::init())
    {
        return false;
    }

    winSize=CCDirector::sharedDirector()->getWinSize();

    BG=CCSprite::create("Yellowbg.png");
    BG->setPosition(ccp(winSize.width/2,winSize.height/2));
    this->addChild(BG,1);

//    _backgroundNode = CCParallaxNodeExtras::node();
//    this->addChild(_backgroundNode,-1);

    asteroid = CCSprite::create("Ball_image.png");
    asteroid->setPosition(ccp(winSize.width*0.1,winSize.height/2));
    this->addChild(asteroid,1);

    this->scheduleUpdate();

    this->setAccelerometerEnabled(true);

    return true;

}

void PhysicsGame::update(float dt)
{

    winSize = CCDirector::sharedDirector()->getWinSize();

    float maxY = winSize.height - asteroid->getContentSize().height/2;
    float minY = asteroid->getContentSize().height/2;

    float diff = (_shipPointsPerSecY * dt);
    float newY = asteroid->getPosition().y + diff;
    newY = MIN(MAX(newY, minY), maxY);

    asteroid->setPosition(ccp(asteroid->getPosition().x, newY));

    float minX=asteroid->getContentSize().width/2;

    float maxX = winSize.width - asteroid->getContentSize().width/2;

    float diff1 = (_shipPointsPerSecX * dt);

    float newX=asteroid->getPosition().x + diff1;

    newX=MIN(MAX(newX, minX), maxX);

    asteroid->setPosition(ccp(newX, asteroid->getPosition().y));

}

void PhysicsGame::didAccelerate(CCAcceleration *pAccelerationValue)
{

#define KFILTERINGFACTOR 0.1
#define KRESTACCELX -0.6
#define KSHIPMAXPOINTSPERSEC (winSize.height*0.5)
#define KMAXDIFFX 0.2

    double rollingX;

    // Cocos2DX inverts X and Y accelerometer depending on device orientation
    // in landscape mode right x=-y and y=x !!! (Strange and confusing choice)

    rollingX = (pAccelerationValue->x * KFILTERINGFACTOR) + (rollingX * (1.0 - KFILTERINGFACTOR));

    float accelX = pAccelerationValue->x - rollingX;

    float accelDiff = accelX - KRESTACCELX;

    float accelFraction = accelDiff / KMAXDIFFX;

    float pointsPerSec = KSHIPMAXPOINTSPERSEC * accelFraction;

    _shipPointsPerSecX = pointsPerSec;

#define KFILTERINGFACTOR1 0.1
#define KRESTACCELY -0.6
#define KSHIPMAXPOINTSPERSEC1 (winSize.width*0.5)
#define KMAXDIFFX1 0.2

    double rollingY;

    rollingY = (pAccelerationValue->y * KFILTERINGFACTOR) + (rollingY * (1.0 - KFILTERINGFACTOR1));

    float accelY = pAccelerationValue->y - rollingY;

    float accelDiff1= accelY - KRESTACCELY;

    float accelFraction1 = accelDiff1 / KMAXDIFFX1;

    float pointsPerSec1 = KSHIPMAXPOINTSPERSEC1 * accelFraction1;

    _shipPointsPerSecY = pointsPerSec1;

}

```
> 0 votes

---
Tags: iphone, ios, cocos2d-iphone
---


# Question
Title: Basic collision issues in gamemaker studio
I'm really new to the game design world so I'm sorry if this question is stupid, but here it goes! I have 3 objects, a square that the player controls, a wall that the square should collide with and be unable to pass, and a floor that the square should be unable to pass through. I have tried playing around with the Solid and the Use Physics characteristics when I create the objects but I cannot get them to collide properly. Any ideas would be appreciated. Could you please help me out?

# Answer
> 2 votes
This method works for me:

```
if (keyboard_check(ord('W') && place_free(x,y-1)) {
    y -= 1;
}
if (keyboard_check(ord('A') && place_free(x-1,y)) {
    x -= 1;
}
if (keyboard_check(ord('S') && place_free(x,y+1)) {
    y += 1;
}
if (keyboard_check(ord('D') && place_free(x+1,y)) {
    x += 1;
}

```

As you can see this is the usual WASD movement code but this time I added `place_free(x,y)` which checks x and y for a collision with a *solid object*.

In this case I check if there will be a collision with a solid object wherever the player will be next. If there is no collision detected a.k.a "place free?" or "is this place free of any solid objects?" then the player will move. Otherwise, the player won't move because there is a collision.

`place_meeting(x,y,obj)` is an alternative check for objects that you choose, and do not have to be solids. If you do not want to make your Wall or Floor object a *solid* then you can replace `place_free(x,y)` with that. Like this `place_meeting(x,y-1,objWall)` for example.

---
Tags: game-maker
---


# Question
Title: A guide on multi-direction and multi-animation sprites?
In YoYo Game Maker Studio: Is there a way (or an already-created library) I can specify all the possible sprite frames and directions in a way I am allowed to do it in Clickteam Fusion?

As far as I read in the docs, I create Sprite resources which are linear: An image resource can be loaded and read in columns and rows, but a single sprite is generated. However, what I want to achieve is the following:

1. Import a single image with layout like this:

```
llll
rrrr
uuuu
dddd

```

Meaning four frames per direction (left, right, up, down).
2. Allow my sprite to have four directions. In such case, the animation will involve just the row corresponding to the direction.
3. Allow the user to stay / not move. In such cases, I would use another image like this (most of the times it would be a subset of the former):

```
l
r
u
d

```

**Question**: Before doing it in the hard way (which for larger games I did in ActionScript already; I'm not net at all at coding) I would like to ask:

1. Is there an already supported way in the environment to do it? Like managing the related sprites as a set.
2. Alternatively: Any good 3rd party plugin which already does that?

I have no problem at all with coding the solution on my own, but honestly I would not like to reinvent the wheel.

# Answer
> 3 votes
Make a new sprite, go to *Edit Sprite* then *File→Create From Stripe...* Pick your sprite sheet then it will show it with a grid.

From there you can set *number of images* and *images per row* so that your `llll` are the 4 images for the left direction.

You can make new sprites that have multiple images for the other directions, when the player is not moving, etc.

If the player presses a certain key you can change the sprite, like this:

```
if (keyboard_check(ord('W'))) {
    sprite_index = spr_character_left;
    y -= 1; // move up 1
}

if (!keyboard_check(ord('W'))) {
    image_speed = 0; // 0 animation speed
    sprite_index = spr_character_face_up;
} else {
    image_speed = 0.1;
}

```

or if you want the sprite to change directions that point to the mouse, make a variable that stores the direction from the object to the mouse:

```
dir = point_direction(x,y,mouse_x,mouse_y);

if (dir > 90 && dir < 270) { // if direction is within 90 and 270 (left)
    sprite_index = spr_character_left;
}

```

where the direction ranges are:

Game Maker Manual regarding strips: Designing Games with GameMaker: Strips

---
Tags: game-maker
---


# Question
Title: Reorder a set of points in order to draw a triangle fan (example)
I'm doing a light engine (c++, using sfml), and to connect the light vertices, I thought about drawing a triangle fan. Here is a representation of a triangle fan (sfml documentation):

---

---

The points HAVE TO be "ordered" to draw the shape correctly, otherwise it would mess the shape I suppose.

I drew the desired effect in **ms paint**:

---

---

As you can probably see, there is a central point, a light, and other points that I want to connect together. The problem is that the points are not always ... "In a row/Ordered" ? Let's see an example and simplify this problem.

---

---

In the example above, I can't connect the points from 0 to 8 because it would mess the shape.

I would like to reorder the points so I can connect them properly, like :

---

---

Do you have any ideas ?

I thought about doing something based on the "point in polygon" algorithm, like checking if the point is "on the right/left" but it seems complicated.

I don't necessarily need code (if you have time it would be nice) but I can try to do some, I just need ideas. Thanks

# Answer
> 3 votes
I finally did it and found a quite simple solution, seems fast enough, I post it if anyone wants the solution.

I created a class Point

```
class Point {
public:
    sf::Vector2f myPosition;
    float myAngle;

    Point(sf::Vector2f thePosition = {}) {
        myPosition = thePosition;
    }
};

```

I made a vector of points : `std::vector<Point> lightPoints`

then, I retreived the angle of each point in the vector

```
for (size_t i = 0; i < lightPoints.size(); i++) {
        lightPoints[i].myAngle = getAngle(lights[ii].position,lightPoints[i].myPosition);
}

```

(By the way, my getAngle function look like this)

```
float getAngle(sf::Vector2f a, sf::Vector2f b, bool inDegrees = false) {
    if (inDegrees)
        return (float)(atan2(b.y - a.y, b.x - a.x) * 180 / pi);
    return (float)(atan2(b.y - a.y, b.x - a.x));
}

```

And after getting all the angles, I sorted the vector:

```
std::sort(lightPoints.begin(), lightPoints.end(),
[](const Point& p1, const Point& p2) {
    return p1.myAngle < p2.myAngle;
});

```

And the sorting works like a charm.

---
Tags: c++, sfml, sorting
---


title: How does Color.Lerp works?

text:
# Question
Title: How does Color.Lerp works?
I want to understand how does `Color.Lerp` works in unity.
According to this page it is quite clear to understand how to use it but I'm interested in how it is implemented. Does it work on RGB channels? and how? In the docs it says that the `t` factor is clamped between 0 and 1 so i wonder to know on which values Lerp works with `Color`.

# Answer
> 5 votes
Color.Lerp in Unity works just as any lerp implementation, which works like this:

```
float lerp(float a, float b, float t)
{
    t = clamp01(t);
    return a + (b - a) * t;
}

```

Or with multiple components, like Color:

```
Color lerp(Color a, Color b, float t)
{
    t = clamp01(t);
    return new Color(
        a.r + (b.r - a.r) * t,
        a.g + (b.g - a.g) * t,
        a.b + (b.b - a.b) * t,
        a.a + (b.a - a.a) * t
    );
}

```

---
Tags: unityscript, lerp
---


# Question
Title: How can I clamp the transform to a range?
I am trying to create a level editor in Unity. When the position of an object is changed, I want that object to have its X and Y positions clamped between 1 and 10. So if the position is changed to 15, it will snap back to 10; and if the position is changed to -5, it will snap back to 1.

I have tried using the OnValidate() method, but without success. It snaps everything correctly when I reload the script (make a change to the script and reopen Unity), but it will not snap it on the fly.

```
void OnValidate(){
    float newX = Mathf.Clamp(child.position.x, 1, 10);
    float newY = Mathf.Clamp(child.position.y, 1, 10);
    transform.localPosition = new Vector2(newX, newY);
}

```

Any suggestions on how I can accomplish this?

# Answer
> 1 votes
OnValidate is only called when the script is loaded or a value is changed in the inspector (Called in the editor only).

You're probably looking for `Update()`

```
void Update(){
    float newX = Mathf.Clamp(child.position.x, 1, 10);
    float newY = Mathf.Clamp(child.position.y, 1, 10);
    transform.localPosition = new Vector2(newX, newY);
}

```

There is a way to get this method to execute in the editor, according to this thread which is ExecuteInEditMode.

> Makes a script execute in edit mode.
>
> By default, script components are only executed in play mode. By adding this attribute, each script component will also have its callback functions executed while the Editor is not in playmode.
>
> * Update is only called when something in the scene changed.

This should get the behavior you desire, by adding `[ExecuteInEditMode]` (C#) or `@script ExecuteInEditMode()` (JS) to the top of your class file.

Alternatively, you can use OnDrawGizmos() which is called when the object is selected in the scene view. Please note:

> This function does not get called if the component is collapsed in the inspector. Use OnDrawGizmosSelected to draw gizmos when the game object is selected.

This means that if your script is collapsed in the inspector, this method won't be called.

---
Tags: unity, validation
---


title: Diamond square algorithm

text:
# Question
Title: Diamond square algorithm
I'm working on generating terrain on already generated landmass. The landmass and ocean around it consist of hexagons. Hexagons aren't really a concern for me, because I can always interpolate the values algorithms generates with the vertices on the grid. As you can see on the image below, blue is ocean, brown is land.

Problem is, I need the shore to have 0 height, can it even be done with diamond square algorithm?

# Answer
Diamond square algorithm works with random height add-on.

One thing you could do is to make a map that will give limits to these random numbers for each part of the map.

This map will have very low to null values in the sea region and on the shore. This map will allow higher values in other parts of the map.

You will then preserve the random generation and have realistic shores.

If you let low values in the sea side, you'll even be able to generate little random private islands ;)
> 1 votes

# Answer
Diamond Square doesn't work well with hexagons, but you did say you have a way around that with interpolation. You can seed the shore line with 0 and default the other heights to something else. During the process, don't generate the heights that are already 0.

Would that work?
> 0 votes

---
Tags: algorithm, procedural-generation, terrain, heightmap
---


title: MonoGame does not generate xnb from png

text:
# Question
Title: MonoGame does not generate xnb from png
I am coming straight from XNA and I installed the latest version of MonoGame today (2015-12-22) for Visual Studio 2015 Community. I created a project from the windows Project template.

I right click the content folder and add a png-file. I compile without error but it stops during runtime because it can't find the content file. My solution look like this

Game1.cs look like this:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace homer
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Texture2D simpson;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            simpson = Content.Load<Texture2D>(@"Images/Homer");
        }

        protected override void UnloadContent(){ }

        protected override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
            spriteBatch.Draw(simpson, new Vector2(200, 100), Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

```

The problem I encounter is that MonoGame do not make xnb-files from the png and put it in my output folder. I tried to copy the file manually from a compiled XNA project to my MonoGame debug folder and it worked. I have done nothing but create a project from the template and trying to load an image. What do I need to do to make MonoGame compile xnb-files for me. It also runs if I change "Do not copy" to "Copy always" but that is not optimal for runtime as I understand it. Also, I don't want it to be too easy for the users to doodle in the graphics.

Content.mgcb look like this

```
#----------------------------- Global Properties ----------------------------#

/outputDir:bin/Windows
/intermediateDir:obj/Windows
/platform:Windows
/config:
/profile:Reach
/compress:False

#-------------------------------- References --------------------------------#

#---------------------------------- Content ---------------------------------#

```

# Answer
> 2 votes
Open the Content.mgcb file with the ContentPipeline tool. From there you can add the .png file and the content will be build for you.

The content pipeline tool is located on my machine in: "C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\Pipeline.exe"

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


# Question
Title: (Unity) Drag and detect object below when dropping
I'm studying game development in Unity and I want to create a idle/clicker game like Cow Evolution.

I'm using `OnMouseDown`, `OnMouseDrag` and `OnMouseUp` to move the GameObject around the scene.

Now I want to detect the collision when dropping (`OnMouseUp`) a GameObject over another GameObject.

Like in this video: https://www.youtube.com/watch?v=3OK77oVV\_G0

Assuming there's more than one object below, I must detect which one is with most below the dropped object.

I apologize if it is difficult to understand my English.

Thank you.

# Answer
I have achieved something like that with this script

```
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof (RectTransform))]
[RequireComponent(typeof (Image))]
public class RayCastMask : MonoSingleton<RayCastMask>, ICanvasRaycastFilter
{
    private Image _image;
    private Sprite _sprite;

    public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        _sprite = _image.sprite;

        var rectTransform = (RectTransform) transform;
        Vector2 localPositionPivotRelative;
        RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform) transform, sp, eventCamera,
        out localPositionPivotRelative);

        // convert to bottom-left origin coordinates
       var localPosition = new Vector2(localPositionPivotRelative.x + rectTransform.pivot.x*rectTransform.rect.width,
        localPositionPivotRelative.y + rectTransform.pivot.y*rectTransform.rect.height);

        var spriteRect = _sprite.textureRect;
        var maskRect = rectTransform.rect;

        var x = 0;
        var y = 0;
        // convert to texture space
        switch (_image.type)
        {
            case Image.Type.Sliced:
            {
                var border = _sprite.border;
                // x slicing
                if (localPosition.x < border.x)
                {
                    x = Mathf.FloorToInt(spriteRect.x + localPosition.x);
                }
                else if (localPosition.x > maskRect.width - border.z)
                {
                    x = Mathf.FloorToInt(spriteRect.x + spriteRect.width - (maskRect.width - localPosition.x));
                }
                else
                {
                    x = Mathf.FloorToInt(spriteRect.x + border.x +
                                     ((localPosition.x - border.x)/
                                      (maskRect.width - border.x - border.z))*
                                     (spriteRect.width - border.x - border.z));
                }
                // y slicing
                if (localPosition.y < border.y)
                {
                    y = Mathf.FloorToInt(spriteRect.y + localPosition.y);
                }
                else if (localPosition.y > maskRect.height - border.w)
                {
                    y = Mathf.FloorToInt(spriteRect.y + spriteRect.height - (maskRect.height - localPosition.y));
                }
                else
                {
                    y = Mathf.FloorToInt(spriteRect.y + border.y +
                                     ((localPosition.y - border.y)/
                                      (maskRect.height - border.y - border.w))*
                                     (spriteRect.height - border.y - border.w));
                }
            }
                break;
            case Image.Type.Simple:
            default:
            {
                // conversion to uniform UV space
                x = Mathf.FloorToInt(spriteRect.x + spriteRect.width*localPosition.x/maskRect.width);
                y = Mathf.FloorToInt(spriteRect.y + spriteRect.height*localPosition.y/maskRect.height);
            }
                break;
        }

        // destroy component if texture import settings are wrong
        try
        {
            return _sprite.texture.GetPixel(x, y).a > 0;
        }
        catch (UnityException e)
        {
            Debug.LogError(
            "Mask texture not readable, set your sprite to Texture Type 'Advanced' and check 'Read/Write Enabled'");
            Destroy(this);
            return false;
        }
    }

    private void Start()
    {
        _image = GetComponent<Image>();
    }
}

```

Just add this script to your target and change texture type property to advanced, enable read/write and check "Alpha is transparency"
> 1 votes

# Answer
For getting all the colliders which are below the touch position , we need to use the RaycastAll function.

This returns an array of hits from which we can determine the GameObject which is at the farthest distance from the camera.

Also take care of the situation where no objects where detected, to avoid the null reference error.

```
void Update()
    {
        if (Input.GetMouseButtonUp (0))
        {
            RaycastHit[] hits;
            Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            hits = Physics.RaycastAll (camRay);

            Debug.Log("hits "+hits.Length);
            GameObject LastGameObject = null;

            for (int i = 0; i < hits.Length; i++)
            {
                RaycastHit hit = hits [i];

                if(LastGameObject == null)
                {
                    LastGameObject =  hit.transform.gameObject;

                }
                else
                {

                    if(Vector3.Distance (LastGameObject.transform.position,Camera.main.transform.position) < Vector3.Distance (hit.collider.transform.position,Camera.main.transform.position))
                    {
                        LastGameObject =  hit.transform.gameObject;
                    }
                }

            }

            if(LastGameObject)
                Debug.Log("last "+LastGameObject.name);
        }

    }

```
> 0 votes

---
Tags: c#, collision-detection, unity
---


# Question
Title: Want to create live-voice chat between players either in unity or unreal engine
I would like to create a real-time voice chat in either in unreal or unity between the players.I would like to associate and apply this voice-chat depend on username. I am saying "or" for the application because I want it to create in easiest(less programming) way. Do you know what class or script I should use? I have a limited budget so I am looking for a in-house or cheap way solution of building it.What would be the easiest way of starting this project?

# Answer
> 1 votes
### For Unity:

This seems great, but cost 30$.
You can also do it by yourself (microphone, network). Take a loot at how RPCs works (you will probably have to send your voice data like that)

### For UE4:

It's fully supported through Steam, but you could use something like Opus Codec to handle your voice capture and send it over the network.

---
Tags: voice
---


title: Text Based Tutorials for Unity3d

text:
# Question
Title: Text Based Tutorials for Unity3d
I hope this is the right place to ask this. I'm very new to Unity but not to programming. I also have some basic game programming experience.

I'm searching for text based versions of the videos from `unity3d.com/learn/tutorials`. These tutorials are very good, but I end up forwarding videos a lot to get key screenshots and code snippets.

Is there any text / pdf / html / .doc / .rtf (i'm very open) version or similar resource to learn unity? Again, those tutorials are amazing and I'd hope to find something of similar quality, but I know that if I have to skim through tens of hours of video I'll end up frustrated. I get that the long hard way is probably the most robust one for deeper understanding, but I was hoping to hack a quick project.

EDIT :

If this can make it a relevant question, then I am currently looking at the "Roll a Ball Tutorial". Really, any other text tutorial would be very welcome

# Answer
You can look into noobtuts.com. I've learn a lot of basics for Unity3D from here.

More text tutorial can be found on catlikecoding.com. And another on raywenderlich.com (it's for Unity 4.3 but it's not very different now)
> 2 votes

# Answer
I highly recommend Catlike Coding tutorials. They are a great resource for learning Unity and game related C# coding.
> 0 votes

# Answer
There are plenty of free options out there.

* Tutsplus \- This might be your best bet. It has Numerous tutorials along the lines of "How to make a game like X" that start right at creating the project.

Some others:
> 0 votes

---
Tags: unity
---


# Question
Title: Polygon edges visible when using per-fragment lighting (OpenGL)
I have created a mesh in Blender (just a sphere with a texture over it; it's supposed to look like mars) and I've exported it as OBJ. I've tried it both with exporting with normals in Blender's export settings and also with the aiProcess\_GenNormals flag. But for some reason I'm still getting this lighting issue.

There's a lot of C++ code but I'm not sure if any of it is relevant to this issue, so I'll just include the shaders.

The vertex shader:

```
#version 330 core

layout(location = 0) in vec3 vertexpos_modelspace;
layout(location = 1) in vec2 texcoord_vertex;
layout(location = 2) in vec3 normal_vertex;

uniform mat4 world;
uniform mat4 view;
uniform mat4 projection;

out vec2 texcoord_fragment;
out vec3 normal_fragment;

void main()
{
    texcoord_fragment = texcoord_vertex;

    vec4 transformed_normal;
    transformed_normal = vec4(normal_vertex, 1);
    transformed_normal = world * transformed_normal;
    normal_fragment = transformed_normal.xyz;

    gl_Position.xyzw = projection * view * world * vec4(vertexpos_modelspace, 1);
}

```

The fragment shader:

```
#version 330 core

uniform sampler2D texsampler;

uniform vec3 light_direction;

in vec2 texcoord_fragment;
in vec3 normal_fragment;

out vec4 color;

void main()
{
    float lighting = 0;
    lighting = dot(normalize(normal_fragment), normalize(light_direction));
    lighting = clamp(lighting, 0, 1);

    vec4 sample = texture(texsampler, texcoord_fragment).rgba;

    color = sample * lighting;
}

```

And the result looks like this:

I can't figure out why this is happening. It doesn't appear this way in Blender, just in my application.

# Answer
Fixed it. Turns out Blender was in flat shading mode instead of smooth shading, so the normals were per-triangle instead of per-vertex when exported (didn't realize that setting effected the exported mesh). And if you want Assimp to generate the normals for you in the same way it requires the aiProcess\_GenSmoothNormals flag (instead of the aiProcess\_GenNormals flag).
> 1 votes

---
Tags: opengl, c++, lighting, 3d-meshes
---


# Question
Title: Why loading ~250mb of compressed texture data spills Out of memory error on Windows
I am making SDL2/OpenGL 2D game for Windows with a lot of pre-rendered sprites. When testing on my laptop I got `SDL_Surface creation failed: out of memory` error during loading assets.

Windows' Application Manager on other machine shows that my game in stress uses less then 170 mb of ram memory and MSI Afterburner shows that vram usage for entire system is below 800 mb.

My laptop has 8 gb of RAM and 2048 mb of vram (GeForce 840 M).

I am obviously doing something terribly wrong, but I don't know wheres my ram usage counting technique is wrong, or maybe for some reasons I have less memory then available on system, or something completely else is happening. But I don't know where to search for.

I will gladly post some code if I need to, but I don't know which parts will be useful in diagnosing the problem.

One more thing, I am using `GL_COMPRESSED_RGBA_ARB` for all textures

**Edited**

It's not exactly the same situation as what's described here. I've already measured vram usage, and numbers are way below available count, yet still I get `out of memory` error. So, the question is: "How measure **properly** vram usage", not "How measure vram usage", as in other question. I am not a native English speaker, so maybe there is some cloud in my title - I will gladly accept correction for title

**Edited**

I reckon the image load procedure might be useful here, since it is heavily related to issue.

```
Game::Texture * Game::Asset::GetTex(const UString & path)
{
    Texture * ret = _assetsTex[path];
    if (ret)
        return ret;

    const UString & absolutePath = GetAbsolutePath(path);
    SDL_Surface * surface = IMG_Load(absolutePath.GetCStr());

    if (!surface)
        ERR(_U("Failed to load surface: #1#"), UString::FromA(IMG_GetError())); // Here's my problem!

    int bpp = surface->format->BytesPerPixel;
    UInt8 * pixels = (UInt8 *)surface->pixels;

    if (bpp != 3 && bpp != 4)
    {
        WARN(_U("Texture '#1#' is not 24 bpp or 32 bpp! Aborting load..."), path);
        SDL_FreeSurface(surface);
        return nullptr;
    }

    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);

    if (bpp == 3)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_ARB, surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
    else if (bpp == 4)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_ARB, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    ret = new Texture(tex, surface->w, surface->h);

    SDL_FreeSurface(surface);

    _assetsTex[path] = ret;

    return ret;
}

```

**Edited**

I moved from SDL\_Image to stb\_image for image load, but I still got `out of memory` error message

**Edited**

I've installed VS Studio 2015 on my laptop and found out:

* Task Manager shows application eats up 650 mb in the moment of Out of memory casted
* `GetProcessMemoryInfo` returns `PeakWorkingSetSize` ~720 mb and `WorkingSetSize` 650 mb as well
* But Visual 2015 UI (Debug Diagnostic, memory usage) shows that application actually consumed 1.7 gb. Even if this is true and both former are not, there is still plenty of room for allocations (application is 32 bit, there are 8 gb of on-board memory, not counting page file)
* I tried to convert png -\> tga and load them up, to check if png uncompressing is eating memory, but the result was exactly the same, the same Out of memory error
* Out of memory is spit in png load function which has nothing to do with OpenGL and GPU at all. I am retagging and retitleing the post

# Answer
Firstly, why aren't you using GL\_COMPRESSED\_RGB\_ARB for your textures which don't have an alpha channel? I'm not that familiar with OpenGL, but I think that should reduce their size in memory significantly.

By default on Windows 32-bit applications only get 2GB of address space. You can improve that so that when run on a 64-bit operating system they get 4GB of address space by using the /LARGEADDRESSAWARE linker option.

That won't solve your problem when your game is running on a 32-bit version of Windows though, and there's no magic setting to fix that. 2GB is the limit.

To get access to more than 4GB of address space you'll need to compile your program as as 64-bit.

You can use the VMMap tool to get some idea of where your address space is being used. Try using it before and after a texture is created for example, to make sure it's actually getting compressed. There's also a "Memory - Commit Size" column you can enable in Task Manager to show you the total address space usage.

If you're only loading 250MB of texture data, then that really shouldn't be consuming so much address space. Do you have any memory leaks in your code? Do you have more than one copy of any of the textures loaded?
> 2 votes

---
Tags: textures, image, memory
---


# Question
Title: How to make nifty gui textfield to use a larger font
Hi I have a text field on my screen but its tiny:

```
<panel height="13%" width="100%" childLayout="vertical">
    <text id="label1" height="50%" font="Interface/Fonts/MinionPro.fnt" color="#f00f"
          text="Hello World!" align="center" valign="center" />
</panel>
<panel height="10%" width="100%" backgroundColor="#55a5" childLayout="center">
    <control name="textfield" text="Some text"/>
</panel>

```

the problem is I can not figure out how to change the font size on it. Please help me out here.

# Answer
In jME/Nifty, each letter is basically a Quad with a Texture on it. Scaling font-textures usually looks horrible and I guess that's why Nifty doesn't provide an option for scaling (you can scale `BitmapText` in jME though).

Easiest way is to generate a new, bigger font. If you're using the jME SDK there's a built-in generator. Right click on a folder in the Projects Window and choose `New -> Other -> GUI -> Font`.

I recommend a padding of 2 for X and Y. Otherwise you might see random dots in the rendered text (these are parts of other letters that are overlapping the letter box in the texture).

Sometimes there's a huge gap between the letters. You can control that by using negative values for "letter spacing".

---

Nifty's Textfield-Control is a composition of panels and text elements. To use a bigger font you have to redefine its style. Grab the original `nifty-textfield.xml` from your `nifty-style-black.jar` or from here: https://github.com/nifty-gui/nifty-gui/blob/1.4/nifty-controls-style-black/src/main/resources/textfield/nifty-textfield.xml

Save it somewhere in your Assets/Interface folder and include it in your other XML like this:
(Make sure to include it *after* `nifty-default-styles.xml`)

```
<useStyles filename="Interface/textfield.xml" />

```

Now you have to adjust the style. Remove the `base="base-font"` attribute from the style with ID `nifty-textfield#text` and add `font` to the `attributes`-Tag. It should look like this:

```
<style id="nifty-textfield#text">
    <attributes ... font="Interface/Fonts/YourFont-24.fnt" />
</style>

```

You probably also want to change the size of the Textfield to match the new font. Edit the other styles in this file as you need.

The Nifty Manual explains controls and styles in more detail:
http://sourceforge.net/projects/nifty-gui/files/nifty-gui/1.3.2/nifty-gui-the-manual-1.3.2.pdf/download
> 1 votes

# Answer
There is no way to resize fonts within a label, as pointed out in this JMonkeyEngine forum post.

> You can't currenty set the text size of a Label in Nifty. This is mainly due to the use of bitmap based fonts which usually don't resize very well. You need to use different fonts for best visual appearance if you need different text sizes.
> 0 votes

---
Tags: gui, jmonkeyengine, nifty-gui
---


# Question
Title: Error When Loading a .tmx TILED map through the TiledMap class
So I made a map using the TILED application and I have it as a .tmx for reasons, but whenever I use the TildMap class in the Slick2D library to render the map on the screen, it gives me an error. Here are the files:

Class file:

```
public TiledMap testMap = null;

//TILE-READER
public static TileReader tileReader;

public Game (int stateID) {}

@Override
public int getID() {
    return Main.game; //GAMESTATE = 1
}

@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    worldMap = new Image ("res/in_game_map.png");
    player = new Player(playerX, playerY, mapX, mapY);
    tileReader = new TileReader();
    player.init(gameContainer, stateBasedGame);
    tileReader.init(gameContainer, stateBasedGame);

    testMap = new TiledMap("res/worldMap.tmx");
}

@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
    player.update(gameContainer, stateBasedGame, delta);
    tileReader.update(gameContainer, stateBasedGame, delta);
}

@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
    graphics.scale(1.05f, 1.05f);

    graphics.translate(player.camera.getCamX(), player.camera.getCamY());
    gameMap.draw(mapX - mapLength, mapY - mapWidth);
    testMap.render(0, 0);
    tileReader.render(gameContainer, stateBasedGame, graphics);
    player.render(gameContainer, stateBasedGame, graphics);
    graphics.translate(-player.camera.getCamX(), -player.camera.getCamY());

    if (inputHandler.keyMAP) {
        worldMap.draw(0, 0);
    }

    graphics.drawString("Player X: " + player.getxPos(), 400, 400);
    graphics.drawString("Player Y: " + player.getyPos(), 400, 415);
}

```

And here is the error message that it provided me:

> Caused by: org.newdawn.slick.SlickException: Unsupport tiled map type: base64,zlib (only gzip base64 supported)

Is there an issue with the way I formatted the .tmx file or is it that I am using the latest version of Tiled and that slick2D is no longer compatible with the newer version?

# Answer
I managed to figure out the answer whilst looking through the Tiled application. Basically, you go to Map --\> Map Properties and under "Tiled Layer Format" you can change it to a gzip base64 compression method. Also, you can change the compression method when you create a new Tiled map.
> 0 votes

---
Tags: java, software-engineering, slick, tiled
---


# Question
Title: SDL Combining text and Geometry Rendering to one texture
Basically I'm trying to end up with a Texture class that can take in text and have it be drawn over simple geometry (such as a letter 'A' over a filled rectangle). However I'm running into issues when thinking about how to combine these two concepts.

First, following lazy foo's tutorials, Geometry rendering is simple and is done with an

```
SDL_RECT and SDL_RenderFillRect(SDL_Renderer*, &SDL_Rect);

```

However, when rendering text it uses Surfaces and Textures in order to 'draw' the text. Specifically these lines:

```
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
mTexture = SDL_CreateTextureFromSurface( SDL_Renderer*, textSurface );

```

My confusing comes from trying to figure out several things:

a) Is it possible to maybe first Render the Geometry to a texture, and then render the text over that same texture?

b) I believe a call to SDL\_SetRenderTarget is going to be necessary, but I'm not sure where and when during my combination stage this would need to be done.

c) Right before posting this question, I saw further down on the tutorials this link which describes rendering geometry to a texture, however I'm still not sure how to combine Text with this.

Any help is appreciated, Thanks

# Answer
To anyone else that ever needs help, I found a simple solution after thinking about it real quick, just set the target and then Draw any geometry you need before rendering the texture.

```
void LTexture::render( int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip )
{
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, mWidth, mHeight };

//Set clip rendering dimensions
if( clip != NULL )
{
    renderQuad.w = clip->w;
    renderQuad.h = clip->h;
}
//Draw geometry
SDL_Rect fillRect = { 0, 0, mWidth, mHeight };
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0x00, 0x00, 0xFF );
SDL_RenderFillRect( gRenderer, &fillRect );

//Render to screen (when mTexture = a font loaded texture/surface)
SDL_RenderCopyEx( gRenderer, mTexture, clip, &renderQuad, angle, center, flip );
}

```
> 1 votes

---
Tags: c++, sdl, sdl2
---


# Question
Title: Function, that is searching for nearest enemy Transform only works sporadically. What am I doing wrong?
so I am trying to implement a "Zelda"- or "Dark Souls"-like z-targeting system. You'll see in the code, that the function compiles a list of every enemy in the current scene. I'm still in the prototyping phase so the only credential for the targeting is the distance between enemy and player. The script is attached to my player and there are three enemies in the scene.

Now for the problem: The function is not reliable. Sometimes it updates the 'target', sometimes it doesn't. The debug.log fires as expected, only the most important thing appears to zoom in and out. This function is supposed to toggle the lockon as well, which doesn't reliably work either.

Tips on how to make the code lighter are appreciated as well!

Edit: Added the FixedUpdate(), which is a hot mess right now:

```
void FixedUpdate ()
{

    // Store the input axes.
    h = Input.GetAxisRaw ("Horizontal");
    v = Input.GetAxisRaw ("Vertical");

    stateInfo = anim.GetCurrentAnimatorStateInfo(0); // 0 is for the base layer.
    if (!stateInfo.IsName("Swing")) {
        if( Input.GetButtonDown("Fire1")){
            anim.SetTrigger("isAttacking");
        }
    }

    if (controller.isGrounded) {
        CalcMovement (h, v);
    } else {
        movement.y -= gravity * Time.deltaTime;
    }
    if (Input.GetButtonDown ("Jump")) {
        movement.y = jumpSpeed;
    }
    if (Input.GetButtonDown ("Fire3")) {
        LockOnEnemy ();
    }
    ProcessEvasion ();
    controller.Move(movement * Time.deltaTime);

    Debug.DrawRay(transform.position, -Vector3.up, Color.blue, transform.position.y + 0.1f);

}

void LockOnEnemy()
{
    //we default to check == false
    bool check = false;

    //we will ONLY scan for new targets if current target is null
    if (target == null)
    {
        GameObject[] enemyList = GameObject.FindGameObjectsWithTag("Enemy");
        if (enemyList.Length > 0)
        {
            int enemyID = -1; //default this to 'invalid' value (just good practice!)
            float closestEnemyDistanceSqr = float.MaxValue; //max lockon distance here (use float.MaxValue unless you have a good reason not to!)

            //find closest enemy (only change is I'm looking at squared magnitudes, as they do the job and are more efficient)
            for (int i = 0; i < enemyList.Length; i++)
            {
                float enemyDeltaSqr = (transform.position - enemyList[i].transform.position).sqrMagnitude;
                if (enemyDeltaSqr < closestEnemyDistanceSqr)
                {
                    closestEnemyDistanceSqr = enemyDeltaSqr;
                    enemyID = i;
                }
            }

            //store the target. we can safely assume enemyID is no longer -1, as we know there is at least 1 enemy in enemyList
            target = enemyList[enemyID].transform;
            Debug.Log("Found: Enemy( " + enemyID + ") at " + Mathf.Sqrt(closestEnemyDistanceSqr));
        }

        //now we set check to true regardless of whether we found an enemy - is this what we want
        check = true;
    }

    //if check is false (i.e. we didn't go through the above if statement), we clear 'target'.
    if (check == false)
    {
        this.target = null;
    }
}

```

Please note: This version of the code has been commented and cleaned up by the user wibble82, over at unity.answers. Unfortunately nobody could really help me there.

# Answer
put

```
if (Input.GetButtonDown ("Fire3")) {
        LockOnEnemy ();
    }

```

into `Update`. In `FixedUpdate` may be called more than once per frame (or input cicle). Reference: GetButtonDown not always firing

> FixedUpdate gets called based on even intervals, the times it ignores your input is the times that it's not updated/called between those intervals.
> 2 votes

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


# Question
Title: Obstacle spawn constraints in Jetpack Joyride
Jetpack Joyride: https://www.youtube.com/watch?v=3KENMuzsras

## tl;dr

What's the best way to add constraints to obstacle spawning (algorithms) or how to design obstacle spawning to allow constraints?

## More details and my understanding

I am trying to understand how to add constraints to a spawning algorithm and I'm using Jetpack Joyride as reference (although I don't mind a general answer, especially if you're not very familiar with the game). I am particularly interested in the electrical obstacles \[see image\], so I will only consider them from now on.

There is probably a list of such obstacles from which one is fetched and placed on the screen. But where and when you place them is extremely important. First, you want to make sure your obstacles are between some minimum height -the floor- and some maximum height -the ceiling-. Then you may also want some minimum distance between any two consecutive obstacles. Also you don't want to spawn them too often, otherwise the game becomes repetitive. Then clearly you want to avoid sequences of obstacles that are impossible to pass. Then in some moments obstacles tend to spawn closer to the ground than usual. And so on.

I have no idea how to integrate, design-wise, all these constraints into obstacle spawning. I could probably have a lot of if statements and flags that are checked for each new item fetched from the available obstacles pool, but if I have a great number of constraints, the code may become very messy. I don't how this is approached in general.

# Answer
One interesting solution might be to first draw a line which you want the player to follow then draw obstacles between random point in space above and bellow the line. You can then tweak difficulty by how many obstacles are spawned the with of this line and how complex the curvature of the line is.

Easiest to get this line right is to first generate a set of target points. You then write a simple ai that tries to go up if it's bellow the point and go down if it's above the next point. You then record the height for each position per unit of width of the map. Congrats you know have a useable line which the player could follow, increase the number of points for a more difficult map.

Now you have this line you generate sets of random point with a height between the height of your screen and you line (add a value to the line to make sure the player fits). And draw an obstacle between the 2 points. Repeat as for bellow the line and for the number of obstacles you want to place (remember more is more difficult).

Another thing to note is that you can add a constraint such as "within a certain radius" or " not crossing another obstacle" by simple testing if the constraint holds true and if it doesn't recreate both point. And you are of course free to place single point obstacles as well.

Of course an alternative is to just place obstacles between sets of random point and let the player deal with it.
> 3 votes

# Answer
I think you should try the Jetpack Joyride way of doing it using interval and probability spawn. It is a simple implementation and allows you to tweak and test it out quickly. And if it works you may have a much cheaper solution rather than having to hand craft each area in your game.

In Jetpack Joyride, everything is placed by an interval system using a minimal and maximal interval length. Every type of entity have a probability of occupying the next slot.

Implementing this plus the possibility to tweak your min/max interval during testing should be a good start trying to achieve a good balance.

If you want even more control over larger areas, you could implement different spawn groups where you can change the probability of the entities and also change the behaviour as the difficulty increases.

Take a look at this GDC talk from 2012 with Luke Muscat

> GDC 2012 — Depth in Simplicity: The making of Jetpack Joyride
> 1 votes

---
Tags: game-design, design-patterns, level-design, spawning
---


title: My game has messed up layouts!

text:
# Question
Title: My game has messed up layouts!
Earlier, I asked this question: Landscape mode for game?

Where I had a directory for each and every layout, but the layout in the `layout-land` directory wasn't showing up when positioning my layout in landscape orientation.

So, someone suggested to me that it maybe that the

* `Layout-normal` directories are overriding my regular `layout-land` directories. Is this true?
* If so, will any other of my layout folders get overriding?\** What is the purpose of `layout-normal` in the first place then anyway?

# Answer
Look at this flow chart from Google that shows how the resource folder is picked.

Android qualifier flow chart

Screen-size comes before orientation. So when you have a folder with screen-size that matches your device, all of the folders without it will be discarded. Since layout-land doesn't have screen-size it will be ignored.

For a list of the qualifiers look at this link. Please look at table 2. Table over Andriod qualifiers
> 1 votes

---
Tags: java, 2d, android, game-design, software-engineering
---


# Question
Title: Game crashes when trying to access function inside of a class, inside of a vector
So, I have a object, inside of a vector and I'm trying to call a function in that object :

```
std::vector<Box>entities;

entities.insert(entities.begin() +1, Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y), b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));

window.draw(*entities[0].getSfShape());

```

But, my game crashes instantly with this error :

> Debug assertion failed!
>
> Program C:\WINDOWS\SYSTEM32\MSVCP140D.dll
>
> File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\vector
>
> Line: 159
>
> Experssion: vector iterator + offset out of range
>
> For more information on how your program can cause an assertion failure, see the visual c++ documentaion on asserts.

Not sure what I'm doing wrong, at all. :(

# Answer
```
std::vector<Box>entities;

entities.insert(entities.begin() +1

```

You try to insert to `begin()+1`... but `begin()==end()` in an empty vector so you're essentially doing `end()+1` which is not ever a valid location.

That also explains the error message as the `begin()` is the only use of an iterator in your code, and the illegal offset being the `+1` that tries to increment the iterator past the end of the vector.

You should probably be using emplace\_back or push\_back.
> 2 votes

---
Tags: c++, box2d, sfml
---


title: libGDX best way to do Game States

text:
# Question
Title: libGDX best way to do Game States
I'm making a JRPG in libGDX, and I'm working with Screens. I have a main Screen called GameScreen, a screen for battles called BattleScreen and I want to make a screen for managing party members and items, as well as for shops. My question is, how can I draw one of those 3 screens without having to reload the whole game when going back to GameScreen.

GameScreen loads everything when Show() is called, so I'll have to save all information everytime I call another screen, so I can continue when I go back to GameScreen. This of course isn't good, and I'm looking for another way to draw a Screen over another one so that all vars wont be lost, or another solution.

# Answer
Carry your relevant variables/screens in other's screen using constructors. For example.

```
//main class extending Game class of libgdx
public class mygame extends Game {

public String var1="i will use it in screen1";
public String var2="i will use it in screen2";

Screen1 scn1;  //instantiating screen 1
Screen2 scn2;  // instantiating screen 2

public void create() {
scn1=new Screen1(this);  //scn1 object will be associated with same instance of this class
scn2=new Screen2(this); //scn2 object will be associated with same instance of this class

   setScreen(scn1);
}

 public void render() {
        super.render(); //important!
    }

public void dispose() {
//dispose
}
}

//Screen1 class
public class Screen1 implements Screen{
mygame game;

public Screen1(mygame mg)
{
game=mg;
}

@Override
public void render(float delta) {
System.out.println("using game class variable var1:"+game.var1);
game.setScreen(game.scn2);  //calling screen 1
}
@Override
    public void resize(int width, int height) {}
@Override
    public void show() {}
    @Override
    public void hide() {}
    @Override
    public void pause() {}
    @Override
    public void resume() {}
    @Override
    public void dispose() {}
}

//Screen2 class
public class Screen2 implements Screen{
mygame game;

public Screen2(mygame mg)
{
game=mg;
}

@Override
public void render(float delta) {
System.out.println("using game class variable var2:"+game.var2);
game.setScreen(game.scn1); //calling back screen 1
}
@Override
    public void resize(int width, int height) {}
@Override
    public void show() {}
    @Override
    public void hide() {}
    @Override
    public void pause() {}
    @Override
    public void resume() {}
    @Override
    public void dispose() {}
}

```
> 1 votes

# Answer
## Solution

An easy and efficient way to manage screens is by using an `enum` which stores multiple constants. This is useful as you can refer to each screen with a meaningful name such as `MENU` instead of assigning a numerical index. This is also advantageous to other solutions as it is much simpler than other built-in systems such as the Scene2D system and can also be used for 3D games and multi-purpose applications.

**Example:**

```
public enum Screen {
    MENU,
    IN-GAME,
    BATTLE,
    INVENTORY
}

private Screen screen = Screen.MENU;

public void render() throws IllegalStateException {
    switch(screen) {
    case MENU:
        Menu.render();
        break;

    //Other cases here

    default:
        throw new IllegalStateException();
}

```
> 1 votes

# Answer
How do you manage your Screens? If you use com.badlogic.gdx.Game class, it just calls screen.hide() on the previous screen and screen.show() on the next screen.

```
/** Sets the current screen. {@link Screen#hide()} is called on any old screen, and {@link Screen#show()} is called on the new
 * screen, if any.
 * @param screen may be {@code null} */
public void setScreen (Screen screen) {
    if (this.screen != null) this.screen.hide();
    this.screen = screen;
    if (this.screen != null) {
        this.screen.show();
        this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    }
}

```

So you should move your initialization to any other method than show() e.g. init()

```
public class MyGame extends Game
{
    GameScreen gameScreen;
    BattleScreen battleScreen;

    public void create ()
    {
        gameScreen = new GameScreen();
        gameScreen.init();
        battleScreen = new BattleScreen();

        setScreen(gameScreen);
    }

    // when you need to show the BattleScreen
    setScreen(battleScreen);

    // when you need to show the GameScreen again with all loaded resources and states
    setScreen(gameScreen);
}

```
> 0 votes

---
Tags: java, libgdx, game-state
---


# Question
Title: Verifying game completion knowing players id
I work at a school and I am producing a simple game for language learners via RPG Maker.

All students have a unique student # that their processor has access to.

At the moment, I am imagining an end-game NPC providing the successful student with a special number that they will then screen capture and submit to their teacher. The number is based on a secret algorithm that uses their student #, so each "end-game number" is unique. The teacher can then verify that each submitted number is the correct end-game number for any given student.

Is there a better way for me to verify whether or not each student has successfully played through the game?

# Answer
Depending on the resources available, you could also set up a server and have the students play online. Even if they don't finish the game, the teacher would be able to see how far the students have gotten. You could even draw a graph of the relation between time passed and game completion percentage. This way, the teacher can see which students started too late on their assignments, and which students are on schedule.
> 3 votes

# Answer
While @Peethor's answer is correct from a Game Development point of view, in a school setting you might have data protection issues. I can imagine that students don't like the feeling that their teacher is watching over every step of them in the game. They might enjoy the game more if only the end results (or certain intermediate checkpoints) are verified by the teacher.

With this in mind, I think your solution is good. Instead of making a screenshot, you could display a link (with a code) at the end of the game which the students have to click.

The server solution works also, if all students have internet access, but I would make a clear policy what you monitor and what data is "private".

However, make sure you use a good algorithm for generating the code, because students who want to cheat can invest more effort into reverse engineering your algorithm than it would have taken them to complete the game.
> 1 votes

---
Tags: game-design
---


# Question
Title: My character just floats up into the sky
So this is the code I'm using for jumping. The character just floats in to the sky. I'm making an infinite runner.

```
using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour {

public float moveSpeed;
public float jumpForce;

private Rigidbody2D myRigidbody;

// Use this for initialization
void Start () {
    myRigidbody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update () {
    myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);

    if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0));
    {
        myRigidbody.velocity=new Vector2(myRigidbody.velocity.x, jumpForce);
    }
}
}

```

Edit:

Code to @Hamzan Hasan:

```
using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour {

    public float moveSpeed;
    public float jumpForce;

    private Rigidbody2D myRigidbody;

    // Use this for initialization
    void Start () {
        myRigidbody.velocity = new Vector2(moveSpeed, 0);
    }

    // Update is called once per frame
    //void Update () {
    //  myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);
    //
    //  if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0));
    //  {
    //      myRigidbody.velocity=new Vector2(myRigidbody.velocity.x, jumpForce);
    //  }
    void Update () {
        if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0));
        {
            Jump();
        }
    }

    void Jump () {
        myRigidbody.AddForce(new Vector2(0, jumpForce));
        }

    }

```

Edit 3: The solution is in the chat below.

# Answer
Try

```
void Update () {
    if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0));
    {
        Jump();
    }
}

void Jump () {
    myRigidbody.AddForce(new Vector2(0, jumpForce));
}

```

As far as your horizontal movement is concern, you can set initial velocity with frictionless collider as,

```
void Start(){
    myRigidbody.velocity = new Vector2(moveSpeed, 0);
}

```
> 3 votes

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


# Question
Title: libgdx - collision detection with tiled map java
currently, I am working on a 2d rpg game which is similar to final fantasy 1-4. I can load up a tiled map and the sprite can walk freely on the map. However, I will like to create a wall for it to stop walking through it.

I created three tiled layer `Background, Collision, Overhead` and one `Collision` object layer with rectangles only.

"How do I handle collisions with the object layer in the tiled map?"

"Do I have to create every single rectangle that is in the object layer with `Rectangle rectangle = new Rectangle() and rectangle.set(x, y, width, height)`in the code?"

Thank you very much in advance. Any help is greatly appreciated!

# Answer
> 2 votes
What I normally have for simple tile map collision, I have a separate tile set with only 2 types of tiles that I use to create a new layer called collision. When I load in a tiled map, I use this layer to create a boolean array version of the map where passability is determined by a tile's id.

# Answer
> 2 votes
If the map is loaded in through pixels, then the tile id's will be in a 2d array, so add something like this to your player class (if you have one, you might do tile-based rpgs completely differently):

```
public void move(int xs, int ys) {
    xo += xs;
    yo += ys;
    if(Level.tiles[xo / 32][yo / 32] == 6) {
        xo -= xs;
        yo -= ys;
    }

}

```

`xs` and `ys` is the speed that the character is travelling at.

`xo` and `yo` is the player position

`Level.tiles[xo][yo]` is the 2d array that stores the id of the tile

the `move` method is the method that sets the player position after the `xs`/`ys` values have been set

# Answer
> 1 votes
Yup there are multiple ways you can go around completing this and it really depends on how you are implementing a movement system and if there's a physics engine in the game. If there is no physics engine in your game and you move only by touching squares, I would suggest you implement a future check system. Where you have a large 2d array that hold the relevant collision for each square. Every time you move the sprite you check whether the move will push him into a new square. If so pull it up on the array and determine what to do! :)

# Answer
> 0 votes
It's not that difficult, just loop through all the map objects in the layer and add if they're a rectangle map object then add them to an array of all the objects in the room. You can then add a move request system in which you create a method that will check if the space you are going to move to contains a collision object and if it does then deny the request else let them move.

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


# Question
Title: How should I store a procedurally generated grid level of an infinite size?
I have a 2d grid level. It infinitely grows. If it was not of infinite size, a 2D array would be perfect, as I need to constantly have each grid talk to its neighbors.

For example, with a 2D array, I can talk to its top neighbor by saying `var topNeighbor = myGrid[x,y+1];`

But if I were to use a List, the indices would be changing.

If I just store a list of all grid separately and then iterate through them for each grid, thats an n^2 algorithm running each frame. Each room would have to iterate through every other room just to ask if they were neighbors.

What is the best way to store a 2D grid of an unknown size, assuming each grid needs to talk to its 4 neighboring grids every frame?

# Answer
> 2 votes
Break the grid into chunks of 2d map. If you have some bounds theb store these chunks in a higher level grid and read/write the chunks to disk as they come in and out of the active area. If you truly have an infinte area store the chunks in a hastable instead but remember to remove chunks that are out of the active area or else the hashtable will be too full. You could also try a two-dimensional grid that rolls the chunks overwhen new loads happen Think a 3x3 grid with the player in the middle. When the player moves too far move the chunks over and load/generate the next set of chunks.

---
Tags: c#, procedural-generation, optimization, grid, storage
---


title: How do 2D shaders work?

text:
# Question
Title: How do 2D shaders work?
Yesterday I was wondering if an Arduino Uno could run some 2d shaders in a 3110 nokia screen (monochrome).

But before all, I want to know understand how they work.

Note: I want theory; ideas. Not how it works in each language.

# Answer
Shaders are a programmable step in the graphics pipeline of whatever rendering technology you're working with. There are several types including Vertex shaders, Tesselation shaders, Geometry shaders, and Fragment shaders.

The term "shader" is misleading because they can serve a much broader purpose than working with lights and shadows ("shade" kind of implies that). This could include manipulating 3d geometry and projecting vertices to a 2d viewport.

The fragment shader is what you might refer to as a "2D shader". A fragment is basically an X,Y position on the window, a depth value (because it's usually coming from a 3d vertex), plus all the interpolated data from previous stages. You can read more about them here.
> 4 votes

---
Tags: c++, shaders
---


# Question
Title: Portal 2 Authoring Tools: func_instance_io_proxy not working?
I have a func\_instance (which I made myself) of a door in my map. It is supposed to open when a cube is fizzled. I also put a checkmark indicator to make sure I had the cube's logic correct. When the cube is fizzled, the checkmark indicator lights up, but the door does not open. To make sure the door was working, I put a logic\_auto into the prefab which opened the door when the map loaded. This worked correctly. I therefore think that there is something wrong with the func\_instance\_io\_proxy, but I do not know what. Here are some screenshots:

The cube targets the openDoor relay's trigger input via the func\_instance\_io\_proxy. It also targets the checkmark indicator, which properly lights up when the cube is fizzled.

My door func\_instance. The relay on the left opens the door, and the one on the right closes it.

The logic\_auto targets the closeDoor relay on startup, which *does* execute properly, as the door is closed when I go to test the map.

Finally, the func\_instance\_io\_proxy targets the openDoor's trigger input. However, when I try and access it via the cube, it does not work, and the door does not open.

\*By the way, I am running this on linux via wine, which is why it looks like windows 98

\**Off-topic question, is this the right place to post this, since it is technically map making, not game development?

# Answer
Turns out the problem was that I had not given my func\_instance\_io\_proxy a name. I will leave this question posted in case anyone else has the same problem.
> 1 votes

---
Tags: logic, source-engine
---


title: Depth testing before fragment shader

text:
# Question
Title: Depth testing before fragment shader
Accoring to this, depth testing is usually performed after the fragment shader stage. Why is that? I thought that a fragment is sent with its depth value to the FS, then the depth test happens *before* the FS executes, so the gpu can avoid a spare FS execution if the pixel is covered by a closer one.

Why is it not like that?

# Answer
> 1 votes
As far as why a depth dest would happen before or after the fragment shader, there is a section in that wiki link on Early Depth Test as well as an entire article about it here.

When a depth test is performed in the fragment shader itself, it's possible that the Fragment's output depth value is tested against the depth of the sample being written to. There is a line in that article:

> If the test fails, the fragment is discarded. If the test passes, the depth buffer will be updated with the fragment's output depth, unless a subsequent per-sample operation prevents it.

This "per-sample" operation means that a fragment shader can be instructed to only perform depth tests on a per-pixel basis and you would therefore want/need it in the fragment shader.

---
Tags: depth-buffer
---