title: Collision Error

text:
# Question
Title: Collision Error
I am having trouble with collision detection part of the game.

I am using touch events to fire the gun as you will see in the video. Note, the android icon is a temporary graphic for the bullets

When ever the user touches (represented by clicks in the video)the bullet appears and kills random sprites.

As you can see it never touches the sprites it kills or kill the sprites it does touch.

My Question is How do I fix it, so that the sprite dies when the bullet hits it?

Collision Code snippet:

```
//Handles Collision
private void CheckCollisions(){
    synchronized(mSurfaceHolder){
        for (int i = sprites.size() - 1; i >= 0; i--){
            Sprite sprite = sprites.get(i);
            if(sprite.isCollision(bullet)){
                sprites.remove(sprite);
                mScore++;
                if(sprites.size() == 0){
                    mLevel = mLevel +1;
                    currentLevel++;
                    initLevel();
                }
                break;
            }
        }
    }
}

```

Sprite Class Code Snippet:

```
//bounding box left<right and top>bottom
int left ;
int right ;
int top ;
int bottom ;
public boolean isCollision(Beam other) {
    // TODO Auto-generated method stub
    if(this.left>other.right || other.left<other.right)return false;
    if(this.bottom>other.top || other.bottom<other.top)return false;

    return true;
}

```

### EDIT 1:

Sprite Class:

```
public class Sprite {

   // direction = 0 up, 1 left, 2 down, 3 right,
   // animation = 3 back, 1 left, 0 front, 2 right
   int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
   private static final int BMP_ROWS = 4;
   private static final int BMP_COLUMNS = 3;
   private static final int MAX_SPEED = 5;
   private HitmanView gameView;
   private Bitmap bmp;
   private int x;
   private int y;
   private int xSpeed;
   private int ySpeed;
   private int currentFrame = 0;
   private int width;
   private int height;

   //bounding box left<right and top>bottom
   int left ;
   int right ;
   int top ;
   int bottom ;

   public Sprite(HitmanView gameView, Bitmap bmp) {
         this.width = bmp.getWidth() / BMP_COLUMNS;
         this.height = bmp.getHeight() / BMP_ROWS;
         this.gameView = gameView;
         this.bmp = bmp;
         Random rnd = new Random();
         x = rnd.nextInt(gameView.getWidth() - width);
         y = rnd.nextInt(gameView.getHeight() - height);
         xSpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED;
         ySpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED;
   }
   private void update() {
         if (x >= gameView.getWidth() - width - xSpeed || x + xSpeed <= 0) {
                xSpeed = -xSpeed;
         }
         x = x + xSpeed;
         if (y >= gameView.getHeight() - height - ySpeed || y + ySpeed <= 0) {
                ySpeed = -ySpeed;
         }
         y = y + ySpeed;
         currentFrame = ++currentFrame % BMP_COLUMNS;
   }
   public void onDraw(Canvas canvas) {
         update();
         int srcX = currentFrame * width;
         int srcY = getAnimationRow() * height;
         Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
         Rect dst = new Rect(x, y, x + width, y + height);
         canvas.drawBitmap(bmp, src, dst, null);
   }
   private int getAnimationRow() {
         double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
         int direction = (int) Math.round(dirDouble) % BMP_ROWS;
         return DIRECTION_TO_ANIMATION_MAP[direction];
   }
   public boolean isCollision(float x2, float y2){
       return x2 > x && x2 < x + width && y2 > y && y2 < y + height;
   }

    public boolean isCollision(Beam other) {
        // TODO Auto-generated method stub
        if(this.left>other.right || other.left<other.right)return false;
        if(this.bottom>other.top || other.bottom<other.top)return false;

        return true;
    }
}

```

Bullet Class:

```
public class Bullet {

    int mX;
    int mY;
    private Bitmap mBitmap;

    //bounding box left<right and top>bottom
    int left ;
    int right ;
    int top ;
    int bottom ;

    public Bullet (Bitmap mBitmap){
        this.mBitmap = mBitmap;

    }

    public void draw(Canvas canvas, int mX, int mY) {
        this.mX = mX;
        this.mY = mY;
        canvas.drawBitmap(mBitmap, mX, mY, null);
    }
}

```

# Answer
> 3 votes
This part of your code does not make logical sense for working collision detection.

```
if(this.left>other.right || other.left<other.right)return false;
if(this.bottom>other.top || other.bottom<other.top)return false;

```

change it to

```
if(this.left > other.right) return false;
if(this.right < other.left) return false;
if(this.top > other.bottom) return false;
if(this.bottom < other.top) return false;

```

This should work assuming the left, right, top and bottom variables are correct at the time of the collision test.

# Answer
> 0 votes
Why not just create 2 rectangle objects, one for the player and one for the bomb, then check if they intersect?

```
Rectangle bullet = new Rectangle(bullet.x, bullet.y, bullet.width, bullet.height);
Rectangle player = new Rectangle(player.x, player.y, player.width, player.height);
if(player.intersects(bullet))
    return true;

```

# Answer
> -2 votes
AttackingHobo had the right idea. you can write the same thing, though, as:

```
if(this.left>other.right || this.left<other.right)return false;
if(this.bottom>other.top || this.bottom<other.top)return false;

```

(note the change from `other` to `this`)

However, this might cause a lack of collisions. This is saying if the position of the bullet image is EXACTALLY the same as the enemy, it will hit. You probobly want some range (based on the size of the enemy and bullet). Try something like this:

```
final int distance = 10; //set to the number of pixel distance you want the max to be for the collision to occur
if (Math.abs(this.left-other.left) > distance) return false;
if (Math.abs(this.right-other.right) > distance) return false;
if (Math.abs(this.up-other.up) > distance) return false;
if (Math.abs(this.down-other.down) > distance) return false;

return true;

```

Try that and see how it works. You may need to play with how big `distance` is, so I separated it from the rest of the code. I hope this helps.

EDIT: Nevermind. I misread the post and misinterpreted what the variables `left` `down` `right` and `up` meant. The second block of code will probably confuse thing even more :P.

EDIT2: Use this with variables `x` and `y` instead.

```
final int distance = 10; //set to the number of pixel distance you want the max to be for the collision to occur
if (Math.abs(this.x-other.x) > distance) return false;
if (Math.abs(this.y-other.y) > distance) return false;

return true;

```

---
Tags: java, collision-detection, android
---


# Question
Title: How to match font size with screen resolution?
So I'm working on a game using LibGDX, and I have a problem.

To make my game fit most resolutions, I created a base asset for each aspect ratio, for example, a main menu background image, I made it in 800X600 for 4:3, 1280X720 for 16:9 etc.

Now I am trying to incorporate `TextButton`s into the game, for the options; My problem is that I can't figure out which font sizes match with which screen resolutions. Is there a way to figure this out, or do I have to go one by one through each of the resolutions I have and just manually match the text to the resolution?

# Answer
> 20 votes
It's easy: Fonts do not need to match resolution, they need to match **pixel density**.

Pixel density is measured as pixels per inch(*PPI*), or pixels per centimeter. There's also a measure unit called **density independent pixels(*DP*)**. It is defined that `1dp` is the size one pixel has on a `160 PPI` screen.

Now coming back to fonts, try to make this test: put your laptop to run on 720p. Take a look on the size of the font. Now plug it into the 1080p 42" monitor of your desktop. If your monitor outputs the right information about its size, then the font should have EXACTLY the same size it had on the 720p screen. Imagine how weird it would be if text in your laptop had a different size than the text on your desktop monitor. With that said, larger resolutions should give more detail to the font, larger screens should give more content to be shown.

The same fact can be observed on text editors. A `72pt` font should look on the screen the same it would when printed on paper.

All this means you probably should want the same size across all display sizes (with some exceptions). If you want to base yourself somewhere, websites usually use `12pt` fonts, MS Windows uses `11pt` and `12pt` fonts.

