# Question
Title: XNA Textures dissappear when game window is resized
**\[SOLVED\] - See linked post in the P.S.**

I have a set of Texture2Ds generated in the Load method with this function:

**Texture Generation:**

```
private Texture2D[,] createTextureSet(TileInfo[,] map)
    {
        Texture2D[,] texSet = new Texture2D[map.GetLength(0), map.GetLength(1)];

        using (SpriteBatch sprb = new SpriteBatch(GraphicsDevice))
        {
            for (int row = 0; row < map.GetLength(0); row++)
            {
                System.Threading.Thread.Sleep(10);
                for (int col = 0; col < map.GetLength(1); col++)
                {
                    RenderTarget2D renderer = new RenderTarget2D(this.GraphicsDevice, 300, 300);
                    System.Threading.Thread.Sleep(2);
                    GraphicsDevice.SetRenderTarget(renderer);
                    renderer.Name = map[row, col].buildings[0].buildingType;
                    GraphicsDevice.Clear(Color.Transparent);
                    sprb.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied);
                    sprb.Draw(TextureFromFile(resourceDirectory + @"Images\Tile Backgrounds\" + map[row, col].tileType + @"\" + map[row, col].tileBackground + ".png"), renderer.Bounds, Color.White);
                    sprb.Draw(TextureFromFile(resourceDirectory + @"Images\Buildings\" + map[row, col].buildings[0].buildingType + ".png"), (Vector2)map[row, col].buildings[0].pointWithinTile, Color.White);
                    sprb.End();
                    texSet[row, col] = renderer;
                }
            }
        }

        GraphicsDevice.SetRenderTarget(null);
        return texSet;
    }

```

The tiles are drawn on the screen using the following code:

**Texture Rendering**

```
for (int tx = -1; tx < 2; tx++)
        {
            for (int ty = -1; ty < 2; ty++)
            {
                gameSpriteBatch.Draw(mapTextureSet[gameCharacter.characterTile.tileX + tx, gameCharacter.characterTile.tileY + ty], determinePositionToDrawTile(gameCharacter, map[gameCharacter.characterTile.tileX + tx, gameCharacter.characterTile.tileY + ty], tx, ty, resizeX, resizeY), null, Color.White, 0f, Vector2.Zero, new Vector2(resizeX, resizeY), SpriteEffects.None, 0f);
            }
         }

```

These textures are then drawn on the screen based on where on the map the player is. The game runs fine, until the game window is resized by the user. After that, only the character sprite remains on the screen during the redraws, and the screen remains the default `Color.BlanchedAlmond` background of my game. Any help is thanked in advance.

**\[ ! \] P.S. \[ ! \]**

Before marking this as a duplicate! I have looked at this and tried most of the applicable solutions from it, none of which have worked, so I assume that this error is deeper than that one.

# Answer
I'm pretty sure that this is exactly the problem described and solved in my answer that you linked. In which case, "Option 3" in that answer is probably the easiest way to get your code working.

(And, indeed, from comments, it seems like that has worked for you.)

But to finish what I was typing up, you can verify that this is the problem by adding this code right after you create your `RenderTarget2D renderer`:

```
renderer.ContentLost += (s,a) => System.Diagnostics.Debug.Assert(false);

```

If that assertion triggers, then you know that your texture has gone missing due to the device reset.
> 1 votes

---
Tags: xna, c#, textures
---


title: Android Object get Jagged at the border

text:
# Question
Title: Android Object get Jagged at the border
I am new to OpenGL ES 1 in android. My 3D Model border getting Jagged. Please help me to look like a smooth border instead of jagged.

Screenshot : https://i.stack.imgur.com/1Gq83.png

```
private class Renderer implements GLSurfaceView.Renderer {
    public Renderer() {
        setEGLConfigChooser(8, 8, 8, 8, 16, 0);
        getHolder().setFormat(PixelFormat.TRANSLUCENT);
        setZOrderOnTop(true);
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glClearColor(0.0f,0.0f,0.0f, 0.0f);
        gl.glDisable(GL10.GL_DITHER);
        gl.glEnable(GL10.GL_DEPTH_TEST);
        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA_SATURATE, GL10.GL_ONE);
        gl.glDepthFunc(GL10.GL_LEQUAL);
        gl.glHint(GL10.GL_POLYGON_SMOOTH_HINT, GL10.GL_NICEST);
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glShadeModel(GL10.GL_SMOOTH);
    }

    public void onSurfaceChanged(GL10 gl, int w, int h) {
        mViewWidth = (float)w;
        mViewHeight = (float)h;
        gl.glViewport(0,0,w,h);

        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        GLU.gluPerspective(gl, 45, mViewWidth/mViewHeight, 0.1f, 100f);

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
    }

    public void onDrawFrame(GL10 gl) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        gl.glPushMatrix();

        gl.glDisable(GL10.GL_DITHER);

        GLU.gluLookAt(gl, 0, 0, 10, 0, 0, 0, 0, 1, 0);

        //draw_model
        gl.glPushMatrix();

        if(mOrigin != null && mRotate != null) {
            gl.glTranslatef(mOrigin.x, mOrigin.y, mOrigin.z);
            gl.glRotatef(mRotate.x, 1f, 0f, 0f);
            gl.glRotatef(mRotate.y, 0f, 1f, 0f);
            gl.glRotatef(mRotate.z, 0f, 0f, 1f);
        }

        if(mModel != null) {
            mModel.draw(gl);
            if(!RendererView.textureFileName.equals(""))
                mModel.bindTextures(mContext, gl);
        }

        gl.glPopMatrix();
        gl.glPopMatrix();

        if(isPictureTake) {

            w = getWidth();
            h = getHeight();
            b = new int[w*(y+h)];
            bt = new int[w*h];

            IntBuffer ib = IntBuffer.wrap(b);
            ib.position(0);
            gl.glReadPixels(0, 0, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib);
            createBitmapFromGLSurface(context);
            isPictureTake = false;
        }
    }
}

```

Thanks in advance.

# Answer
if you were using ES 2.0 you can do something like GL\_LINE\_SMOOTH then the line will get smoothed out themselves tutorials on that here.

* Solution 00 : If you still want o use ES 1.0 still, I recommend what Lasse said in chat; draw anti-aliased texture then render it as your line.
* Solution 01 : Another easier way to do so will be preparing "anti-aliased" texture image with alpha value then draw it where you want to have "smooth line" (Prepare blurred square picture. Then resize/draw it where you want to have "smooth line").

(example of "smooth" texture that can be used for Solution 01)

But really both of them are same in nature; prerender texture for the effect you want, then draw it when you need it.
> 2 votes

---
Tags: opengl, android, 3d, opengl-es, 3d-meshes
---


title: LWJGL SlickUtil Texture Binding

text:
# Question
Title: LWJGL SlickUtil Texture Binding
I am making a 3D game using LWJGL and I have a texture class with static variables so that I only need to load textures once, even if I need to use them more than once. I am using Slick Util for this. When I bind a texture it works fine, but then when I try to render something else after I have rendered the model with the texture, the texture is still being bound. How do I unbind the texture and set the rendermode to the one that was in use before any textures were bound? Some of my code is below. The problem I am having is the player texture is being used in the box drawn around the player after it the model has been rendered.

Model.java

```
public class Model {

public List<Vector3f> vertices = new ArrayList<Vector3f>();
public List<Vector3f> normals = new ArrayList<Vector3f>();
public ArrayList<Vector2f> textureCoords = new ArrayList<Vector2f>();
public List<Face> faces = new ArrayList<Face>();

public static Model TREE;
public static Model PLAYER;

public static void loadModels() {
    try {
        TREE = OBJLoader.loadModel(new File("assets/model/tree_pine_0.obj"));
        PLAYER = OBJLoader.loadModel(new File("assets/model/player.obj"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void render(Vector3f position, Vector3f scale, Vector3f rotation, Texture texture, float shinyness) {
    glPushMatrix();
    {
        texture.bind();

        glColor3f(1, 1, 1);
        glTranslatef(position.x, position.y, position.z);
        glScalef(scale.x, scale.y, scale.z);
        glRotatef(rotation.x, 1, 0, 0);
        glRotatef(rotation.y, 0, 1, 0);
        glRotatef(rotation.z, 0, 0, 1);

        glMaterialf(GL_FRONT, GL_SHININESS, shinyness);

        glBegin(GL_TRIANGLES);
        {
            for (Face face : faces) {
                Vector2f t1 = textureCoords.get((int) face.textureCoords.x - 1);
                glTexCoord2f(t1.x, t1.y);
                Vector3f n1 = normals.get((int) face.normal.x - 1);
                glNormal3f(n1.x, n1.y, n1.z);
                Vector3f v1 = vertices.get((int) face.vertex.x - 1);
                glVertex3f(v1.x, v1.y, v1.z);

                Vector2f t2 = textureCoords.get((int) face.textureCoords.y - 1);
                glTexCoord2f(t2.x, t2.y);
                Vector3f n2 = normals.get((int) face.normal.y - 1);
                glNormal3f(n2.x, n2.y, n2.z);
                Vector3f v2 = vertices.get((int) face.vertex.y - 1);
                glVertex3f(v2.x, v2.y, v2.z);

                Vector2f t3 = textureCoords.get((int) face.textureCoords.z - 1);
                glTexCoord2f(t3.x, t3.y);
                Vector3f n3 = normals.get((int) face.normal.z - 1);
                glNormal3f(n3.x, n3.y, n3.z);
                Vector3f v3 = vertices.get((int) face.vertex.z - 1);
                glVertex3f(v3.x, v3.y, v3.z);
            }
            texture.release();
        }
        glEnd();
    }
    glPopMatrix();
}

}

```

Textures.java

