# Question
Title: Unity Extending Game Object best practice
What is best practice when wanting to add to GameObject class?

I would like all GameObject to be able to change color IF they have a renderer. Ive tried using a helper class that takes a GameObject and lerps the color value but if i want it to have an update method it must inherit MonoBehaviour, and if it does inherit it then i cant instanciate that helper class.

Now im thinking about creating a new class that manages a GameObject and inherits from Monobehavoiur. It would have one GameObject as a member that it can manipulate. But then i would have to instanciate it from somewhere.

Hmmm unity has its logic but i havent found it yet. Is it clear what i am having problems with? Otherwise please ask.

# Answer
> 4 votes
Unity uses a **Component Base Object Management** approach. There's a famous article about it in Game Programming Gems 5.

In a few words suchs systems put the accent on **Composition over Inheritance**. Any object or type (in this case `GameObject`) is defined as a collection of `Components`, each one responsible for a specific domain. When you want to add functionality to an object, you'll add a `Component` instead of extending it. (a full exposition of CBOM is beyond the purpose of this thread, but search for it on the web)

So for what concern your question and unity patterns in general:

> Unity Extending Game Object best practice

The sentence above makes no sense. In fact you never extends GameObjects, but eventually MonoBehaviors that are Components (actually they inheritance chains is `MonoBehavior`-\>`Behavior`-`Component`).

> I would like all GameObject to be able to change color IF they have a renderer

I'd say you want to change the color dispkayed by every `Render Component` that has a `Material` that allows that.

> Ive tried using a helper class that takes a GameObject and lerps the color value but if i want it to have an update method it must inherit MonoBehaviour, and if it does inherit it then i cant instanciate that helper class.

Here you are on the right way. The only thing you are missing is how to extend an operation (`color lerp`) over multiple frames. In fact you don't need to rely on the `Update` callback (in a certain way it would even be wrong or at least inefficient). You should use a coroutine for that.

So you helper class simply becomes a method (for this I usually put a collection of static methods like this in a static class that act as my helper class):

```
IEnumerator LerpColorInSeconds(float sec, Material m, Color newCol)
{
  float t = Time.deltaTime;
  Color startColor = m.color;
  while (t < sec)
  {
    material.color = Color.Lerp (startColor, newCol, sec / t);
    yield return null;
    t += Time.deltaTime;
  }
  material.color = newCol;

}

```

when you need to lerp a color of a Material from inside a given MonoBehavior:

```
StartCoroutine(LerpColorInSeconds(1f, renderer.material,Color.black));

```

For more details on coroutines have a look here.

EDIT

Sorry for the mistake. StartCoroutine isn't a GameObject method but belongs to MonoBehavior. So for what concern your question on extension methods: in order to use StartCoroutine method you need a reference to a MonoBehavior. I don't think use an extension method is a particularly good idea here, btw you can't add an extension method to GameObject because it's not a behavior itself. If you want to extend MonoBehavior:

```
public static class Extension
{
    public static void LerpColor(this MonoBehaviour g, Color col, float lerpTime)
    {
        if (g.renderer != null)
        {
            g.StartCoroutine(LerpColor(lerpTime,g.renderer.material,col));
        }

    }

}

```

# Answer
> 0 votes
Two things that come to issues like this where what you want is essentially a base MonoBehaviour class with extra functions is to either:

1. Write extension methods for the MonoBehaviour class itself and use those to implement the color change effect. There is a very good explanation of such methods up on Gamasutra, so here's the link.(http://www.gamasutra.com/blogs/JoshSutphin/20131007/201829/Adding\_to\_Unitys\_BuiltIn\_Classes\_Using\_Extension\_Methods.php).

Essentially what you would be doing is creating 'extra' methods that a MonoBehaviour could use, and those functions could be called just like any other class function (placed in update or wherever you would want to call them). Such methods require that they are in a static class and then use a static method with a special reference parameter that refers to the class you're modifying.
2. Create a class that inherits from MonoBehaviour with a ChangeColor() method, and then inherit from that class for all of your other classes. Then you can call that function in Update or where you'd like. Probably the simplest to do.

As far as what you're having problems with, it seems like you don't quite have a grasp on the context of MonoBehaviours as far as their place in the Unity engine. Keep in mind that unless you're doing something that is completely data-specific that does not require *any use* of the MonoBehaviour functions like Start, Awake, Update, etc... (which means most GameObjects in any scene), you'll be deriving from it. If you're writing in javascript (unityscript) all of your scripts automatically derive from it and the large majority of your c# scripts will also.

http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.html

---
Tags: unity
---


title: Fast resource management

text:
# Question
Title: Fast resource management
So I'm working on one thing that I can't figure it out at this moment. Lets say that I have my all game data compressed into zip archive. There's a scripting system in the game that lets you to do some stuff. For example spawn npcs, equip specific items, etc.

Where's the problem? When I'm loading my world that is separated into chunks it's quite easy to load needed assets and other data without any notice. But lets say I write a script that triggers an explosion after a button press. In that moment game needs to load explosion textures, etc. Without separate threads, on slower system, the game would definitely freeze for some time. If I would use separate threads after all - on the slower system it may cause missing textures problem or something like that.

So it's quite easy to load up ahead some resources while loading world chunks, but how to foresee what resources should be loaded for objects that will be seen after script execution?

I don't know if it's possible to understand what I want to do, but I can give another example. In Bethesda's games like Fallout 3 or TES you can use spawn command that shows up constructed npc with all the textures right away. Any ideas how they load up textures and models so quick?

# Answer
> 1 votes
Don't load (heavy) ressources directly. Instead cache them and return the already loaded ressource if possible. Since you haven't specified any language or library, here's some pseudo code:

```
Dictionary<string, texture> loadedTextures;

texture getTexture(string filename) {
    texture tex = loadedTextures.find(filename);

    if (tex != null) // texture is already loaded
        return tex;  // return it

    // texture isn't loaded, load it
    tex = new texture();
    if (!tex.load(filename)) {
        log("Failed to load texture: " + filename);
        return default_texture;
    }

    loadedTextures[filename] = tex;
    return tex;
}

```

When done with everything, you'll just have to go through your map/dictionary and clear all members before tearing down your render context etc. for resource cleanup.

This can also be extended with stuff like object lifetime/reference couting, etc.

As for loading stuff so quick: I assume archives with those files are just hold in memory and loading some texture isn't that slow anymore, even on some older hardware.

Also using the code above it's pretty simple to create a short "preloader" that could even be fed by a text file:

```
void preload() {
    // This list could also come from a text file
    string[] preloadFiles = {"first file", "second file", "third file"};

    foreach(string f in preloadFiles)
        getTexture(f);
}

```

---
Tags: loading, assets
---


# Question
Title: Advantages and disadvantages of LWJGL for a beginner?
I am starting a 2D side scroller, tile based RPG sort of game in Java. I do have lots of knowledge in Java, so that's not a problem, but I have NO experience in game development, at all. I had found a couple of books / tutorials and I am trying to decide between using LWJGL or doing everything myself. What do you guys suggest?

Thanks!

# Answer
For a beginner? I can't see any advantage besides learning OpenGL (which is always useful).

OpenGL (and by extension LWJGL) is hard, does your game NEED the extra power you can get from OpenGL? If your goal is to make a game, just make a game and use whatever is the easiest/most simple tool. Don't waste time trying to understand OpenGL.

On the other hand, if making the game is not actually your priority, you just want an excuse to learn something new, try OpenGL. It is very powerful and you will learn a lot about what happens behind the scenes, but very little of your learning will be oriented towards making games.
> 1 votes

# Answer
I can only give you advice from experience but I suggest starting off by using Java2D (awt & swing libraries). By doing that you'll learn a lot of the basic core concepts which frameworks such as Slick2D and LibGDX do for you, such as creating the main loop, sub-pixel rendering, timesteps and so on. You'll also have to think for yourself when you get to creating tile based maps and more complex things, as there isn't much information that can spoonfeed you.

I would suggest using the LibGDX framework for a 2D side-scroller though once you've done the above, because of the features it inherits off the LWJGL.

Don't rush through things. Be a perfectionist. Then once you're confident, move on to 3D if you like. That might be a good time to use the LWJGL.

I think this might be a good question to read.
> 0 votes

# Answer
I created my first Java game (a 2d platformer) using just simple Java (I think the graphics tutorial was at "Thenewboston") and when it started to lag, it wasn't really difficult to switch to LWJGL. You won't need to chnage any game logic, but only the function that draws the sprites.
> 0 votes

---
Tags: java, lwjgl
---


# Question
Title: How can I get animated bone's transformation in LibGDX?
I am trying to get transformation from a bone, but i can't, I exported just a animated armature with just a bone from blender, then I converted to .g3dj, so I just need the bone transformations so that I can get it value for some effects like moving sprites and other things.

any ways to read just transformation in "render()" method, seems bones animation does not effect on bone's value! I want to use just openGL ES 1.x.

# Answer
> 2 votes
Well I finally found the solution, it was easy, I needed to get **AnimationDesc** from AnimationControl's animate method in Show() or Creation function

```
animationDesc = animationCtrl.animate("ArmatureAction", -1, 1f, null, 0.2f);

```

and here I can get the node's that animated and effected by animation

```
animationDesc.animation.nodeAnimations.get(1).node.globalTransform.getRotation;

```

note the "get(1)" here is refer to the second bone from the root.

---
Tags: java, 2d, animation, libgdx, character
---


title: Streaming resources