This chart (also included in the bottom of the answer) tell us `12pt` in CSS is roughly equal to `16px` also in CSS (As if this wasn't confusing enough, a *px* in CSS is the same as *dp* everywhere else), so let's say you'll make your fonts `16dp` on LibGDX.

On your game, use the `FreeTypeFontGenerator` to generate fonts dynamically, this way you can consider the screen density when creating them:

```
BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp)
{
    return ftfg.generateFont((int)(dp * Gdx.graphics.getDensity()));
}
//On Init
BitmapFont buttonFont = createFont(arial, 16); //16dp == 12pt

```

This works because `Gdx.graphics.getDensity()` is equal to `YourScreenDensity/160` thus, is a "scale factor" to bring things to the size they would be on a 160ppi screen.

About the exceptions I mentioned earlier: you'll probably want fonts re-sizing accordingly to screen size in case of logos, promos, etc. But keep in mind that you'll be better off making these on a graphics editor like Photoshop or Gimp, anyway.

The other exception is text on tiny screens. 4.5" or smaller phone screens, wearables. Usually you won't have time to make scrolling content, or you just won't be able to afford putting so much content on that screen. You may try to scale the font `1dp` down, as the reader will probably have the phone very close to their face, they probably won't have a problem reading. Keep in mind you may annoy the player reading unreadable small text.

TL;DR:

* Physical size roughly won't change directly with screen size or resolution, but with a combination of both (`screenSize/resolution` the famous PPI)
* Think of *pt* and *dp*. Forget about screen pixels until you have to draw the final result.
* Create your font at runtime with a reasonable size.
* Converting *dp* to screen pixels: `pixels = dp * Gdx.graphics.getDensity();`
* If you are using a engine which does no give you converter to *dp* like LibGDX's `Gdx.graphics.getDensity()`, you can try: `densityFactor = Screen.getPixelsPerInch() / 160.0f`, then `pixels = dp * densityFactor`

EDIT:

2014, Jun 25 on Google IO, Matias announced a new style guidelines for Android, it includes a new Roboto font and typography guidelines. Take this table as a guide:

EDIT2:

Included CSS font size chart in case the link goes rot:

---
Tags: libgdx, gui, fonts, user-experience, aspect-ratio
---


# Question
Title: Tile textures on 3D models. HLSL shader code maybe?
I'm making a game in C# with XNA. I'm now applying textures to models. However if I change the scale of the model, the texture stretches with it. **How can I make the texture tile over the model instead of stretching?** I'm using UV mapping to load the texture onto the model. This only has to work for a cube so I'm not worried about UV mapping issues. I have just been using the basic effect class in XNA because I haven't needed anything more yet.

Is there a way to set the texture to draw in a tiled manor?

Can this be done in C#? Maybe by changing the `GraphicsDevice.SamplerStates`?

Can this maybe be done with a HLSL shader? I know very little about HLSL.

This is the first 3D game I'm making so everything is very new to me. Please keep that in mind when answering. Thanks in advance.

EDIT:

So I did some testing with the `GraphicsDevice.SamplerStates` Here is my UV map:

Here is my texture:

Here are the results:

```
                GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;

```

```
                GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```

```
                GraphicsDevice.SamplerStates[0] = SamplerState.AnisotropicWrap;

```

```
                var samState = new SamplerState();
                samState.Filter = TextureFilter.Point;
                samState.AddressU = TextureAddressMode.Wrap;
                samState.AddressV = TextureAddressMode.Wrap;
                samState.AddressW = TextureAddressMode.Wrap;
                GraphicsDevice.SamplerStates[0] = samState;

```

```
                var samState = new SamplerState();
                samState.Filter = TextureFilter.Point;
                samState.AddressU = TextureAddressMode.Mirror;
                samState.AddressV = TextureAddressMode.Mirror;
                samState.AddressW = TextureAddressMode.Mirror;
                GraphicsDevice.SamplerStates[0] = samState;

```

```
                var samState = new SamplerState();
                samState.Filter = TextureFilter.Linear;
                samState.AddressU = TextureAddressMode.Wrap;
                samState.AddressV = TextureAddressMode.Wrap;
                samState.AddressW = TextureAddressMode.Wrap;
                GraphicsDevice.SamplerStates[0] = samState;

```

```
                var samState = new SamplerState();
                samState.Filter = TextureFilter.Linear;
                samState.AddressU = TextureAddressMode.Mirror;
                samState.AddressV = TextureAddressMode.Mirror;
                samState.AddressW = TextureAddressMode.Mirror;
                GraphicsDevice.SamplerStates[0] = samState;

```

None of them seem to have tiled the image. So does that mean I need to use the HLSL shader as well?

EDIT: This is what I'm trying to achieve: OR

# Answer
Yes you can do it by changing the sampler state, for example:

```
game.device.SamplerStates[0] = SamplerState.PointWrap;

```

This one means it will "wrap" your texture around the model and sample from the nearest texel. You should try out the other sampler states too. Mirror will mirror your texture if the texture coordinates are outside the (0,1) bounds. Clamp will not tile your texture.

You can also do it in the shader while you are declaring your sampler:

```
Texture xTexture0;
sampler TextureSampler0 = sampler_state {
                                        texture = <xTexture0>;
                                        magfilter = linear;
                                        minfilter = anisotropic;
                                        mipfilter = point;
                                        AddressU = wrap;
                                        AddressV = mirror;
                                       };

```

With these samplers you also need to have texture coordinates which are outside of the (0,1) range.
> 3 votes

---
Tags: xna, c#, 3d, hlsl, models
---


# Question
Title: get current frame from an one row graphic
I need to get the current frame of a image but it does not work and I don't know why... Could someone help me pls... thx

```
package com.android.testgame;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Bomb
{
    private final Bitmap bmp;

    private final int width;

    private final int height;

    private int currentFrame = 0;

    private static final int BMPROWS = 1;

    private static final int BMPCOLUMNS = 13;

    private int x = 0;

    private int y = 0;

    public Bomb(GameView gameView, Bitmap bmp)
    {
        this.width = bmp.getWidth() / BMPCOLUMNS;
        this.height = bmp.getHeight() / BMPROWS;
        this.bmp = bmp;
        x = 250;
        y = 250;
    }

    private void update()
    {
        currentFrame = GameLoopThread.getCurrbombfr();
    }

    public void onDraw(Canvas canvas)
    {
        update();

        int srcX = currentFrame * width;

        int srcY = height;

        Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);

        Rect dst = new Rect(x, y, x + width, y + height);

        canvas.drawBitmap(bmp, src, dst, null);
    }
}

```

# Answer
> 0 votes
Change this line:

int srcY = height;

To:

int srcY = 0;

EDIT (explanation):

If you look at the definition of the source rectangle:

Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);

You are drawing from srcY to srcY + height. However you just set srcY = height, therefore you are attempting to draw from height to height+height. Settings srcY to 0 then changes the draw area from 0 to 0+height which is what you actually want. You're not seeing anything because drawing height to height+height is obviously out of the image bounds.

---
Tags: java, android
---


# Question
Title: How and when to choose which objects to run collision tests on?
This might be problem with plenty of good solutions, but it's all not very clear to me, so I though I could ask and probably get some good hints. I'm having trouble figuring out how to handle interaction between objects in a platformer. Basically it's supposed to have two kinds of collision detection: one for solid objects that's based on line tests, and another to detect when ordinary objects touch.

These are some solutions that I know of, but they all have some serious problems:

* Store global references to the player and to solid objects, and have all other objects manually detect collisions with them.

Good: trivial to implement, efficient

Bad: limiting, since you can't easily have two non-player objects interact on collision; object implementations are strongly coupled to the player object's implementation
* Let objects ask for a list of objects of a certain type, and check for collisions in that list.

Good: simple to use; useful for other things such as finding all solid objects

Bad: I don't know how to implement it nicely (especially in a statically typed language); it requires use of inheritance to classify object types; objects in the same update priority interact slightly differently depending on which one updates first
* Let objects send and receive messages, and have a central collision detection system that runs after the update methods and sends messages to all colliding objects.

Good: update order does not matter; object types need to know little, if anything, about each other

Bad: must use the shapes provided by the collision system (no custom tests); most collision tests and messages will be wasted since collisions between most object types are ignored; a separate way to list all solid objects is still needed

So, any suggestions for improvements, alternatives, or good links to read? Suggestions that also simplify related problems like off-screen objects or objects positioned relative to other objects would be appreciated, too.

EDIT: To be clearer, I'm not asking about how to detect a collision given two objects, but about how the two objects can find out about each other in the first place.

# Answer
> 1 votes
Personally, I use a spin on the first option you listed. When checking if A collides with B, however, a series of disqualifiers (or a singular disqualifier) can be used to reduce the computation required for each iteration of your collision checker. For example:

```
if((b.y >= a.y && b.y <= (a.y + a.h)) || ((b.y+b.h) >= a.y && (b.y+b.h) <= (a.y+a.h)))
{
  bool collide = checkCollision(a,b);
}

```

Obviously enough, if a collision-enabled object does not come within vertical range of another collision-enabled object, the collision system wont even both to run the numbers. There's tons of ways to implement this, too. If your system is texel based, you could even use raycasting as an accurate qualifier which might, in some cases, be simpler.

---
Tags: c++, collision-detection, architecture, objects
---


# Question
Title: Unity3D - Clones won't get destroyed by script
I need some help making this script work.

```
#pragma strict

function OnMouseDown () {
Destroy (gameObject);
}

```

Basicly what the script does is that it destroys the objects that the player clicks on.I also got another object which has a script attached to it,which makes it spawn other objects.

The script clones the objects and makes it spawn multiple times.I attached the first script to the prefab but when I click on it,it won't be destroyed.If I click on the original prefab it works,but not on the clones created by the other script.

Anyone has any idea ?

Thank you.

Edit #1

Spawn script :

```
using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {

    public GameObject[] obj;
    public float spawnMin = 1f;
    public float spawnMax = 2f;

    void Start () {
        Spawn ();
    }

    void Spawn()
    {
        Instantiate(obj[Random.Range(0, obj.GetLength(0))],transform.position, Quaternion.identity);
        Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
    }

}

```

# Answer
The code above is indeed correct, you **MUST** instantiate your objects though!
*I understand how one cannot have knowledge on this topic, we all start somewhere.*

```
using UnityEngine;
using System.Collections;

public class SpawnScript : MonoBehaviour
{
    public float Delay = 4f;       // Time before spawning starts, to allow scene to render/catch up
    public float Difference = 7f;  // Time between each spawn
    public GameObject[] enemies;   // Array of your enemy prefabs.

    void Start ()
    {
        InvokeRepeating("SpawnEnemy", Delay, Difference);
    }

    void SpawnEnemy ()
    {
        // Instantiate one random enemy every time this is called
        int enemyIndex = Random.Range(0, enemies.Length);
        Instantiate(enemies[enemyIndex], transform.position, transform.rotation);

    }
}

```
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: Get the game state using Multithreading in Java Monkey Engine 3
I’ve been trying out Java Monkey’s multi threading recently via the wiki’s tutorial. Since I just wanted to test a prototype clinet, I made a program which creates some cubes using the ‘Cubes’ library (**hub.jmonkeyengine.org/wiki/doku.php/jme3:contributions:cubes**), and then serializes it to some byte data (which is what the server would do to the map chunks near a player). The aim is to imitate a chunk being sent from the server, which would occur in a separate thread, as mentioned in the networking tutorial on the wiki (**hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:networking**).

Each chunk would have it’s own node to store it, and the chunk would be replaced if the server sent either an update of the chunk, or if the player moved into a new region (which would cause the chunk to be replaced). The code is here. The issue is though, is that I need to recreate an empty chunk before I can read from the bytes, which requires collecting the application settings. As well as this, I cannot modify the game scene within a separate thread (which the function does). The code below is from line 93+.

```
//...
//(In Update Loop)
if (future.isDone()) {
    //Binds the temporary data to the clone object
    blockTerrainClone = (BlockTerrainControl) future.get();
    future = null;
//...

Callable<BlockTerrainControl> serverInput = new Callable<BlockTerrainControl>() {
    public BlockTerrainControl call() {
        /*Creates a temporary data storage object, then assigns the data.
        I can't mutate the current BlockTerrainControl which is being rendered,
        as this is a seperate thread.*/
        BlockTerrainControl data = new BlockTerrainControl(CubesTestAssets.getSettings(app), new Vector3f());
        CubesSerializer.readFromBytes(data, serializedBlockTerrain);

        //Returns the data
        return data;
    }
};

```

The multithreading wiki article (near the bottom) does partially cover how to modify the scene and get access to the game state, but not into much detail. Would anyone be able to expand on that section, and explain how I may be able to transfer the blocks from the server to the client in a separate thread (or in this case, make the data transfer from one thread to another)?

If I missed out anything in the question, I'd be happy to add it!