```
public class Textures {

public static Texture FLOOR;
public static Texture PLAYER;

public static Texture SKYBOX_TOP;
public static Texture SKYBOX_BOTTOM;
public static Texture SKYBOX_FRONT;
public static Texture SKYBOX_BACK;
public static Texture SKYBOX_LEFT;
public static Texture SKYBOX_RIGHT;

public static void loadTextures() {
    try {
        FLOOR = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/model/floor.png")));
        FLOOR.setTextureFilter(GL11.GL_NEAREST);
        PLAYER = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/model/tree_pine_0.png")));
        PLAYER.setTextureFilter(GL11.GL_NEAREST);

        SKYBOX_TOP = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_top.png")));
        SKYBOX_TOP.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_BOTTOM = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_bottom.png")));
        SKYBOX_BOTTOM.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_FRONT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_front.png")));
        SKYBOX_FRONT.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_BACK = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_back.png")));
        SKYBOX_BACK.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_LEFT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_left.png")));
        SKYBOX_LEFT.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_RIGHT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_right.png")));
        SKYBOX_RIGHT.setTextureFilter(GL11.GL_NEAREST);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

```

Player.java

```
public class Player {

private Vector3f position;
private float yaw;
private float moveSpeed;

public Player(float x, float y, float z, float yaw, float moveSpeed) {
    this.position = new Vector3f(x, y, z);
    this.yaw = yaw;
    this.moveSpeed = moveSpeed;
}

public void update() {
    if (Keyboard.isKeyDown(Keyboard.KEY_W))
        walkForward(moveSpeed);
    if (Keyboard.isKeyDown(Keyboard.KEY_S))
        walkBackwards(moveSpeed);
    if (Keyboard.isKeyDown(Keyboard.KEY_A))
        strafeLeft(moveSpeed);
    if (Keyboard.isKeyDown(Keyboard.KEY_D))
        strafeRight(moveSpeed);

    if (Mouse.isButtonDown(0))
        yaw += Mouse.getDX();

    LowPolyRPG.getInstance().getCamera().setPosition(-position.x, -position.y, -position.z);
    LowPolyRPG.getInstance().getCamera().setYaw(yaw);
}

public void walkForward(float distance) {
    position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw)));
    position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw)));
}

public void walkBackwards(float distance) {
    position.setX(position.getX() - distance * (float) Math.sin(Math.toRadians(yaw)));
    position.setZ(position.getZ() + distance * (float) Math.cos(Math.toRadians(yaw)));
}

public void strafeLeft(float distance) {
    position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw - 90)));
    position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw - 90)));
}

public void strafeRight(float distance) {
    position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw + 90)));
    position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw + 90)));
}

public void render() {
    Model.PLAYER.render(new Vector3f(position.x, position.y + 12, position.z), new Vector3f(3, 3, 3), new Vector3f(0, -yaw + 90, 0), Textures.PLAYER, 128);

    GL11.glPushMatrix();
    GL11.glTranslatef(position.getX(), position.getY(), position.getZ());
    GL11.glRotatef(-yaw, 0, 1, 0);
    GL11.glScalef(5.8f, 21, 2.2f);

    GL11.glDisable(GL11.GL_LIGHTING);

    GL11.glLineWidth(3);
    GL11.glBegin(GL11.GL_LINE_STRIP);

    GL11.glColor3f(1, 1, 1);

    glVertex3f(1f, 0f, -1f);
    glVertex3f(-1f, 0f, -1f);
    glVertex3f(-1f, 1f, -1f);
    glVertex3f(1f, 1f, -1f);

    glVertex3f(-1f, 0f, 1f);
    glVertex3f(1f, 0f, 1f);
    glVertex3f(1f, 1f, 1f);
    glVertex3f(-1f, 1f, 1f);

    glVertex3f(1f, 1f, -1f);
    glVertex3f(-1f, 1f, -1f);
    glVertex3f(-1f, 1f, 1f);
    glVertex3f(1f, 1f, 1f);

    glVertex3f(1f, 0f, 1f);
    glVertex3f(-1f, 0f, 1f);
    glVertex3f(-1f, 0f, -1f);
    glVertex3f(1f, 0f, -1f);

    glVertex3f(1f, 0f, 1f);
    glVertex3f(1f, 0f, -1f);
    glVertex3f(1f, 1f, -1f);
    glVertex3f(1f, 1f, 1f);

    glVertex3f(-1f, 0f, -1f);
    glVertex3f(-1f, 0f, 1f);
    glVertex3f(-1f, 1f, 1f);
    glVertex3f(-1f, 1f, -1f);

    GL11.glEnd();

    GL11.glEnable(GL11.GL_LIGHTING);

    GL11.glPopMatrix();
}

public Vector3f getPosition() {
    return new Vector3f(-position.x, -position.y, -position.z);
}

public float getX() {
    return position.getX();
}

public float getY() {
    return position.getY();
}

public float getZ() {
    return position.getZ();
}

public void setPosition(Vector3f position) {
    this.position = position;
}

public void setPosition(float x, float y, float z) {
    this.position.setX(x);
    this.position.setY(y);
    this.position.setZ(z);
}
}

```

Thanks for the help.

# Answer
The quick way is enabling/disabling textures using glEnable(GL\_TEXTURE\_2D) / glDisable(GL\_TEXTURE\_2D). Whether it would be best to enable textures before rendering the player and then disabling them after or disabling them before the box and enabling them after, depends on the how/if the rest of your program uses textures throughout.
> 1 votes

---
Tags: 3d, textures, rendering, models, lwjgl
---


# Question
Title: Why can't I set a single value in a game map Java 2D array?
I'm trying to set one character on 2D array.

```
map[0][2] = "0";

```

However, I'm getting

```
11011
11011
11011
11011
...

```

I was expecting

```
11011
11111
11111
11111
...

```

What am I doing wrong?

another example:

```
int arraySize = 20;
        String[] blankLine = {"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"};
        String[][] blankM = new String[arraySize][];
        for (int i = 0; i < arraySize; i++) {
            blankM[i] = blankLine;

        }
        blankM[0][0] = "5";
        return blankM;

```

It gives me in every colum \[n\]\[0\] 5

# Answer
> 0 votes
Just to take this one step further, lets make a function:

```
public static String[][] generateMap(int width, int height, String content)
{
    String[][] blankM = new String[height][width];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++){
        blankM[i][j] = content;
        }
    }
    return blankM;
}

```

This function can be used to generate a map filled with 1's or any other content so you can generate your maps based on your current needs.

```
System.out.println(Arrays.deepToString(generateMap(5,6,"1")));
System.out.println(Arrays.deepToString(generateMap(2,3,"IT'S A TRAP")));
//Results in these arrays:
[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]
[[IT'S A TRAP, IT'S A TRAP],
 [IT'S A TRAP, IT'S A TRAP],
 [IT'S A TRAP, IT'S A TRAP]]

```

# Answer
> 4 votes
You need to create a new instance for each item in the array.

```
String[][] blankM = new String[arraySize][];
for (int i = 0; i < arraySize; i++) {
    blankM[i] = new String[]{"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"};
}

```

---
Tags: java, tiles, maps
---


# Question
Title: How do I double-buffer renders to a JPanel?
I'm trying to make a little breakout game with Java and Swing. The only issue so far is that drawing on the `JPanel` causes lots of flickering!

The relevant code:

```
JFrame frame = new JFrame("Breakout");
JPanel gameField = (JPanel) frame.getContentPane();

private void gameLoop() {
    while(running) {
        update();
        render((Graphics2D) gameField.getGraphics());
    }
}

private void render(Graphics2D g) {
    g.clearRect(0, 0, gameField.getWidth(), gameField.getHeight());
    for (GameObject o : objects) {
        o.draw(g);
    }
}

```

I've looked into manually double buffering (e.g. by making an offscreen `Image`, drawing on it, then doing `g.drawImage(offscreen)`. Is there a better way?

# Answer
Take a look at BufferStrategy, it's the preferred way to use multibuffering for java 2d, - and it works like a charm. Searching google for examples on how to use it should be straightforward :)
> 1 votes

---
Tags: java, rendering, swing, double-buffering
---


# Question
Title: Howdo I create differently sized texture atlases for different screen sizes?
I am beginning game development and using *texture atlases*. I've created textures based on the resolution 1920x1080, so I created a 1024x1024 size Texture Atlas for storing multiple graphics.

If the game is played on a 800x480 size device, the atlas will be very big to load in memory. An atlas of 512x512 would be enough and on devices with 480x320 resolution the game might not even work due to the different texture size.

How can I resize the atlas to save memory? Can I use different texture atlases for different screen sizes?

I just want to know how other game devs do it?

# Answer
> 1 votes
Yes, you can use different texture atlases for different screens. From technical standpoint you need to have a lookup structure to access textures knowing just their ID. Each ID should be linked with texture coordinates and size in relative space (0.0..1.0) or with regard to atlas size.

Basically there are several approaches which differ in quality and effort required:

* Simplest, ship single atlas image with your application and resize it when initializing your application. Downsides are longer loading times on low-end devices (resizing takes some time) and lower image quality (blurry/jaggy depending on resize algorithm used)
* Medium, resize the resulting atlas before packaging it into the application in Photoshop or alike. Then you can better control image quality. Downsides are that you will have to ship several atlases with your application, so that takes a bit more space. Images will still loose in quality.
* Hard, resize (or even redraw) each texture individually for major screen sizes you are going to use and and pack them into different atlases for different resolutions. You should be able to generate atlases at any size with atlas generation tools, just supply list of textures to pack and atlas dimensions.

# Answer
> 0 votes
Resize the image using standard java(?) functionality (BufferedImage) with the desired algorithm before you load it into a OpenGL texture. Otherwise, you'll just do scaling on the fly while rendering, and not saving any real memory usage.

Further things to think about once the resized texture atlas is resized:

How do you reference each texture in the atlas? By relative or absolute position? (Relative: 0.0 -\> 0.1 on x and y coordinates). If it's relative, you can simply resize the atlas and it will still work. If not, you'll have to scale each texture position with the same ratio that you scaled the atlas with.

---
Tags: textures, opengl-es2, texture-atlas
---


# Question
Title: Triangle-triangle continuous collision detection
I am making a 3D game engine and I use continuous collision detection. I am using Sphere-Trees to cull primitive collision checks to a minimum. However, I'd like to perform continuous triangle-to-triangle collision checking.

How does continuous triangle-triangle collision detection work, assuming triangles with linear velocities?

# Answer
> 9 votes
Continuous triangle intersection is explained in a classic Computer Graphics paper (PROVOT) and almost all research in Continuous Collision Detection use it to perform elementary tests.