text:
# Question
Title: Streaming resources
I'm writing a game using the Slick2D library. I recently added a loading screen using deferred loading. I use the Music class to load OGG files to be used as music. These take an excessive amount of time to load. I looked on the wiki for more information on deferred loading. I found:

> No one resource should take so long to load that it keeps the screen from refreshing for a significant amount of time (if it does, then the resource should probably be streamed anyway :)).

So I altered my menu class as follows (this is just an example and I'm leaving out quite a bit):

```
public class MainMenu extends BasicGameState{
private Music[] theme = new Music[1];
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException{
    InputStream[] musicStream = {ResourceLoader.getResourceAsStream("/path/to/theme1.ogg")}
    try{
        theme[0] = new Music(musicStream[0],"path/to/theme1.ogg");
    }catch (Exception e){
        e.printStackTrace;
    }
}
(rest of class)

```

The music array is an array of `org.newdawn.slick.Music`

So I thought I'd done what would reduce loading time. However, when loading, it took just as long, but instead of showing a file as the current resource, it showed the stream.

I'd like to know how to do one or both of the following:

1. Stream a resource to reduce loading time as the wiki suggests.
2. Load only selected resources and load more when changing states (load the game music only when entering game state, etc.).

# Answer
I accidentally came across the answer.

```
public void init(GameContainer gc, StateBasedGame game) throws SlickException{
    try{
        theme[0] = new Music("path/to/theme1.ogg",true);
    }catch (Exception e){
        e.printStackTrace;
    }
}

```

Adding `true` after the file reference indicates that you want to stream the audio.
> 1 votes

---
Tags: java, slick, loading
---


title: I'm not sure why my shape is not moving

text:
# Question
Title: I'm not sure why my shape is not moving
So I am trying to teach my self how to my develop games with java by cloning older games. At the moment I am cloning Pong, and I can not figure out why my paddle is not moving. The move method should be updating the player paddle's position every frame, but is not. If someone can help me that would be great. Also any tips on code that I am using, that I shouldn't be would be appreciated as well! (I am somewhat new to this website as well, so please don't criticize me if I am using the wrong format or what not. I am just looking for help from a community that understands what they are doing more than I.)

Pong Class:

```
import java.awt.BorderLayout;

import javax.swing.JFrame;

public class Pong extends JFrame{

    public Pong(String title){
        super(title);

        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setFocusable(true);
        requestFocus();

        setLayout(new BorderLayout());
        add(new GamePanel(this, 35), BorderLayout.CENTER);
        pack();

        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args){
        new Pong("Pong!");
    }

}

```

GamePanel Class:

```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable{

    private static final int WIDTH = 1200;
    private static final int HEIGHT = 675;
    private static final Dimension SIZE = new Dimension(WIDTH, HEIGHT);

    private int targetFPS;
    private double period;
    private int currentFPS;

    public GamePanel(Pong pong, int fps){
        this.pong = pong;
        targetFPS = fps;
        period = 1000 / (double)targetFPS;

        setPreferredSize(SIZE);
        setMinimumSize(SIZE);
        setMaximumSize(SIZE);
    }

    public void addNotify(){
        start();
    }
    public void start(){
        if (animator == null || !running){
            animator = new Thread(this, "Animator");
            animator.start();
        }
    }
    public void stop(){
        running = false;
    }

    private Pong pong;
    private boolean running;
    private Thread animator;

    private double deltaTime = 0;
    public double getDeltaTime() { return deltaTime; }

    public void run() {

        long beforeTime = 0;
        long currentTime = System.currentTimeMillis();
        double totalTime = 0;

        initialize();
        running = true;
        while(running){
            beforeTime = currentTime;
            currentTime = System.currentTimeMillis();
            deltaTime = currentTime - beforeTime;
            totalTime += deltaTime;

            if (totalTime >= period){
                update();
                repaint();

                totalTime = 0;
            }
        }

        System.exit(0);

    }

    private Paddle player;
    private Paddle enemy;

    public void initialize(){
        player = new Paddle(1100, 100);
        enemy = new Paddle(100, 100);
    }

    public void update(){
        player.move(10);

        for (Paddle paddle : Paddle.paddles){
            paddle.update();
        }
    }
    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLACK);
        g2d.fillRect(0,  0, WIDTH, HEIGHT);

        for (Paddle paddle : Paddle.paddles){
            paddle.render(g2d);
        }

    }
}

```

And Finally, The Paddle Class:

```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

public class Paddle{

    public static ArrayList<Paddle> paddles = new ArrayList<Paddle>();

    private static final int width = 12;
    private static final int height = 120;
    private static final int velocity = 5;

    private Rectangle shape;
    private int xLocation;
    private int yLocation;

    public Paddle(int x, int y){

        xLocation = x;
        yLocation = y;

        shape = new Rectangle(xLocation, yLocation, width, height);

        paddles.add(this);
    }

    public void move(int i){
        yLocation += i;
    }

    public void update(){
        shape = new Rectangle(xLocation, yLocation, width, height);
    }

    public void render(Graphics2D g2d){
        g2d.setColor(Color.GREEN);
        g2d.draw(shape);
    }
}

```

# Answer
> 2 votes
First of all you should use paintComponent instead of paint (paint method is used by Swing it self. Avoid it in application code.) So first of all refactor the method of Pong this way:

```
public void paintComponent(Graphics g)
{
   super.paintComponent(g);
   ....
}

```

Moreover, the way you are trying to use thread is not correct and safe, at least for a Swing application. When you need to execute operations into a separate thread that interacts with the state of a Swing application you should use invokeLater or Timer.

So you should refactor your update method using timer:

```
int delay = 33; //milliseconds
ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      //here update the status of your game

      //refresh
      repaint();

  }
};
new Timer(delay, taskPerformer).start();

```

This should be enough. I don't see any other error. I suggest you to read some tutorials on how works painting in Swing, for example this.

---
Tags: java, game-mechanics, swing
---


# Question
Title: Is it possible to tell Unity3d to ignore part of its hierarchy?
One aspect of the game I'm making is each level is made up of room objects, which contain the sprites, physics objects and so on. When you enter a level the whole level is deserialsed and loaded into memory but only the room you are currently in is considered, nothing else is drawn, updated or whatever.

I was wondering how I would achieve this in Unity3d. I can imagine having a hierachry with lots of rooms with the various room contents as children, can I tell unity to ignore everything (for updating, drawing, physics and so on) in the hierarchy but the current room and its children?

# Answer
> 5 votes
Several ways:

1. **Groups the objects on a per-room basis**. Each room has a root `GameObject` that you should **enable** only when you enter in it (or are next to it), and **disable** the room you were coming from. Maybe it's easier method, but you will load in memory all the room even if only the active one is rendered (if you haven't too much rooms it should be acceptable).
2. Use occlusion culling to limit the rendering to non-occludee objects. You still have all objects load into memory, but unity takes care to decide what to render and what not, based on its visibility.
3. Use a **different scene for each room**, and load(load additive)/unload scene(rooms) when you no longer need them. This generally should reduce the memory footprint, but can create a bit of garbage to be collected, so it may be a little more tricky do handle properly.

---
Tags: unity
---


# Question
Title: How to march tiles together like in Terraria?
I've been trying to get tile marching to work like in Terraria, and I got something to work. I don't think it's actually very good way of doing this, so I'm wondering what would be really the main way of doing this.

Here's a picture of what I want to accomplish:

As you can see, this really does the thing that I want, but it's so horrible looking and it'd be a pain to extend for different types of tiles.

Here is my code for this. I coded this as a test, so my full game would use tile classes etc.

```
for x, tile in enumerate(row):
    if tile:
        try:
            air = row[x + 1]
        except Exception:
            pass
        else:
            if not air:
                if not LEVEL[y - 1][x]:
                    tile = 3
                else:
                    tile = 6
        air = row[x - 1]
        if not air:
            if not LEVEL[y - 1][x]:
                if tile == 3:
                    tile = 5
                else:
                    tile = 4
            else:
                if tile == 6:
                    tile = 8
                else:
                    tile = 7
        LEVEL[y][x] = tile
for y, row in enumerate(LEVEL):
    for x, tile in enumerate(row):
        if LEVEL[y - 1][x] in (6, 3, 14):
            try:
            pos = LEVEL[y][x + 1]
        except Exception as e:
            print(e)
        else:
            if pos in (2, 3):
                LEVEL[y][x] = 11
    if LEVEL[y - 1][x] in (7, 4, 15):
        pos = LEVEL[y][x - 1]
        if pos in (2, 4):
            LEVEL[y][x] = 12
    if LEVEL[y - 1][x] in (5, 8):
        if LEVEL[y][x] == 1:
            LEVEL[y][x] = 13
    if LEVEL[y][x] == 6:
        if LEVEL[y][x - 1] in (2, 4):
            LEVEL[y][x] = 14
    if LEVEL[y][x] == 7:
        try:
            tile = LEVEL[y][x + 1]
        except Exception as e:
            print(e)
        if tile in (2, 3):
            LEVEL[y][x] = 15

```

The basic idea behind this is just to look for some air and dirt, and set the tiles image from those.

Basically then when I'm drawing this I just take the value at a coord and blit the corresponding image to the screen.

So how would I go about making this as readable and easily extendable as possible? Does anyone know how Terraria handles this?

# Answer
> 8 votes
If I understand right, your map stores whether something is dirt or air, and the simplest thing would be to have dirt and air tiles. However, to make things look better, you have separate images for air above dirt, dirt above air, dirt left of air, and so on. So you're trying to figure out which image to use, given a tile and its neighbors. Is that right?

If so, take a look at one of these articles:

---
Tags: python, terrain, pygame, tile-bitmasking
---


# Question
Title: How to code camera for layered map in unity
For a current unity project I need a layered map like in Dwarf Fortress. The game will take place in a 3D city enviroment and the camera should be 'snapped' to layers. So there will be (for example) a cave layer, ground layer and floor 1 - 3 layer. The player should be able to navigate the camera up and down with a keypress. So if the player is looking currently at the ground layer and press + the camera should snip to floor 1 layer. All layers below the current level will be blurred and all levels above wont be visible (or at least faded out very strong)

My question now is: Is the layer system of unity useful for such a scenario, or is it better to implement an own data structure? I know about the ability of ignoring layers for rendering and raycasting but can the system be extended to support the features described above?

# Answer
I would think using multiple cameras + layers would be your best bet/most flexible.

Each camera can use it's own `Culling Mask` property to render only selected layers. Using multiple cameras should allow you to apply effects (such as blur) only to selected layers, and using `Normalize Viewport Rect` you can control where each camera 'draws' to the screen.

So, when a player moves up or down a layer/level you would:

* Disable cameras above the player
* Adjust each cameras `Normalize Viewport Rect` to center the current layer on screen
* Blur the layer below current layer

Also, in this scenario, where each camera has its own layer/level, each camera can be set to a different `Depth` which affects its rendering order.
> 2 votes

---
Tags: unity, camera, layers
---


# Question
Title: Is there a game engine that does not use D3D or OpenGL?
Is there a game engine that does not use a graphics API such as OpenGL or DX? I want a simple 2D game engine for use in my simple game console.

# Answer
> 5 votes
Allegro 4.x is probably the closest you're going to get to this. It has pure software blitting for 2D sprites. Granted, it will still need to use DirectX to draw to the screen, but that would be more or less true for anything.

That being said, you said this:

> i want a Simple 2D GameEngine for use in my simple game console.

This statement suggests that you equate software rendering to "simple". This is not the case.

There's nothing inherently complex about using OpenGL or D3D to do 2D rendering. Indeed, the whole purpose of using a game engine is to *abstract* the details away, so that you don't directly have to do any of that stuff. You don't have to care about OpenGL or D3D code to use Allegro 5 or SFML; they handle all of that transparently.

So really, just use a good engine; don't bother yourself about the minor details.

# Answer
> 1 votes
Running without a graphics API is not necessarily simpler. In fact what you're talking about here is a software rasterizer, which is going to be orders of magnitude more complex than using a graphics API. It will also be custom code so if you hit any problems with it you won't be able to get help as easily.

# Answer
> 0 votes
First-part Answer: id Tech 1 (aka DOOM engine)

Second-part Answer: A simple 2D game is a fun way to learn. Go ahead :)