# Answer
You might want to have a look at the monkeyzone example, and use the \`ActionMessage? or some other Message class to send messages between client and server. You can broadcast from server to the client and the clientlistener invokes a callback e.g.

```
app.enqueue(new Callable<Void>() {
    public Void call() throws Exception {
        app.doActionByBroadcast();
        return null;
    }
});

```
> 1 votes

---
Tags: java, multithreading, jmonkeyengine, cubemap
---


# Question
Title: Why does my SFML game cause screen tearing on Linux?
I wrote a little game of a bouncing ball, using SFML and Box2D.

On Windows, the graphics animate smoothly. However, on my Linux machine, the animation stutters randomly. To be precise, I get a horizontal video tearing effect.

I use the Intel graphics driver. I tried multiple solutions I found online to solve video tearing but I haven't been able to solve this. I've never had video tearing before (even in other OpenGL apps): It appears now for the first time.

# Answer
> 1 votes
If you've got tearing, then you most likely forgot to enable vertical synchronisation (and it's not enabled by default or forced on your system).

Try calling `sf::Window::setVerticalSyncEnabled(true);` before your main loop.

---
Tags: c++, graphics, sfml, linux
---


title: Make GuiText responsive

text:
# Question
Title: Make GuiText responsive
I'm using C# code to make a responsive GuiText. I was abel to make a responsive GuiTexture, but I'm struggling with doing the same for a GuiText.

Code for the responsive GuiTexture

```
using UnityEngine;
using System.Collections;

public class ResponsiveGUITexture : MonoBehaviour {
    public float designScreenWidth = 800, designScreenHeight = 480;
    public bool debugMode = false;

    private Rect pixelInset0;

    void Start () {
        pixelInset0 = this.guiTexture.pixelInset;
        this.guiTexture.pixelInset = new Rect(Screen.width / designScreenWidth * pixelInset0.x, Screen.height / designScreenHeight * pixelInset0.y, Screen.width / designScreenWidth * pixelInset0.width, Screen.height / designScreenHeight * pixelInset0.height);
    }

    void Update(){
        if(debugMode){
            this.guiTexture.pixelInset = new Rect(Screen.width / designScreenWidth * pixelInset0.x, Screen.height / designScreenHeight * pixelInset0.y, Screen.width / designScreenWidth * pixelInset0.width, Screen.height / designScreenHeight * pixelInset0.height);
        }
    }
}

```

# Answer
Once I did a little API to do what I wanted to do, and it worked, it's not finished, but, it could help you out. Use your creativity, and make new things to this API ;)

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

/*
 * @author: Rafael C. Nunes
 * @email: rafaelnunes737@hotmail.com
 *
 * @version: 0.1
 * @date: 08/02/2014
 *
 *
 * This archive is the screen API, that provide a screen configuration of the PC.
 * By default, all the elements that are instantiated on the screen will be on     the    left.
 *
 */

[ExecuteInEditMode]
public class _screen : MonoBehaviour
{
//Return the screen width and height
public int getScreenWidth
{
    get
    {
        return Screen.width;
    }
}
public int getScreenHeight
{
    get
    {
        return Screen.height;
    }
}

/*
 * helping the programmer/designer to position the elements on the screen, positionLeft is the
 * position left of the screen, the positionMiddle is the center of the screen positionRight is
 * the position right of the screen, it is just a draw.
 */
public int positionLeft
{
    get
    {
        return Screen.width - Screen.width;
    }
}
public int positionMiddle
{
    get
    {
        return Screen.width / 2;
    }
}
public int positionRight
{
    get
    {
        return Screen.width;
    }
}

private int screenWidth = Screen.width;
private int screenHeight = Screen.height;

public void setCursor(Texture2D texture, Vector2 hotspot, CursorMode cursor)
{
    UnityEngine.Cursor.SetCursor(texture, hotspot, cursor);
}

public bool createButton(float left, float top, float width, float height, String value)
{
    return GUI.Button(new Rect((screenWidth-screenWidth)+left, (screenHeight-screenHeight)+top,
                                                                        width, height), value);
}

public bool createRepeatButton(float left, float top, float width, float height, String value)
{
    return GUI.RepeatButton(new Rect(left, top, width, height), value);
}

public void createLabel(float left, float top, float width, float height, String value)
{
    GUI.Label(new Rect((screenWidth - screenWidth)+left, (screenHeight - screenHeight)+top,
                                                                    width, height), value);
}
}

```
> -1 votes

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


# Question
Title: Make an object follow the mouse pointer with LÖVE2D
I've been trying to make a picture follow the mouse pointer with LÖVE2D.

I want that the object follow the mouse, and not just **be** the mouse coordinates, I did that. So I toked the distance between the objects:

```
distance = dist(object.x, mouseX, object.y, mouseY)

```

the dist definition is the one from analytic geometry(Distance between two points in the Cartesian plan), well, now I don't know what to do, I tried a timer to update the object's coordinates but didn't work out.

```
if object.timer >= 2 then
    --object.x = mouseX
    --object.y = mouseY
    object.x = mouseX - distance
    object.y = mouseY - distance
    object.timer = 0
end

```

