title: Calculate direction of coordinates

text:
# Question
Title: Calculate direction of coordinates
I wanted conditions that could determine which direction (north, south, east, west, northwest, northeast, southeast, southwest) the player is following, what I got was just north, south, east and west, as shown in the code below:

```
var playerX = player.x, playerY = player.y;

var destX = 8, destY = -15;

    if (playerX < destX) {
      playerX += 0.5; // east
    } else if (playerX > destX) {
      playerX -= 0.5; // west
    } else {
      playerX = destX; // maintains direction
    }
    if (playerY < destY) {
      playerY += 0.5; // north
    } else if (playerY > destY) {
      playerY -= 0.5; // south
    } else {
      playerY = destY; //maintains direction
    }

```

---

**image example:**

# Answer
> 1 votes
I solved this code:

```
var lastX, lastY;
function geraDirecao(player) {
    var playerX = player.position.x,
        playerY = player.position.y;

    if(playerX < lastX) {
        if (playerY < lastY) {
            // top left
        } else if (playerY == lastY) {
             // left
        } else { // playerY > lastY
            // bottom left
        }
    } else
    if (playerX == lastX) {
        if (playerY < lastY) {
            // top
        } else if (playerY == lastY) {
            // Not allowed
        } else { // playerY > lastY
            // bottom
        }
    } else { // playerX > lastX
        if (playerY < lastY) {
            // top right
        } else if (playerY == lastY) {
            // right
        } else {// playerY > lastY
            // bottom right
        }
    }

    lastX = playerX;
    lastY = playerY;
}

```

# Answer
> 1 votes
Imagine your player is a chess piece on a chessboard then look at the picture how every chess piece are moving and which field are valid fields for each piece, How ever your problem is more look like a Queen on a chess board because can move on every direction and you can adapt this algorithm to your player. you need array to loop through every row and column.

Here is the code for how a Queen move on a chessboard.

```
 public class Queen extends Chesspiece {

    protected Queen(char color, char name) {
        super(color, name);
    }

    @Override
    public void markReachableFields() {
        char rw = row;
        byte col = column;

        for (char i = 'a'; i <='h'; i++) {
            rw = (char)i;
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].mark();
            }
        }
        col = column;
        rw = row;
        for (byte j = 0; j < 8; j++) {
            col = (byte)j;
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].mark();
            }
        }
        rw = row;
        col = column;
        for (int i = 0; i < 8; i++) {
            rw = (char)(rw - 1);
            col = (byte)(col + 1);

            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].mark();
            }
        }
        rw = row;
        col = column;

        for (int i = 1; i <= 8; i++) {
            rw = (char)(rw + 1);
            col = (byte)(col + 1);
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].mark();
            }
        }
         rw = row;
         col = column;

        for (int i = 1; i <= 8; i++) {
            rw = (char)(rw + 1);
            col = (byte)(col - 1);
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].mark();
            }
        }

         rw = row;
         col = column;
        for (int i = 1; i <= 8; i++) {
            rw = (char)(rw - 1);
            col = (byte)(col - 1);
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].mark();

            }
        }
    }
    @Override
    public void unmarkReachableFields() {
        char rw = row;
        byte col = column;

        for (char i = 'a'; i <='h'; i++) {
            rw = (char)i;
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].unmark();
            }
        }
        col = column;
        rw = row;
        for (byte j = 0; j < 8; j++) {
            col = (byte)j;
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].unmark();
            }
        }
        rw = row;
        col = column;
        for (int i = 0; i < 8; i++) {
            rw = (char)(rw - 1);
            col = (byte)(col + 1);

            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].unmark();
            }
        }
        rw = row;
        col = column;

        for (int i = 1; i <= 8; i++) {
            rw = (char)(rw + 1);
            col = (byte)(col + 1);
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].unmark();
            }
        }
         rw = row;
         col = column;

        for (int i = 1; i <= 8; i++) {
            rw = (char)(rw + 1);
            col = (byte)(col - 1);
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].unmark();
            }
        }

         rw = row;
         col = column;
        for (int i = 1; i <= 8; i++) {
            rw = (char)(rw - 1);
            col = (byte)(col - 1);
            if ((rw >= 'a' && rw <= 'h') && (col >= 1 && col <= 8)
                    &&Chessboard.this.isValidField(rw, col)){
                int r = rw - FIRST_ROW;
                int c = col - FIRST_COLUMN;
                Chessboard.this.fields[r][c].unmark();

            }
        }
    }
 }

```

---
Tags: c#
---


# Question
Title: How can i make monsters drop items when they are being killed
I am making HTML 5 game with Javascript i am really new to programming,want to know how to make the enemies drop items after they are killed when the enemy dies i want the rectangle to represent an item dropped but the rectangle can't be drawn

```
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>

<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';

var HEIGHT = 500;
var WIDTH = 500;
var timeWhenGameStarted = Date.now();   //return time in ms
var framecount=0;
var player = {
    x:50,
    spdX:75,
    y:450,
    spdY:20,
    name:'P',
    hp:10,
    width:20,
    height:90,
    color:'green',
    Counter:0
};
var upgradelist={};
var enemyList = {};
var bulletList={};
upgrade = function (id,x,y,spdX,spdY,width,height,color){
    var enemy3 = {
        x:x,
        spdX:spdX,
        y:y,
        spdY:spdY,
        name:'E1T1',
        id:id,
        width:width,
        height:height,
        color:color,

    };
    upgradelist[id] = enemy3;
    }

getDistanceBetweenEntity = function (entity1,entity2){  //return distance (number)
    var vx = entity1.x - entity2.x;
    var vy = entity1.y - entity2.y;
    return Math.sqrt(vx*vx+vy*vy);
}

testCollisionEntity = function (entity1,entity2){   //return if colliding (true/false)
    var rect1 = {
        x:entity1.x-entity1.width/2,
        y:entity1.y-entity1.height/2,
        width:entity1.width,
        height:entity1.height,
    }
    var rect2 = {
        x:entity2.x-entity2.width/2,
        y:entity2.y-entity2.height/2,
        width:entity2.width,
        height:entity2.height,
    }
    return testCollisionRectRect(rect1,rect2);

}

Enemy = function (id,x,y,spdX,spdY,width,height){
    var enemy3 = {
        x:x,
        spdX:spdX,
        y:y,
        spdY:spdY,
        name:'E1T1',
        id:id,
        width:width,
        height:height,
        color:'red',

    };
    enemyList[id] = enemy3;
    }

document.onmousemove= function(mouse){
    /*
    var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
    var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;
    player.x=mouseX;
    if(mouseX < player.width/2)
                mouseX = player.width/2;
        if(mouseX > WIDTH-player.width/2)
                mouseX = WIDTH - player.width/2;
        if(mouseY < player.height/2)
                mouseY = player.height/2;
        if(mouseY > HEIGHT - player.height/2)
                mouseY = HEIGHT - player.height/2;

        player.x = mouseX;
    */

}

document.onclick=function(mouse){
    if (player.Counter>5) {
        randomlyGenerateBullet();
        player.Counter=0;
    };
    }

document.onkeydown = function(event){
        if(event.keyCode === 39)        //d
                player.pressingRight = true;
        else if(event.keyCode === 37) //a
                player.pressingLeft = true;
        else if(event.keyCode === 38) // w
                player.pressingUp = true;
}
document.onkeyup = function(event){
        if(event.keyCode === 39)        //d
                player.pressingRight = false;
        else if(event.keyCode === 37) //a
                player.pressingLeft = false;
        else if(event.keyCode === 38) // w
                player.pressingUp = false;}
updatePlayerPosition = function(){
        if(player.pressingRight)
                player.x += 10;
        if(player.pressingLeft)
                player.x -= 10;
      }

updateEntity = function (something){
    updateEntityPosition(something);
    drawEntity(something);
}
updateEntityPosition = function(something){
    something.x += something.spdX;
    something.y += something.spdY;

    if(something.x < 0 || something.x > WIDTH){
        something.spdX = -something.spdX;
    }
    if(something.y < 0 || something.y > HEIGHT){
        something.spdY = -something.spdY;
    }
}

testCollisionRectRect = function(rect1,rect2){
    return rect1.x <= rect2.x+rect2.width
        && rect2.x <= rect1.x+rect1.width
        && rect1.y <= rect2.y + rect2.height
        && rect2.y <= rect1.y + rect1.height;
}

Bullet = function (id,x,y,spdX,spdY,width,height){
    var bullet = {
        x:x,
        spdX:spdX,
        y:y,
        spdY:spdY,
        name:'E1T1',
        id:id,
        width:width,
        height:height,
        color:'purple',
        timer:0
    };
    bulletList[id] = bullet;
    };
    randomlyGenerateBullet=function(){
var x=player.x;
var y=player.y;
var height=10;
var width=10;
var id= Math.random();
var angle=Math.random()*360;
var spdX=Math.cos(angle/180*Math.PI)*5;
var spdY=Math.sin(angle*5.180*Math.PI*5);
    Bullet(id,x,y,spdX,spdY,width,height)};

drawEntity = function(something){
    ctx.save();

    ctx.fillRect(something.x-something.width/2,something.y-something.height/2,something.width,something.height);
    ctx.restore();
}
Newgame=function(){
    framecount=0;
    var timeSurvived = Date.now() - timeWhenGameStarted;

                console.log("You timeWhenGameStarted = Date.now()lost! You survived for " + timeSurvived + " ms.");
                bulletList={ }
                player.hp = 10;
}

update = function(){
    framecount++;
    ctx.clearRect(0,0,WIDTH,HEIGHT);
    player.Counter++;

    if (toRemove) {
        delete bulletList[key];
    };

    for(var key in bulletList){
               updateEntity(bulletList[key]);

                var toRemove = false;
                bulletList[key].timer++;
                if(bulletList[key].timer > 25){
                        toRemove = true;
                }

                for(var key2 in enemyList){
                    var isColliding = testCollisionEntity(bulletList[key],enemyList[key2]);
                    upgrade("U1",enemyList[key2],enemyList[key2],0,0,30,30,"green");
                    updateEntity(upgrade);
                    if(isColliding){
                            toRemove = true;
                                delete enemyList[key2];
                                 break;

                        }

                }
                    }

                if(toRemove){
                        delete bulletList[key];

                }

    for(var key in enemyList){
        updateEntity(enemyList[key]);

        var isColliding = testCollisionEntity(player,enemyList[key]);
        if(isColliding){
            player.hp = player.hp - 1;
            if(player.hp <= 0){
                Newgame();
            }
        }

    }
    updatePlayerPosition();
    drawEntity(player);
    ctx.fillText(player.hp + " Hp",0,30);
}

Enemy('E1T1',150,450,10,15,30,30);
Enemy('E2T1',250,350,10,-15,20,20);
Enemy('E3T1',250,450,10,-8,40,10);

setInterval(update,40);

</script>

```