---
Tags: 2d
---


# Question
Title: Does a game engine affect the quality of pre-baked Global Illumination?
If I were to pre-bake Global Illumination into light maps using a high quality renderer like Mental Ray or PRman, and loaded it into two different engines such as Unity and Unreal, **would there be a noticeable difference in quality?**

If there is a difference, could you give me a few examples of engines that are better at it than others?

# Answer
> 2 votes
As long as color space is handled properly in each engine and you do not use any of the engines lighting effects, they will be the same.

Dynamic effects such as SSAO will cause there to be a noticeable difference if you use the engines to their fullest.

---
Tags: global-illumination
---


# Question
Title: Error while reading TGA file and doing Texture Cube map
In my program, i read a TGA file with a function like this:

```
char* LoadTGA(char* filename, int* width, int* height, int* bpp);

```

As you can see, this function: return a char array of image data (without TGA file header, from the first pixel row of image to the last pixel row of image), width of TGA image, height of TGA image, and bits per pixel of image data. The part of code that read image data is this:

```
    int w = pHeader->width; //width of image
    int h = pHeader->height;  // height of image
    int rowSize = w * pHeader->bits / 8;   //The bit is bits per pixel
    bool bInverted = ( (pHeader->descriptor & (1 << 5)) != 0 );  //My TGA image is not inverted so bInverted is false.
    for ( int i = 0; i < h; i ++ )
    {
        char * pSrcRow = pSrc +
            ( bInverted ? ( h - i - 1 ) * rowSize : i * rowSize );
        if ( pHeader->bits == 24 )
        {
           for ( int j = 0; j < w; j ++ )
           {
               *pDest ++ = pSrcRow[2];
               *pDest ++ = pSrcRow[1];
               *pDest ++ = pSrcRow[0];
               pSrcRow += 3;
        }
    }
}

```

As this code show, for my TGA image, which have bits per pixel (bpp) equals to 24, not inverted, the return char array will be from the first pixel row of image to the last pixel row of image.

I read a image of 512 x 384 pixels like this image below:

I use this image for texture cube so i read 6 parts of this image in following function:

```
bool Texture::SplitTextureCube(int i, char* des)
{
int l, m, size = width/4;
int aTopLeft[][2] = {{size*2, size}, {0, size}, {size, 0}, {size, size*2}, {size, size}, {size*3, size}};
int rowSize = height * bpp / 8;
for (int j = 0; j < size; j++ ) //height
{
    char * pSrcRow = imageData + (aTopLeft[i][2] + j) * rowSize + aTopLeft[i][0];
    if ( bpp == 24 )
    {
        for ( int k = 0; k < size; k ++ )   //width
        {
            *des ++ = pSrcRow[0];
            *des ++ = pSrcRow[1];
            *des ++ = pSrcRow[2];
            pSrcRow += 3;
        }
    }
    else
    {
        for ( int k = 0; k < size; k ++ )
        {
            *des ++ = pSrcRow[m + 0];
            *des ++ = pSrcRow[m + 1];
            *des ++ = pSrcRow[m + 2];
            *des ++ = pSrcRow[m + 3];
            pSrcRow += 4;
        }
    }
}
return true;
}

```

This function is called as below:

```
 char *face = new char[width/4 * height/3 * bpp/8];
    glGenTextures(1, &textureId);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureId);
    for (int i=0; i<6; i++)
    {
        SplitTextureCube(i, face);
        glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X+i, 0, GL_RGB, width/4, height/3, 0, GL_RGB, GL_UNSIGNED_BYTE, face);
        //glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X+i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
    }
    delete [] face;

```

I guess you need no more explain. The problem is when my program running, my cube texture is disordered like this:

I sure that problems are inside my "SplitTextureCube" function, i sure that i read pixels in the wrong order, please help me fix that function.

# Answer
I've solved it. Here is the right code for "SplitTextureCube" function:

```
bool Texture::SplitTextureCube(int i, char* des)
{
int size = width/4;
int aTopLeft[][2] = {   {size * 2 * bpp / 8, size},     //0
                        {0, size},                      //1
                        {size * bpp / 8, 0},            //2
                        {size * bpp / 8, size*2},       //3
                        {size * bpp / 8, size},         //4
                        {size * 3 * bpp / 8, size}      //5
                    };
int rowSize = width * bpp / 8;
for (int j = 0; j < size; j++ ) //height
{
    char * pSrcRow = imageData + (aTopLeft[i][1] + j) * rowSize + aTopLeft[i][0];
    if ( bpp == 24 )
    {
        for ( int k = 0; k < size; k ++ )   //width
        {
            *des ++ = pSrcRow[0];
            *des ++ = pSrcRow[1];
            *des ++ = pSrcRow[2];
            pSrcRow += 3;
        }
    }
    else
    {
        for ( int k = 0; k < size; k ++ )
        {
            *des ++ = pSrcRow[0];
            *des ++ = pSrcRow[1];
            *des ++ = pSrcRow[2];
            *des ++ = pSrcRow[3];
            pSrcRow += 4;
        }
    }
}
return true;
}

```
> 0 votes

# Answer
I spotted a couple of problems with these two lines in `SplitTextureCube`:

```
int rowSize = height * bpp / 8;
...
char * pSrcRow = imageData + (aTopLeft[i][2] + j) * rowSize + aTopLeft[i][0];

```

They should be:

```
int rowSize = width * bpp / 8;
...
char * pSrcRow = imageData + (aTopLeft[i][1] + j) * rowSize + aTopLeft[i][0];

```

Also, in that function you have `l` and `m` variables that are never initialized, but `m` is used as an offset in the 32-bit case, which is presumably not intended.

That's surely contributing to the problem. Beyond that it's possible you'll have to rotate some of the faces as well as cropping them out of the horizontal cross image. I don't know off the top of my head which faces need to be rotated which way, but it should be obvious once the above problems are fixed.
> 0 votes

---
Tags: c++, textures, opengl-es2, cubemap
---


title: Unity Extension method with coroutine

text:
# Question
Title: Unity Extension method with coroutine
Is it possible to have extension methods that starts coroutines? Id like to have an extension method for the GameObject that checks if itself has a renderer and a material and then lerps the color to a target color.

# Answer
I can't think of a way to do it. Since extensions are static and they cannot inherit the `MonoBehaviour` that contains the `StartCoroutine` methods.
> 1 votes

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


title: IOS monogame 17 seconds debug timeout

text:
# Question
Title: IOS monogame 17 seconds debug timeout
I'm trying to debug a monogame application using xamarin studio and breakpoint. Is it possible to disable the 17 seconds timeout on the FinishedLaunching function?