The paper describes how to mathematically model the continuous triangle X triangle intersection problem. There are two types of collision involved: a vertex intersecting a triangle (vertex-face collision) and an edge intersecting another edge (edge-edge collision).

A triangle X triangle intersection is reduced to 6 vertex-face tests (1 for each triangle vertex) and 9 edge-edge tests (each triangle edge against each edge in the other triangle).

Let t0 be the start of the time interval \[t0, t0 + ∆t\] and assume that the positions and velocities in t0 are known. Assume also that the velocities are constant in the interval.

***Vertex-face Collision***

Let P (t) be the vertex and A(t), B(t), C(t) the vertices of the triangle. Let also Vp , Va , Vb , Vc be their respective constant velocities during the time interval. Thus,

P(t) = P(t0) + tVp,

A(t) = A(t0) + tVa,

B(t) = B(t0) + tVb,

C(t) = C(t0) + tVc.

If there is collision, then

∃t ∈ \[t0, t0 + ∆t\] such that

∃u, v ∈ \[0, 1\], u + v = 1, AP(t) = uAB(t) + vAC(t) (Equation 1)

Equation 1 just shows that in the collision time t, P must be inside the triangle ABC. But it is non-linear since u, v, t are unknown and there are factors that depend on two of them. To solve this, another condition is considered: that the triangle normal is orthogonal to the triangle. Thus

AP(t) · N(t) = 0, where N(t) is the triangle normal. (Equation 2)

It is important to note that this equation is not sufficient to verify the collision since it is true if A(t), B(t), C(t), P(t) are coplanar. However it calculates t and therefore eliminates Equation 1 dependency on this variable and turns it linear. N(t) is a t^2 term and AP(t) is a t term, so Equation 2 is cubic. The approach to solve it is described in Section ***Cubic Equations Solver***. Equation 2 can result in three values for t. The lowest positive value t′ for which P(t′) ∈ ABC(t′) is chosen as the final result.

***Edge-edge Collision***

The ideas in Section ***Vertex-face Collision*** can be used in the edge-edge collision case with minor changes. Let AB(t) be one edge and CD(t) be the other one. The collision occurs if and only if

∃t ∈ \[t0, t0 + ∆t\] such that

∃u, v ∈ \[0, 1\], uAB(t) = vCD(t) (Equation 3)

Once again, this is a nonlinear system. The relation used to calculate t is that A, B, C, D must be coplanar, like before.

(AB(t) × CD(t)) · AC(t) = 0 (Equation 4)

This also is a cubic equation, which can lead to 3 values for t. The lowest positive value that makes it possible for Equation 3 to be solved is chosen as the final result.

***Cubic Equations Solver***

There are several methods to get the roots of cubic equations. NUMERICAL RECIPES 3RD ED. shows a good algorithm using a combination of Newton-Raphson and bisection methods. The bisection method gets an interval \[a, b\], where the root is known to be, i.e., f (a) and f (b) have opposite signals. The algorithm iterates by dividing the interval at the midpoint, reducing interval to \[a′,b′\] as a result, and evaluating f(a′) and f(b′). This is done until the error in the root value is acceptable. The bisection method is assured to find the root, but has slower convergence than other methods.

On the other hand, the Newton-Raphson uses the derivative of the function to refine a root guess. If f is the function and a is the root guess, the Newton-Raphson method iterates by evaluating the zero crossing of the tangent line of f passing through f(a). The new root guess will be the abscissa of this zero crossing. The image shows the method. It converges fast, but has some special cases that can lead to divergence or cycling.

The approach of the book suggests using Newton-Raphson while it is converging fast enough and bisection otherwise. This allows fast and safe convergence. The code to implement it can be found in the book.

# Answer
> 3 votes
Erin Catto GDC 2013, Continuous Collision Detection. The video is free for public viewing on the GDC vault. Erin keeps his own version of his slides available, but the GDC vault itself houses the free video.

Erin's link: https://code.google.com/p/box2d/downloads/detail?name=ErinCatto\_GDC2013.zip&can=2&q=

I can't speak for the Eberly work, but the idea of Erin's work is to reduce the problem to that of a root finding problem. GJK is used to compute distances of which are used to step forward/backwards in time to find a time of impact as a root to the equation of separation.

In order to implement Erin's work one must have an understanding of how to implement GJK, which makes use of knowledge of the Minkowski Sum and Support Points. Both of these concepts are fairly simple in isolation, though the implementation of a full-featured continuous collision package is very difficult to author.

All I can say about the Eberly work is that it seems to (after a 10 second skim) compute time impact directly through a fully enumerated system of if statements. Eberly is extremely good with geometry, and in general his work and documentation is quite intensive making it difficult for beginners in read.

Eberly, swept SAT: http://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf

---
Tags: c++, collision-detection, 3d
---


title: How to target an entity that is moving

text:
# Question
Title: How to target an entity that is moving
I want my arrow to chase the minion that I just rightclicked on. I have a Minion Class and an Arrow Class. These are the constructors:

```
    /// <summary>
    ///  Constructs a minion
    /// </summary>
   public Minion(Texture2D sprite, int x, int y, int windowWidth, int windowHeight, bool isFriendly, int minionHealth)

    /// <summary>
    /// Constructor of the bullet from champion to minion
    /// </summary>
   public Arrow(Texture2D sprite, Vector2 sourceEntity, Vector2 targetEntity, float arrowSpeed, int arrowAttackSpeed, int damageDone, bool isArrowActive)

```

In the Game1 I have the standard if-click structure and I check if the click is on the minions. But I check this with

```
    foreach (Minion minion in enemyMinions)

```

So - I want to mark somehow the minion I clicked on and then to send the arrow directly to its moving location.

How to do that?

Update:

```
        //checks if rightmouse button was clicked to activate the arrow
        if (mouse.RightButton == ButtonState.Released && previousButtonState == ButtonState.Pressed)
        {
            //checks if the right mouse click was on a minion and the minion is in champion's range
            for (int i = 0; i < enemyMinions.Count; i++)
            {
                if (enemyMinions[i].CollisionRectangle.Contains(mouse.X, mouse.Y)
                    && (Math.Abs(mouse.X - enemyMinions[i].X) < vayne.ChampionRange) ||
                    Math.Abs(mouse.Y - enemyMinions[i].Y) < vayne.ChampionRange)
                {
                    //mark the minion that the click was made on
                    theCurrentTarget = enemyMinions[i];

                    //sets the arrow.targetEntity to that particular minion
                    arrow.TargetX = theCurrentTarget.X;
                    arrow.TargetY = theCurrentTarget.Y;

                    arrow.IsArrowActive = true;
                }
            }
        }
        previousButtonState = mouse.RightButton;

```

# Answer
From what I have understood from your original post and the other clarifications, I think you want to create an Arrow at the position of sourceEntity and make it move with constant arrowSpeed towards the position of targetEntity until it reaches it, position which may have changed from the creation of the Arrow. Correct me if I am wrong.

I see that you are using a float for the Speed of your arrow, instead of a vector. You can use a 2D vector equal to the difference between the target position and the current arrow position, calculate it's magnitude(or length), and then add to Arrow.currentPosition a fraction of v vector equal to arrowSpeed / length :

Vector2 v = targetEntity.currentPosition - Arrow.currentPosition;

float length = sqrt( v.x\*v.x + v.y\*v.y );

Arrow.currentPosition += ( v * ( arrowSpeed / length ) );

When updating the Arrow's current position, you may want to have the targetEntity passed by reference, so you will have access to the targetEntity's current position. If you don't pass it by reference, the targetEntity's position will always remain the same and your Arrow will stop at targetEntity's original position.

The Arrow will eventually end the chase and hit targetEntity.

EDIT:

For the code you are using, Arrow.TargetX and Arrow.TargetY need to be pointers, instead of floats. Then, you do it like this:

```
//mark the minion that the click was made on
theCurrentTarget = &enemyMinions[i];

//sets the arrow.targetEntity to that particular minion
arrow.TargetX = &theCurrentTarget->X;
arrow.TargetY = &theCurrentTarget->Y;

```

Notice that `theCurrentTarget` also needs to be a pointer.

You will need to make some changes in how you create an arrow, using the constructor:

Say you have 2 objects of class Minion: Entity1 and Entity2. Entity1 is the source of the arrow and always stays in the same spot. Entity2 is the target of the arrow and it is moving.

```
public Arrow(Texture2D sprite, Vector2 sourceEntity, Vector2 targetEntity, float arrowSpeed, int arrowAttackSpeed, int damageDone, bool isArrowActive)

```

Say you create an Arrow object, like this: Arrow chasingArrow( some\_sprite, Entity1.position, Entity2.position, ...(the rest of the arguments are irrelevant) )

When you call this constructor, the object of class Arrow that you create will save the value of the targetEntity vector as it is now and that value (which is inside the Arrow object) will never change, even if the value of the vector inside the Entity2 object will change. You need to *link* the vector in Entity2 with the targetEntity vector in chasingArrow. You do that by not copying the value, but by copying the pointer. That way, the targetEntity pointer in chasingArrow will always point to the current position of Entity2.

Change the constructor like this:

```
public Arrow(Texture2D sprite, Vector2 sourceEntity, Vector2* targetEntity, float arrowSpeed, int arrowAttackSpeed, int damageDone, bool isArrowActive)

```

Notice the only modification: **Vector2\* targetEntity**. Now it will take a pointer to a vector as a parameter instead of a vector.

And when you create an Arrow object, do it like this:

```
Arrow chasingArrow( some_sprite, Entity1.position, &Entity2.position, ...(the rest of the arguments are irrelevant) )

```

You can also pass Entity1.position by reference, but it works as it is now, since the sourceEntity only matters at the moment the Arrow is created.

If you have any other questions, just ask.
> 1 votes

# Answer
Assuming the target entity is moving (since you used the word 'chase'), you would have to pass the target entity's location into an update method for your arrow, and adjust the arrow's velocity based on the vector between it's and the target's location.

It's hard to be more specific considering we only know your constructors.
> 3 votes

---
Tags: game-design
---