# Answer
Something like this:

```
 var items = [];

...

function die() //call from wherever.
{
   for (int i = 0; i < numItemsToDrop; i++)
   {
      var item = {}; //if you don't care about type - else use "new Item()"
      item.name = ...; //enter some name here
      item.damage = ...; //etc.
      items.push(item);
   }
}

...

void update() //called every frame to render the world
{
   for (var item in items)
   {
      item.display(); //this is your own function that does whatever it takes to show the item at the correct position etc. on screen.
   }
}

```
> 1 votes

---
Tags: javascript, software-engineering, html5
---


# Question
Title: Sprite doesn't change material or picture
I am quite new to unity and currenty I'm practicing with a 2D topdown game.

I created a tile map with "tiled", imported it in Unity with "TiledToUnity" and changed some things like player movement, camera and so on.

Now I wanted to create collectible coins. So I created a new 2D Sprite and added the picture of the coin I had to it. But the picture of the coin did not change. I tried the same with adding a material with the coin as picture but it did not work out either.

To check if the object is even there I added a collide box to the coin and my player body did indeed collide.

What did I do wrong while adding a picture to the sprite?

Thanks in advance!

(Sorry fotgot the pictures. ) -- Edit--

# Answer
> 0 votes
After changing the Shader of the material to Sprite -\> Default the problem was fixed.

---
Tags: unity, 2d, sprites
---


# Question
Title: How to create card layout in a trading card game Libgdx
I am trying to create a card layout for my trading card game. Right now I use this code:

```
public class ClientCard extends Table {

    ClientCard(int cost, int attack, int health, String title, String description) {
        Texture texture = new Texture(Gdx.files.internal("data/"+title+".jpg"));
        Image image = new Image(texture);
        this.add(image).width(Gdx.graphics.getWidth() / 10).height(Gdx.graphics.getHeight() / 7).colspan(3);
        this.row();
        Skin skin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
        Label cardName = new Label(title, skin);
        Label cardDescription = new Label(description, skin);
        Label cardCost = new Label(cost + "", skin);
        Label cardAttack = new Label("", skin);
        Label cardLife = new Label(health + "", skin);
        this.add(cardName).colspan(3).padBottom(5);
        this.row();
        this.add(cardDescription).colspan(3).padBottom(5);
        this.row();
        this.add(cardCost);
        this.add(cardLife);
        this.add(cardAttack);
    }
}

```

It works, it shows the card data, but it looks pretty bad and it's not very compact, also I can't set the outer border for the Table (`table.debug` is not good). What I want is something like this:

I want to use scene2d so it's easier to fill the card with the data I want (life, attack etc). Any idea how I could realize this? Thanks!

# Answer
How does this look? *(Green and red lines are only there for debugging)*

What I did to achieve this was to first separate the card into **three columns and five rows**; then I had the *Cost*, *Life*, *Attack*, and *S* field occupy the small **1st and 3rd column** and the *Image*, *Title*, and *Description* occupy the large **2nd column**. I then used a `Stack` (docs) to stack the table of contents on top of the colorful background image.

The general structure looks something like this in code;

```
table.add(cost); //col1
table.add(); //Blank! Used only to create col2.
table.add(s); //col3
table.row(); //New row

table.add(); //col1
table.add(image); //Image only occupies col2!
table.add(); //col3
table.row(); // New row

table.add();
table.add(title);
table.add();
table.row();

table.add();
table.add(description);
table.add();
table.row();

table.add(life);
table.add(class);
table.add(attack);

stage.addActor(new Stack(background, table));

```

But this of course won't size the cells to the correct size. The exact size of the cells will depend on what your layout looks like but for this layout I decided that all red fields will have a width and height of `75`. With that in mind the exact code used looked like this:

```
/* Adds the "Cost" label and centers its text. */
table.add("Cost").width(75).height(75).getActor().setAlignment(Align.center);
/* Important! Adds a column between "Cost" and "S". Used to
 * align "Image", "Title", "Description", and "Class". */
table.add();
/* Same as "Cost". */
table.add("S").width(75).height(75).getActor().setAlignment(Align.center);
table.row();

/* Add "Image" to middle column with a height of 50% of the
 * background's height minus 75 (the top columns height). */
table.add();
table.add("Image").growX().height(Value.percentHeight(.5f).get(background) - 75)
                  .getActor().setAlignment(Align.center);
table.add();
table.row();

/* Add "Title".*/
table.add();
table.add("Title").grow().getActor().setAlignment(Align.center);
table.add();
table.row();

/* Add "Description". */
table.add();
table.add("Description").grow().getActor().setAlignment(Align.center);
table.add();
table.row();

/* Add "Life", "Class", and "Attack". Same deal as "Cost" and
 * "S" */
table.add("Life").width(75).height(75).getActor().setAlignment(Align.center);
table.add("Class").growX().fillY().getActor().setAlignment(Align.center);
table.add("Attack").width(75).height(75).getActor().setAlignment(Align.center);

/* Used to show the table above the background image. You
 * should probably use Table#setBackground(drawable)
 * instead of using a stack! */
final Stack stack = new Stack(background, table);
stack.setSize(background.getWidth(), background.getHeight());
stage.addActor(stack);

/*Shows the green and red outlines. ONLY FOR DEBUGGING!*/
stage.setDebugAll(true);

```

Some of the `grow()`, `expand()` and `fill()` calls might be unnecessary - you'd have to experiment for yourself. If you have any questions just leave a comment and I'll try to answer them :)
> 3 votes

---
Tags: java, libgdx, scene2d, card-game
---


# Question
Title: why one model can have different vertices and normal size?
I am using TinyObj to load models. I found many obj files have different vertices and normal size, how could it happen? I thought in the obj file one normal should be correspond to one vertex.

For example, I am loading one apple model, the vertices size is 6492 and normal size is 6557. How to handle this stituation? Some files have more vertices and some have more normals. Does it means I have to give up some attributes of the model?

I also found the obj file has normal index, but I dont know how to use it. Does it matter to this problem?

In opengl/directx I have only used vertex index in the index buffer.

Can you give me some idea or reference about it?

# Answer
The Wikipedia page about the Wavefront .obj file, contains a lot of information boiled down to less lines than it could be.

> Some files have more vertices and some have more normals. Does it means I have to give up some attributes of the model?

No, that's just how the OBJ format works. Essentially whether the file contains:

```
v 0.5 0.5 0.5
v 0.5 0.5 0.5

f 1 ...
f 2 ...

```

or

```
v 0.5 0.5 0.5

f 1 ...
f 1 ...

```

It would be the same model. The reason you're seeing more normals than vertices, is because there's more common vertices than normals. Some faces are essentially sharing the same vertex in the sense of an OBJ model. So in your case there's more faces shares vertices than normals.

> In opengl/directx I have only used vertex index in the index buffer.

When it comes to drawing the model. Then you can't just leverage the indices from the OBJ model. Because an index buffer needs an index to a vertex. Where a vertex consists of the position, normal, etc. In the OBJ format that's not the case.

So after loading all the vertices, normals, texture coordinates and faces. You'd basically have to remap it. Extracting all the triangles, so to speak
> 2 votes

---
Tags: opengl, directx, models
---


# Question
Title: In UnityScripting C#, What's the distinction between global coordinates and world space?
In Unity game engine and C# scripting; Is there any distinction between global space and world space? Are this two the same thing and identical or there is a distinction? I'm not confusing between local and global. The relation between local-global is the same to local-world? Can I exchange this two words (global and world) without creating confusion?

for example in the Unity manual: https://docs.unity3d.com/Manual/Transforms.html

Make a distinction adding "or":

> world space or global coordinates.

# Answer
I think it is basically the difference between relative and absolute positions.

https://docs.unity3d.com/ScriptReference/Transform-localPosition.html

So that a child gameObject's position/rotation/scale can be relative to it's parent (0, 0 is bottom left of window not screen) instead of

https://docs.unity3d.com/ScriptReference/Transform-position.html

Which is absolute. (0, 0 is middle or bottom left of screen depending on anchors)

there is a toggle for this Local/Global setting in the toolbar too

https://docs.unity3d.com/Manual/PositioningGameObjects.html

Click the Local/Global button on the right to toggle between Local and Global.

* Local keeps the Gizmo’s rotation relative to the GameObject’s.
* Global clamps the Gizmo to world space orientation.
> 1 votes

---
Tags: unity, c#, rotation, transformation, gameobject
---


# Question
Title: Most efficient way to determine if an entity is in a player's field of vision?
So I'm creating a real time multiplayer game.. and I only want entity data to be sent to a user if it's in their field of vision + a little more. (It's third person so it would be a giant box around a person)

What would be the most efficient way to do this? The only thing I could think of is have a giant box around the player and then loop through every entity to see if it's in the box and if it is send the data to the player, but doing that for a lot of players would be way too extensive on the server side.

So what's a workaround to this?

# Answer
> 2 votes
Quake was one of the first games to deal with this problem, and many of the techniques it used are potentially still valid even today.

It's source code is freely available and can be studied (it is also quite grim reading in places).

To summarize some of the techniques:

* Visibility for each map was precalculated so that fast checks could be made for which entities are visible to each player, and only visible entities need be sent.
* Because the client and server potentially tick at different rates, everything potentially visible, irrespective of field-of-view, is sent.
* Baseline states and deltas are used so that only data which has actually changed need be sent. Clients can work from a local copy of anything which is unchanged.

These were valid on low-bandwidth dial-up connections back in the late 1990s so can make a good starting point for today, and can also serve to illustrate areas that you probably don't need to be worrying about. An example of the latter is the fact that the server sends entities irrespective of field-of-view: use of baselines and deltas means that the actual data sent can be kept quite small, and this is probably not a problem.

# Answer
> 0 votes
Ill break it down for you...

Your goal is to find if an entity is 3-dimensional space is visible in the camera's view. Remember that your entity exists in the world space (model space), and your camera represents the screen space (or clip space). So, your goal is to transform your objects 3-dimensional coordinates to the screens location (2-dimensional). This is called world-to-screen.

Steps:

1) Calculate the view projection matrix.