# Answer
> 0 votes
No, it's not possible.

What you can do is to add a timer for whatever you want to debug so that it happens after FinishedLaunching has completed.

---
Tags: ios, monogame, mono, monotouch
---


# Question
Title: How to show other characters in online 2D rpg
I have Player 1 and Player 2

I am using Json to send and retrieve player data between the client and the server, but when another player logs in, and is in the same map, how would I send that data to both players to update the graphics engine to show there are 2 Players on the map?

About my game

* it is a 2D RPG tile based game
* it is 24x15 Tiles
* it is Real time Action
* it should interact anywhere between 10-150 ping
* players interact with each other when in the same map and can see each other moving around
* the game world is persistent, and is saved when the server shuts down

Right now the server just sends the player Only their information which is inside a Json Object

Here is an example of what I am talking about

If you notice there are 2 separate characters in 2 separate clients, but they are running on the same server. I am trying to get them to show up on both clients, but I don't know how I should accomplish this. Should I send it as an added value in the Json object?

Also what is the name of this process so I can look it up and find more info on it?

# Answer
> 1 votes
There are a lot of ways to achieve it. You can achieve it by sending the connected players as an array of players **or** as an added value in the json object ( player1, player2, .... ) along side with the number of connected players.
Also if you want speed you should not use Json because Json stores objects in a text format thus making the data exchanging between client and server bigger, but it is fine for prototyping.

---
Tags: java, client-server
---


# Question
Title: Should I use an arraylist to store client connections
I am running a server, and I have an arraylist of clients.

When a client connects, I create a new object in the arraylist(all running on their own threads)

When a client disconnects, the server closes the Socket. And the thread terminates

My problem is when a client disconnects, it closes the Socket, but it doesn't delete its spot in the arraylist, and shift everything down one. So the arraylist is constantly growing bigger.

What can I do/use to fix this problem?

*I will update with more detailed information/code if need be.*

# Answer
> 3 votes
You should catch the close event ( it is trivial to do in the client thread (that lies on the server) that is listening from the client ) and remove the client from the ArrayList. You could also use a LinkedList in order to make the removal of a client faster.

# Answer
> 1 votes
Weather you can "simply" delete your record in the connection "array-list" depends on how you use it. Especially, if you store and use the index to connections in the array-list somewhere, you must make sure to update them too. Those will change if an item is removed from the list.

Instead of referencing by index you should reference by a direct reference to the connection thread object. But you should implement a mechanism to tell holders of a reference, when it's getting invalid... You could use a callback function for this purpose, that must be given when acquiring a reference to the connection. This callback is then stored in a list inside the connection thread object and the callbacks of all reference owners is called, when the connection closes. This way all objects can safely remove the reference and react accordingly, before the connection reference is finally removed from the connection "array-list".

Note, that we cannot give you more detailed answers until you give us more detailed information about your problem.

---
Tags: java, server, data-structure
---


# Question
Title: Is my calculation of chances correct for my AI?
I'm working on a turn based game where one part is pretty much like playing "Memory": remember where a specific card is located in a grid.

My AI works like this:

* If a card is peeked (turned around and looked at) -by the player or AI - the AI remembers the location of this card 100%.
* If the next card is peeked, a "dementia" factor will be applied to all the previous remembered cards. This means, card one is now only remembered with 80%, card two with 100%.
* This information is kept in an array. Over time, chances to remember a card location decreases.

Now in order to figure out if the AI remembers a specific card X, I get the chance for the card X from the array, let's say the chance is 60%, or 0.6.

I then generate a random float number between 0 and 1. If the random float is lower than or equal to 0.6, I let the AI remember the location.

Is this a valid approach? I'm assuming here that the randomization in .NET is uniformly distributed.

# Answer
> 1 votes
Yes it is. What you described is the standard way of determining if an event which happens with X% probability occurs for any given trial.

# Answer
> 1 votes
Your approach is quite good. But, doesn't completely simulate "everything" that a human player would be like. So, if you want to simulate a human player, you should try to think about the following:

"Remembering" a cards position isn't like true or false. Remembering it "correctly" is of course be true/false. But, forgetting about a card is more like losing accuracy about its definite location. So you'll be able to remind the "region" where it has been, but this region grows with time. This "reminding model" also simulates the following effects: If a card is at the border or in one of the corners, you'll remind it better. The region grows (imaging a circle around the cards center increases) but there are no cards at the outside, so the probability is higher to turn the correct card. This also applies, if a card is isolated (many other cards next to it have already been removed).

Your approach still also lacks the fact, that your rate of forgetting becomes less, if the number of cards on the table reduce.

I would apply the following algorithm:

Cards in memory are stored as exact position (when last turned) and a variance. Assume a Gaussian distribution of the remembered card location. So when trying to turn the card, calculate the chance for each card to be turned by the Gaussian distribution. Then calculate the sum off all probabilities and divide the probabilities by that sum (so the sum of them is 1 == 100%).

Then choose a card by generating a float between 0 and 1.0 and iterate through all cards. For each card, reduce the random value by the probability of the current card and check if the value is below 0. If the value becomes lower than zero, take that card.

The probabilities above can also be used for "planing", that means: The AI can "guess" in advance how well it remembers the location of a card (probability to take the correct one). If it needs to turn two matching cards, the probabilities need to be multiplied. This way, the AI can choose the cards with highest probability to be reminded correctly.

The formula for the Gaussian distribution can be found at: http://en.wikipedia.org/wiki/Normal\_distribution

As the distribution is 2-dimensional use: f(delta\_x)\*f(delta\_y) for the probability. You can assume the average to be zero, if you use the relative position to the real position. This way the only parameter to the function is the offset and the variance.

---
Tags: ai, random
---


# Question
Title: Choosing a heuristic function for RPG character's AI
I am designing an AI for mouse and cat. So they have HP, and cat will chase and eat mouse, mouse will eat cheese. This eating action will help them to gain HP. If they can't eat food, they will die if they use up all the HP.

So I searched through books and I have a basic algorithm for this.

```
def chooseAction(actions, goals):
  # Go through each action, and calculate the
  # discontentment.
  bestAction =  actions[0]
  bestValue = calculateDiscontentment(actions[0], goals)
  for action in actions:
    thisValue = calculateDiscontentment(action, goals)
    if thisValue < bestValue:
      bestValue = thisValue
      bestAction = action
  # return the best action
  return bestAction

def calculateDiscontentment(action, goals):
  # Keep a running total
  discontentment = 0
  # Loop through each goal
  for goal in action:
    # Calculate the new value after the action
    newValue = goal.value + action.getGoalChange(goal)
    # Get the discontentment of this value
    discontentment += goal.getDiscontentment(value)

struct Goal:
  value
  def getDiscontentment(newValue):
    return newValue * newValue

```

This algorithm is quite easy to understand, and quite easy to implement.

So I have to determine Goal and goal value for each action they take.

Let say a mouse, He may want to move, eat.

So I have to come up with a value(wiliness) for these values.

What is a good way to determine these values?

My approach is here.

Ley say my mouse have a view range of 3 cells and it can only walk in four directions up down left and right.

The goal eat value may determine by its MAX\_ENERGY and NOW\_ENERGY and I come out a formula eatValue = MAX\_ENERGY - NOW\_ENERGY. This make sense because, it NOW\_ENERGY is equal to MAX\_ENERGY, my mouse has a wiliness 0 to eat.

What is a good way of come out this simple formulations? What will be the good heriustic for my mouse to move?

# Answer
You may want to add some more formulas and weight them. e.g.: *Mouse want to escape cat*, *mouse want to eat* and *mouse want to roam around randomly*. You an now weight these three formulas and then calculate the actual values for each goal. If you want to make it a bit more random you can choose to select the action from these goals with a semi random algorithm, wheel-of-fortune-selection for example:

```
wof=0;
foreach goal
  calculate goalPower=goalValue*weight;
  wof+=goalPower;
picked=random(wof);

```

So lets say the mouse want to:

* escape the cat in every case (weight=10)
* likes eating a lot (w=5)
* roam around if there is nothing to do (w=1).

Lets imagine a situation where the cat is 3 cells away and the mouse has 6 energy left (from 10):

```
eatPower=(10-6)*5=20;
escapePower=(3)*10=30;
roamPower=(1)*1=1;
wof=51;

```

Now you pick a random number between 0 and 50 and then choose the corresponding action *(0-19 eat,20-49 escape,50 roam)*

I hope this idea get you started
> 2 votes

# Answer
Note: To optimize your values, you can simply use the "survival of the fittest" method. Some basic approach of the evolutionary algorithm. To do this, simulate some mice and some cats (e.g. 10 mice, 2 cats). To optimize values for the mice, simulate until 50% of the mice died or some maximum time has passed. Choose the fittest of them (e.g. look at their Health Points) and duplicate them. Slightly modify the values of the duplicates (=mutation) and put them all again randomly onto the map. And repeat this for some hundred times ("episodes"). Do the same for the cats...

Your parameters will then automatically adapt to the optimum. You'll see, that there are different optimal values for a different environment (e.g. less/more cheese, less/more cats, bigger map size)
> 1 votes

---
Tags: ai
---


# Question
Title: How to choose inputs to an artifial neural network?
I have to implement, as part of an assignment, a learning method that enables minesweepers to avoid colliding with mines. I have been given the choice to choose between a supervised/unsupervised/reinforcement learning algorithm.

I remember in one of my lectures, the lecturer mentioned ALVIN. He was teaching artificial neural networks.

