# Question
Title: Creating a separate renderer for entities in a 2D game
I'm making a 2D shooter game. As of now, every entity "draws itself", meaning every renderable entity has a draw function. I know it is better if rendering is handled separately, but how can I achieve this? What should I put into the **Renderer** class?

# Answer
> 1 votes
You only truly need a separate class if you're multithreading, so you can have separate constructors, one ran in the render thread. Even then its up to you whether or not you want to do that. The big reason is just organization.

More important than anything is to make sure your textures and render programs are static.
You also want to **render all of a single type of renderer at the same time to avoid render state changes**, possibly even rendering everything of the same type in the same draw pass.

# Answer
> 0 votes
It is not necessarily a better way to have a separate class to draw your entities. It is just one way how to implement how your entities get drawn.

But to answer your question. One way could be that each of your entities give access to the the data which are necessary to draw a entity. As soon as your entity provides such function then your rendering class just need to hold a reference to every available entity( e.g. In a vector) which should be drawn .

And then in every update cycle the rendering class will go through the vector access each entity and draw the entity in the same way the entities draw themselves now.

# Answer
> 0 votes
What I have found is that is good to make a handler class that has a list of GameObjects and draws, ticks(update) and can add new objects.

ex:

```
import java.awt.Graphics;
import java.util.LinkedList;

public class Handler {

  public LinkedList<GameObject> objects = new LinkedList<GameObject>();
  private GameObject temp;

  public void tick(){
    for(int c = 0; c < objects.size(); c++){
      temp = objects.get( c );
      temp.tick( objects );
    }
  }
  public void render(Graphics g){
    for(int c = 0; c < objects.size(); c++){
      temp = objects.get( c );
      temp.render( g );
    }
  }
  public void addObject(GameObject object){
    objects.add( object );
  }
}

```

---
Tags: java, 2d, rendering
---


# Question
Title: How to access multiple 2DTexture which is assigned in Unity3D inspector panel created by an array in C#?
I am making a puzzle game, i made 5X5 cube, lets take example of orange. very left column is orange, upper with orange dot is static and lower with orange dot is also static. inbetween there are 3 orange tile, if i click on one orange tile color gets change on every click, if i click 5 times, five different color will appear as i told earlier. i want to connect the orange dot with orange tile as shown in figure(mark as tick),

I assined all 5 color texture in array having 1 to 5 indexPointer using inspector panel... All tile has same TagName "CubeTag" but object Name is different for all tile.

my question is how to tell the engine that all 3 orange tile is connected. and print "Orange is Connected"

For Example take orange texture:

I want to make a path of orange ..if I click on 3 orange tile (tick mark)then If indexpointer of OrangePath1 == 3 and indexpointer of OrangePath2 == 3 and indexpointer of OrangePath3 == 3 then print ("Orange connected")

Here is my code for assigning all 5 2dTexture array:

```
 using UnityEngine;
 using System.Collections;

 public class Raycast : MonoBehaviour
 {
     public Ray ray;
     public RaycastHit hit;
     public Texture2D[] diffuseTextures;
     public int indexPointer = 0;

     void Update()
     {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(ray, out hit))
         {

             if(Input.GetMouseButtonUp(0)){
                 if(hit.transform.tag == "CubeTag"){
                     hit.collider.gameObject.renderer.material.SetTexture("_MainTex", diffuseTextures[indexPointer]);
                     indexPointer++;
                     print (indexPointer);
                     if (indexPointer >= diffuseTextures.Length) {
                         indexPointer = 0;
                     }
                 }
             }
         }
     }
 }

```

# Answer
Wouldn't it be simpler to just use some integer state logic to drive the match comparisons?

For example you could just keep track of each Tile's state and colour and do numerical comparisons instead of interrogating the actual texture of each gameObject? This has the added value of using a single Texture Atlas to store your tile textures and then just map to that Atlas as per the norm if a tile needs to change via a user mouse click.

A quick comparison example for you to Ctrl-F5 (if you run it a few times you'll get a match) :

```
using System;
using System.Collections.Generic;
using System.Text;

namespace CubePuzzle {

    [Flags]
    public enum Colours {
        Red = 0,
        Blue = 2,
        Green = 4,
        Orange = 8,
        Purple = 16,
        Black = 32,
        Grey = 64,
    }

    public class Tile {
        public int xPos; public int yPos;
        public int colourValue;

        public Tile(int x, int y, int colourValue) {
            this.xPos = x; this.yPos = y;
            this.colourValue = colourValue;
        }
    }

    class Program {

        public static void TestForColourMatches(Tile[,] tiles, Array colours, int matchCount) {
            Console.WriteLine();
            int xSize = tiles.GetLength(0);
            int ySize = tiles.GetLength(1);
            bool sequence = false;

            int rowCount = 0;
            // row test
            for (int y = 0; y < ySize; y++) {
                foreach (int c in colours) {
                    rowCount = 0; // reset this value for each colour in each row
                    sequence = false;
                    for (int x = 0; x < xSize; x++) {
                        // test each colour for a row match
                        if (tiles[x, y].colourValue == c) {
                            rowCount++;
                            sequence = true;
                        } else {
                            rowCount = 0;
                            sequence = false;
                        }

                        if (rowCount == matchCount && sequence) {
                            Console.WriteLine("A match was found for colour '" + Enum.GetName(typeof(Colours), c) + " in row [" + y + "].");
                            Console.Write("    --> ");
                            for (int vx = 0; vx < xSize; vx++) {
                                Console.Write(" " + tiles[vx, y].colourValue);
                            }
                            Console.WriteLine("");
                            break;
                        }
                    }

                }
            }

            Console.WriteLine("");

            int colCount = 0;
            // column test
            for (int x = 0; x < xSize; x++) {
                foreach (int c in colours) {
                    colCount = 0; // reset this value for each colour in each column
                    sequence = false;
                    for (int y = 0; y < ySize; y++) {
                        // test each colour for a row match
                        if (tiles[x, y].colourValue == c) {
                            colCount++;
                            sequence = true;
                        } else {
                            colCount = 0;
                            sequence = false;
                        }

                        if (colCount == matchCount && sequence) {
                            Console.WriteLine("A match was found for colour '" + Enum.GetName(typeof(Colours), c) + " in column [" + x + "].");
                            //Console.Write("    --> ");
                            for (int vy = 0; vy < ySize; vy++) {
                                Console.WriteLine("    --> " + tiles[x, vy].colourValue);
                            }
                            Console.WriteLine("");
                            break;
                        }
                    }

                }
            }

            Console.WriteLine("");

        }

        static void Main(string[] args) {

            const int MATCHCOUNT = 3;
            int xSize = 5; int ySize = 5;
            Tile[,] tiles = new Tile[xSize, ySize];
            Random rand = new Random();
            Array colours = Enum.GetValues(typeof(Colours));

            // populate tile set
            for (int y = 0; y < tiles.GetLength(1); y++) {
                Console.Write("[" + y + "] ");
                for (int x = 0; x < tiles.GetLength(0); x++) {
                    tiles[x,y] =  new Tile(x, y, (int)colours.GetValue(rand.Next(colours.Length))); // random colour between (0,4]
                    Console.Write(tiles[x, y].colourValue + " ");
                }
                Console.WriteLine("");
            }

            TestForColourMatches(tiles, colours, MATCHCOUNT);

        }
    }
}

```
> 1 votes

# Answer
This will check whether every tile in a column has the same texture. You should be able to modify it to suit your needs.

You also need to set up the board in the inspector. Set the board size to 5, then each column size to 5, then drag over all 25 gameObjects.

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

public class Raycast : MonoBehaviour
{
    public Ray ray;
    public RaycastHit hit;
    public Texture2D[] diffuseTextures;
    public int indexPointer = 0;
    public List<ColumnOfRenderers> board;

    void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit))
        {

            if(Input.GetMouseButtonUp(0)){
                if(hit.transform.tag == "CubeTag"){
                    hit.collider.gameObject.renderer.material.SetTexture("_MainTex", diffuseTextures[indexPointer]);
                    indexPointer++;
                    print (indexPointer);
                    if (indexPointer >= diffuseTextures.Length) {
                        indexPointer = 0;
                    }
                    if(AllTilesInColumnMatch())
                        Debug.Log("Tiles are connected");
                }
            }
        }
    }

    bool AllTilesInColumnMatch()
    {
        bool sameTextures = true;
        for(int row = 0; row < 5; row++)
        {
            for(int col = 0; col < 5; col++)
            {
                sameTextures &= TilesHaveSameTexture(row, col, row, col+1);
            }
        }
        return sameTextures;
    }

    bool TilesHaveSameTexture(int x1, int y1, int x2, int y2)
    {
        //check out-of-bounds
        if(y2 < 0 || y2 >= 5)
            return false;

        if(board[x1].column[y1].material.mainTexture == board[x2].column[y2].material.mainTexture)
            return true;
        else
            return false;
    }
}