```
vec4 viewProjectionMatrix = projectionMatrix * viewMatrix;

```

2) Calculate the clip space coordinates.

```
vec3 clipSpacePos = entityPos * viewProjectionMatrix;

```

3) Calculate the coordinates on screen.

```
vec2 windowPos = ((clipSpacePos.xy + 1) / 2) * viewSize;

```

**EDIT 1**

If your y-axis is top to bottom, then do `1 - clipSpacePos.y`.

**EDIT 2**

The same concept can be applied in your source code of the server.

# Answer
> 0 votes
You can split the map into big boxes. Like this:

Then for each box, keep an updated list of the entities inside.

So when you want to know what's in the king's field of view (let's assume he sees one field far), just send all the entities in the green boxes.

You can further improve on this by choosing a smart box layout that's based on the level design.

---
Tags: collision-detection, networking, multiplayer, data-structure
---


# Question
Title: How do I create a simple HUD, with ImageButton and background, using LibGDX?
Here is my HUD class:

```
public class UpperPanelHUD extends Table {

    private final TextureRegion textureRegion;
    private ItemButton itemButton;
    private Maze maze;

    public UpperPanelHUD(Maze maze) {
        this.setBounds(0,  RandoMaze.MAZE_HEIGHT+2, RandoMaze.MAZE_WIDTH, 2);
        this.maze = maze;
        this.textureRegion = Assets.gameAtlas.findRegion("Panel_Up");
        this.itemButton = new ItemButton();
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        itemButton.draw(batch, parentAlpha);
        batch.draw(this.textureRegion, this.getX(), this.getY(), 11, 2);
    }
}

```

and here is my `ItemButton`:

```
public class ItemButton extends ImageButton {

    private TextureRegionDrawable textureRegionDrawable
            = new TextureRegionDrawable(Assets.gameAtlas.findRegion("Key"));

    public ItemButton() {
        super(new  TextureRegionDrawable(Assets.gameAtlas.findRegion("Key")));
        this.setBounds(0, 0, 1, 1);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        batch.draw(this.textureRegionDrawable.getRegion(), this.getX(), this.getY(), 1, 1);
    }
}

```

`itemButton` is drawn without relation to its parent `UpperPanelHUD`, and I need it be positioned inside `UpperPanelHUD`.

# Answer
> 1 votes
Here is how I solved the problem:

```
   public UpperPanelHUD(Maze maze) {

    this.setBounds(0,  RandoMaze.MAZE_HEIGHT+2, RandoMaze.MAZE_WIDTH, 2);
    this.maze = maze;
    this.textureRegionDrawable=new TextureRegionDrawable (Assets.gameAtlas.findRegion("Panel_Up"));
    this.setBackground(textureRegionDrawable);
    this.itemButton = new ItemButton();

    this.addActor(this.itemButton);
}...

```

And for my ItemButton:

```
public class ItemButton extends ImageButton {
    public ItemButton() {
        super(new TextureRegionDrawable (Assets.gameAtlas.findRegion("Key")));
        this.setBounds(1, 0.5f, 1, 1);
    }
}

```

---
Tags: java, libgdx
---


# Question
Title: How to manage different shaders dynamically?
Currently I have only a really basic shader and a shader class.

My question is that if I want to make different shaders (with different uniforms, inputs, etc) how should the architecture look like?

---

**Edit: I want it in a way that I can add/remove/modify shaders without recompiling.**

*(#1, #2, #3 were written before this edit, so I'm sorry if they are irrelevant now)*

*(I wrote #4 just now, and currently I am very happy with it, but I would like to hear your opinion about it.)*

---

**I have a few ideas:**

**(1.)** Should I make an abstract shader class, and a derived class for every invidual shader program?

* *(So the abstract class handles the general things, and the derived class handles the specific things, like uniforms, inputs, etc)*

But in my opinion this isn't a good practice, because for every shader I create, I have to create a new class too, which means that if I want to add a new shader, or modify one's source, I have to recompile the engine.

**(2.)** Should I register the shader specific things (location of inputs, uniforms, etc.), and pass EVERY possible required data to the shader, which will use only the ones which were registered during the shader's compile time?

* Like Shader A needs position and normal, Shader B needs position and UV.
* position, normal and UV will be passed to the active shader object, and it will buffer only those which it needs (based on the registered inputs, uniforms, etc) and won't care about the others.

**(3.)** Having every possible input, uniform etc in all the shaders. The active shader will receive every required input, uniform, etc. So a shader is only unique in its main(). Like Shader A uses input 1,2,3, shader B uses input 1,2,5. (But both of them will receive all inputs)

**These are the way I thought of, but these aren't very good in my opinion, there must be a good way for this.**

---

**Edit:**

**(4.)** What I most recently thought of:

* Only one shader class. has a field: **unordered\_map \< name, location at shader \>**
* During shader initialization, I store the input, uniforms, etc in the previously mentioned **map**.
* When I want to render the Object, I call the active shader's `SetInput(...)` or `SetUniform(...)` method
* These methods receive a **string** and a **data** (like vec3, vec4, mat4, etc)
* In these methods, I check if the **string** is in the **map**, and if it is, I buffer the data to the **location**.

I think this is good, because there will be a **few method calls for every object**, and then **finding a key in an unordered\_map** is really fast.

**What do you say?**

# Answer
> 2 votes
If your hardware supports OpenGL 4.1+, you can use separate shader objects and pipeline objects to create new pipelines on the fly:

https://www.khronos.org/opengl/wiki/GLSL\_Object

In this way, you can load your shader stages seperately, and combine them as necessary.

# Answer
> 1 votes
Your options are:

1. Determine all the shaders you will need at the start of your game (using the materials of your meshes for example) and compile and link them to shader programs there. Later when rendering you will change the current program with *glUseProgram(ID)* based on the mesh's material.
2. If you need to assemble shader programs dynamically, you will have to at least link the different modules together before you need them. You could compile a collection of vertex and fragment modules at startup and then link them together based on a more modular material component from your mesh.

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


# Question
Title: What is the logic of 'move_towards_point'?
I think I was using the `move_towards_point` function incorrectly. I discovered that I could not make the object move down.

---

In the create event, if I include the code `move_towards_point(x,y,10);`, the object in question moves to the right:

If I include the code `move_towards_point(-x,y,10);`, the object moves to the left:

I wanted to make the object move up, so I left `x` and used `move_towards_point(x,-y,10);`. It moved up as I wanted.

Yesterday, I had the need to make the object move down. That's where my dilemma began. I thought to use `move_towards_point(x,+y,10);`. It did not work; the object moved to the right, as in the first demonstration. I tried `move_towards_point(0,y,0);`. The object moved to the left, again, as in the second demonstration.

I began to suspect that I was not using the function correctly. By the name, I assumed it would move an object to a certain specific point. I went back to test `move_towards_point(-x,-y,0);`, and the object move diagonally:

---

I found the solution to all cases of movement:

* Down : `move_towards_point(obj_Bola.x,obj_Bola.y+1,10);`
* Up : `move_towards_point(obj_Bola.x,obj_Bola.y-1,10);`
* Left : `move_towards_point(obj_Bola.x-1,obj_Bola.y,10);`
* Right : `move_towards_point(obj_Bola.x+1,obj_Bola.y,10);`

The explanation seems to be that I am now using the `x` and `y`, relative to the object. When I do not want to change it's position on any of it's axis, I simply do not add any value. On the axis that I want the object to move in, I add or subtract a value.

One observation is that the value added or subtracted does not change the speed that the object moves, so `move_towards_point(obj_Bola.x,obj_Bola.y+99999,10);` moves the object down with a speed of `10`.

---

I would like to know the logic behind `move_towards_point`, and if the way I solved my problem is the right one.

# Answer
`move_towards_point()` Makes the character go to a specific position, it's not intended to use it for general movement.

For example, if your character is at `(100, 100)` and you use the function with `(200, 200)`, then it starts moving diagonally in the right-down direction.

Because the x coordinate 0 is at the left edge and the y coordinate 0 is at the top, if you enter these values, the character starts moving towards those edges.

If you enter the character's positions, it defaults to right.

To make the player go in a specific direction, you need to add some amount to the x and y coordinates. For example, to move down you do

```
y += 1;

```
> 2 votes

# Answer
`move_towards_point` makes the object move towards a particular point - as its name implies.

If the object is at coordinates 200,200 and you do `move_towards_point(x, -y, 10)` then you are telling it to move to coordinates 200,-200 which is off the top of the screen. (10 is the speed)

If the object is at coordinates 200,200 and you do `move_towards_point(-x, -y, 10)` then you are telling it to move to coordinates -200,-200 which is off the top-left of the screen.

If the object is at coordinates 200,200 and you do `move_towards_point(x, y, 10)` then you are telling it to move to coordinates 200,200. But it's already there, so I guess it arbitrarily moves right. (Personally, I'd expect it to not move if you tell it to move to where it already is...)
> -1 votes

---
Tags: movement, game-maker
---


# Question
Title: How can I pass an array of matrices to a VertexShader
I'm trying to learn how to use OpenGL but I'm having problems trying to pass an array of matrices to my VertexShader. I think the problem is in the VertexShader because it seems the values in modelvalue are passed correctly to the components of model, but for some reason at the end only one of the three cubes I've created is drawn. Here's the Main code.

```
glm::mat4 model[3];
GLint ModelLocation = glGetUniformLocation(MyShader.program, "model");
vector<GLfloat> modelvalue;
const int n = int(sizeof(model[0]) / sizeof(GLfloat));

for (int i = 0; i < 3; i++) {
    model[i] = glm::translate(model[i], cubePositions[i]);

    for (int j = 0; j < n; j++) {
        modelvalue.push_back(glm::value_ptr(model[i])[j]);
    }

}
glUniformMatrix4fv(ModelLocation, 3, GL_FALSE, &modelvalue[0]);

```

The VertexShader:

```
   #version 400 core
  layout (location = 0) in vec3 Position;
  layout (location = 1) in vec2 texCoord;
  out vec2 TexCoord;
  out vec4 position0;
  out vec4 position1;
   out vec4 position2;
  uniform mat4 model[3];
  uniform mat4 view;
  uniform mat4 projection;
  void main()
  {
  position0 = projection * view * model[0] * vec4(Position,1.0f);
  position1 = projection * view * model[1] * vec4(Position,1.0f);
  position2 = projection * view * model[2] * vec4(Position,1.0f);
  TexCoord = vec2(texCoord.x,1-texCoord.y);
   }

```

And the FragmentShader:

```
  #version 400 core

  layout (location = 0) in vec3 Position;
  layout (location = 1) in vec2 texCoord;

  out vec2 TexCoord;
  out vec4 position0;
  out vec4 position1;
  out vec4 position2;
  uniform mat4 model[3];
  uniform mat4 view;
  uniform mat4 projection;
  void main()
  {
  position0 = projection * view * model[0] * vec4(Position,1.0f);
  position1 = projection * view * model[1] * vec4(Position,1.0f);
  position2 = projection * view * model[2] * vec4(Position,1.0f);
  TexCoord = vec2(texCoord.x,1-texCoord.y);

```

# Answer
As Le Comte du Merde-fou mentioned in the comment to your question, the purpose of a vertex shader is to perform *per-vertex* operations on an existing single mesh. They cannot generate new geometry, so position1 and position2 will simply be ignored by the primitive assembly stage, as it only accepts the first vertex shader output.

If you wish to render more cubes, you would have to write a geometry shader stage, to generate the new geometry, or duplicate your cpu side render code, using different transform matrices for each one.

I strongly recommend you do some research on the GPU graphics pipeline, and understand what each stage does. Once you do, it will make your life a lot easier.
> 1 votes

---
Tags: opengl
---


# Question
Title: Problem with loading models with different shaders
I am lerning opengl programming from http: //learnopengl.com .And i can load any model which i want.But if i want to load two models with different shaders,a problem occurs. For example: First i draw two models with same shader and there is no problem.

```
Model1.Draw(shader);
Model2.Draw(shader);

```

Then if i do this:

```
Model1.Draw(shader);
Model2.Draw(otherShader);

```

The first model is not drown.Only the second model is drown. Here is my Model.h code and Mesh.h code:

Model.h: Model.h

Mesh.h Mesh.h

And if you want, these are my vertex and fragment shaders:

Shaders: http: //pastebin.com/d0v3Y4vU

Thank you for help!

# Answer
The first line in the following code block is unnecessary:

```
glUniform1i( glGetUniformLocation( shader.getProgram(), ("material." + name + number ).c_str( ) ), i );
glActiveTexture( GL_TEXTURE0 + i );
glBindTexture( GL_TEXTURE_2D, this->textures[i].id );

```

So remove it, and change the following GLSL code:

```
struct Material
{
    sampler2D texture_diffuse1;
    sampler2D texture_specular1;
    float shininess;
};

```

To:

```
uniform sampler2D texture_diffuse1;
uniform sampler2D texture_specular1;

```

Texture samplers must be defined as a uniform. Though I've never attempted that sort of GLSL code before, I'm surprised it even compiles.

You are confusing concepts here. Typically a non texture material would look like this:

```
struct Material
{
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    float shininess;
};

```

So, if using a mix of textures and values:

```
uniform sampler2D texture_diffuse1;
uniform sampler2D texture_specular1;
uniform float shininess;

```

Then bind the two textures, and the uniform for shininess separately. Keep your code simple, it really is the best way.
> 1 votes

---
Tags: opengl, model-loader
---


# Question
Title: How do I handle resolution change in OpenGL and SDL2, in combination?
How do I handle resolution change in OpenGL and SDL2, in combination?

Let´s assume I have a GUI window with a fixed position, so it will be on the right corner of the window, and after resolution change it will be at the same position, just resized due to the resolution change. How do I handle the resolution change?

How do I apply these changes to my game physics? For example, with collision boxes, do I need to define some variable like `resolutionRatio` and multiply it against the collision rectangle dimensions?

# Answer
Games are usually made somewhat like this:

* One part of the program models and simulates your game world, using arbitrary units for measurement. That's *world space*.
* This game world is viewed through some sort of camera (possibly multiple cameras).
* The HUD/GUI is drawn on top of what the camera shows, using another set of units (pixels are an option). That's *screen space*.

When you switch resolutions, the shape and size of your screen space changes. The GUI may have to adapt -- it is your choice whether the GUI elements scale and/or reposition themselves.

World space, however, is unaffected. You only have to adjust the zooming level of your camera to an adequate value. The simulation still works with its usual units, and the camera maps them to screen-space coordinates.

**Edit:** I see that you've already touched this concept in another answer, so I'll hinge on that. You're spot on with the "virtual position" vector: that's your world-space coordinates. The only missing piece is that one world-space unit does *not* have to equate one screen pixel: you can very well simulate everything in meters, then the camera maps 1 world-space meter to 32 screen-space pixels, so a one-meter object takes up 32px on-screen.
> 1 votes

---
Tags: opengl, game-mechanics, sdl
---


title: Voxel blocks world physic

text:
# Question
Title: Voxel blocks world physic
I'm making a game like Minecraft. I have a world made of blocks and I'm trying to implement a basic physic system that applies gravity and checks entities colliding with the blocks of the world.

I tried using Bresenham's algorithm, on player move, to get all blocks between, and then get the first solid and set the player on colliding position. That works well if the player is a point, but if it's a complex AABB and the block too, it becomes difficult.

Is there a simple way to make physic in a voxel world like Minecraft?

# Answer
Minecraft used dynamic- or swept-AABB.

The algorithm works by getting the distance between the AABBs on each axis separately, then using the velocity of the dynamic one to calculate the time it takes to reach the block, and then you pick the axis that collides first. You check if it collides in this frame (aka. time is less than 1), and if it is, you set it's new position to be at the point of collision.

Doing this for millions of blocks is of course very slow, so you should first do a broad phase with the same algorithm by taking the bounding boxes of the chunks instead of separate blocks, and only trying to check for collision against the blocks in the chunk, if the first detection returned true.

I'm not sure if minecraft does the latter.

More on swept AABB:

https://www.gamedev.net/resources/\_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084
> 1 votes

---
Tags: physics, voxels, block-world
---


# Question
Title: How to handle day and night in a 2D sprite game
Do I need to draw, for example, a tree how it looks in the day (normal colors) and how it looks at night (colors aligned according to the moonlight)? Or does Unity have a function for that?

# Answer
The quick-and-dirty solution would be to use a camera filter effect. The color correction curves filter might do what you want. Move the end-points of the R, G and B curve down, but the blue-curve a bit less. If you don't want it to affect some objects (like your GUI, for example), render them with a different camera.

But the problem with this is that you can not have any light sources that way. Even emissive light (like a lit window) becomes cumbersome. Also, shading at night is different than shading at day, especially for outdoor scenarios. At day, you have one primary light source (the sun). At night, the light conditions are far more diffuse. But *calculating* realistic light in a 2d environment is very hard to pull off. There are some interesting technologies available in this regard, but most require to manually add some 3d information to your art assets and many aren't universally applicable to every situation. That's why we invented 3d engines :)

The "clean" solution is to redo all your sprites and tiles in two versions: a "night" version and a "day" version. You can use automatic color correction in your image editor for the prototype and then touch up any art assets manually which need it.
> 10 votes

---
Tags: unity, 2d, sprites, rpg, pixel
---


# Question
Title: Would I need to develop a multi-threaded game or will a single thread suffice?
So I've been playing around and developing in C++ for a couple years now and have built a very simple C++ game engine for learning purposes. I now want to try and develop a simple 2d, stick figure fighting game for the windows platform. Up until now I have only been focusing on single core development (to keep things simple while learning). I would like to try and develop a game from start to finish and maybe try and release it on some version of a steam website. I know I always learn more when setting higher goals and trying to create a project from start to finish. I will be utilizing some third party libraries such as SDL (or some equivalent) but want main control over engine systems and overall architecture.

Since my game will be a simple 2D fighter on a specific platform (windows) with a goal of 30+ fps is it necessary to try and multi-thread some tasks? Would I be able to accomplish everything I would need to by utilizing just one core? I ask because I know multi-threaded programming is a huge topic and I would have to spend a lot of time researching and learning before actually developing anything substantial.

Edit: This topic is not related to the above duplicate since I'm not asking where I should look for multi-threaded resources, but if I should even consider multi-threading in the first place for my simple game. Want a basic idea of how much can be done with a single core game.

# Answer
Generally it's best not to over-engineer, solving problems you may not really have.

If you want to make a "simple 2D fighter," well, remember we had those on the NES and even earlier.

Even a single core on today's machines is vastly more capable than the systems on which you first learned to love fighting games, I'd wager.

So, have you encountered any trouble that suggests to you that your game might need additional threads to keep up on modern hardware?

If not, it might not be a problem you need to solve just now.

Focus on making an enjoyable game first, and if your early profiling suggests performance problems, use that information to ask a specific question about how to overcome those particular issues.
> 8 votes

# Answer
Rule number one of multithreading: **Don't even think about it, unless you really need to use multiple CPU cores for performance reasons\***. Multithreading opens up a whole can of worms of obscure and impossible to reproduce bugs:

* **Race conditions!** Because you have no control over the thread scheduling of the OS, you have no control over the order in which things happen. You might *assume* that a certain task takes much longer to complete than another and build on that assumption. But in one of a million executions that assumption is wrong, and an obscure bug happens which is impossible to reproduce.
* **Synchronization issues!** When one thread modifies data while another thread is in the process of reading it, the thread reads a mixed state of old and new data. This can lead to really obscure bugs which are - again - almost impossible to reproduce.
* **Deadlocks!** The two problems above can be avoided by certain synchronization and locking techniques which are available in most programming languages. Unfortunately these features take a lot of knowledge and experience to use correctly. When you use them incorrectly, you will quickly run into deadlocks: Two threads both blocking their data structure and both waiting for the other thread to release theirs. This will lead to an infinite loop and cause both threads to freeze.

Also, keep in mind that creating threads isn't cheap. Spawning a thread and switching between thread contexts are expensive operations for the operating system. So using too much multithreading can even *reduce* performance. You should only use multiple cores when you have tasks which take a long time to complete and don't need to communicate much with other tasks while they are being completed.

<sub>\*) Exception from this rule: Waiting for I/O of files, network or user input. But in that case you shouldn't write your own multithreading code. Use asynchronous APIs with callbacks provided by your platform or a library when you can. These use multithreading "under the hood", but hide the nasty details from you.</sub>
> 4 votes