Since the behaviour I'm looking for is more or less similar to ALVINN's, I want to implement an ANN. I've implemented an ANN before for solving the 3-parity xor problem, here's my solution. I've never really understood the intuition behind ANNs.

I was wondering, what could the inputs be to my ANN? In the case of the 3parity xor problem it was obvious.

\[EDIT\]

The game is not minesweeper. However, it has bots which look like battleships which we refer to as minesweepers. Please see the screenshot below. The goal is for the battleships aka minesweepers to move in one direction each but should learn to avoid mines over time.

# Answer
> 3 votes
The inputs are specific to the function of the learning algorithm. You need to analyze the requirements of your assignment to find what inputs are required.

In this case, you want to give your algorithm all the information a the minesweepers have at their disposal.

If each minesweeper has the distance to the nearest mine (but not the direction), then you'll need to use the information provided from multiple minesweepers to attempt to triangulate the position of mines. While avoiding the mines is a good goal, it seems like it should also be important to *find* the mines (they are minesweepers after all). Once a mine position has been triangulated, you can flag it as found and it can be easily avoided.

So, on top of avoiding mines, you should also (in some cases) steer towards mines. The reason you may want to steer towards mines is to help triangulate the position of a mine that's in the area.

For simple avoidance of mines, you can simply detect if you're getting closer to a mine on each iteration. If you're getting closer, turn in a random direction and move forward. Continue until the distance between the minesweeper and mine is increasing.

# Answer
> 1 votes
What kind of "simulation" are we talking about? Is this a grid based "board", where each mine and each "minesweeper" is located at a tile of the map? Or do we speak about a continous map, where you have objects and positions.... movements in continous angles (not just 90-degree north, east, south, west...)?

Also: Do the minesweepers have a "goal" (e.g. reach some location on the map)? They actually should have, or they could just stay where they are or move forward-backward (or in a small circle).

If you have a grid based board you can use the relative "view" on the map of you minesweeper as the input. This means one input neuron for each tile location relative to your minesweeper, which is 0 if there is nothing and 1 if there is a mine. Then there should be some input neurons that represent the planed direction. And the output should be the expected result of choosing that direction.

If you have a continuous simulation, you should use the relative distance (x,y) of the nearest mines as an input. So there should be 2 input neurons per mine the minesweeper is aware of. All unused inputs (no more mines in sight) should be set to infinity (huge value). Or you should have a third input neuron for each "mine in sight" slot that is 0 when it's unused or 1 if the other two inputs really point at a mines location. One input should then be the supposed planed angle in which the movement is to be continued.

For both simulation types, two input neurons should be reserved for the -relative- location of the goal which the minesweeper is supposed to reach.

The desired output is then designed to be "high" (1) of the solution is optimal and "low" (0 or -1, depending on activation function) for a bad solution (planed direction leads to problems).

How your desired output looks like depends on the kind learning you are implementing.

1. Observed learning (by giving samples): Generate a lot of random situations. Calculate (or manually choose) your optimal solution. For a grid bases simulation you can use the A\* algorithm to find the optimal route to the goal. Then, use the first step in the path as desired output.
2. Unobserved learning: Train your network with reinforcements as: a) how much nearer (good) / farer (bad) it moved to the goal; b) weather it hit a bomb (very negative).

If your algorithm is to be "explorative" (the goal is somewhere, but the minesweeper does not know where), finding a goal should have a positive reinforcement and visiting the same location more than once should have a negative reinforcement.

Also: Think about explaining your problem more detailed. This seems to be a common problem of your questions... Really describe what kind of "rules" exists. For example: If you think it can be done well with Neuronal Networks, but you are free to use any machine learning algorithm you like, state this! What are your minesweepers supposed to do except for avoiding bombs? Else, they can just stay where they are = goal reached. Shall your minesweepers learn by examples given? Or shall they find out by trial and error (just given the result of their actions) = reinforced learned?

---
Tags: algorithm, ai
---


title: Assigning tasks

text:
# Question
Title: Assigning tasks
---

In an RTS where workers are tasked e.g. build wall, how do the workers decide which walls to build?

The player decides which walls are to be built where, but they don't assign individual workers to individual wall squares. In many RTS games, workers simply do tasks that are near them, but in my RTS I want to use the strategic doing of explicit tasks on specific squares as the main strategy, so I don't want dumb workers clustering somewhere and leaving tasks further away not-done.

I use the example building wall; it could be mining stone, making a road, collecting wood or whatever. The key thing is the user picks where, but not who.

Workers can only work on squares that are adjacent to accessible squares; the squares they work on themselves may be impassable until work is complete.

Workers 1 and 2 are told to mine squares A,B,C and D.

They can move one square per game-tick, and mining a square takes 10 ticks.

How do you decide which worker mines which square?

It seems self-evident that 1 should mine A and 2 should mine C.

1 is 4 squares away from A, so will have finished mining it in 14 ticks. Where should 1 go next, and why?

And what if there was another square - E - to be mined directly above B?

What is the logic that a worker uses to decide where to proceed next?

# Answer
Mark the resource node as busy, or limit the number of workers a tree can be used by. If a worked is assigned to gather at a certain point, what you are really telling them to is to harvest the closest available tree.

Two main paths for this: A realistic approach would be to evaluate and mark resource noes before they arrive. To prevent weird queuing issues, give workers a vision range to evaluate trees. This allows the worker to approach a particular resource node while walking to the patch. This gives a limited about of optimization.

However, many RTS's (SC and SC2) don't have workers evaluate a node until they arrive. This leaders workers to wander around until a resource node is found. This allows for more skill/optimization reward, (Ever see awesome worker splits?) However, most of your players are just going to box all, click, and be annoyed that they all go the same location first.

The exact implementation will vary based on how resources are grouped. In AoE trees and fish are continuous expanses, so gatherers might end up quite far away as the game progresses. But in games like SC and Red Alert resources are located in discrete patches. So a worker only has to look around that particular patch.

EDIT after your edit: Don't stress too much over worker inefficiencies. Any RTS I can think of has worker inefficiencies. Things like worker splits arise from the player being better at managing their workers than the game. I think you may be taking a programmers perspective at this and not a designers. The singe tick left issue can be worked around just by tweaking numbers and having nodes be harvestable in a discrete number of trips. Worker inefficiencies are glaring to you, because you know the system behind it. However, if your play testers don't notice then don't dwell too long.
> 6 votes

# Answer
Solution and a thought:

Solution: You could have the gathering nodes be placed in a queue when clicked, then as a job rises to the top of a queue, find the weighted task queue value for the workers then find the nearest neighbor with the best weighted task queue value (queue value).

In your example, you could have the optimal queue value be 0 (implying no current tasks). Add 1 to the queue value for each square they would have to travel (travel time) and 10 for each task (time to do the task). Remove 1 from each worker's queue value for each unit of time that passes (if starting queue value is 10 then after 3 units of time the queue value would be 7). Then you find nearest neighbor (in the event multiple workers have equivalent queue values) to find the worker that should do that task.

So for your example, assuming the gathering nodes pop from the task queue in alphabetical order (A-D) and no movement is done while queue pops:

```
(values in format [total] = [preexisting value] + [current task distance])
A Pops:
    queue value of 1: 4 = 0 + 4
    queue value of 2: 19 = 0 + 19
    Assigned to 1.
B Pops:
    queue value of 1: 24 = 14 + 10 (distance to B from A)
    queue value of 2: 9 = 0 + 9
    Assigned to 2.
C Pops:
    queue value of 1: 25 = 14 + 11
    queue value of 2: 20 = 19 + 1
    Assigned to 2.
D Pops:
    queue value of 1: 36 = 25 + 11
    queue value of 2: 41 = 20 + 21
    Assigned to 1.

```

Downside to doing it like this: highly computational.

---

Thought:

How is your game going to handle being blocked by resources? i.e. if there exists a 4x4 grid where every node is a resource, can workers get the inner 4 nodes? If not, make sure the workers don't just idle there trying to get to them, but maybe assign them a different task and assign one of the workers gathering one of the outside nodes to the inner ones once the outer node is complete (put it in a task queue for the worker).
> 2 votes