It didn't work out either :(. Well, I tried some other stuff, like whale.x - distance, but didn't worked out either, how can I make the object follow the mouse, like, if I let my mouse on (500, 300(Screen coordinates) the image would follow until it reaches the position desired which is the mouse position.

And yea, I really need to learn more math. \>.\>

# Answer
Yeah, vector geometry really helps when thinking about positions of things. It might be helpful to read over that page for a refresher.

To find the vector from your `object` to the mouse position, subtract the `object` position from the mouse position:

```
local objectToMouse = {
    x = mousex - object.x,
    y = mouseY - object.y
}

```

Then you can add some fraction of that vector to your `object`'s position:

```
local fraction = 1 / 10
object.x = object.x + (objectToMouse.x * fraction)
object.y = object.y + (objectToMouse.y * fraction)

```

You can put those in your `love.update` to make them happen every step. Then every step the object will move one tenth of the distance to the mouse position.

It looks like this for me if I render a circle at the `object`'s position:

If you find yourself using a lot of vectors, there's a really good vector class in vrld's `HUMP` library that might simplify your code by letting you do the common vector operations with less code.
> 3 votes

---
Tags: mathematics, lua, love2d
---


# Question
Title: Is there a common way to execute a task at a certain pace, without relying on the task priority feature of the OS?
There is no cross platform way to set process priorities, and I don't want to use threads since there are no standard method of setting priority to certain threads, apart from the fact that threads are hard to use.

Let's say I have a task that takes a certain amount of computing time, which on my computer takes 10 seconds. This task usually takes a long time, like for example, loading geometry chunk dynamically, or opening a new audio ambience file. I don't need this task to be finished instantly because it's a big task so I can't afford to wait for a frame to finish, so I need to execute it over several frames, rather a certain amount of time.

Since I don't want to freeze the game, I can cut this loop into several batches and execute one batch per frame. If my game runs at 50 fps, a 10 second task can be divided in 500 batches. If my program loops over N\*500 iterations, each batch loops over N iterations. If I don't want it impact others parts of my game, I can execute N/2 or even N/5 iterations per batch.

I'm not sure if I'm reinventing the wheel though, isn't there some C++ standard thing or programming pattern that allows me to do that already ? I'm not sure if it's optimal to cut a loop, and I'm not planning to use multithreading.

# Answer
You can use the concept of Coroutines to execute a long task with other activities at the same time on a single thread. Basically it is a function which can yield execution control voluntarily. The next time it is called, execution will continue after the point where the function yielded last time. Implementing this in most compiled languages is tricky, because you have to save all CPU registers in use, as well as any local variables on the stack. Many scripting languages have support for coroutines right out of the box, however, especially ones that lack explicit support for threads. For instance, Lua.

Manually splitting your task up into 500 parts and trying to manage getting it to run correctly is likely going to be a nightmare, especially six months from now when you haven't worked on that code in four months and suddenly need to make some changes.

Despite having to deal with more issues (synchronization, memory barriers, and thread-local memory, etc) multithreading really is the easiest way to deal with this, and will yield the best performance in all likelihood. You can abstract away the platform-dependent code using a library like `boost::thread` or `std::thread` if you're using a C++11 compiler. You can deal with single-core processors by calling `std::this_thread::yield()` every so often in your low-priority tasks, or the equivalent in whatever library you use. Windows will typically give a running thread up to 10ms (most of a frame!) before forcing a context switch (if there are other waiting threads), but calling `yield()` is like saying "Okay, I know I've got more time, but I'm good for now, anyone else?".

So much of game programming does not lend itself easily to multithreading that it's easy to say "No Thanks," but modern processors are usually dual core with hyperthreading or quad-core, so not using those extra logical processors for something is just throwing away performance. The tasks you mentioned, (loading assets from disk) are some of the few tasks that are extremely easy to offload to other threads, since they don't require much access to shared memory.
> 3 votes

---
Tags: c++, multithreading, frame-rate
---


# Question
Title: Fast fullscreen quad rendering in Direct3D 11?
For the last few weeks, I've been trying to port a DX9 implementation of HDR rendering (tone mapping, bloom, stars, etc.) over to DX11. I believe I've got all features working but I'm not getting good enough performance. I'd like to be able to render the whole effect in under 4ms on a fairly low-powered GPU, but using D3D11 Queries I'm noticing that it takes 0.5ms to just render a fullscreen quad with a solid color, and 1.0ms to render a fullscreen texture! And because tone-mapping is the only part of the effect that uses a fullscreen texture, this makes it the most expensive!

I'm already doing some optimisations with my limited graphics knowledge, I've disabled blending and depth-testing, I make sure that the texture sampler uses sensible filtering settings, and I'm pretty sure that the effects of any state-changes are negligible. I've heard that rendering 1 oversized triangle instead of 2 can yield some improvements, but I'm not sure if that will help me in this situation. Basically, does anyone have any suggestions to speed up rendering of a textured quad?

# Answer
So after experimenting a little more with Intel GPA following Sean Middleditch's comment, I noticed that messing around with state changes, including sampler states, seemed to give me no improvement whatsoever.

But sampler states got me thinking about texture formats, so I had another look at the DirectX documentation for a texture format that might be more optimal. Previously I was using R16G16B16A16 textures for all my render surfaces, but DXGI has the 32-bit packed format R11G11B10, which, according to some forum threads, is particularly well-suited to HDR rendering. I changed both my source and target textures to use this format, and BOOM, tone-mapping now takes about 0.65ms on my integrated gpu with no apparent loss of quality, which seems good enough for me.

Clearly I'd underestimated the importance of a compact texture format - I'd guess it has numerous benefits to caching and simplifying arithmetic, but I'd be interested to hear more detailed theory if anyone would like to comment. Worth trying if anyone else gets stuck on the same issue.
> 2 votes

# Answer
Maybe you can save some time if you don't bind a vertex buffer and use SV\_VERTEXID (which is created automatically by the IA stage) to build your quad in the vertex shader, something like:

```
struct VSOUT{
 float4 pos:SV_POSITION;
 float2 tex:TEXCOORD0;
};

VSOUT main(uint vI: SV_VERTEXID)
{
 VSOUT Out = VSOUT(0);
 Out.tex=float2(vI%2,vI%4/2);
 Out.pos=float4((Out.tex.x-0.5f)*2,-(Out.tex.y-0.5f)*2,0,1);
 return Out;
}

```

The vertex shader will output a full screen quad this way if you call a draw for 4 vertices with a TRIANGLESTRIP topology;

Probably you can also save some time if you try out different rendertarget formats and resoulutions.

If you can have depth or stencil testing it can also save you some time in some scenarios.
> 1 votes

---
Tags: directx11, optimization, fragment-shader, post-processing, hdr
---


title: Problem with Raycasting in a 2D Game

text:
# Question
Title: Problem with Raycasting in a 2D Game
I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have,

```
function calculateWalk() {

    yield WaitForSeconds(0.3);

    var hit : RaycastHit;

    if(Physics.Raycast (transform.position, Vector3.down, 100.0)) { // Never evaluates to being true
        var distanceToGround = hit.distance;
        Debug.Log("Hit");

        if(hit.collider.gameObject.tag == "tallGrass") {
            walkCounter++;
            Debug.Log("Tall Grass");
        } // END if
    } // END if
} // END calculateWalk()

```

I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles.

# Answer
> 1 votes
You are not calling the right Physics.Raycast as well - you would need to pass the RaycastHit object into the function as an output variable.

I'm suprised the code is even compiling, since you aren't initializing the RaycastHit, and then using it when it shouldn't have any value assigned to it.

You should also use the 'default' distance of infinity just in case 100 isn't enough

```
Debug.Log("Testing below me");
var hit : RaycastHit;
//Use the overload for Physics.Raycast that allows a RaycastHit object to be an output.
if (Physics.Raycast(transform.position, Vector3.down, hit)) {
    Debug.Log("I'm standing on " + hit.collider);
    //Etc...
}

```

Also, remove the 'yield' statement. That part of the code past the yield might never be getting run.

---
Tags: unity, javascript, raycasting
---


title: HLSL tile shader

text:
# Question
Title: HLSL tile shader
How would I make this HLSL code tile my texture:

```
float4x4 World;
float4x4 View;
float4x4 Projection;
float4x4 WorldInverseTranspose;

float4 AmbientColor = float4(1, 1, 1, 1);
float AmbientIntensity = 0.5;

float3 DiffuseLightDirection = float3(1, 0, 0);
float4 DiffuseColor = float4(1, 1, 1, 1);
float DiffuseIntensity = 1.0;

float Shininess = 200;
float4 SpecularColor = float4(1, 1, 1, 1);
float SpecularIntensity = 1;
float3 ViewVector = float3(1, 0, 0);

texture ModelTexture;
sampler2D textureSampler = sampler_state {
    Texture = (ModelTexture);
    MinFilter = Point;
    MagFilter = Point;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float4 Normal : NORMAL0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float4 Color : COLOR0;
    float3 Normal : TEXCOORD0;
    float2 TextureCoordinate : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    float4 normal = normalize(mul(input.Normal, WorldInverseTranspose));
    float lightIntensity = dot(normal, DiffuseLightDirection);
    output.Color = saturate(DiffuseColor * DiffuseIntensity * lightIntensity * 0);

    output.Normal = normal;

    output.TextureCoordinate = input.TextureCoordinate;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float3 light = normalize(DiffuseLightDirection);
    float3 normal = normalize(input.Normal);
    float3 r = normalize(2 * dot(light, normal) * normal - light);
    float3 v = normalize(mul(normalize(ViewVector), World));
    float dotProduct = dot(r, v);

    float4 specular = SpecularIntensity * SpecularColor * max(pow(dotProduct, Shininess), 0) * length(input.Color);

    float4 textureColor = tex2D(textureSampler, input.TextureCoordinate);
    textureColor.a = 1;

    return saturate(textureColor * ((input.Color) + (AmbientColor * AmbientIntensity) + specular));
}

technique Textured
{
    pass Pass1
    {
        VertexShader = compile vs_1_1 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

This the current result:

I want to tile this texture over the cube instead of stretching it.

# Answer
```
output.TextureCoordinate = input.TextureCoordinate * 100;

```

It would tile it but I imagine you would probably want some controlled tiling? And for that you have to modify your uv texture coordinates by hand for every vertex.
> 0 votes

---
Tags: textures, hlsl
---


# Question
Title: Should entities store other other entities that they spawned?
How should a game entity add another game entity to the game world?

For example, an entity shooting a missile (which is another entity), means the new `Missile` will need to be added to the `entities` list in the `GameWorld` class (so that the next game-loop iteration it will be drawn, moved, etc).

I can think of two approaches:

# Approach 1

The entity adds a new `Missile` to the `GameWorld`:

```
class SpaceShip extends Entity{
    // .. stuff omitted
    void shoot(){
        GameWorld.getInstance().add(new Missile(x,y));
    }
}

```

# Approach 2

Have the `GameWorld` query it's `entities` every gameloop iteration for their 'stored entities'. For example (pseudocode):

```
class SpaceShip extends Entity{
    // .. stuff omitted
    List<Missile> missiles;
    void shoot(){
        missiles.add(new Missile(x,y));
    }
}

class MineCreatorThing extends Entity{
    // .. stuff omitted
    List<Mine> mines;
    void putMine(){
        mines.add(new Mine(x,y));
    }
}

class GameWorld{
    // .. stuff omitted
    void gameloop(){
        while(true){
            // .. more stuff omitted
            foreach entity in entities{
                if(entity instanceof MineCreatorThing)
                    foreach mine in entity.getMines() entities.add(mine);
                if(entity instanceof SpaceShip)
                    foreach missile in entity.getMissiles() entities.add(missile);
            }
        }
    }
}

```

Which approach should I pick?

# Answer
> 1 votes
First option is most likely going to be good enough if you are not developing a really big game. I would (personally) avoid using instanceof in that way.

If you really want to take your design to the next step, you can create an event queue for the GameWorld and just push any event (like addMissile, destroyShip etc.), and then on the beginning of every update handle all those events from queue in the GameWorld class. The good side of this approach is that all logic will be done from withing the GameWorld and before any logic for any particular frame, which means much less bugs and much more easier code to handle. If you got many object messing up with your lists directly, you're gonna have a bad time.

But, just to mention again, if you are not developing any big game that is going to have many objects doing many stuff and changing GameWorld constantly DO NOT do that. It will just be an overhead...

# Answer
> 3 votes
I almost voted that this is too opinion-based, but on thinking on it further, I think it's safe to say with some sureness that the second option presented is just bad. Don't do that.

Among other things, it means that any components which must create objects needs a dependency on another component, potentially a different component for each type of thing it creates.

More complex games do delay the entire creation of the object. This is because you can't just call `new Foo` in complex engines, especially component-based ones. You need a more intricate resource system that can clone objects from blueprint or the like, so you end up doing something like:

```
pGameWorld->SpawnObject(m_BlueprintHandle);

```

The actual creation and initialization of the object may happen immediately or be delayed until next frame (or even later, for engines that allow asynchronous on-demand loading of resources). It's also common to have initialization parameter structs for passing in position, velocity, orientation, and other common per-instance data, like:

```
SpawnData spawn;
spawn.position = Vector2d(x, y);
spawn.blueprint = m_BlueprintHandle;
spawn.baseName = "BlueMissile";
spawn.creator = this;
pGameWorld->SpawnObject(spawn);

```

Or it might take several different structs, some parameters and some structs, or so on. There's also engines that use serialization systems to set parameters, so you see things like:

```
MemoryParameterStream params;
params.write("position.x", x);
params.write("position.y", y);
pGameworld->SpawnObject(m_BlueprintHandle, params);

```

This can be combined with the previous approach to handle both common parameters (position, etc.) and any component-specific parameters that you need to set in less common circumstances.

How and when the game world actually creates the request object is abstracted away. It might return a handle to a temporary object, something like:

```
Handle GameWorld::SpawnObject(Handle blueprintHandle) {
  Handle newHandle = AllocateEmptyObject(blueprintHandle);
  m_PendingInitializations.push_back(newHandle);
  return newHandle;
}

// elsewhere
m_ChildHandle = pGameWorld->SpawnObject(m_BlueprintHandle);

```

Just so that the creator can hold onto references to the object if needed for later use. This is not uncommon for some attack systems that kill or despawn certain attack objects (bullets, laser beams, etc.) when the weapon or attacker that fired them dies, for instance.

In the end, your first suggestion is simple and Just Works(tm) for most simple games. Do that. Do not do your second option; it's more complicated with no benefits and just adds more coupling and dependencies.

---
Tags: architecture, oop, entity
---


# Question
Title: Libgdx Do a fixed rotation for orthographic camera
I'm trying to rotate my `OrthographicCamera` in the render loop to a fixed angle, but I can only make the camera spin. This is the code that I have:

**in `create()`:**

```
OrthographicCamera camera = new OrthographicCamera();
camera.setToOrtho(true, 100, 100);
camera.position.set(50, 50, 0);
camera.update();

```

**in the render loop:**

```
camera.rotate(30);
camera.update();

```

The camera keeps spinning each frame. But **I'd like the camera to stay at 30 degrees**.

I have already seen this answer:

https://stackoverflow.com/questions/16509244/set-camera-rotation-in-libgdx

But I don't like it because this code is too drastic. I wonder if there is a more "common" way to do this.

# Answer
The method `camera.rotate()` (and all other transformation methods on camera) act on the current state of the camera. So if it's rotated 30 degrees, it will add more 30 degrees to the rotation.

If you want to keep at 30 degrees (but still applying the transform every step), you have to make it look back at whatever it was looking before. Assuming you're using an orthogonal camera for 2D rendering with y pointing down, then this should work:

```
camera.up.set(0, -1, 0);
camera.direction.set(0, 0, 1);
camera.rotate(30);

```

If you prefer y pointing up, try:

```
camera.up.set(0, 1, 0);
camera.direction.set(0, 0, -1);
camera.rotate(30);

```

Hope this helps you :)
> 5 votes

---
Tags: java, libgdx, camera, rotation
---


# Question
Title: How does the minecraft main menu play a "movie"
I've been wondering for a while, and been doing a lot of research on the subject: how does the main menu in minecraft play a "video". As far as i can tell, it's not a .gif, it appears to be a movie. What is it that minecraft does that allows the moving background in the menu? Sorry for the lack of depth... but that's the question! Thanks in advance!

# Answer
> 0 votes
It's just a few chunks of a specifically seeded world viewed through a camera with a blur effect added that is slowly moving. I believe there is a way to change it though that would be another question.

---
Tags: java, minecraft-modding, video
---


# Question
Title: How can I limit the movement angle of a Farseer joint?
How can I create rectangles in Farseer that behave like the two red rectangles in this video:

https://www.youtube.com/watch?v=w0p2y4dRylQ

I created an angle joint, but it behaves weird. Should I use an angle joint or is it better to use another joint?

In addition, I don't know how to adjust the angle of the joint so that the rectangle only moves in a predefined angle. How can I limit the movement angle of a joint?

I tried it like this, but the rectangle moves not as it should:

```
       RectangleA1 = BodyFactory.CreateRectangle(world, 3.50f, 0.50f, 1.0f);
       RectangleA1.BodyType = BodyType.Dynamic;
       RectangleA1.Position = new Vector2(10.4f, 5.40f);
       RectangleA1.Rotation = 0f;
       RectangleA1.CollisionCategories = Category.Cat5;

       RectangleA2 = BodyFactory.CreateRectangle(world, 0.10f, 1.00f, 1.0f);
       RectangleA2.BodyType = BodyType.Static;
       RectangleA2.Position = new Vector2(8.6f, 6.2f);
       RectangleA2.Rotation = 0f;
       RectangleA2.CollisionCategories = Category.Cat5;

       AngleJoint1 = JointFactory.CreateAngleJoint(world, RectangleA1, RectangleA2);

       spriteBatch.Draw(RectangleA1Sprite, ConvertUnits.ToDisplayUnits(RectangleA1.Position), null, Color.White, RectangleA1.Rotation, new Vector2(RectangleA1Sprite.Width / 2.0f, RectangleA1Sprite.Height / 2.0f), 1f, SpriteEffects.None, 0f);

       spriteBatch.Draw(RectangleA2Sprite, ConvertUnits.ToDisplayUnits(RectangleA2.Position), null, Color.White, RectangleA2.Rotation, new Vector2(RectangleA2Sprite.Width / 2.0f, RectangleA2Sprite.Height / 2.0f), 1f, SpriteEffects.None, 0f);

```

# Answer
> 1 votes
Please read the documentation. If you're not building Farseer from its source code - please do that so you can easily go in and see these things. (Plus, you can glean even more information from the source code, even where it is not documented.)

---

For now, let's take a look at the documentation. First, `AngleJoint` (from the top of `AngleJoint.cs` in the Farseer source code):

> Maintains a fixed angle between two bodies

That's clearly not what you want. There is no physical "connection" between the two joined bodies with an angle joint. They can move freely in space - as long as they maintain the same angle relative to each other.

What you want is the `RevoluteJoint`. The documentation says:

> A revolute joint \[const\]rains \[two\] bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. **You can limit the relative rotation with a joint limit that specifies a lower and upper angle.** You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated.

(Emphasis mine)

This is exactly what you want. Create a revolute joint as per your last question. Then set the values of `LowerLimit` and `UpperLimit` to the angle limits you desire in radians. Then set `LimitEnabled = true`.

---

It's worth noting that the video you linked is from **2008**. This means it is probably running Farseer 2, rather than Farseer 3. Farseer 3 was a rewrite of Farseer 2. In fact, Farseer 3 is basically a port of Box2D. In the switch to Box2D, a lot of the nomenclature changed.

---
Tags: c#, farseer-physics-engine
---


# Question
Title: How can I can I reduce the write load on a database for an MMO?
I am considering using MySQL as a database for storing the character states or the world for that matter.

The thing is if I will save the character data on an interval, thus giving rest to the mysql database, it means that if the server crashes some game time would be lost.

So I was planning to save everything as it happens and make the database the real source of the states.

But the problem is, this would mean thousands of write per second. How can I alleviate that performance problem?

Additional info:

* This is a MMORPG
* 2000 simultaneous players (so far in beta)
* 3D world

# Answer
> it means that if the server crashes some game time would be lost.

Constantly saving all character data immediately for all players isn't particularly feasible. Fortunately it isn't particularly *necessary*. This is really a scenario where you want to avoid crashing in the game server as much as possible, because that far more serious long-term implications for your game than just a few minutes of progress being reset.

In general, you can get by with a system that keeps character/account data resident in the server's memory and saves either periodically or at certain "critical" moments (such as a level up, or the completion of a quest). It's true that if the game server crashes, you could lose some amount of non-critical progress; this is generally considered acceptable (for example, Guild Wars 2 works this way; this is the phenomenon people often incorrectly call a "server rollback").

You can increase the frequency with which you can make saves by building database cache servers in front of the actual database server. Your game servers enqueue save requests to the cache servers, which distribute the pressure on the game server over time. This also allows you to tune the rate at which the caches flush to the final server without having to directly manipulate the game servers, as you'll likely have many games servers and fewer cache servers.

Try to keep the data you store as simple as possible for the database to consume; if you do anything but store binary blobs (which is what Guild Wars 1 did), design your table schema in such a way as to minimize relationships between tables that might cause locks that slow down an update. Consider your indices carefully, because every index you add can increase the complexity of inserting into a table. Et cetera.

You also need to consider the hardware/machine configuration options for dealing with the problem: if your entire database cannot be kept in memory on the server, you'll want to have very fast disks.

Other than distributing the load as much as possible and finding the appropriate amount of throttling you can make, this is primarily a database optimization problem. There are whole books written on SQL server optimization (and lots of lore on the SQL-alternatives, should you choose to elect to explore one of those as well). I'd recommend going in search of that material.

For most hobby "MMOs" though, this kind of scalability won't be needed.
> 5 votes

---
Tags: performance, databases, game-state
---


# Question
Title: Strange if-else branching behavior in a fragment shader
In my fragment shader I have passed an uniform int `uLightType` variable, which indicates what type of light is in usage right now. The problem is that if-else branching does not work correctly - the fragment shader performs instructions in every `if` statement block.

```
if (uLightType == 1) { // Spotlight light type
    vec3 depthTextureCoord = vDepthPosition.xyz / vDepthPosition.w;
    shadowDepth = unpack(texture2D(uDepthMapSampler, depthTextureCoord.xy));
}
else if (uLightType == 2) { // Omni-directional light type
    shadowDepth = unpack(textureCube(uDepthCubemapSampler, -lightVec));
}

```

In the case when `uLightType` equals 1, unless I comment out the content of the second `if` block, it assigns an another value to `shadowDepth`.

Also while `uLightType` equals 1, when I remove the second 'if' block and change `==` to `!=` like in the sample code below, nothing happens (which means that `uLightType` really equals 1).

```
if (uLightType != 1) { // Spotlight light type
    vec3 depthTextureCoord = vDepthPosition.xyz / vDepthPosition.w;
    shadowDepth = unpack(texture2D(uDepthMapSampler, depthTextureCoord.xy));
}

```

Also, when I manually create an int variable (which is not an uniform) like this: `var lightType = 1;` and replace `uLightType` with it in the if-else branch, everything works fine, so I guess it have something to do with the fact that `uLightType` is the uniform.

# Answer
It's pretty clear that your uniform isn't getting to the shader. As proved by pre-setting lightType manually. My 2nd guess would be precision hints but it looks like you're sending pretty small numbers to it. But also double check the precision can handle the value.

If an IF-ELSE branch isn't working as expected you have to assume it's not the IF-ELSE commands but the logic or values inside the ()'s.

Nine times out of nine when something is going wrong in a NEW shader where all the code looks right to me, it's that I'm not getting the value to the uniform. So however you do that in your system double check it. That's going to be it.

Here's what I would do. First just set `gl_frag =` to your uLightType in a way that will tell you if the value you're sending it is getting there or not. Something like:

```
lowp float test = uLightType/3.0;  // since your value is 1, 2, or 3.
gl_frag = vec4(test, test, test, 1.0);

```

Then keep trying to get a specific value there. Once you know that the uniform is getting what you're sending it, then you can debug the rest of your code.

As a side note, I do believe that one of the commenters is right though. That you will want to avoid if branching in the shader. It really slows it down. UUBER shaders aren't all they're cracked up to be. I always prefer multiple shaders over that.
> 2 votes

# Answer
What's the question - why it doesn't work as expected?

Is `shadowDepth` variable assigned a value before these checks?

Perhaps thread coalescing for some reason doesn't end well and it executes parts of the code it shouldn't.

---

Generally, branching on older versions of the OpenGL (ES) is bad, so you should avoid it, both for performance/readability reasons.

To debug shaders, there are two main approaches:

* write multiple shader (chunks) and test them separately
* use `#define`

Second option is good for keeping things in place, you have to look at just one file, so I would suggest that one.

Creating additional value is just horrible, it takes your time, you have to manage code for it, and strange things (like this here) can happen.
> 0 votes

---
Tags: glsl, fragment-shader, webgl
---


# Question
Title: What timeframe is used to compute ARPDAU for monetization purposes?
I search this for a while now but could't find the answer. ARPDAU - the 'average revenue per daily active user' is a metric for the financial performance of a game/app. But what timeframe is the value measured in?

For example, some statistics that can be found online mention an ARPDAU of $0.05 to $0.1 for casual games and up to $0.8 for hard-core (targeted at hard-core gamers) games. But what's the timeframe over which this is computed? One day? One month? The lifetime of the game?

The acronym itself would suggest it's lifetime revenue divided by DAU (otherwise it should be named ARPDAUPD or ARPDAUPM shouldn't it?), but then these numbers seem incredibly low. Let's say I have a casual game that performs averagely and has (on average, or let's say constantly) 10,000 daily active users. Does that mean I could expect from such a game to generate $500-$1000 over it's entire lifetime? Seems like nothing. Or is that rather $500-$1000 per day?