[System.Serializable]
public class ColumnOfRenderers
{
    public List<Renderer> column = new List<Renderer>();
}

```
> 0 votes

# Answer
From your example I can tell you're making a "connect the pipes" type game. You have two possible approaches here:

1. You can hard code each level, testing the map array for a specific total state, making sure that A2, A3, and A4 are all orange.
2. You can program a pathing algorithm to test if there is a path between the two colors.

The second option will be better for you in the long run, as it means less work for you to design new levels.

Do a little research for finding paths in an array between two points. It's an old problem with many solutions. The most optimal solution, if my memory serves me, is the A\* (A-star) algorithm.
> 0 votes

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


title: Evil Genius styled building system

text:
# Question
Title: Evil Genius styled building system
I'm currently playing around with a base builder/manager-esque type of game similar to Evil Genius. To build a room I would like to have the following process: 1. Select room type 2. Click and hold the mouse. Drag to create a rectangle over the area. 3. On release, place entire room.

I have already implemented this, but I find it inefficient and I would like to improve it. As of now the indicator rectangle is simply a sprite that is scaled and moved to fit. I would, however, like to have the indicator rectangle to be "adaptive". Meaning that if I drag a placement rectangle over an invalid area the indicator will be red at that point.

To do this I figured I could go with some sort of loop. I.e. "A change in rectangle size noticed. Update all new indicator tiles with correct colour". I had all the pseudo code figured out, but then I realised instantiating a number of gameobjects would be kinda inefficient. If the player is making a large rectangle in a short amount of time, that would surely slow down the game? Is there any other way to solve my problem, or is this the most efficient solution?

I should note that this build system is grid based. Each tile has a coordinate given by two integers and is saved in a 2D array. You can easily access the array and see what tile is at any given point or find the coordinate of any tile.

# Answer
There's a trick to this:

## Selecting Areas:

As you move the mouse, the only tiles you need to check for new impassable tiles are the *newly highlighted* tiles. If the mouse is dragged from X=25 to X=26, then you only need to iterate over the tiles at the X=26 column from the Y of the starting tile to the Y of the tile the mouse is over. The worst case scenario is you cross both X and Y axis, in which case you will only iterate over L+W-1 tiles.

## Deselecting Areas:

The catch is if the player selects a large valid area, crosses an invalid tile, then backs off of it to go back to the large valid area he had a moment before.

To keep from having to check the entire space when your area shrinks, keep track of how many impassable tiles were crossed as you cross them. Then when bounds change, subtract the number of impassables that were in the column or row that was deselected. As soon as your impassable count is 0, you no longer need to check *so long as the selected area is shrinking*.

This still ensures you never iterate over more than L+W-1 tiles at any time.

## Highlighting:

While Selecting areas, as you iterate over, spawn a red rectangle at the location of the impassable tile you are currently looking at. Store them in a 2D array for when you need to remove them. You could do some magic and scale a single rectangle for contiguous blocks of impassables with a little thought.

While Deselecting areas, iterate over the column or row in the 2D array mentioned above and remove any object found in the row or column. this will be fast, as you know the column or row you're looking at, and since most will be empty, they will more or less be skipped.
> 0 votes

---
Tags: unity, performance
---


title: Create an 2d Isometric map with tiles?

text:
# Question
Title: Create an 2d Isometric map with tiles?
I'm creating a 2D Tower Defense game and I want it to be isometric. I'm creating it on the XZ plane in Unity(3D mode). I need the map to be based on tiles so I can seperate the monsters' path and the tiles where the player will build the towers on because they will have different scripts attached to 'em. My game will just need one map so I dont need any functionalty like randomizing tiles etc. I've tried using Tiled however, the Tiled2Unity converter doesn't support Isometric maps.

With that said, how do I create a isometric map? Is there any program other than Tiled? Is there any guides or scripts that explain how to create one with different tiles etc, so I can create a path. I've tried looking for something that works but with no results/I dont understand what do do.

This is basicly the look(the angle/path) I want to achieve:

# Answer
> 0 votes
3D objects still have an X and Z coordinate. The only thing you have to do to make it isometric in 3D settings is to ensure the Y value for all the tile objects are the same. Generally we set this to 0. Put your camera wherever you like the angle, and voila! I hope this clears things up.

---
Tags: c#, unity, tilemap, isometric
---


# Question
Title: Unity 2D Graphics Optimization For Mobile Devices
I want some advices on how to create graphical assets for mobile devices so that the game will have a good performance and not lag on mobile devices.

I had 3 issues with my games and that is they all lag after playing a little while, some lag more some less but they all lag, I think the problem is in the graphical assets. Some of the games were simple as flappy bird with a couple of images in the project but the game was lagging after playing it for a minute or two.

Now my question is, how to create graphical assets, do I need to export them on 16bit or 32bit and what is the difference, which options should I set in unity, compressed, true color, 16 bit?

And are there some other options that I can check or uncheck in unity so that the graphics will perform better on my game?

When I pack my assets in a sprite sheet, should I put them on larger sprite sheets for example 2048x2048(which is one of the options for max size in unity) or should I pack them on smaller sprite sheets?

Does a sprite sheet have to be to the power of two e.g 1024x1024 or 512x512 or I can pack my assets until they fit and the size does not matter for example the sprite sheet can be 640x410 or something like that, not on the power of two?

Does it make a difference when there is free space in a sprite sheet does that affect graphic performance or do I need to squeeze the sprites closer to each other so that there will be no empty space in the sprite sheet?

Please answer the question that I'm asking, last time I posted the same question people started asking me about the game, did I do this or that and my question then went off topic and got closed, the game is not the question, the question is everything that I mentioned above or if you have something to add that will help me.

If you can help me about this then please answer, and again please don't ask about the game and did I do this or that in the game. I hope that my question is clear, and that it is not off topic.

# Answer
> 5 votes
Here are some answers to your questions: 1) If you want your sprite sheet to be compressed (which will reduce memory usage, at the cost of some quality), you will want it to be a power of two. If you are going to do completely uncompressed textures, then any size is OK. My recommendation is to stick with the power of 2, since that gives you the flexibility of using compressed textures if you want later on.

2) Free space in your sprite sheet should not affect your graphics performance, other than using up more memory than necessary. You will want to make your sprite sheets as square as possible. In your example, you have a 640x410 texture. This texture, if set to be compressed, will be scaled up to 1024x1024. You are better off modifying that texture to try and get that 640 pixel width down to 512, so that it becomes a 512x512 texture instead of a 1024x1024.

For creating assets, I would probably create them in 24 bit. If you save them in 32 bit, there will ALWAYS be an 8 bit alpha channel, and that becomes relatively expensive. Since it's a 2D game, there's probably going to be a lot of fully transparent and fully opaque pixels, with very few (if any) partially transparent pixels. My recommendation would be to create a full 24 bit image and then have a separate black and white image for your alpha. For your final format, I would then recommend 16 bit, with 5 bit color and a 1 bit alpha channel.

Overall, you will probably not see significant performance differences between different texture types *unless* you are graphics bound. The reason this question is difficult to answer without knowing more is that with Unity, there are many things going on simultaneously that can affect performance. Generally, your game is running each frame of the game while the last frame is being rendered. Your frame rate is going to be whichever of those takes the longest. Generally speaking, on mobile, the most expensive things you can do on the rendering side is to have alpha or expensive shaders. Anything that requires multiple passes is going to be particularly expensive. On your game side, heavy memory access and memory allocation are going to be the big performance killers. Destroying and recreating GameObjects rather than having a pool that gets re-used are the types of things that will slow your game code down (but not your rendering).

From your original description, I would agree with what other replies to your questions have said. If your graphics performance is getting worse over time, you are probably not being slowed down by the graphics (unless the graphics get consistently more complex over time). If there's a specific section that, when on camera, slows things down, then it might be rendering, but if its just getting slower over a period of time, then my first guess would be that you are creating something that is not getting destroyed, so the scene is getting busier as time progresses, which is reducing your frame rate.

*More info on textures and texture sizes* Unity has a few different texture types that you can set, and depending on what the setting is, as well as what is contained in the texture you are applying it to will affect what it turns into by the different settings.

TrueColor - This means that Unity is not doing anything to the color/pixel values in your texture, so they are "true". True color textures can be any width or height. If your texture has any alpha in it, this means it will create a 32 bit texture. A 32 bit texture's size is going to be width\*height\*4. It has a full 8 bit alpha for each pixel. If your texture doesn't have any alpha in it, it will create a 24 bit texture. A 24 bit texture's size is going to be width\*height\*3. It will have no alpha, and adding even a single pixel of alpha will make it convert to 32 bit, so it will become 33% bigger.

16 bit - A 16 bit texture is going to be either 2/3 the size or 1/2 the size of a true color texture, depending on whether the 32 bit texture has alpha or not. Its total size will be width\*height\*2. 16 bit textures can also be any size, like true color. They are smaller than true color, but at the loss of some color resolution. You will get mixed results on this setting, but they do have the advantage of supporting alpha without changing the size, and are not compressed.

Compressed - A compressed texture is *significantly* smaller than either a True Color or 16 bit texture. The compression will look better on some textures than others, and its beyond the scope of this explanation to give you hints on how to improve the visual quality. A compressed texture must be a power of two, and if it is not, Unity will automatically scale it up to the next largest power of two. A compressed texture is generally significantly faster to render and uses a much smaller amount of memory, and can carry an alpha channel. It tends to look best on things that are "noisy", so real pictures, or things that are busy. It tends to look worse on things that are flat colors or have sharp edges that are important. So fonts, text, and UI elements will probably have more obvious signs of compression than a texture of a tree, for example.

---
Tags: unity, 2d, graphics, optimization
---


title: How can I use OpenType Font in libGDX

text:
# Question
Title: How can I use OpenType Font in libGDX
Is there a way I can use an OTF file with libGDX.

The following throws an exception:

```
gameFont = new BitmapFont(Gdx.files.internal("data/font.otf"));