# Answer
The question you need to ask yourself is: "are you developing a game, or are you developing an engine?" (Doesn't have to be a binary answer, but you should definitely be aware of your place on the spectrum).

If you're developing a game, then the answer is no. If your game is fairly straightforward, then more threads will only get in the way of the game development with no real added benefit.

If you're building an engine, then the answer is yes. You may not need threads for strictly performance reasons, but adding parallel capabilities into your engine will make it flexible if you want to add features that may require it (networking, costly calculations, file I/O, etc). You don't have to go crazy and thread everything, but always take a step back and say "Could these things run at the same time with minimal effort?" The game will only suffer in the sense that you'll have to spend more effort into feature implementation rather than game play code.

Either way, don't be discourage from giving it a try. Threaded game engines aren't necessarily complex. It all depends on you want to multithread / how granular your threaded data is.
> 0 votes

---
Tags: c++, 2d, performance, multithreading
---


# Question
Title: Implicit conversion error - why is this code trying to convert a 'World' to an 'int'?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class World {
    Tile[,] tiles;
    int width;
    int height;

    public World (int width = 200, int height = 200) {
        this.width = width;
        this.height = height;

        tiles = new Tile[width, height];

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                tiles[x, y] = new Tile[this, x, y];
            }
        }
    }

    public Tile GetTileAt(int x, int y) {
        if (x > width || x < 0 || y > height || y < 0) {
            Debug.LogError ("Tile (" + x + ", " + y + ") is out of range");
            return null;
        }
        return tiles [x, y];
    }

}