# Question
Title: How do I get the mouse position relative to the window, not the whole screen?
I am developing an XNA game. I run it in window mode.

I need to handle mouse events, but when I use the `Mouse` class from `Xna.Framework.Input.Mouse`, I get the the mouse position on the whole screen.

I use this code:

```
MouseState state = Mouse.getState();
Point position   = new Point(state.X,state.Y);

Rectangle hitbox = new Rectangle(180, 410, 14, 14);

if (area.Contains(mousePosition))
{
    //fire event
}

```

How do I detect the mouse position within the current game window?

# Answer
`Mouse` should default to reporting its position relative to the game window, but can be configured by assigning the appropriate window handle to `Mouse.WindowHandle`.

The documentation is here.
> 2 votes

---
Tags: xna, c#, mouse
---


# Question
Title: GUIText size on 4:3 and 16:9 is different
I have a text (guiText) on the screen.

It shows correctly when viewed on `16:9` resolution.

But it scales up when viewed on `4:3` (e.g iPhone4).

I am using following `ObjectLabel` script to place it on the same position regardless of screen resolution. Which is working fine for 16:9 and 16:10.

Object Label

# Answer
GUI units are screen pixels. If you resize your screen, the GUI objects remain anchored to their positions relative to the top left screen corner. There are two ways to reescale GUI coordinates: calculating them based on screen size in the OnGUI routine, or change the GUI matrix to keep them proportional to the screen size. Both methods have their pros and cons. Calculating the coordinates proportionally to the screen size will keep things in their relative places (itens aligned to the right side of the screen will still be right aligned, for instance) but the text itens will not be scaled - in a bigger screen they may seem too small.

Changing the GUI matrix will scale everything. It's easier, but the problem is when the screen aspect differs from the original. If you design your controls in the 4:3 format, in a wide screen they will appear stretched horizontally, and vice versa. You can set the proportion only to height or width, but the relative position of controls aligned to the right or bottom sides may be clipped or shifted to the left.

The original width and height must be defined in the originalWidth and originalHeight variables below. In the OnGUI function, the original GUI.matrix is saved and substituted by a new one with the scale modified to keep the original proportions. Everything in GUI will be scaled, from coordinates to text and images. If some GUI item Rect uses Screen.width or Screen.height to calculate its position (to align at the bottom or at the right, for instance), substitute by originalWidth and originalHeight.

```
 var originalWidth = 640.0;  // define here the original resolution
 var originalHeight = 400.0; // you used to create the GUI contents
 private var scale: Vector3;

function OnGUI(){
  scale.x = Screen.width/originalWidth; // calculate hor scale
  scale.y = Screen.height/originalHeight; // calculate vert scale
  scale.z = 1;
  var svMat = GUI.matrix; // save current matrix
  // substitute matrix - only scale is altered from standard
  GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
  // draw your GUI controls here:
  GUI.Box(Rect(10,10,200,50), "Box");
  GUI.Button(Rect(400,180,230,50), "Button");
  //...
  // restore matrix before returning
  GUI.matrix = svMat; // restore matrix
}

```

> original solution was provided by 'aldonaletto' on unity3d forum, I dont take credit for this, but I hope this helps you.
> 1 votes

---
Tags: unity, gui
---


# Question
Title: Should I use inheritance or interfaces for an inventory system?
I'm about to start programmin an inventory, harvest and loot system. I will need enemies that drop items, harvestable environmentals that yield resources and an inventory system that takes items and resources.

Should I solve this with interfaces, class inheritance or both? Why? Or is it just up to my programming style? I'm more familiar with inheritance, but if interfaces give an advantage I'd use them and get used to it.

# Answer
> 2 votes
In my humble opinion you should use neither. I would go with the Entity Component System and use composition instead of inheritance in this case. If you do choose to use one of the two, I reccommend using an Interface.

You should avoid inheritance and use interfaces when there is no substantial inherit connection between the various classes that share the same functionality. If you do use inheritance then the base class might be pretty abstract. This is pretty much the same thing as an interface. The main advantage of interfaces over inheritance (in the languages that have interfaces) is that you could easily have a class that implements multiple interfaces. Multiple inheritance is not available in some languages and even in languages where it's available (e.g. C++), it is known to cause trouble (e.g. Diamond of Doom).

---
Tags: unity, interface, inheritance
---


# Question
Title: With what projection matrix should I render a portal to a texture?
I'm using OpenGL. I have problem with my engine's portal implementation. To create the first portal I do:

1. create a virtual camera with the position of the second portal and the correct orientation
2. render whole scene from virtual camera to the texture using FBO
3. render the first portal using the texture created before.

The problem: The virtual camera is rendering to the texture with the main projection view, so when I use this texture to render the first portal, everything is rescaled. The virtual camera should only render some part of the view to prevent scaling.

The problem could perhaps be solved by changing the virtual camera's projection matrix, but I don't know how to calculate such a matrix.

Here's how it looks:

This picture shows one portal (the texture is a little bit deformed on bottom and top, but that's not important now) and some other objects. The second portal is behind the camera, and the camera is in the middle between the two portals.

We can clearly see that the portal texture is rescaled down to the portal size. As I said before, I think the virtual camera should have another projection matrix, but how do I calculate it? Or is there a better way?

# Answer
> 4 votes
**Disclaimer**: I haven't tried making a portal system, but I think this should work.

From your description I gather that you are rendering the "portal camera" to a buffer then applying this buffer as the portal texture. This is what I would do for a security camera, but for a portal I think we can do something else. If you stick with this method though, then changing the projection matrix would probably work.

However I think you should be doing is;

* Draw the scene as normal (Builds a depth buffer)
* draw the portal geometry to a stencil buffer.
    + Keep depth testing on so you don't draw the portal stencil over occluding geometry.
* Flush the depth buffer
* Render using the portal camera (which has the same projection matrix) and the stencil buffer such that you only draw to the portal area.

For more info on how to do this please see here.

**PS:** If sticking with the first method, then I don't know how to work out the projection matrix but you can fix this by simply changing the UV coordinates for the portal geometry. The UV coordinates can be calculated by projecting the portal vertices to the screen (multiply each vertex by world * view \*projection) then dividing the x and y by the screen width and height (you may not need that last division, I can't currently remember if you get screen coordinates after multiplying by the projection or just some screen coordinate expressed from 0-1).

**PS2:** If I was to guess at calculating the projection matrix then;

For the portal camera projection matrix I think the FoV would be half the angle between vectors Vert1-CamPos & Vert2-CamPos (where Vert1 and Vert2 are either the top or bottom 2 vertices of the portal) and the aspect ratio would be the ratio of the width and length of the portal geometry. When calculating the angle you may need to 0 the y component of each vertex and the camera position and keep in mind this would only work for a rectangular, y-axis aligned portal.

If doing the whole projection matrix yourself, then the frustum is created by the 4 vectors defined by going from each vertex of the portal to the camera position.

---
Tags: opengl, textures, rendering, portals
---


# Question
Title: XNA and HLSL shaders - Instancing using World Matrix array
I have posted this question on StackOverflow and was directed here, so I'll just copy the question:

I am attempting to improvise some sort of hardware instancing in my game. I wish to draw multiple trees with only one Draw Call.

So far, I have set up a class which holds the model, texture, and an array of Matrices. Each matrix corresponds to a location of one tree in the game world.

I have determined to use 50 copies of object as hard coded limit within my class and my shader.

I am sure that the matrices generated are correct ones. Using Basic effect with multiple draw calls and switching out World matrices between them does yield in correct number of trees on their correct locations.

I have tried a shot-in-the dark approach:

```
float4x4 View;
float4x4 Projection;
float4x4 World[50];

...

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output[50];

    for (int i=0; i<50; i++)
    {
        float4 worldPosition = mul(input.Position, World[i]);
        float4 viewPosition = mul(worldPosition, View);
        output[i].Position = mul(viewPosition, Projection);
        output[i].texCoord = input.texCoord;

        return output[i];
    }

}

```

To my surprise, this actually did compile, and to even greater surprise, didn't melt my GPU.

To not so big of a surprise, this draws only one tree, the first one, as the loop ends as soon as it hits the "return" keyword as any sane mind would expect it to.