```

Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Invalid padding.

This is the same error thrown if I were to try to use a non font file type as well. (i.e. .png .mp3 etc). I have been able to use .fnt files in the past. Is there anyway around this? Thanks.

# Answer
Not directly, but you could create a font for libgdx from a `.otf` using the Hiero tool to convert your font, or create one at runtime but (like the author of this site says), it's something that you should try to avoid.

An example of how to load an `.otf` font can be found here
> 1 votes

---
Tags: java, libgdx, fonts
---


# Question
Title: Is it possible to load asset bundle dependencies manually in Unity 5.0?
Is it possible to tell Unity to not load asset bundle dependencies automatically so they can be loaded manually. If so, how can this be done?

# Answer
The asset bundle dependencies are not processed in the "load", but when the asset bundle is created. Unity basically loads the entire asset bundle in at at a time, and then instantiates particular assets inside the asset bundle. To remove asset bundle dependencies at build time, take a look at the AssetBundle.PushAssetDependencies function. Any assets that are pushed into the dependency list will be automatically excluded by bundles built afterwards.
> 1 votes

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


# Question
Title: How does Unity load asset bundle dependencies and how can they be accessed?
Loading assets from an asset bundle is done explicitly. You give the bundle the name of the asset to load, then it returns it( either now or later. ) However, loading dependencies is done completely automatically.

How is this done? Is the asset bundle completely removed from memory after the required objects are loaded? Are all the bundle's assets loaded, or just the necessary ones? How can these assets be accessed outside of the reference that caused the dependency in the first place?

I ask this because I am trying to collect some type information about the assets loaded in asset bundles. I need to be aware of all assets of a certain type that are loaded into the game.

# Answer
The asset bundle system does not automatically remove anything nor does it load dependencies automatically. Dependencies are included in asset bundles automatically, but actually exist in each asset bundle that depends on them, unless you manually removed them. For example, if you have a 2 different player models, Hero1 and Hero2. They both share a Gun texture. If you put hero1 into an asset bundle, that asset bundle will contain Hero1 and the Gun Texture. If you put hero2 into an asset bundle, it will contain Hero2 and the Gun Texture. If you load both asset bundles simultaneously you will have 2 copies of the gun texture loaded. The way to get around this is with the asset bundle dependencies. The way these work is that at *build* time, you would create an asset bundle with the Gun texture, and then call AssetBundle.PushAssetDependencies(), passing it the gun texture. You can then build the Hero1 and Hero2 asset bundles, and each of them will *not* include the Gun texture. At runtime, it will be up to you to load the Gun texture bundle along with the Hero1 and/or Hero2 asset bundles, but it will be only loaded a single time.

The memory management of asset bundles gets a bit more complex than this too, as far as memory usage is concerned. If you have a compressed asset bundle, what will happen when you load it is the entire compressed asset bundle is loaded into memory. From there, individual assets are decompressed and loaded. Once all the assets have been loaded, you can unload the asset bundle and you'll still have the assets inside in memory (assuming something is referencing them). The downside of this approach is that at some point, you'll have both the entire compressed asset bundle in memory, and simultaneously the uncompressed asset bundles in memory as well. With the new parameter to AssetBundle.Unload, you can specify whether you want it to destroy only the compressed asset bundle or whether you want it to free the uncompressed copy as well.

The other way to generate asset bundles is to generate them as uncompressed asset bundles. If you generate uncompressed asset bundles, they will be larger, which will negatively affect your download time in getting the assets, but your loads will be much faster. When you load an uncompressed asset bundle, there isn't a second copy of all of your data, the objects that reference data in your asset bundle are pointed to the actual asset bundle in memory. When you unload the asset bundle, anything pointing to things inside the asset bundle are unloaded, and so you can't unload the asset bundle while still referencing things inside it. The upside is that you avoid the extra memory of having both loaded, and you don't have the performance hit that is incurred by the decompression, since its loaded in place.
> 4 votes

---
Tags: unity, c#, resource-management
---


# Question
Title: LibGDX Box2D Lights - Illuminate background
I have a box2D world made of tiles. I use a custom DirectionalLight for light up the scene from above (It shines through transparent blocks \[eg.: the water\] more deeply). The problem is (as expected), as soon as I build a bridge-like thing in the air, I'll get shadows underneath. What I'd like to achieve, is to get light in the places where there aren't any blocks (i.e. neither in the foreground nor in the background).

Should I completely forget the DirectionalLight, or is there any method to easily "post-fix" these shadowed areas?

# Answer
> 0 votes
I'm just starting out with lighting myself, but one of these two solutions might help you.

set an ambient light to brighten up the world:

```
rayHandler = new RayHandler(world);
rayHandler.setAmbientLight(new Color(.1f, .1f, .1f, .5f));

```

or allow the light to ignore bodies:

```
pointLight = new PointLight( ... );
pointLight.setXray(true);

```

---
Tags: libgdx, box2d
---


# Question
Title: LibGDX - how to detect touchUp with GestureListener?
I'm making a game and I have implemented GestureListener as my inputprocessor. It came with a bunch of methods such as fling, pan, tap etc etc including touchDown. However, there is no touchUp method!

What I want to do is have something happen when the user does a 'fling', but I want something to happen when the user then takes their finger off the screen after flinging, probably setting a flinging boolean and testing if true when taking finger off the screen.

However, I don't see how I can get a touchUp method into my inputprocessor! Is there any work around to this or an alternative solution?

Thanks!

# Answer
> 2 votes
From here, you can see how to use the `touchUp`method that is in the `InputProcessor` interface with the `GestureListener` that you already implemented.

For what are you asking, it should be something like this:

```
public class Inputs implements ApplicationListener, GestureListener, InputProcessor {
    boolean isFling= false;

    //A lot of code with the GestureListener methods
    @Override
    public boolean fling(float velocityX, float velocityY, int button) {
        // do something...
        isFling = true;
        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        if(isFling) {
            isFling= false;
            // Do something when touchup trigger and fling finished
            doSomething();
        }
        return false;
    }
    // the rest of the methods
}

```

In the same link, you can learn how to manage a lot of inputs at the same time with the `InputMultiplexer`.

Hope this helps!

---
Tags: java, libgdx, touch
---


# Question
Title: Rescale pixel art scenery before rendering in SDL2
I looked at this page that mentions the SDL2\_gfx library for rescaling SDL\_Surfaces without the image getting blurry: SDL zooming/upscaling without images becoming blurry?

I wanted to know if it was a good idea and if there was any way (instead of individually resizing each texture, all relationships of space, and fixing the proportions of the speed for each object) to take the tiny scene of little sprites and tiles and rescale it before the image blits on the screen.

If there's a more reasonable solution, someone tell me, but this seems to make the most sense to me.

Thanks for the help!

# Answer
> 9 votes
In SDL 2, you must set the scaling interpolation algorithm for the whole renderer, using

```
SDL_SetHint (SDL_HINT_RENDER_SCALE_QUALITY, Value);

```

where Value should be, in your case (pixel art) 0. 1 means linear interpolation, and 2 is anistropic (only supported if the app runs on D3D/Windows) (documentation)

As far as saying itself is concerned, you can do it when you copy a texture to the renderer by specifying a target rectangle larger/smaller than the source rectangle.

```
// let's say the texture is 16*16px
SDL_Rect dest = {.x = 0, .y = 0, .w = 32, .h = 32}; // Scale by 2 -> 32*32.
// If SDL_SetHint was called properly, it will scale without blurring.
SDL_RenderCopy(renderer, texture, nullptr, dest);