```

anyone see anything wrong with this code because on line 18 of my code i get this error "cannot implicitly convert type 'World' to 'int' and i don't know what is going wrong.

# Answer
> 6 votes
Is it safe to presume this line is the culprit?

```
tiles[x, y] = new Tile[this, x, y];

```

(It never hurts to annotate your code with a comment like `\\ This line generates the following error...` to ensure it's clear for people trying to help)

It looks like you're trying to call a constructor for the `Tile` class, passing `this` world as the first argument. But instead of using **round parentheses ( )** for a function call, you've used the **square brackets \[ \]** of an array index or size declaration.

So, this says "Make a new 3-dimensional array of tiles, where the first dimension's length is the integer `this`" ...but `this` isn't an integer, `this` is a `World`!

Thus the compiler throws up its hands and says "fix this - you've asked me to do something nonsensical here" ;)

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


# Question
Title: Does LibGDX share preferences with Android API?
Can I get a value from LibGDX preferences like this:

```
Preferences preferences = Gdx.app.getPreferences("someName");
int value = preferences.getInteger("intValue");

```

And then in the same project, in a different activity, do this:

```
SharedPreferences preferences = getSharedPreferences("someName",Context.MODE_PRIVATE);
int value = preferences.getInt("intValue",0);

```

So assuming there is a value already stored, would both methods retrieve the same value?

# Answer
Yes, you are right in assuming that both codesnippets do the same thing. Checking the implementation for the Android backend, they show that the same Android methods are being called.

```
@Override
public Preferences getPreferences (String name) {
    return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}

```

Source

and

```
@Override
public int getInteger (String key) {
    return sharedPrefs.getInt(key, 0);
}

```

Source
> 0 votes

---
Tags: java, android, libgdx
---


# Question
Title: How to see my plane & ball in the camera during play?
At the 13:00 mark of this tutorial, the narrator manages to launch a scene and control the ball (player) in that scene.

However, when I launch my scene after following his instructions till then, I do not get anything viewable in my camera.

After playing around with the camera, I discovered how to manipulate the camera icon ( which looks like a video camera with 2 film reels on the top ) to have its cone like thing projecting from it include the plane on which my ball is on ( see image below). Still no luck.

What am I doing wrong?

# Answer
> 0 votes
This might be a silly way to fix the issue, but it worked for me. Any additional commentary or better ways to fix the issue are always welcome.

1. Double click on the 'Main Camera' in the 'Hierarchy' view.
2. Access the 'Inspector' pane. In the pane, set the position of the camera to origin, which is '0,0,0'. ( This makes the next step more manageable ).
3. Play with the camera until it has a view of the ball and the ground. The co-ordinates I used were '2,2,0'.

---
Tags: unity
---


# Question
Title: Implementing Achievement System in Javascript
I understand that for more complex achievements, specific code can't be avoided, but for simple ones like (player clicked 100 times) or (player earned 30 bajillion cookies) or (player played for 1 hour) it should be as simple as abstracting the achievements to something like a list of properties/values and having some event handler.

My problem is that since I'm using Javascript and there's no really clean way to do pointers, how am I supposed to create an achievement class that can be iterated through procedurally?

Ideally I'd like something like this:

**Achievement class:**

```
function Achievement(name, property, value, text, points){
  this.name = name;
  this.property = property;
  this.value = value;
  this.text = text;
}