I have tried my google-fu skills with googling this kind of problem, but majority of the results deal with C++ code (I'm using C# + XNA), and their approach to the problem is basically to collect all needed model's vertices and forward all that, as one huge model drawn with one World matrix position.

Is there a reliable way to draw one model using an array of World matrices on a shader, or must I collect all vertex data and batch it that way?

P.S. I am attempting to toy around with nested structures, like these:

```
struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 texCoord : TEXCOORD0;
};

struct VSOUT
{
    VertexShaderOutput output[50];
};

VSOUT VertexShaderFunction(VertexShaderInput input)
{
    VSOUT output;

    for (int i=0; i<50; i++)
    {
        float4 worldPosition = mul(input.Position, World[i]);
        float4 viewPosition = mul(worldPosition, View);
        output.output[i].Position = mul(viewPosition, Projection);
        output.output[i].texCoord = input.texCoord;

    }

    return output;
}

```

But, of course, as the loop gets unrolled, the very next instance of Output gives an overlapping semantic error. I am pretty sure there are no POSITION50 and TEXCOORD50 semantics :p So, how would I go about solving this problem?

Thank you in advance!

# Answer
Just as the vertices can stream through the GPU pipeline to be modified per the shaders you write when calling `Draw`, so can the 50 world matrices be streamed through the pipeline at the same time. So you set up 2 streams, one for the vertices that repeats itself each time a new matrix from the other stream goes through.

Check out how that is done in Xna in this sample: http://xbox.create.msdn.com/en-US/education/catalog/sample/mesh\_instancing
> 0 votes

---
Tags: xna, c#, shaders, hlsl, instancing
---


# Question
Title: What is the license you need to publish to Xbox 360 from Unity3D?
I have a license for deploying and releasing games using XNA.
What is the license I need to deploy and publish games using Unity3D, and how do I get it? I have found very little and unclear information about how to publish to Xbox360 from Unity3D, and I can't come up with search words to get this information.

# Answer
Unity for consoles is only available to you if you are also a licensed developer for that console. Once you have such a license from the platform vendor (Microsoft, in this case), you can contact Unity for further details via their contact form (this is the advice they give you on this page).

Unity doesn't build on XNA, and having the ability to publish to the 360 via XNA does not qualify you for the use of Unity on the 360. You need to be a fully-licensed developer for the platform, with access to the XDK, et cetera.

Microsoft's Xbox developer portal is here. You may want to read their FAQs.
> 5 votes

---
Tags: xna, unity, licensing, xbox
---


# Question
Title: Is it sensible to run a Socket.IO setImmediate loop for each connected player?
Instead of a game loop, I want something different: My game does not have much action going on; just moving users over a tile map with correct timers in between.

Since I am using Socket.IO, I want to run a "mini game loop" inside the `io.sockets.on("connected"`-part of my script. I am thinking to run a `setImmediate` checking a few variables to know what to do with the player.

The way I understand socket.IO, it would create this `setImmediate` function for each client that joins the server. (Because it runs inside the "connected" event handler.)

Let's say 1000 players join the game. If what I fear is true, this approach seems bad. Have I misunderstood `setImmediate`?

# Answer
> 5 votes
Socket.io will emit `connected` event for every connected socket. So in your case you will create loads of loops there.
It is better to have list of sockets, and one loop separately.

As you've said - your case is simple - so keep it simple, do not overcomplicate.

```
var sockets = { };

server.on('connected', function(socket) {
    // runs for every connection
    sockets[socket.id] = socket;

    socket.on('disconnect', function() {
        delete sockets[socket.id];
    }
});

var UPS = 20;
var gameLoop = setInterval(function() {
    var socket;
    for(var id in sockets) {
        socket = sockets[id];
        // ...
    }
}, 1000 / UPS);

```

---
Tags: node.js, websocket
---


title: Browser UDP Relay with TCP Websocket

text:
# Question
Title: Browser UDP Relay with TCP Websocket
I'm wondering if this is possible and what obstacles I might face.

I have a game that's browser based, and since I can't send UDP packets from a browser, Can I use a plugin that the browser connects to via a web socket, and have that plugin send the UDP messages?

When the plugin receives a UDP packet, it'll then relay it to the browser via the TCP websocket?

Could this work? And can TCP handle tons of messages from the plugin even though it's connecting to 127.0.0.1? At least 64 players in this game. The UDP packets are usually no more than 40 bytes.

# Answer
Performance advantages of UDP over TCP is very case dependant based on your specific needs (delivery persistence, order, frequency), in most cases in fact people implement many mechanics to make UDP as reliable so at the end it performs same as TCP.

Plugin can actually can create JS interface to use UDP communication directly without need to create local WS server socket. But implementing such plugin will be an overkill in terms of game development.

You have another option in modern browsers: **WebRTC** which is made for performance over quality, and that can be used for peer-to-peer communication so that players can talk to each other directly but not through the server.

64 players is a lot, and do not try to find "easy solutions" there will be none. You will have to think of "visibility" of clients between each other based on your gameplay, as well you need to think how to simulate 64 players - this is not easy as well, and probably will be hardest bit.

BTW, you might be OK using WebSockets as well, depends on how often you want to send data and how much. Take in account that if you think that it is to hard for WS, maybe you want to much regardless of tech?
> 1 votes

---
Tags: multiplayer, mmo, websocket, udp
---


# Question
Title: Optimising a bool spread on a 2D Grid/List
I'm trying to work out a more efficient way of spreading a bool flag across a 2D tilemap, as the way I currently have it setup works, but has to run far too many times to work properly. This isn't a massive performance problem as the code doesn't run every tick, but it's still annoying as there must be a better way! Hopefully somebody on here can help...

At present, the game code grabs a map XML file and deserialises it into a List of "mapsquares" (simple little class that holds all the info about that square in memory, so it can be modified). This works great for most of what I want to do, but is causing an issue with "power spreading".

Each square that contains a building uses a powered/notpowered bool, with the idea that power spreads from the station along power lines to other buildings. If it's connected to the grid, it's powered.

However, trying to get this working properly is proving messy, I've already followed the advice on here and generated neighbouring tile co-ordinates for every square when first loading the map file, this is used for exploration, but I thought it would also do power spreading.

It kinda works:

```
public void RegeneratePower()
    {
        MapSquare msnsq = new MapSquare(0, Vector2.Zero);
        MapSquare msssq = new MapSquare(0, Vector2.Zero);
        MapSquare msesq = new MapSquare(0, Vector2.Zero);
        MapSquare mswsq = new MapSquare(0, Vector2.Zero);

        foreach (MapSquare ms in mapSquares)
        {
            if (ms.HasBuilding)
            {
                Vector2 msn = ms.North;
                Vector2 mss = ms.South;
                Vector2 mse = ms.East;
                Vector2 msw = ms.West;

                foreach (MapSquare msa in mapSquares)
                {
                    if (msa.Location == ms.North) msnsq = msa;
                    if (msa.Location == ms.South) msssq = msa;
                    if (msa.Location == ms.East) msesq = msa;
                    if (msa.Location == ms.West) mswsq = msa;
                }

                if (msnsq.HasPower || msssq.HasPower || msesq.HasPower || mswsq.HasPower) ms.HasPower = true;

            }
        }
    }

```

However, it has to be run multiple times to actually spread the power more than 1 square at a time - theoretically I might have to run it as many times as the length or height of the map to ensure it covers everything :(. I thought about using the .Reverse() command to change the List order, or using a different kind of construct instead of a list. What would be the best way of doing this?

Thanks.

# Answer
Use BFS,here. You want to spread power from node A to all the tiles connected to it. Take the node that's spreading power as your initial then do your search to find out all the connected nodes to it.

If that sounds not so familiar, I found this tutorial for you. I quickly read through it and seems like a good fitting example for you.

Good luck :).
> 1 votes

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


title: Representing realistic population

text:
# Question
Title: Representing realistic population
What's the best way to represent a realistic population number (e.g USA:317,569,000) in game?

For example, Civilization your city has 1 Citizen. Obviously, a city can't just have one person in a city but Civ seems to do a good job at representing citizens that way.

What I'm after is to represent 300+ million in an easy to swallow number to a player.

I have a calculation which states that, in theory, to have 300+ people you would need 79 million 4 person dwellings. (I understand this may not be totally accurate, but it works for my needs)

It seems tedious to have the player do that with a couple of methods I've thought about.

So my question then is I need some way to make the game and the player aware that the player's city has 100,000 people in it without making the player create 25,000 dwellings.

**Update 1:**

As **@Patrick M** states, in Civ you only have to build one of a building type.

Much like dwellings, it doesn't make sense to force the player to build one police station/1000 people.

I have a formula that calculates the theoretical population limits of an area and I want to constrain the player to this limit. (Players have a reason for wanting larger regions)

However, I don't want the player to instantly have 10,000 citizens simply because he built a "house/neighborhood".

I want to represent real world constraints and requirements without the super micro management that would be present in forcing the player to build 2,500 dwellings (to get the 10k)

# Answer
> 5 votes
Making an answer from my comments, because I'm ending up more long winded than I expected.

Riffing on your Civilization thought, consider that you build one theatre or one supermarket and that's "enough" for the city whether it has 3 or 30 citizens in it. Whether your goal is to get a reasonable looking visual proxy or to require a reasonable amount of building management for a player to grow their city controls what type of abstraction will work for you.

You ask for a 'best' approach: well, "it depends" :-)

I think you might provide even more context over what your game is like. For example, Sim City does require you to build a police station for X many citizens or crime skyrockets. But the scope of Sim City is smaller than Civilization, so it works with that granular level of micromanagement.

Consider answering at least

1. What is the overall objective of the game? Conquer the world with might or subtler methods?
2. What type of gameplay are you wanting? Tactical? Strategy? Simulation? Real-time or turn-based?
3. What is the scope of the game? How many cities/regions do you expect a player to control?

These should get you a rough guideline of what to start with, but ultimately, you'll probably have to tweak the micromanagment characteristics of the game based on what feels right (requires effort and thought, but is still fun without bogging you down).

So for example, you have listed USA as a region at ~317 million population. Say you decide this is a reasonable halfway point for the scope of your game, so you want people to be controlling twice this amount of people & resources at the end of the game. So you set your target at ~750 million population. Now you decide you want your game to last for ~5 hours under typical circumstances and you decide that if a user has to manage their housing more frequently than once every 15 minutes, they'll get bored with that mechanic. That gives you a guideline for ~20 houses (skyrises, neighborhoods etc.) = ~750 million people, or around 37.5 million capacity for each (house building) they build.

You mention not wanting to immediately grant citizens to fill these buildings. That means you will have to decouple your growth calculation from your infrastructure building. I would suggest you have separate resources be consumed for each (e.g. it takes `wood`+`workers`+`time` to build houses and `food`+`time`+`happiness` to fill them with people).

It sounds like you want to impose a 2-tier cap on the population for a region: population will grow until the minimum of either the built infrastructure total or the region total is built. A region population max cannot be increased, but you can built more infrastructure up to (or even over) the region cap. Or, you could make this abstraction work by only allowing a given region to have **y** number of housing buildings built in it.

Also, a citizen Civ is a flexible thing. A Pop1 city might have ~100 citizens, a Pop2 ~500, Pop3 is ~2,000 etc. until Pop30 is ~50 million. You can usually see the 'real' number on the city management screen somewhere, as well as your nation's overall population. This neatly encapsulates the exponential growth of populations.

If it seems weird to you to have the first building immediately support millions of people (for instance, you have the game start in prehistory), then an exponential scale could be right for you. Or you could take a different approach with upgrade-able buildings. The Ceasar video game series had housing that started out at low level and would automatically upgrade if you provide it with certain resources (like food, water and goods). Alternatively, you could use a resource-spend model where upgrading the buildings make them exponentially bigger and better, but each upgrade costs progressively more resources.

This obviously isn't a direct answer to your question, but hopefully you'll find some inspiration from my ideas.

P.S. It sounds like a fun game! Good luck!

# Answer
> 8 votes
TL;DR Represent key elements in your city such as neighborhoods, armies, huge-centers such as malls, stadiums, instead of representing each dweller individually.