```

Other possibility, you could set the renderer's logical scale to a fixed value (`SDL_RenderSetLogicalSize(renderer, width, height)`) that's smaller than the window's size. SDL will scale the renderer to fit the window using the algorithm given in `SDL_SetHint()`.

The way I go about it when making pixel art game is the one you were hinting at: work at 1x resolution (sprites are not upscaled), and scale everything at the end.

If you want to scale only certain bits (let's say, HUD layer), you could render everything to a texture, and then upscale that texture before rendering it to the screen. To do that, the target texture must be created with the right flag (`SDL_TEXTUREACCESS_TARGET`), and then the renderer must be set to draw on it:

```
SDL_Texture* target = SDL_CreateTexture(renderer, PIXEL_FORMAT, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetRenderTarget(renderer, target);
SDL_RenderClear(renderer); // to make sure the texture is "clean"
//
// render everything you want here
SDL_SetRenderTarget(renderer, nullptr); // to switch the renderer back to the screen
// render your target texture here, after upscaling it if you want

```

Hope all that helps! :)

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


# Question
Title: Is it possible to convert vec4 to int in GLSL (using OpenGL ES)
I need GPU to do some computations, and I pass shader an int array using `glTexImage2D` (internal format is `GL_RGBA`). I use `texture()` to get the data, but it returns a vec4 value. Is it possible to convert vec4 to int in GLSL?

# Answer
> 3 votes
I think you can convert it manually by manipulating the bytes yourself.

```
vec4 bytes = ivec4(col * 255);
uint integerValue = (bytes.r << 24) | (bytes.g << 16) | (bytes.b << 8) | (bytes.a)

```

The code is untested, but the basic idea is to convert your normalized RGBA colors (0-1) into 0-255, and shifting them appropriately and OR-ing the bytes together.

# Answer
> 2 votes
Shaders are heavily optimized for floating point, not integer math. The four values you will get are your RGBA values, each from 0 to 1. That's what the texture is meant to represent, and that's what you'll get.

If you need to convert these four values to one larger value, you are more than welcome to do something like

```
highp float encoded = (sampled.a * 256) + (sampled.b * 65536) + (sampled.g * 16777216) + (sampled.r * 4294967296);

```

Or the other way around if you encoded your values in big endian.

Remember that the resulting value is a float, and you may have precision problems if you start jockeying with the result.

---
Tags: opengl-es
---


# Question
Title: Client interpolation for 100% serverside game
I'm developing an online browser MMO 2d war game.

And I'm having some issues with the interpolation. The server sends updated positions to the clients every 90 ms.

I've managed to make it smooth, and it works very well on low latency, but if the latency is high, everything skates around like its on ice (OVERLY SMOOTH).

I would like to achieve normal movement (visually), and I don't care about input-lag, as 3-400 ms input lag doesn't matter for this game.

**This is how I'm doing it now (simplified for readability):**

The "Server" object is the one processing the updates send by the server, and "animate()" is the gameloop.

```
    var Server = {
        msAhead: 0,
        Time: Date.now(),
        SetData: function (data) {

            //Set date.now() to calculate ms since last update
            var now = Date.now();

            //calculates ms since last update
            var ms = now - this.Time

            //sets new time (for calculating ms next update)
            this.Time = now;

            //Keeps track of how many milliseconds the server is ahead (position vice)
            this.msAhead += ms;

            //Attatch a reference with the players new position to each player
            $.each(data["players"], function (id, data) {
                Players[id].target = data;
            });
        }
    }

    var Time;
    function animate() {
        //Sets time if first call
        if (!Time) Time = Date.now();

        //Sets new time and calculate ms between frames, sets deltatime
        var now = Date.now();
        var ms = now - Time;
        var delta = ms * 0.001;

        //reset info for next frame
        Time = now;

        //Calculate and normalize lerp
        var lerp = ms / Server.msAhead;

        //update the "msAhead" so we know that we are closer to our target position
        Server.msAhead -= ms;

        //normalize lerp (it can be off on the first frames since time isn't set yet, or is heavy spikes occur)
        if (lerp > 1) lerp = 1;
        if (lerp < 0) lerp = 0;

        //Update player positions lerping towards the target position set by the server object
        $.each(Players, function (id, player) {
           player.position = Lerp(player.position, player.target.position, lerp)
        });

        //Request next animationframe
        requestAnimationFrame(animate);
    }

```

**EDIT:** I can simulate my goal on high latency by doing: **var now = Date.now() + 300;** in the animation loop.

But that will crash (stop updating) low latency players, since the client will think its ahead of the server, and lerp will become negative (zero).

# Answer
Actually I solved the problem.

The solution was to manipulate the "ms" variable in the Animate() function before calculating the lerp.

I know the server sends updates every 90 ms, so if i want to add a fake delay of 100ms i need to make sure that the target "msAhead" should be 190-200.

So i did like this.

```
if (Server.msAhead > 200)
  ms += 1;
else if (Server.msAhead < 190)
  ms -= 1;

lerp = ms / Server.msAhead;

```

This looks like a hacky solution, but it actually works very well, It smoothly guides the client to be rendered at the exact delay i want. If the server is more then 100 ms ahead, it will cause the client to interpolate further to catch up.

And it looks the same on high and low latency, the difference is that people with high latency will see it all delayed. (which is not a problem in my case).
> 2 votes

---
Tags: javascript, networking, interpolation
---


# Question
Title: Weird member of float4 structure in the HLSL
I have encountered a weird `x.wwww` component of the `float4 x` vector in a HLSL code. I haven't seen such a member or member function of float4 structures in HLSL, so please tell me what is the meaning of that. It is in the code of this pixel shader:

```
float4 PSConstantColor( PS_PARTICLE_INPUT input ) : SV_TARGET
{
   // Sample particle texture
   float4 vColor = g_baseTexture.Sample( g_samLinear, input.Tex ).wwww;

   // Clip fully transparent pixels
   clip( vColor.a - 1.0/255.0 );

   // Return color
   return vColor;
}

```

At first I thought it should be the `w` component replicated to all the members of the `float4 vColor` vector, but it does not make sense for the color value, does it?

# Answer
> 4 votes
From my understanding they are called swizzle operators. In this case they make a float4 of the 4th element in the given float4:

```
vColor = (w, w, w, w)

```

Where w is g\_baseTexture.Sample( g\_samLinear, input.Tex ).w

Here is an example of a swizzle operator in practice:

```
float3 cross( float3 a, float3 b ) {
    return float3( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.z*b.y - a.y*b.z );
}

```

and its equivalent swizzle implementation

```
float3 cross( float3 a, float3 b ) {
    return a.yzx*b.zxy - a.zxy*b.yzx;
}

```

---
Tags: hlsl
---


title: Bukkit "Could not pass Event" error

text:
# Question
Title: Bukkit "Could not pass Event" error
I'm trying to make a bukkit plugin, which implements backpacks in the game if the player has the correct item (Enchanted Normal book with Efficiency 10 and Unbreaking 10, to be uncraftable).

I want to save the inventory using the built-in YamlConfiguration feature in Bukkit.

I use a InventoryCloseEvent to see when the player closes the backpack, but I always get an error when I close the backpack.

```
    [12:28:27] [Server thread/ERROR]: Could not pass event InventoryCloseEvent to ServerAssets v1.0
org.bukkit.event.EventException
    at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:310) ~[spigot.jar:git-Spigot-f928e7a-994b2aa]
    at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62) ~[spigot.jar:git-Spigot-f928e7a-994b2aa]
    at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:502) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:487) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at org.bukkit.craftbukkit.v1_8_R3.event.CraftEventFactory.handleInventoryCloseEvent(CraftEventFactory.java:838) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:1384) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.PacketPlayInCloseWindow.a(PacketPlayInCloseWindow.java:18) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.PacketPlayInCloseWindow.a(PacketPlayInCloseWindow.java:1) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_45]
    at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_45]
    at net.minecraft.server.v1_8_R3.SystemUtils.a(SystemUtils.java:19) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:718) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:367) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:657) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:560) [spigot.jar:git-Spigot-f928e7a-994b2aa]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
Caused by: java.lang.NullPointerException
    at com.isoStudios.main.BackPack.inventoryClose(BackPack.java:84) ~[?:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_45]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_45]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_45]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_45]
    at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:306) ~[spigot.jar:git-Spigot-f928e7a-994b2aa]
    ... 16 more
[12:35:50]

```

The 84th row is:

```
File file = new File("plugins/ServerAssets/saves/" + player.getName() + ".yml");

```

Here is the source code for the BackPack class:

```
package com.isoStudios.main;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

public class BackPack implements CommandExecutor, Listener {

    YamlConfiguration config;