# Answer
> 1 votes
I'd assume it's simply per day for ease of calculation (and since it's an average value).

* Get the unique players logged in on one day.
* Get the total money spent on that day.
* Divide the amount of money by the amount of players and you've got your *ARPDAU*.

Of course, this may go up/down a lot on a daily basis. As such you can average the result over a month or even a year. It's up to you, but the result would still show you an average per day per user.

Regarding your numbers:

If you've got an ARPDAU of 0.05$ and an average of 10,000 players active a day, then you could assume that they might spend around 500$ on that day. Just keep in mind that this isn't your net revenue. There's still some money to be taken by service providers/shops, taxes, etc.

# Answer
> 0 votes
It means nothing, because there is no such thing as "*a* daily active user". You can have "an active user" or "daily active users", but not "*a* daily active user".

This is probably yet another case of "business people who have no idea about math and therefore make stuff up"

Probably, what they meant was "daily average revenue per active user", which is self explanatory.

The difference word order makes...

---
Tags: monetization
---


# Question
Title: How should I store grid-based character inventories in the database?
I used to encode the whole inventory data into binary but I'm thinking of doing something different now.

The inventory has a 64 slots in an 8×8 grid. Large items like weapons fill up 6 to 8 slots in a vertical rectangle, while potions take 1 slot.

How would you store this data in a database?

# Answer
I would probably start with the following schema:

```
Slot (ID, CharacterID, SlotID, ItemID)

```

where

* *Slot* is the name of the table
* *ID* is the table's primary key
* *CharacterID* is a foreign key that points to the character
* *SlotID* is the slot's ID going from 1 to 64 (or 0 to 63, or whatever)
* *ItemID* is a foreign key that points to the item (ID of a specific weapon, potion...)

In case of weapons and other multiple-slots inventory items you'd simply repeat the same *ItemID* over different *SlotID*'s.

**An example of a character that has a "potion of knowledge" at the bottom-right corner of the inventory, and a 6-slot "spear of fire & death" at the top-left corner:**

```
1, 1, 1, 666
2, 1, 2, 0
3, 1, 3, 0
4, 1, 4, 0
5, 1, 5, 0
6, 1, 6, 0
7, 1, 7, 0
8, 1, 8, 0
9, 1, 9, 666
10, 1, 10, 0
11, 1, 11, 0
12, 1, 12, 0
13, 1, 13, 0
14, 1, 14, 0
15, 1, 15, 0
16, 1, 16, 0
17, 1, 17, 666
18, 1, 18, 0
19, 1, 19, 0
20, 1, 20, 0
21, 1, 21, 0
22, 1, 22, 0
23, 1, 23, 0
24, 1, 24, 0
25, 1, 25, 666
26, 1, 26, 0
27, 1, 27, 0
28, 1, 28, 0
29, 1, 29, 0
30, 1, 30, 0
31, 1, 31, 0
32, 1, 32, 0
33, 1, 33, 666
34, 1, 34, 0
35, 1, 35, 0
36, 1, 36, 0
37, 1, 37, 0
38, 1, 38, 0
39, 1, 39, 0
40, 1, 40, 0
41, 1, 41, 666
42, 1, 42, 0
43, 1, 43, 0
44, 1, 44, 0
45, 1, 45, 0
46, 1, 46, 0
47, 1, 47, 0
48, 1, 48, 0
49, 1, 49, 0
50, 1, 50, 0
51, 1, 51, 0
52, 1, 52, 0
53, 1, 53, 0
54, 1, 54, 0
55, 1, 55, 0
56, 1, 56, 0
57, 1, 57, 0
58, 1, 58, 0
59, 1, 59, 0
60, 1, 60, 0
61, 1, 61, 0
62, 1, 62, 0
63, 1, 63, 0
64, 1, 64, 42

```

In this case the ID (first column) are just some generated IDs, they could be something else like GUIDs or something unique.

The CharacterID (second column) is the same the whole way because it is referring to the same character. If you store info about characters in the database as well, this ID would point to the table `Character` which has its own primary key.

The third column represents the inventory slots and they will always be within the 1,64 interval.

The last column refers to actual items. If you store info about items in the database as well, this ID would point to the table `Item` which has its own primary key. You will three different value in this column: 666, 42 and 0. *666* is an item ID that represents the spear, *42* represents the potion, and *0* is a dummy item ID which represents nothing. I.e. this slot is empty. You could also use `null` here, if you wish.

**How do you get a 2D grid of 8x8 slots out of this 1D array of slot IDs?**

Since you know the slots form a grid of 8x8 elements, you can use this information in your favor. Here's a pseudocode example when using 0-based SlotIDs (0-63 instead of 1-64):

```
int x = SlotID % 8;
int y = floor(SlotID / 8);

```
> 5 votes

---
Tags: data-structure, databases, storage, inventory
---


title: Predicted target location

text:
# Question
Title: Predicted target location
I'm having an issue with calculating the predicted linear angle a projectile needs to move in to intersect a moving enemy ship for my 2D game.

I've tried following the document here, but what I've have come up with is simply awful.

```
protected Vector2 GetPredictedPosition(float angleToEnemy, ShipCompartment origin, ShipCompartment target)
{
    // Below obviously won't compile (document wants a Vector, not sure how to get that from a single float?)
    Vector2 velocity = target.Thrust - 25f; // Closing velocity (25 is example projectile velocity)
    Vector2 distance = target.Position - origin.Position; // Range to close
    double time = distance.Length() / velocity.Length(); // Time

    // Garbage code, doesn't compile, this method is incorrect
    return target.Position + (target.Thrust * time);
}

```

I would be grateful if the community can help point out how this is done correctly.

# Answer
Labelling the shooter's position `x`, the target's initial position `y`, the speed of the projectile `v` and the vector velocity of the target `dy` you must choose a unit vector direction `d` to shoot in that satisfies the equations

```
x[0] + v*t*d[0] = y[0] + dy[0]*t
x[1] + v*t*d[1] = y[1] + dy[1]*t

```

for some time to impact `t`. Rearranging yields

```
v*t*d[0] = dy[0]*t + (y[0]-x[0])
v*t*d[1] = dy[1]*t + (y[1]-x[1])

```

Noting that `d` is a unit vector we have

```
d[0]^2 + d[1]^2 == 1

```

and hence

```
(v*t)^2 = (dy[0]*t + (y[0]-x[0]))^2 + (dy[1]*t + (y[1]-x[1]))^2
        = dy[0]^2*t^2 + 2*dy[0]*(y[0]-x[0])*t + (y[0]-x[0])^2
        + dy[1]^2*t^2 + 2*dy[1]*(y[1]-x[1])*t + (y[1]-x[1])^2

```

so

```
a*t^2 + b*t + c = 0

```

where

```
a = v^2 - dy[0]^2 - dy[1]^2
b = -2*dy[0]*(y[0]-x[0]) - 2*dy[1]*(y[1]-x[1])
c = -(y[0]-x[0])^2 - (y[1]-x[1])^2

```

This is a quadratic equation in `t` and has solutions

```
t = (-b +- sqrt(b^2 - 4*a*c)) / (2*a)

```

If this doesn't have a positive real solution then you can't hit the target (it's moving too fast). If it does, substitute it back into the rearranged equations to get `d`.
The counter clockwise angle that this makes with the positive x-axis is `Math.Atan2(d[1],d[0])` and the difference between it and the angle in which the shooter is facing is the one you're after.

**UPDATE**: Note that I've assumed that the shooter is stationary. If it's moving and its velocity `dx` should affect that of the projectile, you need to replace `dy[i]` with `(dy[i]-dx[i])` throughout.
> 3 votes

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


# Question
Title: How to change pixel color of Texture with Fragment Shader
I want to change the pixel color of a texture. I don't know where to start and what to add. Really need help, I only find useless snippets in the internet.

My current Code:

```
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
...
GLES20.glAttachShader(riGraphicTools.sp_SolidColor, vertexShader);
GLES20.glAttachShader(riGraphicTools.sp_SolidColor, fragmentShader);
GLES20.glLinkProgram(riGraphicTools.sp_SolidColor);

vertexShader = riGraphicTools.loadShader(GLES20.GL_VERTEX_SHADER, riGraphicTools.vs_Image);
fragmentShader = riGraphicTools.loadShader(GLES20.GL_FRAGMENT_SHADER, riGraphicTools.test_Image);

riGraphicTools.sp_Image = GLES20.glCreateProgram();
GLES20.glAttachShader(riGraphicTools.sp_Image, fragmentShader);
...
}

```

The riGraphicTools Class:

```
public class riGraphicTools {

public static final String test_Image =
        "precision mediump float;" +
        "varying vec2 v_texCoord;" +
        "uniform sampler2D s_texture;" +
        "void main() {" +
        "  gl_FragColor = texture2D( s_texture, v_texCoord );" +
        "}";

public static final String vs_Image =
    "uniform mat4 uMVPMatrix;" +
    "attribute vec4 vPosition;" +
    "attribute vec2 a_texCoord;" +
    "varying vec2 v_texCoord;" +
    "void main() {" +
    "  gl_Position = uMVPMatrix * vPosition;" +
    "  v_texCoord = a_texCoord;" +
    "}";
}

```

# Answer
The texture2D() function returns a vec4 containing the rgba values of that texel. You can then manipulate this just like any other vec4. For example, to make everything darker, you can do...

```
gl_FragColor = texture2D( s_texture, v_texCoord ) * vec4(0.5, 0.5, 0.5, 1);

```

The trick is the fragment shader runs on every fragment in whatever you're drawing, and choosing a single texel to manipulate is generally unreasonable. If that's what you want to do, I recommend doing so outside of the shader, perhaps with glTexSubImage2D.
> 3 votes

---
Tags: android, shaders, opengl-es, fragment-shader
---


# Question
Title: How can I find the "end" vertices on an open-ended mesh?
I was looking at a video of a system that extrudes meshes along a curve, connecting them end to end but adjusting the vertices for a smooth connection. It does this with a mesh that as far as I know is guaranteed to have open ends that are later capped with a separate mesh.

Here is a video showing the effect I am trying to reproduce.

Let's suppose I have a mesh, then, that is open like in the picture below. How can I find the vertices that are on one edge *only* of this mesh? For example the ones that are selected here.

Previously I used a plain cylinder with open caps as an example, and finding edges that were only used for one face might have been able to do the job, but in a case like this, it would end up selecting any vertices in the middle along the bottom as well, which I don't want.

I want to be able to find the ends of a particular side like those that are selected in the picture. Theoretically I can then manipulate these into new positions if I wanted to, for example, string cylindrical segments into a curved cable structure.

For what it's worth, I'm trying to accomplish this in Unity with C#, but it's the algorithm I need help with.

# Answer
> 2 votes
You need more info about your mesh geometry and topology than you currently have, otherwise you will need to do alot of tests. Half edge data structure which gives you a directional edge info, *can give you this information easily*. Boundary half-edges and hence vertices don't have adjacent faces, so you simply check if a half-edge has an adjacent face, if not, it is a boundary edge and hence its vertices.

Half edge data structure deals with each edge as two separate direction edges. Boundary half-edges don't have adjacent faces. keep in mind that half edge data structure stores much more info than the usual vertex-face data structure which makes it able to perform fast geometry queiries and lookups. In case of detecting boundary edges, what you need to do is only asking if a half edge have an adjacent face. Adjacent faces are stored in the half edge info.

But your problem is that you need to build your data structure using half edge data structure.

# Answer
> 0 votes
Based on your picture, you appear to want to know the vertices that are not fully enclosed in a group of faces.

If kat0r's answer suffices, go with that.

Otherwise, you need to look for vertices that either:

* Have two or less edges connected to them or,
* Have edges that all participate in faces, without gaps.

Like this: https://i.stack.imgur.com/zAaD2.jpg

One way of doing that would be to sort all the edges for a vertex based on angle, then check if there is a face for every edge and it's neighbour.

---
Tags: unity, procedural-generation, 3d-meshes, vertex
---


# Question
Title: How does game asset file encryption work?
How does file encryption in game assets work, for example the unreal engine has a `.assest` extension, or I also see a `.dta` extension in another game, are these `.zip` type packages which have a custom encryption algorithm set by the developer or how does it work?

Is it as simple as coming up with your own encrytion algorithm then extracting all the file such as in a `.pk3` file?

# Answer
> 10 votes
> How does file encryption in game assets work, for example the unreal engine has a .assest extension, or I also see a .dta extension in another game, are these zip type packages which have a custom encryption algorithm set by the developer or how does it work?

Most of the time, those are **not** encrypted data files.

There's a difference between *encryption* and a *custom file format*. Most games tend to use the latter, not the former. Encryption is concerned with protecting data in such a way that only certain people can read it; a custom file format is generally only about storing a particular collection of data in the most-efficient or otherwise most-useful form for the program that will consume the data.

Encryption is relatively pointless for most game data that will be directly read client-side, on the user's computer. The user's computer must perforce decrypt the data to use it, at which point somebody could intercept the data in-memory without much more effort than it took to read the data on disk, so all that extra effort and potential extra file size that went in to "protecting" the data is lost.

The games that *do* use encryption somewhere (in a network protocol or a server back end, or even the few that do make use of it somewhere on a client side) will generally use an established encryption protocol of some flavor (and *not* rely on security through obscurity). Reinventing your own is a very bad idea, because it's surprisingly easy to create something that looks secure but is open to one of the many vulnerabilities or attack vectors that have been developed over the years. It's a fascinating subject if you're into that sort of thing, and you might consider taking a few classes on the subject.

# Answer
> 2 votes
Truth to be told, there's no reason to encrypt data in a program that will run client-side (that does include any flash/HTML or unity based games running in the browser). Anyone that's inclined enough can get the data anyway - be it by hijacking internal function calls, the OpenGL/DirectX calls, etc. Once it's on the PC of the user, you must understand that there's no way you can prevent a dedicated user from extracting the data.

So the only thing you can prevent is casual users from browsing the data, and honestly, just renaming your zip-files to dat will do the trick here.

# Answer
> 1 votes
I believe this might help you.

In short, there are unlimited number of ways to encrypt your game data. Anything from simply bit swapping to more complicated key based, or even using PGP are all valid ways of storing and encrypting the game data.

Compression should happen before encryption as Kornel Kisielewicz has pointed out. You can use whatever compression format you like for this, although I've had good results with huffman based compression.

---
Tags: c++, assets, encryption
---


# Question
Title: How can I run a Phaser engine game without a window?
I'm currently creating a multiplayer game using the HTML5 framework Phaser.

It's a game where zombies spawn on the map and players have to shoot them to kill them. The zombies target players that are closest to them.

Currently, I'm having my an issue with my design strategy. I'm not sure if this type of game is possible with Phaser due to the movement tracking.

At present, the client is handling all of the player movement, so whenever a player moves, it broadcasts it to the server which sends it to all of the other clients.

However, I would like for the zombies and the bullets to be controlled by the server exclusively. The server then updates each client with the velocity of each zombie and their current position. My reasoning is that anything that isn't player input should be calculated by the server. This will prevent issues such as two clients saying that a zombie died at different times and then trying to communicate with one another, having bullets at different locations at the same time, or zombies spawning at separate times between clients.

Here's an example of a zombie class:

```
function Zombie(game, data){

this.game = game;

this.id = data.id;
Phaser.Sprite.call(this, this.game, data.x, data.y, 'zombie');
this.anchor.setTo(0.5,0.5);

this.animations.add('right', [0,1,2,3], 7, true);
this.animations.add('left', [4,5,6,7], 7, true);
this.game.physics.arcade.enable(this);
this.body.collideWorldBounds = true;

this.health = data.health;
this.maxHealth = data.maxHealth;
this.speed = data.speed;
this.target = this.game.player;
this.waiting = 100;

this.name = "zombie";
this.healthBary = 20;
this.healthBar = this.game.add.sprite(this.x, this.y + this.healthBary, 'player_health');
this.healthBar.anchor.setTo(0.5, 0.5);
CollisionManager.addObjectToGroup(this, 'baddies');
this.game.add.existing(this);

}
Zombie.prototype = Object.create( Phaser.Sprite.prototype );
Zombie.prototype.constructor = Zombie;
Zombie.prototype.update = function(){

this.updateHealthBar();

                this.moveTowards(this.target);

Zombie.prototype.uTarget = function(target) {
    this.target = target;
};
Zombie.prototype.moveTowards = function(target){
var x = target.x - this.x;
var y = target.y - this.y;

var mag = Math.sqrt((x * x) + (y * y));

var nx = x / mag;
var ny = y / mag;

this.body.velocity.x = nx * this.speed;
this.body.velocity.y = ny * this.speed;

if(this.body.velocity.x >= 0){
    this.animations.play('right');
}
else if(this.body.velocity.x < 0){
    this.animations.play('left')
}

}
Zombie.prototype.updateHealthBar = function(){
this.healthBar.x = this.x;
this.healthBar.y = this.y + this.healthBary;

var p = (this.health / this.maxHealth);
p = parseFloat(p.toFixed(1));
this.healthBar.frame = 10 - (p * 10);
}
Zombie.prototype._damage = function(amount){
this.health -= amount;
if(this.health <= 0){
    this.kill;
    this.die(true);
}
}

Zombie.prototype.die = function(points){

if(this.game){
    //this.game.baddie_die_sfx.play();
}

WaveManager.onMap--;
CollisionManager.removeObjectFromGroup(this, "baddies");
if(this.healthBar){
    this.healthBar.destroy();
}
socket.emit("kill zombie", {id: this.id});
this.kill();
this.destroy();
}

```

The problem is that I can't create a Phaser game object on the server (as it's running on a Linux server) because there's no window that can be used. The bullets and zombies need to be Phaser objects for the sake of collision detection, but I can't do that on the server.

I know that I could create a vector of zombies and bullets server-side that would have the information for each bullet/zombie's position at any given time and then update the client, but then I wouldn't be able to use the CollisionManager in Phaser.

Right now, it seems like my only solution is to create my own collision detection system. Are there any alternative ideas?

# Answer
While in theory it should be possible given that you can construct the Phaser game object with a `HEADLESS` renderer type, this post from one of the developers seems to suggest that that won't solve *your* problem, since Phaser still requires the canvas to initialize. That post was in 2013, but I don't see any obvious proof that the issue has been addressed yet (I didn't actually trawl through the source code though).

Your best bet is likely to use something like node-canvas, as per the comments.

However, *also* as suggested in the comments, I wouldn't recommend using a front-end-oriented game engine like Phaser on your back-end server like this. You should just be able to build a "regular" node.js application that had logical representations of your bullets and zombies, did the simulation on them, and sent them back to clients. JavaScript's dynamic nature should make it easy to interpret or serialize/deserialize the client-side Phaser objects.
> 5 votes

---
Tags: collision-detection, html5, server, node.js, phaser
---


# Question
Title: How to structure complex global game state?
Assume you're working on an RPG like Fallout and you have all sorts of flags and variables tracking the state of the world. Stuff like:

* Talked to NPC X
* Opened chest Y
* Completed quest 1
* Visited some dungeon
* Defeated 30 goblins
* etc.

You also want to save and load this information. My question is about the best way to structure this information. You could simply have a big global list of variables, but it's obviously better to break it up into smaller scopes. You could associate certain states with the current location, objects/NPCs, quests, or other scopes, but occasionally you have truly global information shared between multiple quests and locations. Furthermore, sometimes it's difficult to tell where the state belongs and you have to spend time thinking where to store it or find it.

The answers to this question suggest using a finite state automation, which might be fine for some examples like badge progress in Pokemon or keeping track of quests in a game, but it can get really complex if you have a more open game with a large number of states and hidden variables that influence multiple quests and interactions.

So to iterate, what are some good approaches for structuring game state? (particularly for RPGs and adventure games)

# Answer
> 6 votes
Your list includes several things which should have their tracking abstracted separately, rather than pooled into a single global pile of state.

For example, quest completion is something that *all* quests will track. Similarly, *all* dungeons will likely need to have their completion status tracked. However, dungeons are generally a *binary* value (you completed it, or you didn't) whereas quests might not be (you may have finished it, but did you succeed or fail?). So while you might have functions like `DidFinishDungeon(dungeon)` and `DidFinishQuest(quest)`, the former will probably just return a Boolean value while the latter could very well return some kind of `QuestResult` object.

By way of contrast, you probably *won't* want to track whether or not *every* NPC has or has not been talked to. That's generally handed by setting and checking scripting flags within the dialog or script system.

You'll probably want to track chest opening, at least for special chests with unique rewards, but you'll probably want to store that data in a dedicated block of character data representing chest-recovery state (or perhaps tie it to dungeon completion state, if your game mechanics allow so).

---

Underneath the abstraction, you can store all the Boolean values for a character together in a single blob of storage, using "progress bits." This sort of storage is basically an array of integer values used to represent a collection of bits; you assign bit indices to particular events (such as "talked to Farmer Bob") and provide a way to expose the checking and setting of those bits to dialog or scripting systems in your game. You'll also want a want to recycle the indices of bits you remove or repurpose, so you don't leave holes in the address space; good toolset support really helps here, although if you game is small enough in scope you can simply track this manually in a spreadsheet or something.

It generally makes the most sense to use this system for more freeform "player has done stuff" flags, like talking to NPCs, reaching certain parts of a level to trigger an event, et cetera. One-off things for which you only need to store a true/false value. In the interest of reducing dependencies *and* keeping the progress bit space confined, I'd store things like quest/dungeon completion and chest-opening data elsewhere, in a section dedicated to that storage.

Achievement-like data ("kill 30 goblins") is similarly better off stored with or by the achievement itself, because it likely varies so wildly between achievements and often requires more than a single bit to store progress towards the achievement. You could also extend the progress bit system to allow for both toggle bits and range bits, since you are only really limited in storage by the memory/storage limits you impose on yourself for you game.

---
Tags: rpg, game-state, quests
---


title: Multithreading issues - Frame skips

text:
# Question
Title: Multithreading issues - Frame skips
So I am trying to multithread a Voxel engine in C# made with Sharpdx and I am having a few issues:

This is the class I have :

```
#region

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using HyroVoxelEngine.Voxels.Chunks;
using HyroVoxelEngine.Voxels.Comparators;
using HyroVoxelEngine.Voxels.Meshing;
using HyroVoxelEngine.World.Cameras;
using HyroVoxelEngine.World.Procedural.Terrain;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.Toolkit;

#endregion

namespace HyroVoxelEngine.Voxels
{
    public class ChunkManager
    {
        private GreedyMeshing Mesher = new GreedyMeshing();
        private static ConcurrentDictionary<ChunkIndex, Chunk> Cache;
        private static ConcurrentQueue<Thread> BuildingThreads = new ConcurrentQueue<Thread>();
        private readonly List<Chunk> LoadList;
        private readonly int MaxChunkLoadPerFrame = 1;
        private readonly List<Chunk> RebuildList;
        private readonly List<Chunk> VisibilityList;
        public FPSCamera Camera;

        private bool ForceVisibilityUpdate = true;
        public List<Chunk> RenderList;
        private ChunkIndex lastIndex;
        private Matrix lastView;
        private volatile int taskCount = 10;
        private volatile int buildCount = 1;
        #region Loading and Building
        private void Load(Chunk c)
        {
            if (c.State != Chunk.ChunkState.New)
                return;

            new Thread(() =>
            {
                c.State = Chunk.ChunkState.Generating;
                taskCount--;
                PlanetaryGenerator.GeneratePlain(c);
                taskCount++;
                c.State = Chunk.ChunkState.Complete;

            }).Start();

        }
        private void Rebuild(Chunk c)
        {
            if (c.State != Chunk.ChunkState.NeedBuilding)
                return;
            if (buildCount > 0)
                Task.Run(() =>
                {
                    c.State = Chunk.ChunkState.Generating;
                    Mesher.Mesh(c);
                    c.State = Chunk.ChunkState.Complete;
                });

        }
        #endregion

        public ChunkManager()
        {
            LoadList = new List<Chunk>();
            RenderList = new List<Chunk>();
            VisibilityList = new List<Chunk>();
            RebuildList = new List<Chunk>();
            Cache = new ConcurrentDictionary<ChunkIndex, Chunk>(2, 500, new ChunkIndexComparator());
        }
        public void Update(GameTime gt)
        {
            UpdateLoadList();
            UpdateRebuildList();
            UpdateVisibilityList();
            UpdateRenderList();
            if (lastView == Camera.ViewMatrix)
                return;
            lastView = Camera.ViewMatrix;
            UpdateRenderList();
        }
        private void UpdateVisibilityList()
        {
            if (!ForceVisibilityUpdate && Camera.ChunkIndex == lastIndex && VisibilityList.Count != 0)
                for (int i = 0; i < VisibilityList.Count; i++)
                {
                    LoadList.Add(VisibilityList[i]);
                }
            else
            {
            Chunk c;
            lastIndex = Camera.ChunkIndex;
            LoadList.Clear();
            VisibilityList.Clear();
            int VisibilityRange = Configs.Configs.ViewDistance;
            for (var x = -VisibilityRange; x < VisibilityRange; x++)
            {
                for (var z = -VisibilityRange; z < VisibilityRange; z++)
                {
                    c = GetChunk(Camera.ChunkIndex.X + x , 0, Camera.ChunkIndex.Z +z );
                    VisibilityList.Add(c);
                    switch (c.State)
                    {
                        case Chunk.ChunkState.New:
                            LoadList.Add(c);
                            break;
                        case Chunk.ChunkState.NeedBuilding:
                            RebuildList.Add(c);
                            break;
                        case Chunk.ChunkState.Complete:
                            break;
                    }
                }
            }
        }
        VisibilityList.Sort((x, y) => x.DistanceTo(Camera.Position).CompareTo(y.DistanceTo(Camera.Position)));
        RebuildList.Sort((x, y) => x.DistanceTo(Camera.Position).CompareTo(y.DistanceTo(Camera.Position)));
        LoadList.Sort((x, y) => x.DistanceTo(Camera.Position).CompareTo(y.DistanceTo(Camera.Position)));
        ForceVisibilityUpdate = false;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private Chunk GetChunk(long x, int y, long z)
        {
            var ind = new ChunkIndex(x, z, y);
            Chunk c;
            if (Cache.TryGetValue(ind, out c))
                return c;
            c = new Chunk(ind);

            if (Cache.TryAdd(ind, c))
            {
                return c;
            }
            return null;
        }

        private void UpdateRenderList()
        {

            RenderList.Clear();
            Chunk c;
            for (int i = 0; i < VisibilityList.Count; i++)
            {
                c = VisibilityList[i];
                if (c.Empty)
                    return;
                BoundingBox b = new BoundingBox();
                BoundingFrustum f = new BoundingFrustum(Camera.ViewMatrix*Camera.Projection);
                if (!f.Intersects(ref c.BoundingBox))
                    continue;
                if ( c.State == Chunk.ChunkState.Complete)
                    RenderList.Add(c);
            }

        }
        private void UpdateRebuildList()
        {
            int loadedChunks = 0;
            Chunk c;
            for (int i = 0; i < RebuildList.Count; i++)
            {
                //if (i > MaxChunkLoadPerFrame)
                //    break;
                c = RebuildList[i];
                if (c.State == Chunk.ChunkState.NeedBuilding)
                {
                    Rebuild(c);
                    if (c.State == Chunk.ChunkState.Complete)
                    {
                        //Rebuild the neighbours

                        //TODO:: REBUILD THE NEIGHBOURS
                        loadedChunks++;
                        ForceVisibilityUpdate = true;
                    }
                }
            }
            RebuildList.Clear();
        }

        private void UpdateLoadList()
        {
            int loadedChunks = 0;
            Chunk c;
            for (int i = 0; i < LoadList.Count; i++)
            {
                //if (i > MaxChunkLoadPerFrame)
                //    break;
                c = LoadList[i];
                if (c.State != Chunk.ChunkState.Complete)
                {
                    Load(c);
                    if (c.State == Chunk.ChunkState.NeedBuilding)
                    {
                        loadedChunks++;
                        ForceVisibilityUpdate = true;
                    }
                }
            }
            LoadList.Clear();
        }
    }
}

```

The issue being that some of the chunks get "broken"

Just like that image

My Second issue is that whenever I move the camera, I get "hiccups" and my framerate drops to under 10.

I have profileed my code and obviously my issue with performance is the Meshing, but my CPU is not even maxed out. and since I am running in anothe rthread it should drop my FPS that much. So how and what could I possibly do to fix this issues?

**EDIT**

```
private void Load(Chunk c)
{

    if (c.State != Chunk.ChunkState.New)
        return;
    Stopwatch t = new Stopwatch();
    t.Start();
    if (taskCount > 0)
    {
        new Thread(() =>
        {
            GreedyMeshing Mesher = new GreedyMeshing();

            c.State = Chunk.ChunkState.Generating;
            taskCount--;
            PlanetaryGenerator.GeneratePlain(c);
            Mesher.Mesh(c);
            taskCount++;
            c.State = Chunk.ChunkState.Complete;

        }).Start();
    }
    t.Stop();

}

```

So I have found that this code is actually the one behind the stutters, probably I should Implement a Pool Mechanism for the threads, but still it should be that lenghty to create a thread I think. Any ideas on how to fix this?

# Answer
1. In UpdateVisibilityList(), Why are you sorting the lists? Doesn't seem to need it, since every voxel will be calculated on each frame
2. In UpdateRenderList(), You probably shouldn't clear the list, and proceed to fill it with 90% of the same voxels. Calculate the new frustum, then add the new blocks, and remove blocks that don't intersect. Also, why is UpdateRenderList() being called twice per updated?

Can you also explain what all of the 4 lists are supposed to do, specifically the load and rebuild lists.
> 2 votes

---
Tags: c#, performance, multithreading, voxels
---


# Question
Title: How to set HUD elements position and size depending of resolution
How can I set HUD elements' position and size when changing resolution and maintain the desired layout? All HUD elements (including menu items such as play button, setting button etc) need to get some scaling.

# Answer
The best solution is using relative scales. CEGUI has a nice system for that, it might give you some inspiration:

http://cegui.org.uk/wiki/Unified\_Positions\_and\_Sizes\_System
> 0 votes

# Answer
Maybe you can make a class which takes the video monitor configuration, taking the resolution and then making methods to calculate the position of the elements on the monitor. A pseudo method would be something like:

```
bool writeText(std::string const& text) {
    screen.write(text, screen.resolution-screen.resolution);
/* suppose that we want it on the left, the screen.resolution would return the     monitor resolution, subtracting by himself would result in 0, which is the left corner of the screen.
*/
}

bool spawnButton(int const& width, int const& height, std::string const& label) {
    video.newButton(width, height, label, screen.resolution/2-(width/2));
/* Suppose the we want the button on the center of the screen, then is just take  the    screen resolution, divide by two minus the width size of the button divided by two.
*/
}

```
> 0 votes

---
Tags: c++, software-engineering, hud, metaprogramming
---