If your city has 100,000 people you don't really need to represent those 100,000 or even 25,000. The player only cares about the output/input those 100,000 represent as numbers. For example if your city has 1 million and increased into 1.5 the player only needs to know that the consumption of electricity will increase by 50% factor (that's just an example).

Regarding managing those dwellers, IMO, you don't need to introduce too much micro management, even 200+ can be too much to manage. You only need to represent key elements in your population, for example armies, scientific centers, neighborhood, so the player won't manage each citizen but actually the facilities and areas that represent those citizens.

# Answer
> 2 votes
You can represent population groups by some small populated regions (maybe 5-6 houses or a whole neighbourhood), and so 100 000 citizens can be represented by 600 regions with an average 166.6 citizens/region or even less regions for simpler micro-management. You also don't need to be aware of what each citizen is doing, you only need to be aware of what the entire region is doing.

---
Tags: game-mechanics, mmorts
---


# Question
Title: Procedural terrain - how to blend textures between dynamic meshes
I think I should structure this question better.

I'm developing a procedural terrain structured with voxel chunks.

**Every chunk**:

* contains a NxNxN voxel array generated with perlin noise 3d
* contains a Mesh derived from the surface points of the voxel array
* is rendered with marching cubes algoritm

**Every mesh** has its own Material

**Every Material** is made of 3 texture: one main texture and 2 minor textures to be blended with the main one depending on the slope. Every material has its own shader attached.

So I have a terrain made of a certain number of chunks, that are a certain number of meshes generated as the game launches. Inside every chunk blending if okay, since I have the only material for the current mesh I have only to blend its textures depending on heights - and this is done by the shader.

In this attached image

you can see quite clearly what I acheived until now. As you can see, everything is mostly divided in "squares", which are the meshes. Each square has a texture green or beige (grass or sand).

**My concern is that**: When passing from grass to sand there is no blending, i.e. blending between 2 meshes is my real problem, because inside the shader if have the surf function which iterates over all the input vertices. But those vertices are only from one mesh. To blend correctly I would need informations also about the vertices of the mesh nearby.

So the question is: **how can I blend properly materials belonging to different meshes?**

# Answer
Check out this link(Archive.org mirror), it should work for you (massive terrain + blended textures). Has a huge demo project size since he uses a big static mesh, but he applies the textures using a shader as well so you can take a peek at his blending algorithm. He also managed to make it seamless with multiple meshes.
> 1 votes

---
Tags: unity, procedural-generation, blending, mesh
---


# Question
Title: How do I make the screen shake when the player takes damage?
I am making a 2D game and I'd like a visual cue when the player gets hurt. Currently, I have a simple blinking red dot that shows up for 2 seconds after damage, but it's not very immersive.

Many games shake the screen to indicate damage. How could I implement such an effect?

# Answer
Define a vector that shifts the rendered position of everything.

When that vector is `(0,0)`, the screen is still. Changing it randomly every 5-10 frames causes the screen to shake. You can smooth this change if you like.
> 4 votes

---
Tags: 2d, graphic-effects, screen
---


title: Viewport Pixels trouble - Intel XDK

text:
# Question
Title: Viewport Pixels trouble - Intel XDK
I'm creating a game in Intel XDK, and using their API to get the viewport width and height. These are coming back at 1122 pixels and 746 pixels, respectively.

When adding my text at 150 pixels down and 100 pixels across its being placed in the center at the bottom.

```
var canvas= document.getElementById('game');
var ctx = canvas.getContext('2d');
var width = 1122,height = 746;

ctx.fillText(window.innerWidth+' - '+window.innerHeight,100, 150);

```

That is writing on the screen 1122 - 748, but it's placed at the bottom of the screen. Not 100 pixels down by 150 pixels across. - It's directly in the middle.

# Answer
This is an issue of what sets the size; imagine the whole canvas is the default size (300x150), and the CSS stretches that to display over the size of the screen. The point where you write the text is in the middle bottom, as expected in that context, but doesn't look like the right spot.

There are a few ways to address this, but the easiest might be setting the size of the canvas (in JavaScript, to manage the draw order):

```
        var canvas= document.getElementById('game');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var ctx = canvas.getContext('2d');

        ctx.fillText(window.innerWidth+' - '+window.innerHeight,100, 150);

```

If you add some alignment to the canvas style (top:0; left:0; position:absolute) and get rid of the scroll bars (body { overflow:hidden }) this should get you the output you expect.
> 2 votes

---
Tags: android, ios, intel, window-management
---


# Question
Title: Finding the nearest object, considering obstacles
For the purposes of this question, we'll assume it involves a Janitor assigned to clean up trash in a building. Given that it is a building, it is safe to assume there are one or more rooms, walls, etceteras that act as physical obstacles.

It's time for the janitor to earn his paycheck, and he heads to the nearest piece of trash to clean up. We can resolve this in two ways:

1. The cheap way. Simply do a distance check and head to the nearest.
2. The expensive way, Path-find to pieces of trash and pick the one with the easiest/shortest route.

Now, (1) is cheap computationally but can give false results. A piece of trash could be on the other side of a wall but only 3 "squares" away - it'll actually take the janitor a lot more time to get there then say, a piece of trash in the same corridor 5-squares away.

(2) would give more accurate results, but requires a metric-ton more computation.

Are there better approaches to "nearest thing", or would you just have the janitor wander around on a pre-set route that covered "as much as possible" and just have him clean up as he goes?

# Answer
If you have rooms and corridors separated by walls and inter-connected by doors you can assume each door is a node in a graph. The door-graph can be pre-computed, with costs equal to the distance between the doors. You create a cost graph, including the minimum costs from the janitor to each door based on the current position of the janitor and the constant distances between the doors. Then for each pile of trash, you check all the doors in the same room and pick the minimum cost (that cost is the distance from the janitor to that door + the distance from the pile of trash to that door). After that, you just pick the pile of trash with the minimum cost.

It is still a path-finding algorithm, but I think it will work pretty fast, even for massive amounts of data, but I don't think one janitor can clean that much trash :).

Hope it helps.
> 1 votes

# Answer
Well this is assuming that this janitor is some form of god who knows where all the trash is. Pathfinding to every piece to figure out distance is a pretty bold move for someone undercover. In fact he may consider using something such as A\* to figure out the nearest objects.

Instead let's look at it from an alternative perspective:

> The janitor knows he must clean, but does not know where there is trash. The janitor must then go search for trash to clean.

Now this janitor could either clean as he goes, or he can scout things out first. Using a grid system similar to the A\* pathfinding above, you could create a grid that constantly searches outwards until it finds trash, starting with the janitor.
> 1 votes

---
Tags: 2d, path-finding
---


title: Slick2D: constructor vs. init method

text:
# Question
Title: Slick2D: constructor vs. init method
What is the difference between the constructor of a `BasicGameState` and the `init` method? It appears that they are both called at the same time when the `BasicGameState` is registered in `StateBasedGame`, so what makes them different?

A follow up question to this is how do I run a method only when a state becomes active? Initially I thought the `init` method was only called when a new state becomes active, but this is not true. Note that I'd like to call this method only once at the beginning of the new state, so putting it in the `update` method seems like the wrong place.

# Answer
This really boils down to coding conventions. The general idea is that the constructor's primary purpose is to create the object itself. However that object is a dumb object and shouldn't actually *do* anything until specifically told to do so.

The `init()` method, also known as `create()`, `initialize()`, etc... is the used to actually run code on the object.

In most cases, you're going to use your object as soon as it's created. Therefore you might not notice the need to separate these concerns in many cases. However there may be cases where you want some object, but you don't need it doing anything just yet.
> 3 votes

# Answer
I agree with what Terje said, as you might want to go into the documentation and poke around until you find what you're looking for, but here's a quick thing for you.

Whenever a game class offers a different choice to use rather than a constructor, it is almost always best to use that. LibGDX has a similar method called `create()`, which is custom-tailored so that the game objects are spawned in the correct manner. While there's nothing wrong with using constructor's, if a framework provides you with that alternative, use it. I would still recommend looking into it, however.
> 1 votes

---
Tags: java, lwjgl, slick
---


title: Demo (and real game) Protection

text:
# Question
Title: Demo (and real game) Protection
In a few months I plan to start showing off the (hopefully commercial) game I'm working on to the public (internet). The thing is, besides screenshots and a trailer (of say feature functionality), how does one properly go about making a demo that can be protected?

Let me explain a bit. The game is a cross-platform RPG of a sort. Right now, the way I have the game coded is that it reads in map, character, etc data from files and that decides everything which allows me to expand the world/story just by config files and adding assets.

Meaning, my worry is if I make a demo version of the game, which is say the real game but then all the assets/config files/etc are removed so that its just a demo with the very first map/level. Is there a way to protect against someone just then putting out the datapack of the real game (when released) and now suddenly anyone with the demo EXE can play the real game?

The demo protection is kinda my first priority as I want the demo out there for a while before the real game is released. I can always decide on what protection methods I choose from the real game later (before release, but still later.. )