    public BackPack(YamlConfiguration config) {
        this.config = config;
    }

    Inventory inventory = Bukkit.createInventory(null, 9, "BackPack");
    Player player;
    boolean opened = false;

    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

        boolean cancelled = true;

        if (sender instanceof Player) {
            player = (Player) sender;

            ItemStack[] inv = player.getInventory().getContents();
            for (ItemStack item : inv) {
                if (item != null) {
                    if (item.getEnchantmentLevel(Enchantment.DIG_SPEED) == 10 && item.getEnchantmentLevel(Enchantment.DURABILITY) == 10 && item.getType().equals(Material.BOOK)) {
                        File file = new File("plugins/ServerAssets/saves/" + player.getName() + ".yml");
                        inventory = Bukkit.createInventory(player, 9, "BackPack");
                        if (file.exists()) {
                            try {
                                config.load(file);
                            } catch (Exception ex) {
                                Bukkit.getLogger().info("Failed to load config file, while trying to restore backpack content!");
                            }
                            for (int j = 0; j < 9; j++) {
                                ItemStack i = config.getItemStack(""+j);
                                inventory.setItem(j, i);
                            }
                        } else {
                            try {
                                file.createNewFile();
                            } catch (IOException e) {
                                Bukkit.getLogger().info("Failed to create player save file!");
                                e.printStackTrace();
                            }
                        }
                        player.openInventory(inventory);
                        cancelled = false;
                    }
                }
            }
            if (cancelled) {
                player.sendMessage(ChatColor.BLUE + "You don't have a backpack!");
                return true;
            }
        } else {
            sender.sendMessage(ChatColor.RED + "You need to be a player, to use this command!");
        }

        return false;
    }

    @EventHandler
    public void inventoryClose(InventoryCloseEvent event) {
        File file = new File("plugins/ServerAssets/saves/" + player.getName() + ".yml");
        if (!(new File("plugins/ServerAssets/saves*" + player.getName() + ".yml").exists())) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                Bukkit.getLogger().info("Failed to create user save file!");
                e.printStackTrace();
            }
        }
        List<ItemStack> items = new ArrayList<ItemStack>();

        for (ItemStack i : inventory.getContents()) {
            items.add(i);
        }

        save(items, file);
    }

    public void save(List<ItemStack> items, File file) {
        int i = 0;
        for (ItemStack item : items) {
            config.set(""+i, item.serialize());
        }
        try {
            config.save(file);
        } catch (IOException e) {
            Bukkit.getLogger().info("Failed to save config file while saving backpack content!");
            e.printStackTrace();
        }
    }
}

```

# Answer
> 0 votes
When a null pointer exception is thrown when creating a new file object, that means one of the parameters is null, described in detail Here. What you're looking for on line 84 is

```
 File file = new File("plugins/ServerAssets/saves/" + event.getPlayer().getName() + ".yml");

```

Which according to the Bukkit API

> final HumanEntity org.bukkit.event.inventory.InventoryCloseEvent.getPlayer ( )

will return the player associated with this event. The reason why the player object is null is that the event can be thrown before you execute a command, resulting in player never being set equal to anything.

---
Tags: inventory, bukkit
---


title: Is there a way to use scala with html5?

text:
# Question
Title: Is there a way to use scala with html5?
I want to create a very simple 2d multiplayer browsergame in html5. Something like Scalatron

I mainly want to do this to improve my scala skills, the problem is I would have to code the clientside code in javascript and the serverside code in scala. This would result in duplicated code.

Another option would be to ignore the html5 part and write it in opengl. But I would still prefer to have a html5 game.

I could do this is in javascript, but then it would destroy the whole purpose of learning scala.

Is there a way to use scala with html5? Or what would you recommend me to do?

# Answer
The programming language for HTML5 is Javascript. Web browsers can't interprete any other programming languages. When you want to create a HTML application in Scala, you will need a transcompiler which turns your Scala code into Javascript.

I found a project with that goal via Google, but I have no idea if it's usable yet: http://scalagwt.github.com/

By the way: I am currently developing a client/server application with the client in Javascript and the server in Java. There is surprisingly few duplicate code, as long as you follow a strict separation of concerns between client and server (the server does all the game logic, the clients job is taking user input and displaying the game state as told by the server).
> 2 votes

# Answer
Have a look to http://www.scala-js.org/ \- it is Scala to JavaScript compiler. Supports source maps and since version 0.6 is not longer experimental.

http://www.scala-lang.org/news/2015/02/05/scala-js-no-longer-experimental.html
> 2 votes

---
Tags: opengl, html5, browser-based-games
---


# Question
Title: How do game bots perceive the game world & other entities?
This question has been on my mind for a while...mainly because I see bots for all sorts of games like WoW and others. My question is; how do the bots know what is appearing on the screen? I don't play WoW so my example may be wrong but if for example there is a monster, how does the bot know where that monster is on the screen and how does it know how to interact with it?

Can you apply this to any game or is it specific for each game? I'm sorry if the question isn't clear...and I'm not asking how to make a bot, more asking how they detect things on the screen as its quite fascinating to me!

Thanks in advance :)

# Answer
There are many points where a bot can inject itself into the game.

* The screen is one of them, but by far not the most useful. However, I have once seen a very early aimbot for Counter Strike which used color coding. It came with alternative character models with single-colored textures (the game was modding-friendly enough to allow this) and then just detected pixels of those colors. Not a very effective method, though. It was already quite clunky back then, and becomes less and less viable because graphic engines become more and more powerful, which means more and more detail to confuse any optical recognition algorithms.
* Another point is reading the memory directly\[1\]. It is possible to have one program on your computer read the memory of another. So the developer just needs to find out at which memory address the game is saving the information which is relevant to the bot. There are tools which assist the developer with finding what they want by creating a memory image and providing various search tools. A countermeasure is to use address layout randomization, but a smart bot might be able to still find what they are looking for automatically.
* It is possible to modify the game executable itself. In order to do this the bot developers need to be able to read and program in assembler, which isn't that hard with some practice. They then look for the code which handles the information they are interested in and rewrite it to pass it to their bot. A possible countermeasure from the perspective of the game developer is to use an obfuscator to make the game's assembler code less readable, but these are usually not good for performance and there are tools for many obfuscators which reverse their work.
* And then there is the netcode. In an online game, the server sends the properties and positions of all objects in the game via network. The network data stream between server and client can be intercepted and analyzed. A popular tool for doing this is wireshark. When the developer reverse-engineered the netcode, they can write a bot which intercepts the network traffic just like Wireshark does and uses the information to make its decision. When the developer is more motivated, they can even develop a complete game client from scratch which implements the network protocol and plays the game without even having any graphical output. Such bots are very popular with gold farmers because without the graphics output the client is usually far more resource-friendly, which means they can run a lot of them at once on a small server.

---

1: Since you mention WoW, it's worth pointing out that the early and notorious WoWGlider botting program used direct memory access. Blizzard had a subprogram called Warden that was designed to detect and block outside programs from accessing WoW's internal game state. Since the bot program circumvented this protection and read the memory without permission, the 2006 lawsuit MDY v Blizzard was decided in favor of Blizzard on the grounds that the bot maker was encouraging and enabling its users to commit copyright infringement and violate the DMCA.
> 78 votes

# Answer
Bots are players. They just read the player's/monster's positions from the server just like every other player does and use those values combined with a simple AI script to perform actions in the game by simulating keyboard strokes and mouse clicks programmatically. If bots actually had an algorithm to detect what monster is on the screen and interact with it, that would be a quite impressive piece of software which would worth millions. That's basically AI for robots.
> 18 votes

# Answer
Phillip already gave a great overview of how how most bots operate, but I just wanted to cover things in a little more detail, as I have a bit of personal experience developing on or for all the types of bots he covered.

In Runescape, there was a large project (RSBot) that would copy the contents of memory from the Runescape client into its local memory, where it could then view the entire state of the game with no risk of the client catching on. It required a bit of reverse engineering to determine where in memory to look in order to find the pointers to the data, but once they had done so, they exposed an API to take advantage of the information. It would know exactly what was where in the world by getting the coordinates of an object and then transforming them with the camera transform matrix to get the on-screen position. The hit masks were also readable, so it was trivial to determine exactly what range to move the mouse into in order to get a desired result.

The bot provided a bunch of debugging information, such as annotations that told the developer which tile coordinates are where, which ID this object has, what ID belongs to a given item, etc. This information could then be used to make bots. The actual process of making the bot scripts was actually quite simple. The framework provided many utility functions, such as `move_to(world_coordinates)` or `mouse_move(x,y)` which would perform the specified actions in a somewhat believable way (moving the mouse along a random spline, repeatedly moving via both the minimap and screen, and so on)

Also in Runescape, you have the option of drastically reducing the quality of the graphics. It was actually pretty easy to make certain kinds of bots by filming the screen and applying some basic computer vision concepts in order to construct a model of the world. I made both a curse bot and smelting bot using this technique, both of which worked quite well. It would just take the frame, increase the saturation as much as it could, and then try to extract patterns from it which it could then generate a probability map for click zones.

In the case of the curse bot, the target was a lesser demon, which is just a huge red thing, which is trivial to find. In the case of the smelting bot, it would look for a small orange trapezoid surrounded by grey, and that would be the furnace. It would also try to find a large, light-grey 'L' shape, which would be the bank desk. That was just done with downscaling and basic heuristics. It could also orient itself with the handy compass next to the minimap, so it could orient the camera in a more reliable position to find the target objects.

In various Nexon games, the servers are very trusting of the clients. I abused this a ton in Maplestory by modifying maps to remove hazards or add warps so that a bot doesn't have to be nearly as sophisticated. I would also monitor the traffic to and from the server in order to build a model of the world which could then be used to quickly find and kill monsters.

Once I realized that I didn't actually play MMOs anymore and just automated them, I decided to stop playing altogether. If I wasn't as worried about exposing myself legally, I could have probably made a killing selling MMO bots, but I really didn't want to get sued. That is why I spend my time doing real programming these days!
> 7 votes

# Answer
Phillip's answer is great, but just a quick note about the **Model/View/Controller** pattern, or MVC for short.

Your screen is part of the "view", which presents data from the "model", which is the real state of the game if you like. The bots, and your character, all 'exist' (in a sense) within the model. Imagine if you unplugged your screen - the game would continue even though the view has gone.

In a networked game, the concept of a "model" is a little complicated, as you actually have lots of models. You have the model on the server, and then a model on each client, which updates itself in part due to data it receieves from the server. You could think of the "model" as encompassing the server's model and your client's model, or you could think of it as just your own client's model. Either way, this is where the bots live. So, their "perceptions", which we could use as a shorthand for their data input and state, are based on the state of the model at that time and the interaction between the different entities/objects within that model. In practise, each bot might have a function called "refreshState" which runs once per frame or something, and which causes it to update it's own state by looking up some data from inside the model, which in turn might affect the decisions it makes.
> 2 votes

# Answer
They can read the coords from a file or a server but also with a ray collision detection system. It is common to use rays that goes from the bot(in that case) to outside him. If the ray collides with something then it returns some information to the bot such as if what the ray found was a player, a bot, an animal or a simple wall. That is because in the case of the player and the bot for example they have an invisible capsule that involves them entirely with information about its type for example (human, bot, ...). With that they can avoid crashing with walls and other elemnts if they are following you for example.

You can see the part **Collision detection** of this Page
> 0 votes

---
Tags: bot
---


# Question
Title: WaitforSeconds() not working as it should
I searched for using WaitforSeconds and used as it was mentioned(using a return type of IEnumeration and using coroutines instead of update). but it did not work. Initially it showed Waitfor Seconds and IEnumerator were not "present in the current context". I had to r-install unity to get it fixed but this problem still remains. The following is my code. Am I using WaitforSeconds in correct way? Is it the 'if' code block that ruin my complete work(I mean have I used it in wrong place)?

```
using UnityEngine;
using System.Collections;