# Answer
try having some weight system, that if the tree is being collected, calculate some sort of stacking penalty and also some sort of distance bonus. ( how long does it take to get from point A-\>B with the wood, and so on. then you can do some algorithm that does check for the closest wood, and check it´s weight, and then comparing if it´s desirable. and then use the one with the lowest weight.

of course this requires some fine tuning. but the idea is simple.
> 1 votes

# Answer
Each job should have a) an importance b) assignment status (# of workers assigned)

A worker could then decide for the job that gives him the most "reward" per time. The reward is calulated by the importance divided by the number of workers assigned divided by the time he needs to invest (walking and doing the job). If your worker can specialize on jobs (e.g. wood chopping) they will actually prefer tasks they can efficiently do. Jobs should of course only be assigned, if they can be continued at the right moment (e.g. resources needed must be available).

To avoid having some jobs undone for long time (e.g. because its far away). The importance should increase with time. In case of harvesting the importance should also be dependent on how much resources of that type are available / needed at the moment (e.g. produced units divided by unit requested in a give period).

To avoid workers to change their job to quickly, let them only change their current job, if the reward gets significantly better (by a given threshold). Also you could apply the doubled costs for the initial walking to the job, when calculating the reward per time values. Furthermore, you should let recalculate the workers optimal job one after each other, not all at the same time.

Additionally, add some randomness to the calculated rewards. This will cause a better distribution of the workers to different jobs (this way they do not just "all" go to do the same job). But, this effect is already reduced by serially recalculating the next optimal job for a worker and adapting the number of workers already assigned (more workers on the same job reduce the expected reward).

The algorithm maybe needs to be adapted a bit, if your jobs can only be assigned to one worker. If this is the case do the following: A worker chooses the job with highest reward per time (importance divided by individual time needed). If another worker can do the same job with a higher expected reward per time, he kicks off the currently assigned worker. The new "unemployed" worker then tries to find another job. In your example this could be like this:

* "C" has a very high importance. And worker 1 assigns itself to "C", even he's farer away.
* Worker 2 is assigned next and has a higher reward per time for "C" (less walking). So it kicks worker 1 off the job and assigned itself to "C". This did not cost time, as we are still within the same simulation time slice. So the user will not see this reassignment of the job.
* Worker 1 is then looking for another job. Worker 1 doesn't kick off worker 2 from "C", as his reward per time isn't better. So he is assigned to "A" or "B" (depending on importance). Again, this is still within the same simulation time slice.
> 1 votes

---
Tags: ai
---


# Question
Title: How stencil buffer and glFrontFace help making a shadow?
I'm trying to understand the tutorial 27th in Nehe website. This is about how to cast a shadow of an object using stencil buffer in OpenGL. The idea here is checking the directions of all the faces of the object with the direction of light, and the result will define whether or not this face make a shadow. In the case of making a shadow, we will draw "shadow" into the stencil buffer as the following code.

```
// First Pass. Increase Stencil Value In The Shadow
glFrontFace( GL_CCW );
glStencilOp( GL_KEEP, GL_KEEP, GL_INCR );
doShadowPass( object, lightPosition );
// Second Pass. Decrease Stencil Value In The Shadow
glFrontFace( GL_CW );
glStencilOp( GL_KEEP, GL_KEEP, GL_DECR );
doShadowPass( object, lightPosition );

```

My question here is why "glFrontFace" function in the second pass help remove shadow between objects in the scene?

I Hope to see your answer. Thanks so much!

P/S:this is the explanation in the tutorial, but I don't get it

"They are rendered in two passes as you can see, one incrementing the stencil buffer with the front faces (casting the shadow), the second decrementing the stencil buffer with the backfaces ("turning off" the shadow between the object and any other surfaces)."

# Answer
For staters this technique is quite outdated, actually all of NeHe is outdated. You might want to look at something like OpenGL 3 and OpenGL 4 with GLSL. I recently had to unlearn allot of stuff, you should learn the correct OpenGL from the start.

Back to your question. If you look at the code in CastShadow (3Dobject.h) you will see that the object is not rendered normally, but each edge (line between two vertices) is extended in the direction of the shadow. (Away from the light.)

That is what this code does:

```
glBegin(GL_TRIANGLE_STRIP);
    glVertex3f(o->points[p1].x,
                o->points[p1].y,
                o->points[p1].z);
    glVertex3f(o->points[p1].x + v1.x,
                o->points[p1].y + v1.y,
                o->points[p1].z + v1.z);

    glVertex3f(o->points[p2].x,
                o->points[p2].y,
                o->points[p2].z);
    glVertex3f(o->points[p2].x + v2.x,
                o->points[p2].y + v2.y,
                o->points[p2].z + v2.z);
glEnd();

```

The first pass sets the stencil buffer to 1 where the outer shell is. The rendering is obstructed by the depth buffer. This currently looks a little bit like the cone of a spotlight. (That would be fig1 in the NeHe article if the image was not AWOL.)

To make this the actual shadow the bits of the cone are not in shadow must be put back to 0. To do this the same thing is done as in pass one, but with the faces revered. Since only front face is rendered now the cone is rendered "from the inside".

So the shadow comes into being by the interaction of the two passes and the the depth buffer. Take the test scene, the back plane is first rendered and thus the depth buffer is filled. The first pass is rendered and only the bit of the cone that faces you and is visible is rendered filling the stencil buffer with 1 and then the bit of the cone that is visible that away from you is rendered setting the buffer back to 0. The result is that only the bits between the two and "on the depth buffer" are not set to 1 and now the scene can either be darkened or lit based on that.
> 1 votes

---
Tags: opengl, shadows, stencil
---


title: How do I load BSP files in Android?

text:
# Question
Title: How do I load BSP files in Android?
I understand that Opengl directly cannot load BSP files. How would I go about loading them into my Android game?

# Answer
> 1 votes
Luckily, the BSP file format is well documented (with an overview on wikipedia). While this is great, it's clear from the documentation that you have a good deal of work ahead of you to write a importer for .BSP files.

Your first steps should be getting your file parser working through the lumps and printing out when when it reaches each face/vertex. (Make sure you start testing with a *very* simple scene).

Next up start loading the vertices into whatever data structures you're using to store meshes. From there you can pick and choose which features the file includes you want to include in your game. Incorporate each feature one at a time, continuing to test along the way.

Good luck!

---
Tags: android, opengl-es, binary-space-partitioning
---


title: Working with floats in OpenGL ES 2

text:
# Question
Title: Working with floats in OpenGL ES 2
Are there any reasons or situations one would use in their shader `float(1)` over just `1.0` ?

# Answer
Not really, any decent compiler will evaluate `float(1)` to `1.0` at compile time. The only thing you're doing by using `float(1)` is making your shader a little less readable.
> 0 votes

---
Tags: glsl, opengl-es2
---


# Question
Title: Is it worthwhile investing time learning Unreal Script when UDK 4 will be replacing it with C++?
Should I continue to get more familiar with Unreal Script or just wait for UDK4 with C++?

# Answer
I don't understand the question. When will the UDK4 be out? One year, *at the least*? Plus, you'll have to wait for it to become stable enough to reasonably use.

The question you *should* ask is, "Do I want to make a game?" If the answer is "yes," then you should use the tools you have *available* to do so. There will always be some new tool coming in a couple of years. If you want to get something *done*, that means picking your tech and sticking with it.

Plus, if new tech comes along and actually *exists* that you like more, you can always switch to it.
> 8 votes

# Answer
I think you should learn both. I agree with Matt that you can run into a lot of difficulty swapping out technologies mid-project. That being said it might be helpful for you to learn a scripting language as well as a high-level language like C++. Scripting languages are very valuable because they can be accessible enough for designers to use for game logic as well as being faster because the ease of reloading the code without having to recompile.

Hope this helps.
> 1 votes

---
Tags: udk, unreal
---


title: Using external music mp3 in flash game

text:
# Question
Title: Using external music mp3 in flash game
sorry for my english. Im relative new to flash game development, Im creating a game and I need some big size mp3 files. If I add them into flash, .swf file will be too big. I guess I need to host mp3 files somewhere and use URL Request? Where can I upload mp3 files so they are always ready for use?

# Answer
I'm not seeing the aim of your question, are you asking can you host and import or are you asking where should you host your files to import into your code.

Personally I'd recommend you compress the MP3 files, there is a good answer on another Stack Exchange which you can find here

If you're looking to host your MP3 files I'd recommend Dropbox \- it's free to download and you can easily upload/remove your files. You'll get a link to use in your code..

~ Will
> 1 votes

---
Tags: flash, actionscript-3, actionscript
---


# Question
Title: Using interpolation to traverse waypoints
I'm making an isometric turn based strategy. Characters can move between tiles and tiles only, so I made a function for moving one tile in any direction. Regarding path-finding, I implemented A\*, which returns a list of directions to the target, for example: North, North, West; etc. Also, the game loop calls a `MovementUpadate()` for the character, to check if it has reached the next tile, if it has, move to the next, if there is one. For starters, is this good or is there a better approach?

Now with the character movement/animation, I'm using linear interpolation between tiles 'till the target cell is reached. In the end, there is a lag between tiles, little, but still. Also, how to interpolates so, that the character doesn't start off fast, and slow down at the end?

```
void Character::MovementUpdate(){
if(moving){ //if moving, then do the calculations
    float rate=(float)(moveTime-movesLeft)/moveTime; //ratio between coordinates
    posX=(int) ( (float)(currentTile->x+20)*rate + (float)posX*((float)1-rate));
    posY=(int) ( (float)(currentTile->y-25)*rate + (float)posY*((float)1-rate));
    movesLeft--; //it has, for example 30 updates to move to that position

    if(movesLeft==0){ //if no moves left, reset and move to the next
        if(moveList.size()>0){
            Move(moveList.at(0));
            moveList.erase(moveList.begin());
        }else{
            moving=false;
            characterSprite->UpdateAnimateSprite(moving);
        }
        movesLeft=moveTime;
    }
}

```

}

# Answer
> 0 votes
I don't normally recommend interpolation for movement, but it should work fine in your turn-based case.

Your issues boil down largely to a single design flaw. Interpolating between waypoints in a turn-based move is insufficient. You need to interpolate along the whole path, initially using a linear piecewise interpolation most likely (easy to find the algorithm/code for that). That is, `t=0` needs to be on the starting node and `t=1` needs to be directly on the final node. Interpolating between each node is going to make that pause between nodes a bit harder to eliminate. The "slow start/end" feature is also going to be a bit less direct/obvious if you interpolate each waypoint than if you interpolate the whole path. You'll also be able to apply a small bit of smoothing around each node much easier if you interpolate along the whole path.