I guess it boils down to is there any real way to protect the game anyway (I don't want to restrict users to having to do any online checks because this game will be cross-platform and not require internet to play it). Last thing I want to do is mess with legit users. And I'd like to leave the assets open if possible since that just means easily patching folders and allowing modders to mess around a bit.

I mean, even if I set up a basic key license system, whats really stopping 1 person from uploading their key and a copy of the game somewhere? I've seen people talk about doing frequent updates so that the binary changes and they have to re-crack the game. But, who needs to crack the game at all when you can get 1 legit copy and then spread it around?

I'm not sure if maybe I'm missing something, I'm just trying to make sure I'm not. Does it really just boil down to:

1. Slap basic key license protection on it.
2. Remove asset/config files from demo
3. Hope for the best

*Any and all advice* is appreciated! I'm very new to all this ; - ;)

**Sorry if this is a duplicate! Couldn't find much on the demo concept.**

# Answer
> 12 votes
Have you considered hardcoding something like a time limit into the demo version of the engine?

The thing is, no matter how much you protect your demo, the game will be pirated somehow once it comes out. Whether it's by using the demo or just by using the main game, it's going to happen if the game's popular enough.

People who don't want to pay for your game *won't pay for your game.*

People who do want to pay for your game *will pay for your game.*

This applies to anything from the smallest indie game to the the largest triple-A title - about the only way to get around it is to make connecting to your servers not only mandatory but gameplay-related, i.e. an MMO, rather than the silly Assassin's Creed always-online DRM. Since you've already said that's not an option, I suggest you embrace it.

As an independent developer, the best way for you to get more sales is to get more eyes on your game. People that aren't inclined to piracy will play your demo and then either buy the game or not. People that are inclined to piracy may play your demo, find the assets as you described, and so on, and then *still may or may not buy the game.*

# Answer
> 5 votes
Not sure what you meant by "branch" in your comment, but it's possible to make two different executables (demo and full version) from the same source code tree using conditional compilation. You can make a compile-time option to include only the ability to play the first episode. (For example, in C++, you might use `#ifdef` commands around code intended only for the full version.) You could have the demo version produce at least the following gameplay effects:

* The first episode's assets are stored in a zipfile, and the demo version checks for a digital signature on this zipfile before starting. To use mods, players would have to pay for the full version.
* Reshuffle the encoding of opcodes in your scripting bytecode when compiling the demo.
* Completely remove the handlers for one or more script opcodes used only in later episodes. This will cause set pieces in later episodes to fail even if the file modification check and the opcode encoding are patched.

---
Tags: assets, copyright, demo
---


# Question
Title: Do the predefined HLSL semantics carry any meaning?
I'd say there are 3 kinds of HLSL semantics:

* `SV_*` group - these are "system value" semantics which DO carry special meanings (e.g. assign special input/output data to/from shader stages)
* predefined semantics - e.g. `NORMAL`, `POSITION` and so on... They are mentioned in the docs but I failed to find any special meaning assigned to them
* semantics defined be the user - which can be anything (e.g. `MY_AWESOME_TEXTURE_SEMANTIC`) which apparently have no special meaning either

In addition, the docs say that more than one input/output value can have the same semantic assigned (e.g. '`NORMAL2` and `NORMAL2`). I guess that it doesn't include the `SV_*` group, though.

So besides the first group - do semantics carry any meaning at all? Do they even serve any purpose at all? :P

# Answer
> 7 votes
> Do they even serve any purpose at all?

Yes for the user and developer of the shader, semantics conveys information about the intended use of a parameter. So you will know that `POSITION` is intended to be used as vertex position, `NORMAL` as vertex normal etc. Think of this as in-code documentation (not strictly the same though).

> Do semantics carry any meaning at all?

They don't carry a meaning for the system, as they are not interpreted, but again for the user. You don't want to give vertex position a NORMAL semantic, it's really like deceiving the user/developer of the shader, it's confusing, it's like writing wrong documentation.

---
Tags: hlsl, directx11, tessellation
---


title: Heightmaps with several textures

text:
# Question
Title: Heightmaps with several textures
I got a full functioning heightmap loader, however I can only use one texture. Now I want to implement more textures (like diffrent textures depending on heights ect, Possibly a structure that makes it easy to implement diffrent coditions of where to use certain textures)

But I'm a bit unsure how to go about doing this. Could anyone point me in the direction of a good guide on how you would implement something like this.

# Answer
The term you are looking for is multitexturing. For this, you have to send every texture you want to use to the pixel shader, and there decide from some per-vertex weight factor how much each texture will add its value to the final color. For example, if you want to use 4 textures, you add a float4 value to your vertices (I'd call this weight). Then in pixel shader sample your 4 textures into `float4 col1,col2,col3,col4` values. The final color then would be:

```
 float4 finalColor = col1*weight.x + col2*weight.y + col3*weight.z + col4*weight.w;

```

You should set the weighting while generating your heightmap, and the weights should normally add up to 1. The logic, which you generate those should be trivial for you, but if you are having problems, then I recommend Riemers' tutorials which is XNA, but it can be easily implemented. You can even look at his multitexturing algorythm based on terrain heights.
> 1 votes

---
Tags: c++, textures, directx11, heightmap
---


# Question
Title: Easiest way to smoothen coarse mesh with HLSL?
I've browsed through a couple of presentations and papers about DX11 tessellation and they all say that one of the most common usages of tessellation is to take a coarse (low poly) mesh, smoothen it and then apply displacement mapping. They mention mainly two smoothening algorithms (although I might be wrong, I'm new to the topic): Catmull-Clark and PN Triangles. The former's algorithm is pretty simple to understand but honestly I don't know how to implement that with HLSL. PN Triangle's algorithm seems pretty straightforward.

But maybe there are other important algorithms. Which one is the easiest to implement? Or maybe one is significantly faster that the others?

Or maybe I'm doing it all wrong? :P

# Answer
I think phong smoothing is the easiest to implement and it is the most lightweight algorithm for this (as far as I know), though it may produce lower quality results. Implementing it is as easy as copy-pasting this code and applying it in your domain shader (that is if you already have tessellation working):

```
struct ConstantOutputType //This is what the hull shader outputs
{
    float edges[3] : SV_TessFactor;
    float inside : SV_InsideTessFactor;

    float3 f3B0 : POSITION0;
    float3 f3B1 : POSITION1;
    float3 f3B2 : POSITION2;

    float3 f3N0 : NORMAL0;
    float3 f3N1 : NORMAL1;
    float3 f3N2 : NORMAL2;
};

//The new functions
float3 project(float3 p, float3 c, float3 n)
{
    return p - dot(p - c, n) * n;
}

// Computes the position of a point in the Phong Tessellated triangle
float3 PhongGeometry(float u, float v, float w, ConstantOutputType hsc)
{
    // Find local space point
    float3 p = w * hsc.f3B0 + u * hsc.f3B1 + v * hsc.f3B2;
    // Find projected vectors
    float3 c0 = project(p, hsc.f3B0, hsc.f3N0);
    float3 c1 = project(p, hsc.f3B1, hsc.f3N1);
    float3 c2 = project(p, hsc.f3B2, hsc.f3N2);
    // Interpolate
    float3 q = w * c0 + u * c1 + v * c2;
    // For blending between tessellated and untessellated model:
    //float3 r = LERP(p, q, alpha);
    return q;
}

// Computes the normal of a point in the Phong Tessellated triangle
float3 PhongNormal(float u, float v, float w, ConstantOutputType hsc)
{
    // Interpolate
    return normalize(w * hsc.f3N0 + u * hsc.f3N1 + v * hsc.f3N2);
}

```

Use these functions on your hull shader output vertices to get the smoothed vertices (positions,normals). I think AMD released this code some time ago, though I may not remember correctly.
> 2 votes

---
Tags: hlsl, directx11, tessellation
---


# Question
Title: When would you use an octree in a voxel Engine?
I've been reading about Octrees, and I understand how they work (or at least I think I do). However, I can't figure out why you would use octrees instead of a simple multidimensional array.

In my project, I use chunks in my world. Every chunk is made up of 16x16x16 voxels. If I need to access a voxel, I just use the notation `myChunk[x][y][z]`. If I need to check neighboring voxels, I can use the same notation. I've already implemented frustum culling, face merging, and hidden surface determination. With these optimizations and this simple multidimensional array, I can render about 500 chunks at 80 fps. So, in which situation would I use octrees in this kind of Voxel Engine? Or is it useless?

I can see the purpose of octrees if I would implement LOD into my voxel engine (which I'm not planning to do). Is my lack of experience in Game Development blinding me on something?

# Answer
**Short Answer**

The Octree is favoured in games and rendering, because

1. It supports *visual* level of detail, sensibly.
2. It provides extremely tight compression of sparsely-populated spaces. (c.f. SVOs)
3. At its lowest level it matches the uniformly-sized / -placed cells required for a voxel world. Other 3D accelerative structures may not do this, as explained below.

**Full Explanation - TL;DR**

Hierarchical spatial subdivision is used for two main reasons

* LoD: To avoid iterating over detail that is far away and thus not of interest;
* To accelerate iteration through a space, e.g. in raytracing or AI pathfinding, by walking a shallow level of the data structure where possible, i.e. where there are fewer nodes across a given distance.

Why is the octree commonly touted? As compared against it's usual competitor, the KD-tree, it...

* Provides uniform subdivision at every level. This is an excellent way to achieve smoothly-degrading LoD (level of detail) while maintaining equal "smoothness" across each LoD grade. So visually this works better than a KD-tree, which isn't really suited to the purpose of LoD.
* Is exactly the same form of subdivision at each level (8 children per parent with the same layout each time) so certain assumption can be made, resulting in fewer conditionals. Perhaps more importantly, this gives us more accurate bounds on processing cost than a KD-tree, which may have `N != 2` subdivisions in each axis... there is a general rule in engineering real-time systems that it is better to have a lower but stable FPS than an FPS with a high maximum rate and a too-low minimum.
* Provides extremely rigourous compression as compared with other 3D spatial subdivision approaches; hence the term, "sparse voxel octrees" (SVOs). This means you can store a relatively enormous space containing a very small amount of voxel solids, efficiently, using an octree.

To give you some further persective, pros and cons for KD-trees:

* KD-trees tend to make more efficient use of space / time overall, in terms of the number of boundary planes the data structure contains, which also improves speed of traversal.
* Simply not suitable for distance-based LoD, due to variable granularity and alignment.

For most, it turns out that the pros of octrees end up winning the day. From an engineering standpoint, conceptual uniformity (simplicity) and predictability of execution paths win the day.

**Less compact alternatives**

In many instances it has been proposed that in spite of the conceptual simplicity of octree traversal, the octree is non-optimal in this sense due to the sheer number of levels of subdivision, which results from the division ratio (1:2 per axis) being so low. If, as in your case, instead of 2x2x2 children per node, there are 16x16x16, we would greatly reduce the number of node boundaries, simplifying cache linearisation which leads to better performance on the overall. Of course, what is crucial to note is that, as with most engineering decisions, this is a trade-off between space and time; the compression of sparse spaces will be far worse with 16x16x16 subdivisions, than with an octree. We call this *flattening* the data structure.
> 6 votes

# Answer
Like any data structure octrees come with pros. and cons.

Octrees are hierarchical. This is usually a compelling reason to use them, if you don't need this property then you probably don't need octrees. Remember to always use the appropriate data structure when actually needed.

You can use a uniform grid for your voxels engine, and it works. But you won't have the extra benefits (and complexity) that comes with an octree. For example octrees are good for voxels LOD, and like any hierarchical data structure they can speed up certain tests like ray casting and frustum culling.

On the down side Octrees are also known as harder to make cache friendly. Also a complete octree with certain depth takes a lot of memory, and that's why sparse voxel octrees exist.
> 1 votes

---
Tags: opengl, c++, voxels, octree, space-partitioning
---


# Question
Title: Monogame: Why is my sprite looking the same on every resolution?
I want that my sprite(Mario) don't look the same on every Windows Phone resolution. If I use this code, the sprite is on every resolution on the right position but it also has the same size on every resolution. In this picture, you see that the sprite on a resolution of 1280x720(it looks the same on 800x480)

Full Size

But if I don't use this code, my sprite looks smaller, but my sprite is no more on the right position if I change the resolution from 800x480 to 1280x720. Is it possible that my sprite changes it's size automatically when I change the resolution and in addition, the sprite should be drawn on the right position. In my case, the sprite should always be drawn in the center of the screen. In this picture, the sprite is smaller on a resolution of 1280x720, but the position is not correct. It should be in the center.

Full Size

What should I change so that the sprite is always drawn on the right position when I change the resolution? I don't know how to do that.

I'm not sure what is/looks better. The first possibility(the sprite has always the same size) or the second possibility(the sprite changes it's size when I change the resolution). In addition, I want that the proportions of the sprite don't change. For example, a circle should look on every resolution like a circle. It should not look oval on a different resolution.

In my opinion, the second possibility looks better, but I'm not sure if I should do it like that. What do you think? Which possibility is better? How would you do it? What possibility is used by professional game designers?

# Answer
> 1 votes
What are you trying to do is to implement resolution independent rendering with Camera2D features. The sprite shift is caused by the device viewport not being resized correctly when you change screen resolution so it is always begin to draw the scene from the left screen side.

If you don't like to reinvent the wheel let me advice you to look at the complete resolution independent rendering and Camera2D logic implementation for Monogame at: http://panthernet.ru/forum/index.php?/topic/17-monogamexna-examples-v18/

Examples are also included so it's very easy to start using it.

---
Tags: xna, c#, monogame, windows-phone-7, windows-phone-8
---


# Question
Title: What do I need to get an independent developer license for CryENGINE 3?
I have searched Google and CryEngine forums and I can't seem to get a solid answer to this question.

I have seen threads where developers are complaining that they can't sell their game because they can't get a licence after finishing their project.

Now, I am considering using CryEngine for my game because I like the royalty system, as it means I do not have to make any upfront payments but I don't want to have to get through the game and then find that I Crytek refuse to give me a license because I didn't know what the rules were, or something.

# Answer
> 5 votes
While the main source of information should be the developer's website, as indicated by @Josh, I would also suggest to take a look at CryDEV and look for information about this on the forum, where myself in the past I found several threads discussing about this.

EDIT: Ok, my bad, here's more: unlike Unity, for example, you can't just buy the license and publish your game. In order to be eligible for seeking a license with CryENGINE, you must show them some demo/work in progress that might suggest that your project is worth licensing. Said that, you can read some *horror stories* on the CryDEV forum I mentioned earlier about indies who worked months on a project and they didn't manage to get their game licensed. In that case, you happen to have a product which, from your point of view, is complete, but that can't go commercial since you have no license for it, so that's kind of a limbo.

Here's a rather recent thread talking about this: http://www.crydev.net/viewtopic.php?f=355&t=116498

# Answer
> 3 votes
Crytek's page is pretty clear on the subject. It says:

> If you are looking to use CryENGINE® 3 for a commercial game or in any way that is not specifically allowed in the End User License Agreement (EULA), you must contact Crytek to agree on commercial terms and a license for your use.

Furthermore, the FAQ says:

> We have attractive licensing options for small indie developers. Please visit www.mycryengine.com to contact Crytek to find out more.

Note that as of this writing, http://www.mycryengine.com suggests you visit http://cryengine.com instead. On that site you can find a link to register to get in touch with Crytek and discuss the terms of your indie license agreement.

---
Tags: licensing, cryengine
---


# Question
Title: How do I check in which region of a map an object is located?
For example I have a character and two areas A and B, I want to test which area, A or B, my character is on.

# Answer
you could make a function that returns the character's position coordinates and displays it on screen, the function being called everytime the character recieves input.
> -2 votes

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


title: board game card spacial events handling

text:
# Question
Title: board game card spacial events handling
im implementing a not so simple board game, i have a way to do most stuff (start game handling,turn handling,combat system,movment etc).

im having a problem with spacial cards that players draw,the simple ones like "lose life" or "gain item" etc are simple change to one variable.

but i have rule changing ones ,something like "monster x you encounter have 2 more life, and if you pass a combat roll gain an item",the first part is just having monsters of said type have 2 more life(changing their stats for the duration of the card.

but changing the combat system to give item on success roll?

should i run an event list every combat move? i dont know how that will work at all. in real life board game you just do what the card says but in a computer vartion the game shold do it, and im not sure of the logics.

also there is no other resource to consult (ive searched google a lot).

please help me.

# Answer
> 0 votes
This is first of all about code organization, so there is many different ways of doing it, and what works depend both on the job and the skills and preferences of the programmer.

Try to imagine your card effects in a 2D grid, on one axis your cards are listed, on the other all the possible places where they may take effect are listed, the "hooks". Any number of the cells may contain a function, but most of them are probably going to be empty.

What you want is to slice up this grid so that all the effects of a single card are collected in one place, that is easy, you can just make an object containing the functions for each card:

```
var allcards={
    card1:{
        onplay:function(args){...}
        ,ondrawcards:function(args){...}
        ,onpasscombatroll:function(args){...}
    ,card2:{
        ...
    }
}

```

Now the tricky part is calling them at the right time, for this purpose I suggest that you keep a list of all active cards, and that you make a function iterating over that list. Something like:

```
function effectiterator(hook,args){
    for(var card in listofactive){
        if(listofactive[card] && listofactive[card][hook]){
            listofactive[card][hook](args)
        }
    }
}

```

Where you would have to maintain the `listofactive` like so:

```
listofactive[cardid]=allcards[cardid] //Add to list
listofactive[cardid]=false //Remove from list

```

If you initialize the `listofactive` with all the possible keys you have in a specific order, that order will be the order in which the cards take effect, so you avoid unpredictable race conditions.

The `args` in this case should be an object referencing all the objects that are relevant to the event, so for instance in the `onplay` event you would include the object of the player playing the card so that the function may read and modify the attributes.

---
Tags: game-design, javascript, mobile
---


# Question
Title: How to reduce a rectangle without problems?
I'm developing an asteroids' game and I'm needing to reduce the rectangle of the spacecraft because when I use the method intersect() of Rect class to detect a collision with an asteroid they are far.

Here is a part my game:

As you can see, if the red rectangle of the spacecraft intersects with the red rectangle of the asteroid the game will detect a collision.

My problem it's that there is a big space in the bottom and the top part of the spacecraft which can confuse the player.

To solve it, I'm trying to modify the rect values of top and bottom but when i do this the image dissapear of the canvas.

# Answer
Several things you could try :

* Subdivide your main ship `bounding box` into smaller bounding boxes .

You can keep the main bounding box as it is now, then if collision is detected, perform additional tests using custom boxes (see picture). You can probably use Rect class and `Intersect()` method to implement this.

While not being perfect it will still be a lot precise that what you have now.

* use `bounding spheres` for rocks (see picture)

Keep main bounding box to check potential collision, and use additional circle collision test for further precision. I dont know if `Android` provide any helpers/classes for this. You can have a look here for circle to rectangle collision detection examples.

* (Optionally) implement per `pixel collision`. Bounding volumes could still be used but only for preliminary tests. see this stackoverflow answer for more details
> 4 votes

# Answer
The problem with reducing the rectangle size is that then the ships wing can hit the asteroid and nothing will happen. At that point you're trading accuracy for accuracy, and nobody wins that way.

Alternatively you would want to find a suitable collision or physics (which includes collision) library to handle this part for you. With something like that, you'd be able to define the actual collision shape to better match your objects.

Some notable libraries:

Otherwise you could use a framework built for Android that takes care of the heavy lifting for you, such as:
> 0 votes

# Answer
in my experience in games tells me it is far more acceptable to not have a collision when objects intersect, than the other way round. So i would suggest you to put your collision boxes inside of your objects. Then you can also compose your collision of the player of several boxes, eg one for the wings and one for the body. Keep in mind it is not a problem at all when they overlap, just make as few as possible. Then there are also more collision shapes available then just boxes. For your asteroids you could use circles, because they match the shape of your asteroids much more than boxes.
> 0 votes

# Answer
There is always a trade off on generalisation vs. accuracy. If you are doing basic rectangle intersection, you will never achieve perfect hit detection. You'll simply have to make a decision when it's good enough. However, as you pose this question, it's obvious current implementation is not good enough for you. So you have to decide what is.

Most accurate hit detection will always be pixel by pixel detection. And it's also the computationally most expensive solution. I doubt you need it. But you could benefit from different shapes for your entities. Your ship looks like a triangle, and your asteroids look like circles. It won't be perfect, but it might be good enough. Or, if you for some reason need to use rectangles, break the ship down into several smaller rectangles for hit checking.

You could also use the vectors to "look ahead", and calculate the timestamp for when a collision occurs. Then instead of changing the bounds of an object, you could add timestamp modifiers based on collision angles.

As you see, multiple alternatives ... Pick one that suits your level of need.
> 0 votes

# Answer
Use a rectangle for quick rejection and a convex hull/polygon to approximate the actual intersection. You can use Polygon odd/even intersection test or divide the polygon into smaller triangles and test with them. Regardless you don't necessarily need pixel collision.
> 0 votes

---
Tags: 2d, android
---