```

And then I'd add an achievement like so:

```
achievements.push(new Achievement("Clicktastic", &numClicks, 1000, "You clicked 1000 times!");

```

And have some kind of function bound to a Window.setInterval that was constantly looping through all achievements and for these simple types doing something like:

```
for (var i = 0; i < achievements.length; i++){
  if (*achievements[i].property >= achievements[i].value){
    //deal with earning achievement
  }
}

```

I'm just using some C style pointer/dereferencing notation here.

Basic idea is that I'm not sure how to create a generic achievement that can arbitrarily care about specific properties without pointers.

# Answer
> 0 votes
Javascript supports "pointers" in form of object references. All variables which contain objects actually contain pointers to objects. Further, you can access fields of objects using the `object[fieldname]` syntax. Assuming you have an object `clickManager` and want to monitor its variable `numClicks`, this would look like this:

```
achievements.push(new Achievement("Clicktastic", clickManager, "numClicks", 1000, "You clicked 1000 times!");

```

The code to check the variable monitored by an achievement would then look like this:

```
var a = achievents[i];
if (a.monitoredObject[a.monitoredVariableName] > a.value) {

```

If you want to access a global variable, you can access it over the global object "window".

But as you said, this isn't really a very beautiful solution. First, it's a bit cumbersome. Second, it's not very flexible, because all it can do is monitor numerical variables. What if you have an achievement with a more complex condition? And third, it ignores one of JavaScript's most powerful features: Closures!

Javascript allows you to define inline-functions which can access variables in the current scope. These inline-functions can be passed around as variables and called from somewhere else (just like function-pointers in C). To make use of this, your achievement class would look like this:

```
function Achievement(name, text, checkFunction){
  this.name = name;
  this.text = text;
  this.checkFunction = checkFunction;
}

```

An example of creating an achievement:

```
function initClickHandling() {

     var numClicks = 0;

     achievements.push(new Achievement(
           "Clicktastic",
           "You clicked 1000 times!",
           function() {
               return numClicks > 1000;
           })
     );

     window.onclick = function() {
          numClicks++;
     }
}

```

This unnamed function "captures" the local variable `numClicks`. When that function is executed, it will use the then-current value of `numClicks`. This even works when the function-call which declared that variable has already returned.

Also notice the second function, the click handler for `window`. It captures the same variable and manipulates it. When it does that, the check function will notice.

Your achievement management code would then look like this (using `Array.prototype.forEach` instead of a for-loop. Another example of using ad-hoc unnamed functions):

```
 achievements.forEach(function(achievement) {
      if (achievement.checkFunction()) {
            // award the achievement
      }
 });

```

---
Tags: javascript, achievements
---


# Question
Title: Why Unity3d takes so long time to "rebuild" when I change build platform?
I would like to know what happens "behind the scenes" when I change my unity game target platform .

If I switch from Android to iOS or Pc or etc, Unity rebuild something and takes a lot of hours to complete.

What is the reason ?

Thanks

# Answer
When the target platform is changed, Unity has to (re)import the asset data for all your assets, since that data is platform-dependent. The process can take a long time if the project has many assets (although I'd say "*a lot of hours*" is really extreme, unless the computer is really slow).

If you want to accelerate the process you can use Unity's Cache Server, which, as its name implies, caches the data of the assets and allows Unity to just download it when needed instead of recreating it, and it's much faster. It works fine as a server in the local computer, no need for a dedicated server in the network.
> 2 votes

---
Tags: unity
---


# Question
Title: How to design a class for an object that its state varies over time
I have a soccer team with 14 players (11 active + 3 substitutes). The team is going on a tour participating in different matches across the world. I have two very different design ideas of how for the classes for such match, and I am wondering if there is a better approach here. The language is Python and the database is Mongo.

My requirements:

1. At any time during a match, I want to know the current status of a player. (substitutes, active, injured) as well as their penalty cards if they got any. If they are actively playing, I want to know when they started. If they got back to sitting or got injured, I want to know their most recent start time and end time.
2. I want to be able to retrieve the information about a past match. For any player in a past match, I only need to know their latest status (as described above)

Here is my idea about db collections:

```
Players collection:
- Player ID
- Player Name
- Player Tshirt Size

Teams collection:
- Team ID
- Team Player IDs []
- Team Name
- Team logo

Matches collection:
- Match ID
- Team ID
- Match Location
- Match Time

Match Participants collection:
- Player ID
- Match ID
- Latest Status
- Latest Start Time
- Latest End Time
- Latest Penalty Card
- Latest Injury Note

```

As you see, I tried to separate the static information about a player (Players collection) from their dynamic information in a match (Players History collection) but I not sure how to define classes?

```
Class Player:
- Player ID
- Player Name
- Player Tshirt Size
- Latest Status
- Latest Start time
- Latest End time
- Latest Penalty Card
- Latest Injury Note

Class Match:
- Match ID
- Player IDs []
- Match Location
- Match Start time
- Match Tshirt color

```

The second option would be creating another class for the dynamic part to match to my db collection:

```
Class Player:
- Player ID
- Player Name
- Player Tshirt Size

Class Match:
- Match ID
- Player IDs []
- Match Location
- Match Start time
- Match Tshirt color

Class Match Participant:
- Player ID
- Match ID
- Latest Status
- Latest Start time
- Latest End time
- Latest Penalty Card
- Latest Injury Note

```

I do not know how I should decide which approach is better. I would appreciate if you help me figure out the approaches pros and cons or even just what criteria I need to think about when deciding between the two.

Is there any design patterns that would describe any of these approaches?

# Answer
The first point of your requirements describe events that belong to the match itself, you can define a base class for that

```
Event
- matchId
- time

```

And construct specific classes based on it: `MatchStarted`, `PlayerInjured`, `PlayerEnters`, `PlayerLeaves`, `PenaltyCardShown`, if want to avoid that, you can create classes with a `type` property (less oop). Each class can contains specific properties for each event, like playerId for example.

Now. using a service or a query class, you can query against the event list to get the status of players or the match at any time. With the `time` field is easy to get the last one. Also you can have methods like `latestPenaltyCard` in your match class to get the data more at hand

In that way your model classes gets very clean, just holding the static data

For raising and storing the events you can use event sourcing or something like that

For storing in the database, maybe I would use an event class that contains all the columns for every event type (and the "type" field), for facilitate querying
> 1 votes

---
Tags: oop, design-patterns
---


# Question
Title: Why does texture-sampling only work at (0,0,0)?
I want to save the color of every point of one object in the `RWTexture3D`(UAV Resource) and transfer them to another object in its shader.

I made a test in the two shaders. Both in the fragment shader.

In first shader, I gave

```
RWTexture3D<float4> gUAVColor;
gUAVColor[uint3(0,0,0)] = float4(1.0f,0.0f,0.0f,1.0f);

```

In second shader:

```
Texture3D<float4> gVoxelList;
float4 output = gVoxelList.SampleLevel(SVOFilter, uint3(0,0,0),0);

```

The result is correct, I got `red` as the result.

But when I change the code, the texture cant be sampled correctly.

In first shader, I gave

```
RWTexture3D<float4> gUAVColor;
gUAVColor[uint3(1,0,0)] = float4(1.0f,0.0f,0.0f,1.0f);

```

In second shader:

```
Texture3D<float4> gVoxelList;
float4 output = gVoxelList.SampleLevel(SVOFilter, uint3(1,0,0),0);

```

I only changed the pos which save the red color from `uint(0,0,0) to uint(1,0,0)`, but what I got changed to `black`, which means it's uncorrect.

If I use `gVoxelList[uint(1,0,0)].xyz` ,it works.

I have no idea where the mistake will be.

# Answer
I have found the answer, `gVoxelList[texcoord].xyz` this texcoord is the same as the texture size. If we have 512x512x512 size 3Dtexture,then the texcoord should be in \[0,512\] of every axis. The same to function `texture.Load(texcoord)` .

However, `gVoxelList.SampleLevel(Filter, sample_texcoord,0)` in sample function, this sample\_texcoord should be in \[0,1\] of every axis. If we have 512x512x512 size 3Dtexture, we should use `gVoxelList.SampleLevel(Filter, texelpos/512.0f ,0)`, `texelpos` is where each texel is.
> 2 votes

---
Tags: opengl, shaders, textures, directx, hlsl
---


title: Pygame falling shape and keyboard input

text:
# Question
Title: Pygame falling shape and keyboard input
I want a shape in pygame to fall down slowly. The user should be able to move the shape with the arrow keys. My code is given below:

```
while Running:
    Keys=pygame.key.get_pressed()
    if event.type == pygame.QUIT:
        Quit()
    elif event.type == pygame.KEYDOWN:
        if event.key ==pygame.K_LEFT:
            x=x-1
    y=y+1
    pygame.time.wait(3000)

```

However, it doesn't always take in the keyboard input if the shape is falling. e.g I will have to press the left arrow key 5 or 6 times for the shape to move. Any idea how I can sort this out?

update: I think the error is in the following code, but if I don't have it then the shape falls too quickly.

```
    pygame.time.wait(3000)

```

# Answer
You don't want to halt your game for three seconds. Instead you want to look into more proper frame-rate limiting. See this answer to get you started. That is a much more sustainable and better way to move your object.

If you pause the game for three seconds, no events are captured and that's probably why you need to spam your key to get through the blocking wait call.

Also note, that you don't have to use integers here. You can just as well decrement `x` by 0.1 for an example. This would end up meaning that the block moves one pixel in ten frames.
> 0 votes

---
Tags: python, pygame
---


# Question
Title: How to make Unity game moddable with scripting in a friendly way?
I am building a game in Unity using C# and visual studio. I want to make it possible for users to write code in some scripting (for modding purposes) without necessarily opening the source. What are my best options?

I'd prefer well-supported and battle-tested options that integrate well with Unity and visual studio, but I am willing to do a fair amount of work myself **as long as it makes scripting as seamless as possible for future modders.**

# Answer
> 5 votes
A somewhat blunt approach would be to let modders write C# code and then have your game read & compile those scripts, using them as though they were code the game was built with.

This has some advantages:

* Modders can use the existing Unity API, so it's already familiar to many, with extensive documentation and tutorials.
* It's very fast to get up and running, exposing a very large feature set, with very little API development or supporting code you need to provide.

...And some disadvantages:

* The exposed feature set is **very** large, roughly everything C# can do. As described in the linked answer, a modder with this kind of access can do basically anything they want to your game. I don't know any ironclad way to lock them out of particular functionality or constrain what they can mod once you've let them execute arbitrary code.
* This means that installing a mod written by a stranger requires a high level of trust. They might have coded-in spyware, or other malicious content, so your game can be used as an attack vector against unwary players. Not necessarily a situation you want to be in.
* As described in the linked answer, compiling at runtime is not supported on all platforms Unity can target, and requires additional plugins on some.

A more robust solution, as mentioned at the link, is to build your own virtual machine — using eg. The Bytecode Pattern — so you can execute scripts you've loaded as data at runtime, with strict control over what they're allowed to do.

# Answer
> 2 votes
You could do it like Kerbal Space Program does it: Allow your game to load AssetBundles at runtime by having it read config files which tell it where and in what way the assets in the bundle are supposed to appear in the game.

Then tell your modders to get Unity Personal Edition and use it to build their mod as one such asset bundles with an appropriate config file. You might need to open source some of your interfaces and offer them as a "mod SDK" asset bundle for your modders in order to interface properly with the rest of your game.

This method has the advantage that your modders can do anything Unity can do, which is a lot of nice stuff. But unfortunately, this method has the disadvantage that modders can do anything Unity can do, which also includes a lot of malicious stuff. So you need to educate your players to not download any mod they find.

If you want more secure modding, then you need to invest some more work. A good method to properly sandbox mods is by using a scripting language which allows you to selectively expose certain functionality of your game. You could write it yourself, but designing a good programming language and writing an interpreter for it is much more difficult than it seems. A better solution can be to use an existing scripting engine. There are scripting engines for C# available for pretty much any well-known scripting language.

# Answer
> 1 votes
As more advanced and more powerful alternative you could try using either MAF or MEF frameworks for C#. Among other things it handles for you automatic mod discovery, runtime loading and unloading, controllable security and improves stability (can run in separate domains).
The downside is that designing addin-aware architecture is much harder than simple compiling text file. While powerful it also imposes some requirements on loaded code as it is made primarily for plugin/DI systems which you might find too restricting - or ideal, depending on what are the mods supposed to do/add/modify.

---
Tags: unity, c#, scripting, modding
---


# Question
Title: Are very long floating point numbers a problem?
Very simple question, but important: I was using a floating point number ('float') in C++ to handle movement speed, and it suddenly ran crazy. It turns out the speed increased very fast to 259614846795304004193338175520768.0. That's 33 digits, on a typical (non-double) floating point number. How is that even possible, and can it cause the rest of my program to derail? Or will this number simply be cut down to the 23 bits of significant digits that floating point numbers usually have?

(edit: This is not a bug hunt. I am simply trying to understand how a float can hold such a large number with perfect precision (it's not an exponent, because that would just leave a trail of zeroes after a few significant digits). I am not looking for flaws in my code, just a better understanding of how floating point numbers work, and how this can happen)

EDIT: The solution seems to be a mix of bits from several answers, so I don't know whom to assign as the correct answer. Floating point values are apparently assigned by exponent, which means that some numbers can be amazingly huge without losing precision, as long as they are precise exponents of 2 somehow. Mine was. I thought the size was limited to 23 bits, flat out. As soon as I started using variations of the number that were NOT precise exponents of 2, everything went crazy. Sorry for the radio silence, I had to figure this whole thing out experimentally, once I learned that about floating point numbers from various answers.

I seem unable to close the question. Could someone with proper clearance close it down? And thanks to everyone for the help, I am now far more enlightened regarding floating point numbers!

# Answer
> 17 votes
All single-precision floats have the exact same distribution of bits for the components. Your number, assuming it's properly formatted, is when put into a float the following bit pattern:

```
0b0111'0101'0100'1100'1100'1100'1100'1101

```

A IEEE 754 single precision floating point number has one bit for sign, eight for exponent and twenty-three for mantissa, so splitting it up yields:

```
sign: 0b0
exponent: 0b1110 1010
mantissa: 0b100 1100 1100 1100 1100 1101

```

The value of a floating point value is (using ^ as exponentiation and interpreting the mantissa as the fractional part of a binary number):

```
-1 ^ (sign) * 1.mantissa * 2 ^ (exponent - 127)

```

Putting in your values yields:

```
v = 1 * 0b1.110011001100110011001101 * 2 ^ (234 - 127)
v = 1 * 1.60000002384185791015 * 2^107

```

As the bits for your fraction represent the fractional places of the mantissa (1/2th place, 1/4th place, etc.) the last bit of your fraction there is the 1/(2^24)th place, which contrasted with the exponent of 107 means that the nearest number to your number differs by around 2^83.

In summary, this is typically a problem as the magnitudes of the numbers involved in your operations are very likely to have essentially no range in common. Operations on floating point numbers typically "normalize" the numbers to have the same exponent and doing so with your numbers end up obliterating pretty much all the bits involved.

# Answer
> 16 votes
They aren't a problem, per se. But they are often a signpost towards a problem, especially if you're seeing them and you don't expect to.

If you're *seeing* very large floating point numbers (or very small ones) appear in your data during runtime and you don't expect them to, that's usually indicative of a bug somewhere. Without more information we can't really say, but if you're seeing a particular variable's value increase rapidly it's probably possible for you to break into the debugger at the point where the variable is incremented and work backwards to see *what* is contributing to the unexpectedly large increase, and then debug from there.

Conversely (for generality), if you're trying to *write* very long floating point numbers, you should remember that not every floating point value can be accurately represented. Floats have a limited precision and as you get further from zero or try to add more numbers after the decimal you're going to start getting larger and larger deltas between what you wrote and what you actually get in memory.

# Answer
> 4 votes
It's a display issue. Your enormous looking number can be exactly represented by a single-precision floating point number:

13431773 * (2^84) = 259808274926442344861291163680768

That large number is an exact representation of the floating point number, it's just rather misleading, as it implies your floating point number is far more accurate than it really is. A better float-\>text conversion would be something like 2.5980827e32 which does not pretend to have accuracy that isn't there.

It does seem awfully fast for a movement speed, but I guess it's your decision whether that needs fixing.

# Answer
> 3 votes
Very big numbers aren't a problem, neither are very small numbers (unless you approach the limits of representation) what really matters is if you have *both* big and small numbers because then you start getting serious inaccuracies. This can easily happen in space scale games where strange bugs can start manifesting if you're too far from the origin of your co-ordinate system.

# Answer
> 1 votes
**Regarding Precision:**

As pointed out by @James Hollis, it's possible that the system representing the number is filling in the remaining digits to give an illusion of precision.

The higher an IEEE754 number gets in terms of magnitude, the worse its precision gets. This relationship is near-linear as demonstrated with this diagram (that I shamelessly borrowed from Wikipedia).

The typical way this behaviour manifests is by small ammounts of imprecision. An example in C++:

```
void main(void)
{
    static_assert(sizeof(float) <= 4, "");
    for (float f = 0; f < 1; f += 0.01f)
    {
        std::cout << f << ", ";
    }
    std::cin.get();
}

```

On my computer this runs fine up until 0.83, after which the numbers deteriorate:

> 0.839999, 0.849999, 0.859999, 0.869999, 0.879999, 0.889999, 0.899999, 9, 0.909999, 0.919999, 0.929999, ...

These sorts of errors soon mount up. Thankfully in the majority of games these small errors aren't large enough to impact gameplay. The only time the errors become a problem is when trying to do comparisons, because 0.899999 may or may not be equal to 9. Thankfully most languages provide an *epsilon* value that represents the smallest amount of deviation that can be attributed to expectd error from imprecision.

As @Jack Aidley notes though, this can cause an issue in games where vastly varying scales are present (scales ranging from values in the order of 4 decimal places to values in the millions or billions). In some cases these are unavoidable because (for example) physics involves both incredibly large forces and incredibly small forces. Worst case scenario: you fail to correctly intercept an missile and people die.

In addition, I refer you to some of the interesting exaples of the perculiarities of floating point numbers as found on StackOverflow:

---
Tags: floating-point
---


title: Interpolation Jitter

text:
# Question
Title: Interpolation Jitter
I am trying to interpolate players in a multiplayer game like so:

```
var lastTime = now - (1000 / config.serverUpdateRate);
for (var i = 0; i < players.length; ++i) {
    tmpObj = players[i];
    var total = tmpObj.t2 - tmpObj.t1;
    var fraction = lastTime - tmpObj.t1;
    var ratio = fraction / total;
    tmpObj.x = UTILS.lerp(tmpObj.x1, tmpObj.x2, ratio);
    tmpObj.y = UTILS.lerp(tmpObj.y1, tmpObj.y2, ratio);
}

```

The server update rate is the frequency with which the server send the player positions. The x2 is the newest position and x1 is the position from the previous update.

Now this works fine on my localhost and on an empty server. But as soon as the game server has around 60 people on it, it begins to stutter. I am assuming that this is because the positions are coming in at an inconsistent rate. How can I adjust for that in my interpolation?

You can see the issue in action here: http://moomoo.io

I have tried to simply interpolate without lerping, but the movement felt too floaty. Also client prediction is not an option in this case

# Answer
> 1 votes
I doubt there is any healing interpolation magic...

You could try to synchronise time for all clients, against one or multiple time servers, then embed a timestamp in the packages and inter/extrapolate movement based on that. Then it won't matter if the transmission times are unstable.

By that you don't *change* the computer clock, just calculate and use an offset between that (the local crystal and frequenxy) and sync'ed world time. You should get an accuracy of a few milliseconds. PC clocks typically have an error of 0...a few seconds per 24 h, so one may have to re-sync now and then.

The local crystal is stable and fixed (eg. the QueryPerformance API in Windows). Windows "stretches" that (adjusts over a longer time period) when announcing clock time, so the "clock time" itself is useless - one must get down to the hardware.

---
Tags: networking, multiplayer
---


title: Physics for curved edges?

text:
# Question
Title: Physics for curved edges?
I'm learning how to program simple two-dimensional games in C++ using SFML, I've done a relatively simple pong game already I would like to ask how I could go about creating the physics for a curved edge such as one on an air hockey table Such as this:

Do I have to code a type of reflection of xVelocity/yVelocity for every single point or what? How do I even add a curved edge such as that in the first place?

# Answer
I'd suggest looking into a physics library/engine like Box2D or bulletphysics.

If your primary interest is getting the circles to behave like pucks on ice, then just add the library to your project to have the collision handling - including the frictional responses (that deal with spin) - done for you.

If learning about handling the physics is your primary goal, then take a look at the library's documentation, tutorials, white papers, and/or source code. You'll probably want to focus on material related to continuous collision detection (CCD).

In Box2D for instance, there's:

* Code for generating a collision description (code related to the `b2Manifold`);
* Code for dealing with resolving positional overlap (like in `SolvePositionConstraints`);
* Code for dealing with resolving velocity responses (see `SolveVelocityConstraints`); and
* Code for calculating an upcoming time of impact (see `b2TimeOfImpact`).

Depending on how realistic you want your collisions to look, you may need to learn about all of these things and more.

Note that realism is typically at the expense of loss of performance. This shows up in terms of how many frames can be simulated and rendered per second. So a compromise has to be struck between these.
> 0 votes

# Answer
Since you're asking about physics, I assume you want to do things like reflect the puck off of the rounded corners, correct? You currently have code to reflect the puck off of the straight edges along the sides and top and bottom, so the easiest thing to do is to simply convert the rounded corners into a series of connected straight edges and re-use the straight-edge code you already have. I bet if you replaced each corner with a single diagonal edge, most users wouldn't even notice. But you can probably do better with 3-4 small line segments.

For reflections, you may recall from physics class that "the angle of reflection is equal to the angle of incidence." What this translates to is the angle the puck's vector of direction makes with the surfaces normal should be reflected across the normal to figure out where the puck is going to go to. See this question for a description of the math.

Note that for circles (or semi-circles), the surface normal is just the direction vector from the point on the edge of the circle where the puck hits to the center of the circle. So in this case, you could even use the actual value without doing too much work.
> 0 votes

---
Tags: c++, 2d, physics, sfml, intersection
---


title: I need a name for a space survival game

text:
# Question
Title: I need a name for a space survival game
I am making a game similar to planetbase. It will have mining systems, and you trade resources with traders that come periodically. You can sell your extra minerals, and buy other things with the money.

What is different about this game than planetbase is that there is also a space station orbiting the planet, and you have a space elevator to go between them. Some minerals you can only find in asteroids orbiting and some only on the planet.

***Question:*** **What is a name idea for this game?**

# Answer
I wanted to give you a serious answer, so here it goes. First off, this is an opinion based question. We can only give you our opinion on what a good name will be, and thus, this question is off topic for this site. Also, let me paraphrase your mentality right now with a single sentence: "A thousand ideas, zero lines of code."

Make your game. Use a codename at the beginning, like "Project Black". Most game companies do this, even for major games, but this is also to keep the project somewhat secret. My point is, you're wasting time and procrastinating. Make your game, then name it. It should also be noted that even games like Minecraft were first created without a name; the earliest builds of it were just called "RubyDung". You need to avoid wasting time on trivial things like this until far later into your project. Like right now, and I'm not trying to brag or anything, but I am currently sitting on (Runs code metrics for entire solution) 44,324 lines of code for my game. That's with a working inventory system, rendering, player attributes, loot systems, entity systems, weather systems, etc, and all hosted within a custom game engine framework that I created from the ground up.
> 4 votes

---
Tags: game-design
---


# Question
Title: How do I implement object picking, using OBB in OpenGL?
I am trying to make 3D drawing software. I wanted to have the drag feature so I am using object picking using the OBB algorithm. I am facing problems in understanding the algorithm, and my implementation thus is having bugs.

How do I implement object picking, using OBB in OpenGL? As I am new to OpenGL (free-glut library), a step by step explanation would be helpful.

# Answer
> 2 votes
First you have to implement AABB picking with AABB-ray intersection test. Picking an OBB is then achieved by transforming the ray inside the OBB's local space and doing an intersection test with an unit AABB - local ray. Transforming the ray into the OBB local space is done by transforming the ray origin and ray direction by the inverse of the OBB's transformation matrix.

To get a picking ray, you have to unproject your pick position (mouse position) to the camera near and far planes by transforming it by the inverse view projection matrix. Something like this:

```
vector3 near = vector3(mouse.xy,0,1) * matInverseVP;
vector3 far = vector3(mouse.xy,1,1) * matInverseVP;
vector3 rayOrigin = near;
vector3 rayDirection = normalize(far - near);

```

---
Tags: opengl, 3d, raycasting, glut, picking
---


# Question
Title: How do I teach the players that their strong but slow attack can not be cancelled?
Designing the combat mechanics of my current project I've come to a problem: **How do I make players feel responsable of their mistakes instead of they blaming my game?** This is the scenario:

Among other things your character has two basic abilities a quick and a strong melee attacks, and as you may guessed the quick attack does less damage and has a smaller control(time enemies are pushed/stunned after hit), as the strong attack has a slower and obviously longer animation that (here is the catch) **cannot be cancelled**. And here is my concern; **many players may feel that the game is unresponsive instead of realizing that they shouldn't had used a strong attack in that moment.**

Extra info:

* Neither of the attacks consume resources as stamina.
* Receive a hit is a big penalization for the player as heal is hard and the difficulty lies in progressing through levels loosing less health than you can find.
* Both attacks has a 3 hit chain with cool down after the last, this means that the managing of this ability to cancel or not the attack is a core mechanic that the player should learn in order to succeed.
* Enemies always give a big hint before attacking the player.

Solutions I thought:

* Explain to the player via tutorial.
* Pop a message sometimes when the player got hit during a strong attack animation.

Pd: I'm looking to the solution to the problem described above, but any general tips in this mater are also appreciated

# Answer
In your UI, if you have a way to display the currently available skills, disable all the other skills, and overlay a timer of some sort on them which should indicate how long until the next attack is available.

I haven't played World of Warcraft since the Open Beta Test, but I think there is something like this in that game:

(Clip from this video.)

This technique has the advantage of teaching the user that this skill causes the others to be locked, while giving them a clue about when they're going to be unlocked and usable again.
> 8 votes

# Answer
Here's an example to get you thinking: put a section in one stage where the player must break down walls that can only be broken with the heavy attack (this shows the attack's increased power), while being chased or having a wall close in behind. Since the player has a reason to move as quickly as possible, they will now clearly notice the wind-up freeze resulting from this more powerful attack. This gives a gameplay element that is potentially challenging and is showing them the benefit and consequences of using the attack. There's plenty of ideas for stuff like this, this is just one I thought of quickly.

As a side tip, there's actually a great video about this that I've watched several times to get an understanding of how to teach players about features of your game. This video is part of a small series called Sequelitis. In it the narrator examines the Megaman series and compares Classic and X. Much of his focus in this video is how they teach the players through gameplay, and not through manuals or tutorials. **There is bad language in this video.** However he really makes some good points and got me thinking much more in the direction you're looking towards.
> 3 votes

# Answer
People would likely forget mention of it in tutorials. It is better to teach them when they try it for themselves. The message seems like too strong of an interruption.

One idea would be to give feedback in the attempt to cancel the attack without actually cancelling the attack. You could use a sound (I am thinking a buzzer sound like in a game show when you get the wrong answer to a question) or have an X appear in the corner of the screen, or both.
> 2 votes

---
Tags: game-design
---


# Question
Title: How can I efficiently resize sprites every frame?
I want to animate UI elements, like HP bars, by moving and resizing them. How can I efficiently resize sprites every frame?

I am using the LibGDX framework.

# Answer
> 1 votes
When creating your texture, fill in the 2nd parameter to tell LibGDX to generate a mipmap chain:

```
Texture tex = new Texture(Gdx.files.internal("image.png"), true);

```

Then enable mipmapping in the texture filter:

```
tex.setFilter(TextureFilter.MipMapLinearLinear, TextureFilter.Linear);

```

This approach is hardware accelerated and there is no drawback to drawing the image at different sizes every frame.

---
Tags: libgdx, animation, sprites
---


# Question
Title: Exp equation for enemy and player in rpg
I am making an rpg game with specific leveling system I want when a level 1 player fights a level 25 monster to level up to level 20-25 then when he goes and fight the same monster he then levels slowly like level 30 then level 32, 35, 36 on his next 4 fights respectively meaning you must always fight a monster higher than your level else you will level up really slow

At the same time I want a level 1 player to fight a 20000 enemy and then gains like 10000 levels then on his next fight he gains like 50000 then he gains another 50000 meaning that if the player fights a really strong monster he levels up fast until he reaches the level of that monster then he level up real slowly, This system doesn't have to be perfect at all but you get the idea So any help on the equations, I searched really hard and found elementary functions like

Power function:

y = a * x^b + c

Or Linear functions:

y = mx + b

Also exp. functions and log functions but I cant seem to get the desired effect or even get any close to it, Any help or any tip on where I can find my answer is highly appreciated ty

# Answer
> 0 votes
It will be a different solution for each game, for example, some games will only give, you experience if the enemy is on a similar level. You need to start by giving a hard look to your requirements.

---

First, we need to start by recognize that the experience gained shall never be negative. Furthermore, I am inferring from your description that when you fight monsters of lower level than you are, it will never result in zero experience, but in increasingly diminishing values instead.

Second, I suspect you want to fix the amount of experience the playing will gain by fighting a monster of the same level.

If we are looking for a function `g`, that given a difference of levels `x` (`monster_level - player_level`) with the description provided, it follows that:

* `Lim(g(x))_x->-∞ = 0`: When the difference tends to negative infinity, the gained exprience tends to zero
* `g(0) = k`: When the difference is zero, the gained experience is a constant value `k`
* `dg(x)/dx > 0`: The gained experience is a growing function, the greater the difference of levels the greater the gained experience

We cannot represent this with a linear function. To speak is loose terms, a stright line that doesn't cross the origin, and meets the horizontal axis at negative infinity... is an horizontal line. So its slope would be zero. However, we need a slope greater than zero.

It cannot be a quadratic function, because they are not always growing. In fact, you will have a similar problem with higher order functions.

Trigonometric functions are periodic functions, so we can discard those too...

Logarithms are growing on the positive, but decreasing and with an imaginary part on the negative. So, do not base the function on that either...

Exponential functions fit the bill. For example take `g(x) = 2^x`:

* `Lim(2^x)_x->-∞ = 0`
* `2^0 = 1`
* `d/dx {2^x} = log(2) * 2^x > 0`

It is very easy to tweak by changing the cosntant `2` to a parameter, but whatever constant we put there, we will get `1` when `x = 0`. We could consider to add another term, but that would change the limit when `x -> -∞`. Therefore, what we do is mess with the exponent, in particular:

`g(x) = k^(x+1)`

With this function, you get `g(x) = k` when `x = 0`. The next thing you will want is to tweak how fast it grows, you can do that by adding a factor to `x`:

`g(x) = k^(fx+1)`

If I want to make sure that `g(a) = b`, I do this:

```
g(x) = k^(fx+1)
g(a) = b
=>
b = k^(fa+1)
=>
log(b) = log(k^(fa+1)
=>
log(b) = (fa+1)*log(k)
=>
log(b)/log(k) = fa+1
=>
log(b)/log(k) - 1 = fa
=>
log(b)/log(k) - 1
------------------ = f
        a

```

I can rewrite the function like this:

```
g(x) = k^((log(b)/log(k) - 1)*x/a + 1)
=>
g(x) = k*k^((log(b)/log(k) - 1)*x/a)
=>
g(x) = k*(b/k)^(x/a)

```

It will have the following properties:

* `Lim(g(x))_x->-∞ = 0`
* `g(0) = k`
* `g(a) = b`
* `dg(x)/dx > 0` Where `k`, `a` and `b`. In addition, remember that `x` is `monster_level - player_level`.

---
Tags: mathematics, game-design, rpg
---


# Question
Title: How do I delete the parent game objects attached to a script?
How do I delete the parent game objects attached to a script? You can see my code as an example, which is only removing the script on a game object. I am using Unity 5.5.2f1.

```
void destroySpawnersAndItems ()
{
    //FIX: It's deleting the script and not the complete object.
    var spawners = FindObjectsOfType(typeof(spawnerItem));
    var items = FindObjectsOfType(typeof(itemFood));

    foreach (var spawner in spawners)
    {
        Destroy(spawner);
    }

    foreach (var item in items)
    {
        Destroy(item);
    }
}

```

# Answer
> 1 votes
As pointed out, your using a reference to the *components* in your call to `Destroy()`. This removes the specific *component*, but not the *game object* you have that component attached to.

The following variation to your script will remove the game object too which the component is attached to, and in doing so, will also remove that component, and any other component attached to the game object.

Note the inclusion `#if UNITY_EDITOR`. If you use this code via the Editor, Unity will complain that your not using `DestroyImmediate()`; however, this method is unsafe to use outside of the Editor, so we will tell the Editor to use `Destroy()` in normal compiles.

```
void destroySpawnersAndItems()
{
    var spawners = FindObjectsOfType(typeof(spawnerItem));
    var items = FindObjectsOfType(typeof(itemFood));

    foreach(var spawner in spawners)
    {
        #if UNITY_EDITOR
        DestroyImmediate(spawner.gameObject});
        #else
        Destroy(spawner.gameObject);
        #endif
    }

    foreach(var item in items)
    {
        #if UNITY_EDITOR
        DestroyImmediate(item.gameObject});
        #else
        Destroy(item.gameObject);
        #endif
    }
}

```

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


# Question
Title: Show the progression of a loop in GameMaker Studio
I'm using a loop to destroy some objects in my code.

```
for (var i = 0; i < instance_number(obj_item); i++)
{
    var inst = instance_find(obj_item, i);
    with (inst)
        instance_destroy();
}

```

I would like to make them disappear one at a time on screen (i.e., the first one disappears, one second after that the second one disappears, etc.).

However, it seems that the screen is updated only when the loop has finished: all objects disappear at once.

In Unity, I would use coroutines for such a situation. How do I do that in Gamemaker?

# Answer
> 0 votes
Use `alarm` for this, like:

```
if instance_exists(obj_item)
{
    with instance_find(obj_item, 0)
        instance_destroy();

    alarm[0] = room_speed; // one second
}

```

place this code in `alarm 0` and then start it using `alarm[0] = 1;`

---
Tags: game-maker
---