For starting out and ending slow, you want an *easing* function. Again, this is much easier once you interpolate along the whole path, assuming you don't actually want to ease into each individual waypoint. (You could ease out from the start node to the second node, ease in to the last node from the second-to-last, and then special case when you have no intermediate nodes to both ease out and ease in from start to end, but that's just extra work). Again, you should be able to easily find a lot of information on interpolation easing; the gist of it boils down to applying a function over `t` so that the actual `t` value you supply to interpolation is not your time-based `t`, which often involves some simple exponents or `cos`.

---
Tags: movement, sdl
---


title: Implementing smooth object rotation

text:
# Question
Title: Implementing smooth object rotation
I declared two variables on class level. One is the angle the object is rotated by. The second is a stopwatch.

```
float yRot = 0.0f;
static CStopWatch rotTimer;

```

I rotate the cube using the *SpecialKeys* function.

```
void SpecialKeys(int key,int x,int y)
{

    if(key == GLUT_KEY_RIGHT)
    {
        yRot = rotTimer.GetElapsedSeconds() * 10.0f;
    }

    if(key == GLUT_KEY_LEFT)
    {
        yRot = rotTimer.GetElapsedSeconds() * -10.0f;
    }

    glutPostRedisplay();
}

```

Finally the rotation matrix is calculated using the rotation variable, in the `RenderScene` function.

```
// Create a rotation matrix based on the current value of yRot
m3dRotationMatrix44(mRotate, m3dDegToRad(yRot), 0.0f, 1.0f, 0.0f);

```

It actually works. My problem is that when I hold the key the animation looks fine. But if I press it the animation looks a little jumpy, like the angle is bigger then when I hold it. I suppose this hangs together with the stopwatch. How to solve this issue?

# Answer
From what you describe I suspect that it has something to do with your timer. I think the timer is calculating the delta time from the last time you pressed a key and not from and display update. It's pretty simple keeping your own delta time (in a display or update function):

```
 int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);
 int deltaTime = timeSinceStart - oldTimeSinceStart;
 oldTimeSinceStart = timeSinceStart;

```

Other then that, as someone else pointed out, you probably want to do update the rotation in the update function based on the state of the key (down or up) not in the keypress itself. You would use the glut key down key up function manage the state of that key.

http://www.swiftless.com/tutorials/opengl/keyboard.html
> 2 votes

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


# Question
Title: How Do Shapes (Rectangles) Work in Quad Trees?
I've been told that a quad tree is the ideal data structure for my game, but I'm having trouble understanding how exactly shapes work within quad trees.

I'm doing this in JavaScript, but I think these questions could apply to quad trees in any language.

I think I mostly understand how basic (x,y) *points* and *point insertion* works in quad trees, and that I could do it on paper.

Here is a JSfiddle of my experimenting with points.

Aside from one case, my tests with points are working as expected.

But my confusion starts when shapes like rectangles are involved. When you are retrieving from a quad tree with shapes, does it check each point of the shape, and what nodes they fall into? And how do shape insertions even work, when it accepts (x,y,width,height) parameters for each shape? Does it use the width/height from the starting point to calculate other corner points, which are then dispensed into appropriate nodes? If an inserted shape spans into four nodes, is that shape's data saved into all four nodes?

And when a retrieval method accepts a shape as the parameter(x,y,width,height), what is actually going on? Is it first seeing what nodes the shape would span to if it were to be inserted, and then retrieve all the objects of those nodes?

I have a JSfiddle working with shapes, but I am utterly confused on the results of my testing. I am getting duplicate objects being returned!

For example, the red square is a drawn equivalent of the parameters I am entering into my retrieval method. I would think that since this red square spans all four nodes, it should return every object in the quad tree! But it doesn't, and I am having trouble rationalizing what it does return. I have a number of other tests that are currently commented out, but you can un-comment and run them to see more confusing results!

As say, if I want to return all points in a quad tree, how would I do that? A retrieve method using a shape the entire size of the bounds? In example, retrieve(0, 0, canvas.width, canvas.height)?

The JavaScript QuadTree library I am using has been referred to by various other sources, so I assume the actual implementation is correct and reputable.

I think a lot of my confusion may stem from a misunderstanding of quad tree terminology. Like, why do they say bounds instead of dimensions, when a "point" has width/height parameters as well? Is it a matter of convention/short-hand, or are they completely different concepts?

Thanks for your time!

# Answer
Quadtrees typically store and retrieve rectangles. A point is a specific case where width and height are zero. The following logic is used to find home for new rectangles in the tree, starting with the root node:

```
void Store(Rectangle rect)
{
    if(I have children nodes)
    {
        bool storedInChild = false;
        foreach(Node childNode in nodes)
        {
            if(this rectangle fits entirely inside the childNode bounds)
            {
                childNode.Store(rect);   // Go deeper into the tree
                storedInChild = true;
                break;
            }
        }
        if(not storedInChild)
        {
            Add this rectangle to the current node
        }
    }
    else
    {
        Add this rectangle to the current node
    }
}

```

Note that rectangles can be stored at any depth, it does not have to be a leaf quad. If the rectangle straddles the boundary right at the root level, the root quad will store the rectangle.

> For example, the red square is a drawn equivalent of the parameters I am entering into my retrieval method. I would think that since this red square spans all four nodes, it should return every object in the quad tree! But it doesn't, and I am having trouble rationalizing what it does return.

When querying the quadtree, it will only return rectangles that are contained by the query. In your example, you force each of the 4 child quads to be looked at in further detail because the red query rectangle intersects each child quad. Since the children have no further children, each of the rectangles in these child quads will be compared with the red rectangle. Since none of the rectangles in the tree collide with the red query rectangle, nothing should be returned.

You really start to see benefits of quadtrees when you have lots of objects, and lots of space for the objects to exist in compared with the query area(s). In these cases, a small query area can quickly eliminate vast chunks of the quad tree from consideration. Only quads that intersect with the query rectangle will ever be looked at in more detail.

**EDIT**

Retrieval is usually done like the following:

```
List<Rectangle> Query(Rectangle queryRect)
{
    List<Rectangle> results;
    foreach(Node childNode in children)
    {
        if(queryRect intersects with childNode bounds)
        {
            results += childNode.Query(queryRect);   // Dig deeper into the tree
        }
    }

    foreach(Rectangle I have stored in this quad)
    {
        if(queryRect intersects with rect)  // Your library doesn't do this
        {
            results += rect;
        }
    }

    return results;
}

```

In your library however, it doesn't seem to check if if the rectangles it's returning intersect with the query, so you'll need to add that yourself.
> 12 votes

---
Tags: javascript, html5, data-structure, quadtree
---


title: Calculation of Inertia Tensors

text:
# Question
Title: Calculation of Inertia Tensors
Bit of a complex and lengthy question that, I'll admit, I don't quite understand very well yet so I will try and explain as best as I can.

**Short Version:** Is there a general c++/physx formula out there to calculate inertia tensors based off an objects shape?

**Long Version:** For our physics, we need to specify x, y and z inertia tensors. Currently the way we do it is pretty much just a ratio based off of mass. So if an object is long on the X axis and thin on Y and Z, and the mass is 10000, we will set Z and Y to 7000 and X to 3000. (This isn't exact, but just to give an idea)

This works relatively well but our biggest problem is when there is joint instability somewhere, we have to keep guessing at tensors until we figure out what works best. This can become very time consuming if we have a very big physics simulation and one out of 20+ joints is causing all the others to lose stability.

What I am working on is a function that will take the bounding box of an object and hopefully calculate relatively accurate tensors. I have taken some of the math from http://en.wikipedia.org/wiki/List\_of\_moment\_of\_inertia\_tensors and made a function that basically works like the following for similar rotations below.

Or if the rotation is on an end, like this:

So, this seems to give me results that are similar to the way we have been doing it, but I dont want to switch to this way without making sure that it will work for general use. Below is the code for my function based on the first image with a cube and center pivot.

```
NxVec3 CalculateInertiaTensor( VisBoundingBox_cl boundingBox, float m )
{
    float width = boundingBox.GetSizeX();
    float height = boundingBox.GetSizeZ();
    float depth = boundingBox.GetSizeY();

    float xTensor = 0.083f * m*(height*height + depth*depth);
    float yTensor = 0.083f * m*(width*width + depth*depth);
    float zTensor = 0.083f * m*(width*width + height*height);

    return NxVec3(xTensor, yTensor, zTensor);
}

```

I can't guarantee that this is the right way to do it (as the most accurate way is to use the actual shape instead of a bounding box) and i am not very familiar with inertia tensors and the math but it seems to return numbers fairly similar to what we were using. Anyone here happen to know if there is a better way to do this?

# Answer
I was going to suggest that this is a hard problem because the usual formulations based on using Green's Theorem to convert volume integrals into surface integrals don't apply, and so you actually do have to provide a tetrahedral decomposition of your figure - but it turns out that that's not correct. As long as your shape is of uniform density (which is an approximation you're already making anyway, presumably, and a perfectly reasonable one for most circumstances) then the volume integrals can be simplified to surface integrals, and the latter simplified even further. Better yet, there appears to be a pretty good-looking algorithm and code out there on the net to do this; have a look at http://www.cs.berkeley.edu/~jfc/mirtich/massProps.html , Brian Mirtich's page describing his algorithms for calculating moments and center of mass. It should cover pretty much all your needs on this front. Note that this is something you'll want to do one time, either as a tool on export of the shape or at import time, but not something you'll need to do every frame; just store the inertia tensor about the center of mass along with the rest of the shape info, and if you ever need to find the tensor for moments of inertia about some other axis then you can use the standard theorems to derive it.