public class EnemyCreeator : MonoBehaviour {
public float xmin,xmax,zmin,zmax;
public GameObject enemy;
public float spawnWait,StartWait,waveWait;
public int turretCount;
public int enemyCount;
int i=0;
void Update() {
    StartCoroutine (TurretWaves());
}
IEnumerator TurretWaves() {

    while (true) {
        Vector3 pos=new Vector3(Random.Range (xmin,xmax),0.5f,Random.Range(zmin,zmax));
        yield return new WaitForSeconds(StartWait);
        while(i<turretCount) {
            //Debug.Log ("The vaue of game time in spawnwaiting is: "+Time.time);
            Instantiate (enemy, pos, Quaternion.identity);
            enemyCount++;
            i++;
            //Debug.Log ("value of i in loop is: "+i);
            //Debug.Log ("The vaue of game time is: "+Time.time);
            yield return new WaitForSeconds (spawnWait);
        }
        //Debug.Log("cHECKing Before WAVE WAIT(value of time )is: "+Time.time);
        yield return new WaitForSeconds(waveWait);
        if(i>=turretCount) {
            i=0;
        }
        //Debug.Log("cHECKing AFTER WAVE WAIT and value of time is: "+Time.time);
        //Debug.Log ("value of i outside the while loop is: "+i);
    }
}
}

```

The code needs to wait until the spawnWait before spawning each turret and wait till the wavewait before spawning the next wave. even though the Startwait works fine, I still am unable to find the problem with others...

(I had this question asked in StackOverflow but since i did not get any answer ,and i didnt know about this specific game-development website, so sorry for the repetition)

Thanks in advance.

# Answer
This bit:

```
void Update() {
    StartCoroutine (TurretWaves());
}

```

Once you start a coroutine, it will continue processing automatically. If you call `StartCoroutine` twice, you will launch two independent coroutines. If you call `StartCoroutine` once per frame, you will start a new, fully independent coroutine on every frame.

By the time your game finishes running 50 frames, you will have 50 copies of `TurretWaves` running. This is probably not what you want or expect.

If you want 1 copy of `TurretWaves`, you will need to start it exactly once:

```
void Start() {
    StartCoroutine (TurretWaves());
}

```
> 4 votes

# Answer
Usualy it's a good practise to use StartCoroutine into the Start(), you're "starting" a coroutine on every update!!

Here can find some examples on using StartCoroutine.

```
using UnityEngine;
using System.Collections;
    public class ExampleClass : MonoBehaviour {
        void Start() {
            print("Starting " + Time.time);
            StartCoroutine(WaitAndPrint(2.0F));
            print("Before WaitAndPrint Finishes " + Time.time);
        }
        IEnumerator WaitAndPrint(float waitTime) {
            yield return new WaitForSeconds(waitTime);
            print("WaitAndPrint " + Time.time);
        }
    }

```
> 0 votes

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


title: XNA/C# Convert polygons into tilemap

text:
# Question
Title: XNA/C# Convert polygons into tilemap
I'm currently working on my 2D survival game, where the world is infinite and generated by perlin noise. I wanted to also include biomes and this article interested me - http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/ .

I downloaded the source ported to C# and edited it to 2D, but there's the problem. I generated simple map 100x100 but then, I dont know how to convert those polygons into the tiles. I tried a simple technique:

```
for (int x = 0; x < map.GetLength(0); x++)
        {
            for (int y = 0; y < map.GetLength(1); y++)
            {
                float rozdilP = 100000f; Biome b = BiomeTypes.Snow;

                foreach (Center center in EnvironmentService.MapGenService.Centers.Values)
                {
                   float rozdil = Vector2.Distance(new Vector2(x, y), new Vector2(center.Point.X, center.Point.Z));
                    if (rozdil < rozdilP)
                    {
                        rozdilP = rozdil;
                        b = center.Biome;
                    }

                }
                map[x, y] = b;
            }
        }