Hopefully this should cover what you need - if there's more that I can try to help with, just let me know!
> 8 votes

# Answer
I have never done this myself, but if I had to write a quick solution for arbitrary meshes I would probably generate enough mass points inside the object to approximate it and calculate the inertia tensors from those.

The points could be generated uniformly inside the bounding box of the shape and then discarding those that are outside the actual shape. This would reduce the problem to just checking if a point is inside a shape.
> 4 votes

# Answer
For most game applications (i.e. "blowing up stuff") just using the equation for a rectangular solid given above is probably good enough. Provided that the object is axis-aligned, not a diagonal across the bounding box, that should work. Some game physics engines, such as ODE, only use the terms on the main diagonal of the inertia tensor. For them, your objects need to be at least roughly axis-aligned to work right.

I used Mirtich's algorithm in Falling Bodies back in 1997. It works well, but you must have clean geometry - a topologically correct closed non-self-intersecting mesh. If there are holes, the inertia computation will produce totally bogus results. I used only convex geometry, so I ran QHull first to get a convex hull for collision purposes, then computed the inertia from that.
> 0 votes

---
Tags: mathematics, physics, physics-engine
---


title: Directional light causes an FPS drop

text:
# Question
Title: Directional light causes an FPS drop
I have only one object in the scene and it is lit with a directional light. It uses the mobile/diffuse shader. The issue is that on iPhone 4 the FPS drops from ~42FPS to ~11FPS when the directional light is enabled. Rendering is set to forward rendering and there are no other light sources. Shadows are not enabled.

Scene stats give a total of five draw calls, 3k tris and 2.6k verts. Having a single directional light should not have that kind of effect on FPS. What could cause this FPS drop?

# Answer
> 1 votes
So after spending hours to figure out why it did that, it turned out to be rather simple. Even though the rendering was set to `Forward` in the player settings it was overridden to `Deferred` in the camera itself.

This caused more draw calls than it should have, as @Heisenbug pointed out, and the very poor performance as the iPhone4 is nowhere near capable to use deferred.

---
Tags: unity, shaders, performance, lighting
---


# Question
Title: AndEngine: Painting on a canvas rather than composing image from objects
I'm trying to implement drawing a line with a finger, similar to a Pencil tool in image editors. From what I've found on AndEngine, it seems like the recommended approach would be to create a **line entity** on every finger move, from the previous position to the new one. To me it seems rather inefficient to mimic this raster tool by vector graphics: apart from creating tens on objects per simple swipe, I guess that all these objects are repainted on each frame which is bad for speed. So I'm looking for a way to do all the painting on a **bitmap canvas** and draw it as a single entity. Am I missing something conceptually or did I just overlook some method?

# Answer
Yes, you are missing something conceptually - AndEngine is based on OpenGL ES. Now OpenGL is very well suited to the following use case:

1. Load a texture to bitmap memory
2. Define texture region in the texture
3. Create transformation (scale, position, ...)
4. Draw the Region from the texture memory to display

AndEngine exploits this by defining a 2D sprite that is a representation of the region. It uses ortographic projection to show textured quads. It is certainly not suited for drawing on "canvas".

Using Line object is not recommended, because it is up to the OpenGL ES implementer how the line will look like in the end. Each implementation has to follow certain rules, but still the lines can look different.

So your best bet is to:

1. Use the line and bear the consequences (I do that in my game btw)
2. Use line texture + sprite
3. Temporarily show something (draft using 1 or 2), then create a bitmap from it and load it to texture memory as a new texture and then show it.
> 1 votes

---
Tags: android, andengine
---


title: Math to steer a car

text:
# Question
Title: Math to steer a car
I'm in the early stages of a city driving simulation project, and I'm having trouble with the math to determine how the AI should steer the cars. My car model is very simple, with nothing like physical wheels or friction; the AI simply sets a turning radius (FLT\_MAX means drive straight) and an acceleration each frame. My question is, **given a starting position and direction, how do I work out the turning radius each frame to have the car arrive at a destination position and direction?** As an example, think of a car stopped at a stop sign ready to turn right around the corner. The car should follow a curve so that is is pointing along the road onto which it is turning when it arrives at the "start" of that road.

I think Bezier curves would be helpful, since they can be used to create smooth curves that are tangent to my initial and final directions, but I can't work out exactly how to pick a point a little way ahead along the curve to aim for. I also open to completely different ideas.

Here's my car update code for reference.

```
mSpeed += mAcceleration * deltaTime;
float distance = mSpeed * deltaTime;
float theta = distance / mTurningRadius;

mPosition += mTurningRadius * sin(theta) * mDirection + mTurningRadius *(1.0f - cos(theta)) * mLeft;

mDirection = rotate(mDirection, theta * 180.0f / PI, mUp);
mLeft = -cross(mDirection, mUp);

```

# Answer
Assumed your Ackermann drive simulation model is correct, you can do the following for the usual driving situations (where primarily only need to steer direction):

* Simulate (projection) multiple (e.g. in steps of 20 degrees) possible steering directions, statically. That means: You assume, the driver would put the steering wheel in is fixed position and then just drive forward.
* Simulate (projection) the borders of your car. Stop the simulation as soon as the borders of the car collide with any borders of the lane (or any other obstacle) -OR- if very long time has passed. Measure the time until the collision would happen.
* Select the direction with longest simulation time. If there are multiple of them with the same value (because the timeout was reached) take the average of the angles.
* Optional: Repeat simulation and selection for +/- 10 degrees in smaller steps, to refine the result.
* Simulate (execution) the real simulation for the next time step.

This works as a first approach, but still causes several "problems". The steering may oscillate and lead to unrealistic, quick movement. The reduce this effect, do the following: * Project the next steering direction like above * Calculate the difference between the current and the projected steering direction and reduce it, if it is above a given change-threshold (maximum speed a realistic driver would be able to turn the wheel in a time slice).

You can optimize the refinement by divide and the conquer algorithm (http://en.wikipedia.org/wiki/Divide\_and\_conquer\_algorithm). Meaning: you set a min and a max for the steering direction and then recursively split that range in half and further investigate only the better performing range (left or right half of the old range).

For changing the lane you must allow your car to use both lanes (border of "lane" for collission detection). But, to force the car to actually change lane and not to driving in the middle of both, you have to limit how long the time until which the car must have changed lane (e.g. 10 seconds in future). You can convert this time into a distance using the current speed. Then just let the lane "end" with a straight line (orthographic to the lanes direction) at this distance. Project the lane change, with other cars continuing their current plans. If this works (no collissions, no driving rules are breached) execute the lane change. If not, continue driving on that lane.
> 1 votes

# Answer
For an axis aligned 90 degree turn, the turning radius is simply the minimum of the x and y differences in the positions as long as you start and stop turning at the correct point.

If it isn't axis aligned you can always do a rotation to fix that before doing the calculation as it doesn't affect the radius.

For non-90-degree corners it's a bit more complicated to construct the circle, but the idea is the same.
> 0 votes

# Answer
> given a starting position and direction, how do I work out the turning radius each frame to have the car arrive at a destination position and direction?

Note, a simple "calculation" will only work if the "optimal" way is free from obstacles (e.g. other cars, borders of the road) -and- if you can drive there without changing direction (e.g. needed when get out of a paring space).

All more complicated actions can't be just calculated in a simple way. Even just stupidly using a A\* search won't work with an "Ackermann drive". A former PhD collegue was looking for a student to do a masters thesis about that, he meant this would need to apply some algorithms as "sampling" (machine learning). This is what is meant by "sampling" in matters of machine learning: http://lear.inrialpes.fr/~jegou/bishopreadinggroup/chap11.pdf

Instead of trying to optimally calculate it, I would let the AI use some machine learning technique. For automatically steering air planes the "Temporal Difference" (=Reinforced Learning) algorithm has been successfully used. I think this would be applicable here. Reinforce your agents by: speed (positive), not obeying the traffic rules (very negative), fuel usage (negative).

Try to train different agents with different "personalities", as speed-affine, high-speed aversive, very accident avoident (very high negative reinforcement for crashes), fuel-safer, only negative reinforcement then getting caught while not obeying rules. You'll get a really realistic scenario this way. You'll even be able to see how changes to street signs, traffic control, speed limits, speed cams will affect driving behaviour and safety on the street in a quite realistic way.
> 0 votes

---
Tags: mathematics, ai, simulations, car
---


title: Using native code with Libgdx, (Raknet)

text:
# Question
Title: Using native code with Libgdx, (Raknet)
I was searching for a game engine (Java- maybe C#) with built-in real time networking library to develop 2D cross platform (Android - iOS) multiplayer game. Actually I have not found well suited solution apart from Unity, however I don't like some of the features of Unity. (Here is Discussion)

After a while I decided to use Libgdx and tried to find a network libray that meets my requirements and I found Raknet as network engine which is written in C++ and cross-platform. So here is my question:

**Is there any way to use Raknet with Libgdx, or any other solutions you recommend as engine or anything else? And also is it possible to use any C/++ library with Libgdx like Android's NDK?**

# Answer
> 2 votes
There is little to no documentation on it, but LibGDX does have a platform independant (Android, Desktop, iOS and GWT) socket class.

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Net.html

and if you dont want to mesh with you can try kryonet networking library

https://code.google.com/p/kryonet/

---
Tags: libgdx, networking, multiplayer, cross-platform
---