```

it works, but it's really, really slow. Isn't there any better solution or algorhytm for this or is the polygon method of generation supposed to be used only in 3D?

Ty for your time and answer :)

# Answer
> 1 votes
Please, at all cost, avoid using vector2(or 3 or 4 for that matter).Distance(). If you can, use DistanceSquared() instead. To get the actual distance, XNA uses the pythagorean theorem, which ultimately means that it needs to use the square root function. This is a relatively slow function. So use this instead:

```
for (int x = 0; x < map.GetLength(0); x++)
    {
        for (int y = 0; y < map.GetLength(1); y++)
        {
            float rozdilP = 100000f; Biome b = BiomeTypes.Snow;

            foreach (Center center in EnvironmentService.MapGenService.Centers.Values)
            {
               float rozdil = Vector2.DistanceSquared(new Vector2(x, y), new Vector2(center.Point.X, center.Point.Z));
                if (rozdil < rozdilP * rozdilP)
                {
                    //rozdilP = Mathhelper.sqrt(rozdil); (Unless you really need this one, don't use it)
                    b = center.Biome;
                }

            }
            map[x, y] = b;
        }

```

When handling a square root function, you really need to ask yourself if you NEED to use it, or if it only seems logical to you. Because knowing that it costs a lot of processor power, you might have to come up with a calculation that seems a bit convoluted, but is much faster. Especially, of course, in a loop function.

# Answer
> 0 votes
There is only 1 optimization you need to implement:

```
Vector2 Min, Max;
Min = poly.Vertices[0];
Max = poly.Vertices[0];
for (int i = 1; i < poly.Vertices.Length; i++)
{
    Vector2 Vertex = poly.Vertices[i];
    if (Vertex.x < Min.x)
    {
        Min.x = Vertex.x;
    }
    else if (Vertex.x > Max.x) {
        Max.x = Vertex.x;
    }
    if (Vertex.y < Min.y)
    {
        Min.y = Vertex.y;
    }
    else if (Vertex.y > Max.y) {
        Max.y = Vertex.y;
    }
}

```

This calculates the minimum and maximum of the polygon on the X and Y axes. On the grid, this allows you to cull out all grid nodes outside of the polygon's bounding box.

i.e.:

```
for (int i = (int)Min.x; i < (int)(Max.x + 1); i++)
{
    for (int j = (int)Min.y; j < (int)(Max.y + 1); j++)
    {
        CheckNode (i, j);
    }
}

```

The number of checks goes from the total number of grid nodes to only the grid nodes relevant and surrounding the polygon.

---
Tags: c#, xna, tilemap, rasterization
---


# Question
Title: Is using camera and viewport in Libgdx always necessary?
I understand that **camera** and **viewport** are important to keep virtual measurement units and handle different aspect ratios and resolutions when building games with worlds bigger than the screen (e.g. side-scrollers / map based games).

I am not sure whether it is the proper way to go for a simple game that fits on the screen entirely - like a puzzle or card game for example.

Is it still better to use camera and viewport in this case, or is it more simple, effective (and hence better) to use directly screen absolute coordinates for these types of games?

Or to put it in other way - what are the advantages to use camera and viewport for games that fit on the screen entirely?

# Answer
With a camera you separate your game measurements from the screen size and ratio.

It is not always better. If you make a board game for example, you can just fit it to the width of the screen, the view will never move anyway.

When using pixels to measure, you have no floating point positions.

By the way i made a full pong like game without a camera. I just used precents of screen width. For example: platforms are 1/4 screen width, ball is 1/8 screen width
> 3 votes

# Answer
Adding to what Erez said, you can make any game without using a `Viewport` and just scaling your textures to a fraction of the screen size, but most of the time using a `Viewport` is a better option because it scales everything for you.

Although you can use any measurement for the game width and height, I like to choose a target resolution for my game measurements (say 1920 x 1080), then just design all the assets for that target resolution. The `Viewport` and camera will then scale them to look good on most screens. This might not be a good option for all games but it has worked well for the games I have made.
> 2 votes

---
Tags: libgdx, camera, resolution, viewport
---


# Question
Title: How to only render whats on screen (Tilemap, Java2D)
I have some problems with my rendering of a 2Dimensional Map.

```
for (int col = 0; col <= view.getWidth () / Tile.TILE_SIZE; col ++)
    {
        for (int row = 0; row <= view.getHeight () / Tile.TILE_SIZE; row ++)
        {
            if (checkBounds ((int) topLeftX + col, (int) topLeftY + row))
            {//tiles is an array of Tiles, tiles1 is the mapData
                g.drawImage ((tiles[tiles1[(int) topLeftX + col][(int) topLeftY + row]].getImage ()), col * Tile.TILE_SIZE, row * Tile.TILE_SIZE, null);
            }
        }
    }

```

But the scrolling of the map is not smooth (tiles move in a TILE\_SIZE distance and not with pixelmovement).

Someone has an idea on how to solve this?

# Answer
> 2 votes
You need a finer-grained method of moving your viewport. What you're doing now is essentially moving it by the size of a single tile every time you scroll, when what you want is a smaller increment.

You do this by using a camera object represented by an x, y coordinate. Update its position with your scrollIncrement, then use that as the starting point for the row/col variables of your loop. By dividing/modding the coordinate by the size of your tile, you will get the data you need.

For example;

```
row = camera.y / TILE_SIZE;
col = camera.x / TILE_SIZE;

offsetX = -camera.x % TILE_SIZE;
offsetY = -camera.y % TILE_SIZE;

```

Then you start your render loop at row, col and offset the rendering of each tile by offsetX and offsetY, rendering a number of tiles equal to (in your case) screenWidth / TILE\_SIZE. That should give you the effect you want.

To clarify that last bit, your columns for-loop should look something like this;

```
for (int col = starting_tile; col++; col < starting_tile + (screenWidth / TILE_SIZE)

```

Also relevant:

How to Use World Coordinates

---
Tags: java, tilemap, tiles
---


# Question
Title: How can I modify the UV co-ordinates on a texture so they converge to a point?
I'm building a roof visualiser app, where someone can take a picture of their roof, define its outline, then visualise a new roof texture on it.

I'm generating a 3D plane that matches the roof outline points, but I'd like the 3D planes material's UV's to match the perspective of the existing roof (i.e the lines converge into the distance as they move away from the user.

Is this possible?

The alternative solution is to figure out how to rotate the generated 3D plane to match the roof outline points, while matching the perspective too, but I'm thinking this may be more complicated.

*Step 1 - Define roof oultine with points*

*Step 2 - Texture 3D plane with UV's mapped to maintain roof perspective based on slant defined in the 4 points*

Any tips on how to solve this?

# Answer
> 1 votes
If you map the UV coordinates of a square texture to that quad it will automatically give you the effect you're looking for.

In other words, map the texture the same as you would for the face of a cube;

```
Upper-left:  0, 0
Upper-right: 1, 0
Lower-left:  0, 1
Lower-right: 1, 1

```

Unfortunately, doing it this way will cause perspective issues because you're working with a trapezoid. See the Accepted answer here (Perspective correct texturing of trapezoid in OpenGL ES 2.0) for what else you'll need to do - which is provide a depth coordinate to your process;

> You need to provide more than a 2D texture coordinate to make this work - you need to provide a 3D (or rather, projective) texture coordinate, and perform the perspective divide in the fragment shader, post-interpolation (or else use a texture lookup function which will do the same).

Having said that, my gut feeling is that you would probably be better off just using a 3D square plane and rotating it backwards a bit, which will also solve your problem and not require any extra gymnastics.

---
Tags: rotation, uv-mapping
---


# Question
Title: LWJGL: loading textures of various types
I googled around a bit and nobody seems to have asked this question.

I have images in multiple color formats (all of them are PNGs). Most of them are ARGB but my bitmap fonts are gray scale, and I would like them to stay that way. All I want to do is find out what format `BufferedImage` uses to store my pixel data and then use that information with `glTexImage2D`. Java, in all its wisdom, seems to be determined to hide that information from me at all costs...

I also need to know how `BufferedImage` aligns its pixel data in both of these formats (`glTexImage2D` cares).

Could someone please tell me how to:

* Determine the pixel format of my `BufferedImage`. If it is ARGB32, I'm going to have to reorder the bytes and use `GL_RGBA`. If it's grayscale, I will be using `GL_INTENSITY`.
* Extract the actual bytes from the image. I have seen a few examples on the web that use `BufferedImage.getRaster().getDataBuffer()`. This is nonsensical. Why are there different types of buffers like `DataBufferInt`? Because of Java's strong typing, I need `DataBufferByte`. If this is the only way, could somebody give me specific directions to use the different type of buffers with `glTexImage2D`?
* Figure out how the aforementioned image data is aligned. I will use this information with `glPixelStorei`.

In addition, I come from C and C++ programming. In C this was 100 lines of simple libPNG and GL calls. Should I expect more trouble like this in the future?

# Answer
> 0 votes
It seems that BufferedImage does not keep that kind of information from the original PNG file. The type of the BufferedImage may or may not correlate with the type of the PNG. You can check the type of the BufferedImage with BufferedImage.getType(), which may help you, but the implementation of image loading is free to convert the images to other formats at will.

As you are comparing to C/C++ and libpng, I'll offer you an alternative solution. Use a similar low level library in Java as libpng. PNGJ: Java library for PNG encoding looks very promising. This gives you access to the actual PNG data instead of loading them to BufferedImages.

> In addition, I come from C and C++ programming. In C this was 100 lines of simple libPNG and GL calls. Should I expect more trouble like this in the future?

Yes, you should always expect trouble when expanding to unfamiliar areas. And you will learn a lot when you do encounter those. Respectively a Java developer who has used to passing BufferedImages always as just RGBA data to OpenGL would be annoyed for needing to write 100 lines of low level code for that.

From my own experience I can tell that the biggest issue when moving from C++/OpenGL to LWJGL was the need to use java.nio buffers instead of arrays. See https://github.com/LWJGL/lwjgl3-wiki/wiki/1.5.-Bindings-FAQ for more information. Once I learned that, the transition was pretty straightforward.

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


title: Loading models with opengl

text:
# Question
Title: Loading models with opengl
I'm developing a video game using OpenGL as graphic API and C++ programming language, and I'm creating all models with blender.

One question I have is how you deal with models (vertices), I mean, once you have created a model and want to load them with OpenGL you use hard-coded or a software module to load them on runtime?.

# Answer
## Loading:

To expand on what Sandalfoot said:

You must create you models in an external application, (Blender is popular and free, 3DSMax is free for non-commercial use) and then export them in a suitable format. There are many different model formats which target different things. Here are some:

* The Wavefront .OBJ format is very simple and easy to load, it is just a text based list of Vertices and Faces, with optional normals, UV textures and basic materials. The OBJ format is only used for static, non-animated models.
* The 3DS file format is binary format. This means that it is smaller and faster to load, but less intuitive. It is limited to storing 65536 Vertices. 3DS files can also be animated, but this is not as common.
* The DAE (COLLADA) file format is an XML based format. It is a free and open standard and can be animated. A bit complicated compared to .OBJ and .3DS but widely supported in many 3D packages.

If you are planning on writing your own importer for your program, then you should start with the .OBJ format. There are dozens of tutorials about loading .OBJ files with OpenGL and C++.

Alternatively, you can use a model loading library to load almost any model for you. ASSImp is a good one that supports .OBJ, .3DS, .DAE, and many more. This is the recommended path! Maintaining model loads in probably not your idea of fun, so you should use an external one.

## Protecting:

And as to encryption and model protection? If you're really into encrypting you models (this is called DRM) or hardcoding them (just... bad), it won't *still* won't work. Each model must be uploaded to the graphics card, unencrypted. The unencrypted models can be intercepted with a fake OpenGL library, or some other method my pure and unsullied mind cannot comprehend. :) It is impossible for you to secure your models so there are three (typical) ways of dealing with this:

* Copyright them and have a good lawyer on the payroll. Sue people who steal your models. This is what big game studios generally do.
* Copyright them and hope they are not stolen. If they are stolen, send a letter and/or a lawyer. This is what some indie game devs and small studios do.
* Put your models under one of the CC licenses (or another similar license) and *let people use your models* but require attribution and other terms. You get free publicity whenever someone uses your models! This is what I would do, and what many open source projects end up doing.
> 3 votes

# Answer
It depends. Generally speaking, yes; you will create your models in an external program (Blender, 3DSMax, etc.) and export them into a format that your game can read. Unless you feel like writing a parser for an existing format from scratch, though, chances are you will be able to find a library to load any kind of model format your software can export.

That's not to say you can't write your own format and then create plugins/libraries for your tools and code that reads and writes it (which I've done in the past), but unless you have a really good reason for doing it, don't waste your effort.

As to how to keep your assets "safe" from being exported by someone? You can't, so don't even try.
> 2 votes

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


# Question
Title: How to load chunks of 2d map segments when player reaches a certain point?
In my 2d platformer (made with Java and Slick2d), random maps are made by combining different segments together and displaying them one after the other. My problem is that I can't load too many segments or the game will run out of memory, so I want to load n number of segments at a time in chunks, then load the next chunk when the player comes near the end of one.

I've attempted to do this for a couple of hours now, but I just can't get it to work at all.

This is my chunk generation function where chunkLoad is the number of segments to load and BLOCK\_WIDTH is the number of blocks/tiles each segment is across. Chunk1 and map are arrays of segments.

```
Random r    = new Random();
for(int i=0; i<chunkLoad; i++) {
    int id  = r.nextInt(4)+2;
    chunk1[i]   = new BlockMap("res/window/map"+id+".tmx", i*BLOCK_WIDTH);
}
map = chunk1;
chunksLoaded++;

```

The map is then drawn on the screen like this. tmap is a TiledMap object and each block/tile is 16 pixels wide

```
for(int i=0; i<chunkLoad; i++) {
    map[i].tmap.render((i * BLOCK_WIDTH * 16) + (cameraX), 0);
}

```

I can successfully load new chunks, but I can't display them in the correct position, nor the hitboxes.

Any suggestions? Thanks.

# Answer
> 0 votes
Only display the squares the user will see. If your game 'map' is 100 X 100 and the user can only see 10 X 10, then there's no sense in displaying all 10000 squares. Here's some code that might answer your question or push you in the right direction:

```
public void draw()
{
    //Tile tiles[][] = new Tile[100][100]; // map array

    // player cords
    int playerX = 0;
    int playerY = 0;

    // display the map appropriatly

    int viewRow = 15;
    int viewColumn = 15; // 15 By 15 game board
    int tileSize = 10;

    int startX = (playerX % tileSize);
    int startY = (playerY % tileSize);

    int startRow = (playerY / tileSize) - 1; // -1 is for when the player is 'in between' tiles
    int startColumn = (playerX / tileSize) - 1;

    for(int row = 0;row < viewRow;row++)
    {
        for(int column = 0; column < viewColumn; column++)
        {
            int displayRow = row + startRow;
            int displayColumn = column + startColumn;
            // these are your row/column variables. This is where you would do your drawing.

            //ex
            //Rect rect = new Rect(row * tileSize - startX, column * tileSize - startY, ...);
            //canvas.draw(rect);

            //if you want to draw a specific tile or whatnot, you could do this:
            //canvas.draw(tiles[displayRow][displayColumn]);

        }
    }
}

```

That example is a little rough around the edges, but I hope it helped.

# Answer
> 0 votes
From your example, I assume you are making a 2D horizontal scrolling game.

If I assume your game scrolls from right to left (player moves toward the right edge of the screen), and that the CameraX value is 0 at the start of the game and increase when the player moves right, then your rendering code should be:

```
for(int i=0; i<chunkLoad; i++) {
    map[i].tmap.render((i * BLOCK_WIDTH * 16) - (cameraX), 0);
}

```

(I assume here that you're scrolling by redrawing your maps at an offset opposed to the Camera's offset).

That's a lot of assumptions, but there is a lot you're not telling about the way you handle things, so I'm just guessing.

Now about the way you dynamically load chunks of maps in a horizontal platform game: Your initial problem as far as I understand it is to not have all the maps in RAM, but only a subset, and load the new chunks when you need them. Here are a few consideration that may help:

* You don't want your camera to move continually to the right; The trick is to have a small number of "chunk slots" and to wrap the camera back to the 0 position when you reach your last chunk-slot.
* A commonly used trick is to render the last n-chunks (n being the number of chunks needed to fill your viewport) twice: once in the last chunk slots, and once in the first ones; This way, as soon as only those n slots are visible, you can warp the camera back to the first slots

Here is an example:

* The viewport (part visible on screen) is the red rectangle (and you need 2 chunks to fill it)
* We are using 5 chunk-slots (areas where a chunk can be rendered)
* The 5 colors show where are the chunk slots, while the black number is the ID of the chunk being rendered (or in your case, its position in the list of random IDs you selected for your level)

Some additional considerations:

* The minimum number of chunkslots needed is 2\*n (n being the number of chunks needed for filling your viewport) but it means every single chunk will be rendered twice
* The idea is to find the number of chunkslots which is reasonable depending of the RAM you can spare, and the number of double rendering

# Answer
> 0 votes
Maybe you should consider making a two dimensional array for the chunks, \[0\]\[0\] being the top left chunk of the map. That way you always know which chunks are surrounding the player and if the player reaches an end, you can put the first chunks next to the last ones, if you want to make the map loop.

---
Tags: java, slick, platformer
---


title: USB NES controller

text:
# Question
Title: USB NES controller
I just recently bought the Retrolink USB NES Controller.

I would really like to make simple platformer games (for PC - engine/ frame/ library doesn't matter) for this pretty popular retro controller. But **I can't find a website associated with the company** where I could find either **dev tool/ sdks** or a **library of existing games**.
Ever since I bought this controller I did nothing, but testing the buttons. - I didn't even find a game that supports it 100% and I don't own an NES.

# Answer
As others have explained, controllers (especially simple controllers like these) are supposed to work out of the box, with the standard input libraries of your operating system (DirectInput in Windows).

It seems like you're interested in knowing who makes these, so I tried a bit of google, and found that "RetroLink" is a registered trademark of a USA company called "Kool Brands LLC" registered in Reno, Nevada.

From what I could see in a low resolution scan of the back of another controller of the same brand, the bottom part barely reads "???????? and RetroLink ????? are trademarks of Kool Brands LLC", which corroborates this information.

They also seem to hold trademarks for "GameBully", "Robokit", "Exo-Guard", "Buck-Shot", "Retro gen" and "Sumoto". All game controller related.

They don't seem to have a website, but you can find more information about this company if you google them.

From what I see, they seem to be a tiny operation, probably solely a trademark holding company, and the RetroLink products are very likely rebranded generic chinese products.

I don't think they will have SDKs or other information like those you're looking for.

Googling a bit further, it seems like Kool Brands LLC is deeply involved with another company, which does have a website, called Innex. They sell RetroLink as well as other brands. If you have specific questions about the RetroLink products, they may be able to help you.
> 4 votes

---
Tags: controllers
---