# Question
Title: Calculate the distance/number of moves one square is from another
Say I have a 9x7 grid (could be any size) I want to be able to calculate the distance any square is from another. In the image I have selected 5,4 is my target square. Now square (1,2) is 4 moves away (if you can move left, right, up, down and diagonal), as denoted by the orange dot. It is clear from the diagram that the distance from the target square is simply showed by a growing square surrounding the target square. Is there a function which will calculate me the distance of a particular square to my target square using the x and y values of both squares.

e.g. I want to know how many moves it will take from (8,5) to the target square, looking at the diagram I know this is three but is there a function I can use?

# Answer
> 8 votes
If you don't need to navigate around obstacles along the way, you can do this with a simple formula.

Just like in continuous space we can use the Euclidean distance metric:

$$d\_{\text{Euclidean}} = \sqrt{ \left(\vec b - \vec a\right)^2} = \sqrt {(b\_x - a\_x)^2 + (b\_y - a\_y)^2}$$

```
distance = sqrt((end.x - start.x)^2 + (end.y - start.y)^2)

```

In a discrete square grid we can use the Chebyshev distance metric (if we can move on diagonals):

$$d\_{\text{Chebyshev}} =\max\left(\left| b\_x - a\_x \right|, \left| b\_y - a\_y \right|\right)$$

```
distance = max(abs(end.x - start.x), abs(end.y - start.y))

```

Or, if we can't take diagonal moves, we'd use the Manhattan distance metric:

$$d\_{\text{Manhattan}} =\left| b\_x - a\_x \right| + \left| b\_y - a\_y \right|$$

```
distance = abs(end.x - start.x) + abs(end.y - start.y)

```

All of these extend naturally to 3 (or more) dimensions by adding more terms following the same pattern.

---

If you **do** need to navigate around obstacles, then as mentioned in the comments, you need to use some type of pathfinding function like A\*. But you can use the metrics above as your heuristic function, to help A\* prioritize searching the most promising options.

If you want to know the path distance to *many* cells from a given seed cell, rather than just a single path from start to end, then you can use breadth-first search, which will enumerate the cells in order of increasing "hop count" from your initial cell.

---
Tags: mathematics, grid
---


# Question
Title: Moving a sprite along a circle given by an implicit equation
I’m trying to create a hyperbolic version of Pong in a Poincaré disk, using C++ and SFML.

Here is my problem: when the ball rebounds on a paddle, I deduce two coordinates allowing me to recover the equation of the hyperbola (as a circle in the Poincaré disc), in implicit form:

$$x^2 + y^2 + ax + by + 1 = 0$$

So, I have my equation, and I can only move my sprite using its x and y Cartesian coordinates - I don’t know how to do it differently.

How can I move my sprite following this circle equation?

Moreover, I would like to represent the Poincaré metric, so the ball's velocity will also vary as a function of the metric and its position (slowing down on the screen as it gets closer to the edge of the disc where space is compressed)…

# Answer
> 4 votes
We can solve this by completing the square:

$$\begin{align} x^2 + y^2 + ax + by + 1 &= 0\\ \left(x^2 + ax \right) + \left(y^2 + by \right) + 1 &= 0\\ \left(x^2 + ax + \frac {a^2} 4\right) + \left(y^2 + by + \frac {b^2} 4\right) + 1 - \frac{a^2}4 - \frac{b^2} 4 &= 0\\ \left(x + \frac a 2 \right)^2 + \left(y + \frac b 2 \right)^2 &= \frac {a^2 + b^2} 4 - 1 \end{align}$$

This means the circle's center is at \\$\left(-\frac a 2, -\frac b 2\right)\\$ and has radius \\$r =\frac {\sqrt {a^2 + b^2 - 4}} 2\\$ (meaning we lack a real solution if \\$a^2 + b^2 \< 4\\$)

You can compute an offset from the circle's center to your sprite's current coordinates to get its phase angle theta:

```
theta = atan2(sprite.y + b/2, sprite.x + a/2)

```

And then move your sprite along this circular arc by incrementing/decrementing theta (depending on whether you want to move counter-clockwise or clockwise).

```
newPosition.x = cos(theta) * radius - a/2
newPosition.y = sin(theta) * radius - b/2

```

I'll have to punt for now on the magnitude of the increment to theta that corresponds to a consistent speed under the Poincaré metric, but hopefully this gives you enough to get started. :)

---
Tags: c++, mathematics, movement, geometry, sfml
---


# Question
Title: Java - Why does my game loop stutter randomly?
I'm a beginning game developer and I'm trying to make a game in Java, but for some reason, it keeps stuttering at random times. I believe what I'm experiencing could also be called microstuttering.

At first, I though my framerate of 60 fps was the problem, so I've tried setting it to 30 and 120. In both cases, however, did not only the microstutters persist, but the player also started moving shakingly, as if it were moving back and forth while moving in one direction, the same way pigeons move their heads when walking.

Next, I've tried changing my game loop. I've read that sleep based game loops are very unreliable, so I changed it to a timer based game loop. Unfortunately, that didn't work either. The microstutters still persisted, the player still moved shakingly and for some reason, my framerate also seemed to have halved.

I've been looking into this for a while now, but I haven't been able to fix the problem. Is there anyone with more experience who could help me, please?

Here's my game class for the sleep based loop:

```
package collisiondetection;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.net.URL;

@SuppressWarnings("serial")
public class Game extends Applet implements KeyListener, Runnable {

    final boolean DEBUG = true;

    public static int health = 13;

    public static Player player;
    public static Terrain terrain;

    public boolean running = true;

    public Graphics graphics;
    public Line line;
    public Image background, image;
    public URL base;

    @Override
    public void init() {
        setSize(1280, 720);
        setBackground(Color.WHITE);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Collision Detection");

        base = getDocumentBase();

        background = getImage(base, "data/background.png");
    }

    @Override
    public void start() {
        player = new Player();

        try {
            terrain = new Terrain();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }

    // fix lag
    @Override
    public void run() {
        while (running) {
            if (health <= 0)
                running = false;

            player.update();
            terrain.update();
            repaint();

            try {
                Thread.sleep(1000 / 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            graphics = image.getGraphics();
        }

        graphics.setColor(getBackground());
        graphics.fillRect(0, 0, getWidth(), getHeight());
        graphics.setColor(getForeground());
        paint(graphics);

        g.drawImage(image, 0, 0, this);
    }

    @Override
    public void paint(Graphics g) {

        if (running) {
            g.drawImage(background, 0, 0, this);
        } else {
            // handle death
        }

        if (DEBUG) {
            g.setColor(Color.BLUE);
            g.fillRect(player.hitbox.x, player.hitbox.y, player.hitbox.width, player.hitbox.height);

            g.setColor(Color.RED);
            for (int i = 0; i < terrain.lines.size(); i++) {
                line = terrain.lines.get(i);
                g.drawLine((int) line.line.getX1(), (int) line.line.getY1(), (int) line.line.getX2(),
                        (int) line.line.getY2());
            }
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            player.moveLeft();
            break;

        case KeyEvent.VK_RIGHT:
            player.moveRight();
            break;

        case KeyEvent.VK_UP:
            player.jump();
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            player.stopLeft();
            break;

        case KeyEvent.VK_RIGHT:
            player.stopRight();
            break;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    public static Player getPlayer() {
        return player;
    }

    public static Terrain getTerrain() {
        return terrain;
    }

}

```

And my game class for the timer based loop:

```
package collisiondetection;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

@SuppressWarnings("serial")
public class Game extends Applet implements KeyListener {

    final boolean DEBUG = true;

    public static int health = 13;

    public static Player player;
    public static Terrain terrain;

    public boolean running = true;

    public Graphics graphics;
    public Line line;
    public Image background, image;
    public Timer timer;
    public URL base;

    @Override
    public void init() {
        setSize(1280, 720);
        setBackground(Color.WHITE);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Collision Detection");

        base = getDocumentBase();

        background = getImage(base, "data/background.png");
    }

    @Override
    public void start() {
        player = new Player();

        try {
            terrain = new Terrain();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        timer = new Timer();
        timer.schedule(new TimerTask() {

            // fix lag
            @Override
            public void run() {
                if (health <= 0) {
                    running = false;
                    timer.cancel();
                }

                player.update();
                terrain.update();
                repaint();

            }

        }, 0, (long) (1000.0 / 60.0));
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            graphics = image.getGraphics();
        }

        graphics.setColor(getBackground());
        graphics.fillRect(0, 0, getWidth(), getHeight());
        graphics.setColor(getForeground());
        paint(graphics);

        g.drawImage(image, 0, 0, this);
    }

    @Override
    public void paint(Graphics g) {

        if (running) {
            g.drawImage(background, 0, 0, this);
        } else {
            // handle death
        }

        if (DEBUG) {
            g.setColor(Color.BLUE);
            g.fillRect(player.hitbox.x, player.hitbox.y, player.hitbox.width, player.hitbox.height);

            g.setColor(Color.RED);
            for (int i = 0; i < terrain.lines.size(); i++) {
                line = terrain.lines.get(i);
                g.drawLine((int) line.line.getX1(), (int) line.line.getY1(), (int) line.line.getX2(),
                        (int) line.line.getY2());
            }
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            player.moveLeft();
            break;

        case KeyEvent.VK_RIGHT:
            player.moveRight();
            break;

        case KeyEvent.VK_UP:
            player.jump();
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            player.stopLeft();
            break;

        case KeyEvent.VK_RIGHT:
            player.stopRight();
            break;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    public static Player getPlayer() {
        return player;
    }

    public static Terrain getTerrain() {
        return terrain;
    }

}

```

If you want to import the game in Eclipse to see how it works for yourself, you can download both the sleep and timer based projects from here.

Thanks in advance.

# Answer
> 1 votes
Java is quite not controllable enough to allow you to enforce a constant framerate. The best you can do is try to make each `run()` begin on a 1/60 second boundary. Your `Timer` method might be as good as you're going to get. Even so, it's making a really big assumption, which is that your game's process will be running exactly when that 1/60 second interval ends. That may not happen, and so you'll need to deal with the cases where it has not.

To deal with this, there are two standard methods.

**Method 1:**

Set a fixed "update rate", say 1/60 second. At the start of your `run()` method, figure how much time passed since the last `run()`. Divide that time by the update rate, and update that many times. The update rate probably will not divide the time change evenly. If you want to interpolate (note: I know, you said you don't want to. Still...) you update one more time, and then interpolate between the two positions. If you don't want to interpolate, you store the amount of extra time and add it into the next frame's time change.

**Method 2:**

At the start of your `run()` method, calculate how much time passed since the last `run()`. In your game's update code, accelerate and move objects in proportion to the time change.

---

Method 1 is particularly useful for fast-action games where precision in movement and physics is an absolute necessity. Method 2 is far simpler, and in many cases will behave well enough (or exactly the same as method 1) in practice.

\[Note: The `Thread.sleep()` method you posted isn't quite correct, because it sleeps for 1/60 second after updating the game. This is adding 1/60 second to the amount of time that the frame already took to run. You should be subtracting the time it took to run the update code from 1/60, and sleeping for that amount of time.\]

# Answer
> 0 votes
One potential issue could be java's garbage collector. The garbage collector runs every now and again and deletes any objects that are out of reference, does your terrain object contain tile objects? This cannot be stopped but it can be reduced significantly.

A way to ease this issue is something called object pooling where you create all your objects at start up and then just use them when needed giving them an active or inactive state.

Object creation is also quiet time consuming, pooling will help this.

---
Tags: java, movement, game-loop
---


# Question
Title: GUI scaling: Viewport-based scaling or individual logic
I want to use scene2d for creating a GUI for a libGDX game. In scene2d all sizes are provided in pixel units (instead of percentages). So I wonder what is the best approach to deal with different screen resolutions? Two solutions came into my mind and I wonder how to proceed:

* Use a fixed resolution for the GUI (e.g. 1920x1080), optimize all widgets for this size and let the viewport do the rest (so there will be super- or subsampling)
* or write a resizing logic for the gui to properly adapt the widget sizes and positions to the screen's resolution

Is there any known best practice how to deal with this problem?

# Answer
The Android-style would be to create custom layouts for each viewport size. This limits you, of course, to only handling a fixed set of viewport sizes but there are only a limited number of monitor resolutions and each one would look its best.

The fixed resolution master layout used with viewports that scale all the contents will work to a degree (I use this here at work on one project), but texts will suffer a little at the smallest percentages. I find that you can limit the monitor requirements to enforce a minimum size that looks good and lose almost no potential customers in today's gaming environment.
> 1 votes

# Answer
libgdx provide a utility class called viewport to deal with different screen resolutions problem , each time the screen resolution changes you have to update the viewport:

```
private Viewport viewport;
private Camera camera;

public void create() {
    camera = new PerspectiveCamera();
    viewport = new FitViewport(800, 480, camera);
}

```

Whenever a resize event occurs, the viewport needs to be informed about it and updated. This will automatically recalculate the viewport parameters and update the camera:

```
public void resize(int width, int height) {
    viewport.update(width, height);
}

```

For further informations take a look at https://github.com/libgdx/libgdx/wiki/Viewports
> 1 votes

---
Tags: libgdx, gui, scene2d, scale, window-management
---


# Question
Title: Serialize ScriptableObject without creating an asset out of it?
Is it possible to do something like this?

```
public class SomeScriptable : ScriptableObject
{
    public MyScriptable myScriptable;

    public void OnValidate()
    {
        if (myScriptable == null)
        {
             myScriptable = ScriptableObject.CreateInstance<MyScriptable>();
         }
    }
}

public class MyScriptable : ScriptableObject
{

    public int MyVar1;
    public string MyVar2;

}

```

I tried this but am getting a "Type Mismatch" error in Unity.

# Answer
> 1 votes
It's odd, as it is now, you should get a CS0103 compiler error, due to the fact that you need to write:

```
myScriptable = ScriptableObject.CreateInstance<MyScriptable>();

```

Moreover, if the `MyScriptable` class it's inside the `MyComponent` script attached to a game object, you'll get a warning - to get rid of it you need to cut the `MyScriptable` class code from it and put it in its specific script, named ofc `MyScriptable`.

And remember that the `myScriptable` instance will be serialized in edit mode as soon as you finish compiling the script for the first time, since you put `CreateInstance` inside `OnValidate()`.

**EDIT**

You're getting the `Type Mismatch` error in the prefab of the game object with the `MyComponent` script, and that's normal, since prefabs can't get a reference to any kind of instances in the hierarchy of the scene, but only to assets.

For example, if you create a game object in the hierarchy, then attach the `MyComponent` script, you'll be able to access the `myScriptable` instance, by double-clicking on the `My Scriptable` field of the script in the inspector.

But, if you now create a prefab from it, you'll get the `Type Mismatch` error in the field of the script attached to the prefab.

And you can't really escape from it: if you want to have a reference in the prefab, you HAVE to create a `myScriptable` asset which can be then referenced by the prefab.

Of course you can do that by using

```
AssetDatabase.CreateAsset(myScriptable, "pathname+assetname.asset");

```

just after the `CreateInstance` method in `MyComponent`, or you can add the `[CreateAssetMenu]` attribute in the `MyScriptable` script, so you can create any asset you want in the editor, and then drag-and-drop it in the reference field of the prefab.

That's pretty much it, hope it helped.

---
Tags: unity, serialization
---


title: Libgdx is Character on Screen

text:
# Question
Title: Libgdx is Character on Screen
Inside an entity class:

```
public boolean onScreen(Camera camera){
    if(position.x + getWidth() > camera.position.x
            && position.x < camera.position.x + camera.viewportWidth
            && position.y < camera.position.y + camera.viewportHeight
            && position.y + getHeight() > camera.position.y){
        return true;
    } else {
        return false;
    }
}

```

The function returns false even when the entity is on the screen. What am I doing wrong?

# Answer
Why not use the Camera.Frustum? https://github.com/libgdx/libgdx/wiki/Orthographic-camera

Also try switching your \> and \<. Im not sure what camera.position is, whether its the bottom left or center, but that may be your problem
> -1 votes

---
Tags: camera
---


title: Advanced dice probability

text:
# Question
Title: Advanced dice probability
I want to find a formula to get the probabilities of dice roles in the game Infinity. In this game people are rolling a set number of 20 sided die against another number of 20 sided die, hoping to roll the higher number. In addition each person has a set target number that limits how high a die value he can use. So if my target number is 13 any number I roll above a 13 does not count.

For example if I am rolling 3 dice (20 sided) and need to roll a 11 or below, and my opponent is rolling 1 die (20 sided) and needs a 14 or below. What are my chances of getting a higher number than him without going over 11?

# Answer
> 3 votes
Let's say out of \\$n\\$ \\$D\\$-sided dice, the highest roll I get is an \\$x\\$. What are the chances of that?

Well first, I had to roll nothing higher than \\$x\\$. So that's `x` eligible rolls per die \\$(1, 2, 3, ... x-1, x)\\$, out of \\$D\\$ I could have rolled, compounded `n` times:

$$P(n \text{ rolls} \le x) = \left(\frac x D\right)^n$$

Now out of these \\$x\\$ possible values, I must have rolled the biggest one, \\$x\\$ itself, at least once. That means I *didn't* roll \\$x-1\\$ or lower all \\$n\\$ times:

$$\begin{align} P(n \text{ rolls} \< x | n \text{ rolls} \le x) &= \left(\frac {x - 1} x\right)^n\\ \\ P\left((\text{rolls} = x) \ge 1 | n \text{ rolls } \le x)\right) &= 1 - \left( \frac {x-1} x\right)^n \end{align}$$

So, putting these together, the chance that my best roll was `x` is:

$$\begin{align} P\left(\text{highest roll} = x \text{ in } n\right) &= P(n \text{ rolls} \le x) \cdot P\left((\text{rolls} = x) \ge 1 | n \text{ rolls } \le x)\right)\\ &= \left( \frac x D \right)^n \cdot \left(1 - \left(\frac {x - 1} x\right) ^n\right) \end{align}$$

---

So far so good. But some of my dice might get ruled out by rolling too high. To account for that, I'm going to leave the pure math world and go into some imperative code so we can work iteratively, hopefully a bit clearer than sigma notation. ;)

```
float[] ProbableBestRollsUnderLimit(int numDice, int numSides, int limit) {

    // Initialize an array to hold our probability of rolling each value.
    // Here I'll assume C# conventions where the array comes pre-initialized with 0s.
    float[] pBest = new float[numSides + 1];

    // Set the zero entry to the probability that we roll every die over the limit.
    pBest[0] = power(numSides - limit, numDice);

    for(int d = 1; d < numDice; d++) {
        // Get probability that we roll exactly d dice within our limiting value.
        float piWithinLimit = power(limit, d) * power(numSides - limit, numDice - d);
        // Factor in combinations of *which* dice were over/within limit.
        piWithinLimit *= choose(numDice, d);

        // Using the formula worked out above, accumulate probabilities of rolling
        // a best-of-d-dice result of i. Here we treat the dice as only limit-sided
        // since our P(i dice within limit) term already rules out the higher rolls.
        for(int i = 1; i <= limit; i++)
            pBest[i] += piWithinLimit * (1f - power((i-1)/i, d))*power(i/limit, d);
    }

    return pBest;
}

```

This method returns a table of probabilities, where the `i`th entry is the probability that my best roll is `i`.

---

With two of these tables, one for me and one for my opponent, I can work out the probable results of the match:

```
// My probability table.
float[] myBest = ProbableBestRollsUnderLimit(myDiceCount, 20, myLimit);

// My opponent's probability table.
float[] vsBest = ProbableBestRollsUnderLimit(vsDiceCount, 20, vsLimit);

// Compute a cumulative probability table for "P(opponent rolled lower than X)"
float[] vsLowerThan = new float[21];
for(int i = 0; i < 20; i++)
   vsLowerThan[i+1] = vsLowerThan[i] + vsBest[i];

float pWin = 0f;
float pLose = 0f;
float pTie = 0f;

for(int i = 0; i <= myLimit; i++) {
   // I win if I roll i and my opponent rolled less than i.
   pWin += myBest[i]*vsLowerThan[i];

   // We tie if we both rolled exactly i.
   pTie += myBest[i] * vsBest[i];
}

pLose = 1f - pWin - pTie;

```

Running these numbers with your example above (3 dice limit 11 vs 1 die limit 14),the 3-dice roller has a 55.97% chance to win, 7.28% chance to tie, and 36.75% chance to lose. (The dominant factor here being that the opponent has a 30% chance to roll over their limit and have their lone die discarded, while with 3 dice we've got only a 9% chance of complete disqualification this way)

This at least looks right to me. I'll offer this for now with the disclaimer that it's after midnight and I haven't tested this thoroughly, so it's entirely possible there's some blatant bugs lurking in there. ;) If you find one, let me know in the comments and we'll get it sorted out!

---
Tags: mathematics
---


# Question
Title: How do I avoid big switches in my message system?
I've been implementing a message system for my small engine, and I have started to think about optimizing and maintaining it. Right now, my message class looks like this (at its simplest - only member variables):

```
typedef unsigned int MessageID;

class Message
{
    std::string message;
    MessageID messageID;
    MessageData* data;
};

```

At first I was only using `std::string` to recognize each event, and handling was done in cascade-if style:

```
void GUI_system::handleMessage(Message* message)
{
    if (message->message == "DELETE_HP")
    {
        deleteHearth(static_cast<AttInfo*>(message->data));

    }
    else if (message->message == "PAUSE_GAME")
    {
        showPauseIcon();
    }
}

```

However, I felt it is uncomfortable to work with, and for a switch I needed a numeric variable. This is why is `MessageID` is generated from `unordered_map` each time a message is created; each message has its own ID, and if not, a new one is created. So now it looks like this:

```
void GUI_system::handleMessage(Message* message)
{
    switch(message->messageID)
    {
        case 1 :
        {
            deleteHearth(static_cast<AttInfo*>(message->data));
            break;
        }
        case 2 :
        {
            showPauseIcon();
            break;
        }
    }
}

```

However, this was more confusing than the cascade-if style, where I at least had a little knowledge of what is going on, internally, apart from a plain `int`. I know enumerations are easier to use and implement, but this was the first method I tried, and I also wanted to try it the other way.

---

This brings me to my question; how do I avoid big switches in my message system? Should I just use enums?

My first suggestion was to create an unordered map of function pointers that define the behavior for a message, where the `MessageID`s would act as keys, so the initialisation function would be defined in some `init` function, like this:

```
typedef void* func(Message*) messageF;

std::unordered_map<MessageID,messageF> _messageMap;

void GUI_system::InitBehaviorFunctions()
{
    _messageMap[MessageIDMapper::findID("DELETE_HP")] = deleteHearth;
    _messageMap[MessageIDMapper::findID("PAUSE_GAME")] = showPauseIcon;
}

void GUI_system::handleMessage(Message* message)
{
    //Or the right way as this is just a sketch
    _messageMap[message->messageID](message);
}

```

# Answer
> 1 votes
If you go with `enum`s, you could just make an array of function pointers to call for each value instead of a `map`. Something like this:

```
typedef enum {
    Delete_HP = 0,
    Pause_Game,
    //... etc.
} MessageID;

```

Then the array of function pointers:

```
typedef void* function(Message*) messageF;
messageF msgHandlers[] = {
    deleteHearth,
    showPauseIcon,
    // ... etc.
};

```

Then your message handling function becomes something like:

```
void GUI_system::handleMessage(Message* message) {
    msgHandlers[message->messageID](message);
}

```

This is very similar to your `map` example, except there's no function call overhead for the lookup, and the setup is just adding the function name to the array in the correct position. It's harder to keep updated if you delete messages frequently, but very straightforward to understand.

---
Tags: c++, architecture, events, messaging
---


# Question
Title: How do I make spring animation for a 2D game?
I want to create a realistic spring object, as a sprite, that compresses and expands when a force is applied and released, respectively. The only thing I know is that it requires some complex animation, but have no idea how to do it. I'm using the Unity engine, but otherwise, it is a general question.

# Answer
> 1 votes
You might be over-complicating the problem. It sounds like you're really looking for a spring that does the following 3 things:

1. Compresses
2. Springs upwards
3. Springs upwards and sideways

Try using three simple animations and some simple code to recognise when each should happen. With a nice animation that springs up and wobbles both ways when horizontal pressure is applied, that covers both directions, and the down and up are simple enough.

This would take far less work, and make the solution much more reliable and less prone to error.

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


# Question
Title: Can you achieve a non-square look with tiles or a similar technique?
Just to explain the kind of look that is refered to in the question, it is apparent in the game Toejam and Earl 2.

Not asking how this was made but would like to know how you could efficiently blit a level design that isn't made or doesn't appear to look like easily identifiable square tiles. Another example for a "non-blocky" world would be worms but that looked more like a bitmap which sounds like it would require a lot of memory and could potentially limit the game world size.

# Answer
> 2 votes
The modern way to achieve this effect are polygonial "tiles", (they don't really have a name, but Unity calls them Smart tiles, more in this video).

Basically, instead of using squares, you create a polygon and fill it with a repeatable image. Then you can define on which parts of this polygon you want to have a different tileset covering the top, like a grass layer.

---
Tags: tiles, level-design
---


title: Weird behaviour dragging a UI Image

text:
# Question
Title: Weird behaviour dragging a UI Image
I'm making a classic card game in Unity. I created the first deck, and when I click on the top card, it is discarded and moved to a second card stack. When the first card stack is empty, then it is refilled, when it is clicked. Furthermore, I should to be allowed to drag and drop the cards in to the second deck.

My problem is that I can't drag and drop a card from the second deck until the first deck was refilled a first time and I don't understand why.

Why am I having this weird behaviour?

# Answer
> 0 votes
I solved the problem. I flip a card by a rotation quaternion, so the normal of the card will be in opposite position of the casted ray when I click. Since this a 2D project, I decided to simulate the card rotation by scale vector (by uniform scale on the x component).

---
Tags: unity, gui
---


# Question
Title: Instantiated objects sharing the same animator cannot animate independently?
I have two scripts and an animator. The first script is attached to an empty gameobject and creates eight plane (for use as cards). The second script runs a flipping animation if the plane/cards are click.

**Card Init**

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

public class cardInit : MonoBehaviour {

    List<Texture> cardFront = new List<Texture>();
    List<GameObject> cardList = new List<GameObject>();

    public GameObject newCard;

    Vector3 startPos;
    Vector3 endPos;

    // Use this for initialization
    void Start () {

        startPos = new Vector3(-10, 0, 0);
        Vector3 left = new Vector3(3 ,0 ,0);

        for (int i = 0; i <= 7; i++)
        {
            cardList.Add(GameObject.Instantiate(newCard,startPos,Quaternion.Euler(90,0,0)));
            startPos += left;
        }
    }

    // Update is called once per frame
    void Update () {

    }
}

```

**Card Flip**

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

public class cardScript : MonoBehaviour {

    private Animator animator;

    // Use this for initialization
    void Start ()
    {
       // animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                //gameObject.animator.SetInteger("onMouse", 1);
                gameObject.GetComponent<Animator>().SetInteger("onMouse", 1);
            }
        }
    }
}

```

However, since the instantiated objects all uses the same animator, changing the animator parameter to flip a single card causes all the cards to flip.

I believe the issue lies with the instantiated objects all referencing a singular animator rather than initialising a copy of its own. Is there a way to rectify it so each card only flips itself on click?

# Answer
The issue is not that you are sharing the same instance of the Animator. Each card has its own instance. The problem is that you are not checking what is being hit by your raycast:

```
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            // Here you are not doing any sort of check
            // The code below will fire for every single card on scene
            gameObject.GetComponent<Animator>().SetInteger("onMouse", 1);
        }
    }

```

What you want to do is check to see what card was clicked, and then set the animator of that card only:

```
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            // Check if you hit this object
            if (hit.collider == gameObject.GetComponent<BoxCollider>())
            {
                gameObject.GetComponent<Animator>().SetInteger("onMouse", 1);
            }
        }
    }

```

Although a much better way would be to have some sort of "CardManager" that would handle the click event across all cards.
> 2 votes

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


# Question
Title: requestAnimationFrame handles game ticks weird when tab isn't viewed
So i have the game logic and render in the callback for requestAnimationFrame, and somehow the ticks run very weird.

In fact, the rendering happens alright. But the ticks seem to skip an `if`, to be specific.

The questionable code moves the entity a few pixels until an amount of pixels is traveled.

When the tab isn't viewed the movement happens, and gets rendered correctly, but when going back to the tab i see that the movement went way to far and to make it more dubious, the entity travels back to its actual target position.

It feels a bit like the frames get rendered with the tick-function using kind of a state, like the variables keep the same value while the tab isn't viewed, and when viewing the tab again all the frames get played back reverse until the movement should actually stop.

Is there any reason for this and maybe a solution, too?

# Answer
Indeed, that's one of the "features" of requestAnimationFrame, it frees resources from not-focused tabs.

To use this animation method you should use deltatime to keep track of the time elapsed between frames so you can adapt your movement and calculations to that span.

```
int last;
int now = Date.now();
int elapsed = 0;

function Draw() {
  last = now;
  now = Date.now();
  elapsed = now - last;

  my_player.moveX(speed * elapsed);
  requestAnimationFrame(Draw);
}
Draw();

```

In this case, as you see, the player will move the same distance per second even if you are in other tab cause the real calculation will be done with the time elapsed between ticks instead of using the amount of ticks
> 2 votes

---
Tags: javascript, html5, game-loop, browser-based-games
---


# Question
Title: Unity - Ignore mouse click outside of the UI
I am having a problem with my in game UI menus like the pause menu.

When I hit the escape key the mouse cursor and pause UI is shown with 2 buttons "Continue" and "Exit". I have locked the player from moving when this UI is shown. But when I click outside of the buttons the mouse disappears and the player can move once again, the UI is still shown but it's lost focus or something.

Is there a simple way to stop this? I've seen some scripts which seem to try to catch this behavior and ignore the click but I'm hoping there is a property on the canvas or something that I can use built into the engine.

Thanks, Sam

# Answer
> 4 votes
Easiest way to handle this is to make a transparent background for your UI and let it catch the raycasts (if you're using them) or the mouse clicks so that the main game doesn't gain the focus of the program.

Another way would be to put an `if` on the mouse script you're using and reset focus to the UI after a click is made on anywhere but the UI (this will mean that the mouse will disappear momentarily and the player might be able to control stuff if you didn't do your pause checks properly).

I'd suggest using the first method. You could even add a blur effect (if you can manage to do it properly) to the layer of that background and give a more menu-like feeling. (this part is harder than it sounds)

---
Tags: unity, gui
---


# Question
Title: Unity - Creating light that's visible to a shader but not to the camera/player?
I'm writing a vertex deformation shader that can react to the presence of certain objects. Originally I was passing coordinates to the shader with SetVector, but from my understanding having the CPU set properties on a shader is somewhat expensive. So another idea I had was to have the shader react to light, and do some matrix multiplication to have the shader deform itself based on the intensity of the light hitting it. My question is, how could I approach writing a shader that would react to a light source, when that light would be invisible to the camera/player? In such a scenario I could write a fast & reasonably simple shader that could react to a special light source that would allow it to dynamically react to the light's location and distance. Only, such a light source would need to be invisible to the player, since its just being used as a representation of location and distance (with the added benefit of mixing multiple different sources easily). Or is there some other equally fast better way to do this that I'm not thinking of?

Thanks for the help!

EDIT: Imagine a shader that causes a surface to grow outwards when a certain type of object is near it, and its extrusion distance is proportional to the distance and "intensity" (some float) of the object. If there were several of these objects near the surface then it will form a pattern taking into account all of these nearby objects.

# Answer
> 3 votes
Given your edit and the comments about how you're using your data, you should probably look into packing the relevant object data (position, size, etc) into a Structured Buffer for use in your vertex shader.

Don't let the name fool you, the way to do this is through a compute buffer. https://docs.unity3d.com/ScriptReference/ComputeBuffer.html

To use, you create an array of the types on the cpu, set the buffer data, and then set it for the material.

You have a struct

```
//This struct exists in your shader AND in your script
struct data {
    float3 position;
    float3 scale
}

```

Your setup on the CPU

```
//CPU side
var objects = GameObject.FindGameObjectsWithTag("shaderstuff");
var dataArray[];

/*fill your data array here */

// struct has 2 float3's so it's 24 bytes
var buffer = new ComputeBuffer(dataArray.Length,24);
buffer.SetData(dataArray);
material.SetBuffer("dataStuff",buffer);
material.SetInt("_dataCount",dataArray.Length);

```

your gpu code

```
//put this with the rest of your uniforms
StructuredBuffer<data> dataStuff;
uniform int _dataCount;

```

now you can access your data (in your shaders) as if it were an array.

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


# Question
Title: How do I use coroutines to animate properly?
I have a coroutine, which I called from the `Update()` method on every click.

First, I call `AddTrunk()` to add to my `trunkList`, then I use my coroutine to move the animation for 0.3 seconds. After 0.3 seconds, it calls `Destroy()`, and then it changes `transform.position`. However, before completing the animation, it runs `transform.position`; it first my tree down *first*, and then does the animation.

---

This is where I call my coroutine:

```
void Update ()
{
    if (Input.GetMouseButtonDown (0))
    {
        AddTrunk ();

        if (!isRunning)
        {
            StartCoroutine (BranchOutAnimation ());
        }
    }
}

```

Here is the coroutine `BranchOutAnimation()`:

```
IEnumerator BranchOutAnimation()
{
    while (true)
    {
        isRunning = true;
        iTween.MoveTo (trunkList[index],
            new Vector3 (trunkList[index].transform.position.x
            - 5f, trunkList[index].transform.position.y,
            trunkList [index].transform.position.z), 0.3f);
        yield return new WaitForSeconds (0.3f);

        Destroy (trunkList [index]);
        trunkList.RemoveAt (index);
        transform.position = new Vector3 (transform.position.x, transform.position.y
            - treeHeight, transform.position.z);
        isRunning = false;
        yield break;
    }
}

```

---

What am I doing wrong?

# Answer
Calling `yield break` breaks the coroutine and the while loop in it won't start over again. The while loop goes through only once after waiting for 0.3 seconds. Use the `yield break` only when you want to break out from the coroutine. If you want the while loop to go through multiple times, try `yield return null;` which will just make the coroutine to wait for one frame.

If you actually want to run the whole code block only once, just remove the while loop as it would behave exactly the same.

Based on your code I'm guessing/assuming you want to grow the tree until there are no more trunks in the list, and finally just remove the whole tree. Here's some untested code to help you out:

```
IEnumerator BranchOutAnimation()
{
    // Make sure we are running only one coroutine
    if(isRunning)
        yield break;

    isRunning = true;

    // Which index did we start from?
    int trunkIndex = index;

    // Just make the animation interval configurable for easier modification later
    const float animationInterval = 0.3f;

    // Loop until instructed otherwise
    while (true)
    {
        // Do some nice animation
        iTween.MoveTo (trunkList[trunkIndex], new Vector3 (trunkList[trunkIndex].transform.position.x - 5f, trunkList[trunkIndex].transform.position.y, trunkList [trunkIndex].transform.position.z), animationInterval);

        // Make the coroutine wait for a moment
        yield return new WaitForSeconds (animationInterval);

        // Increase index of the animation
        trunkIndex++;

        // Check if we have reached the last index
        if(trunkIndex == trunkList.Count)
        {
            // Break the while loop, NOT the coroutine
            break;
        }
    }

    // Finally just remove the whole tree
    for(int i = trunkList.Count - 1; i >= 0 ; i--)
    {
        Destroy (trunkList [i]);
        trunkList.RemoveAt (i);
        transform.position = new Vector3 (transform.position.x, transform.position.y - treeHeight, transform.position.z);
    }

    isRunning = false;
}

```
> 4 votes

---
Tags: unity, animation, unityscript, coroutines
---


title: How Many Threads is 'Too Many'?

text:
# Question
Title: How Many Threads is 'Too Many'?
I writing this as I have run into a dilemma that I cannot readily answer.

> Specifically, how many threads is too many?

**Background tl;dr**:

* Writing a game (Surprise.)
* C++11, all server-side bits running on Linux server installs (headless)
* Login server and chat server are on a single server
* Database server/processing is its own server (eventually)
* The world server is the 'master' server, in which zone 'servers' (threads) are spun up. Each zone 'server' is responsible for a specific planet and all that entails (npcs, entity lists, etc).

With that brief intro, is there a point in which there are too many threads? Assuming there are 10 planets (zone "servers"), each with their own thread, would there be any extreme problems (not performance bottlenecks) that need to be accounted for in this type of situation utilizing an 8 core server? Would the same problem persist at 16 cores?

The end goal would be to allow for up to three "instances" of each planet, with maybe 20 planets (~60 threads) in the end. I understand that this could cause CPU contention as each thread is waiting for CPU cycles, but not enough to effectively hang the system (excluding a zone server locking up). If the game progresses to that point, 32 core servers would be an (expensive) option.

Is there anything that I am missing or not understanding?

Thank you in advance!

# Answer
**What matters is not the number of threads, but their CPU time**

Probably you do not need your threads to have full utilization. If you do, get better hardware. In fact, you can use CPU utilization as an ad hoc metric to decide when to improve your hardware.

Let us say that your server threads have to complete a tick each 50ms, yet, your CPU is fast enough that it can do the required computations in only 20ms. Now, you can afford to have a core switch between two instances, because each needs less than 50% utilization. You may want your threads to yield or sleep to archive this.

On the other hand, chances are you may have to compute things that do not fit in your tick. In addition, you may want to do those asynchronously, perhaps taking threads from a thread pool.

**Know how to scale your server**

Before you buy hardware for a public release, it might be good idea to do the following:

* Identify what are the performance variables (number of players, number of objects, size of the maps, etc…)
* Know your performance and requirements scale respect to those variables. You will know this from analysis of your algorithms.
* Estimate projections of those values for your public release (how many players will you support, etc…)
* Most importantly: measure the performance of your server (on the hardware you have, for known parameters). In such way, you can calculate how it will behave on a CPU X times faster with Y times more players, and so on…

This should give you enough information to know what hardware you need to start with, and some idea of how it will scale.
> 7 votes

---
Tags: c++, mmo, multithreading, linux
---


# Question
Title: What counts as a successful ad view in a mobile app?
There is one thing about mobile ads that I can't completely understand. Let's say I put ads in my free mobile game. **What counts as a successful ad view?** When it is just displayed on a user's screen or the user has to open the ad in order for it to count as viewed?

# Answer
It depends. The standard as of April 6, 2016 put forth by the Media Rating Council (MRC), Interactive Advertising Bureau (IAB), and Mobile Marketing Association (MMA) in their updated Mobile Web Measurement Guidelines and Mobile In-Application Measurement Guidelines call for "reasonable assurance that the ad was rendered on the device in order to count it as a valid ad impression." (as reported by MarketWatch).

That being said, guidelines may be adopted to varying degrees by providers. Generally the fine print of legal agreements, EULA, etc dictate what will & will not count toward monetization, unless trumped by law. When in doubt, read your contract &/or hire a lawyer for legal advice.
> 1 votes

# Answer
There are many ways you can monitise adverts. Different add providers will use different conditions or a mix.

The most common is click through, i.e if the user clicks through the game developer would get a small amount.

Video ads on the other hand are an example of where they would pay just for users to view the ad.
> 0 votes

---
Tags: mobile, advertisements
---


# Question
Title: How is custom-written music generally licensed for a small game?
I am relaunching my career as a game musician; previously I have done a little bit of licensed work and writing music for game jam-type games, after having written music as a secondary job duty for my full-time job at various game studios. As I am entering into the world of freelance game music composition, however, I am not sure what sort of license terms are common.

In particular, one developer I was in contact with wanted me to do the music entirely as a work-for-hire; I would retain the ability to showcase the music I do for him on my portfolio and the like, but I would not be allowed to, say, release a soundtrack album that contains the work, and he would retain the rights to re-license the music as he sees fit (including to other developers or for entirely different purposes). This doesn't seem to be in keeping with how I've seen other game music work, legally-speaking; if I do agree to these terms I would of course charge more than I would for music that is licensed, rather than sold.

I would, on the other hand, be totally fine with providing an *exclusive* game license for the music – that is, he would be the only one allowed to use my music within a game, but I would retain the rights for publication in other media. This seems to be how most indie game music is licensed, judging by how the original artists release their OSTs on Bandcamp and iTunes and the like.

Are there any standard contracts for game music licensing in various circumstances, or at least an explanation of the standard practices involved?

# Answer
Reposting this as a possible answer rather than a comment.

This is going to vary widely by publisher and whether you've created the music for the property (as opposed to licensing music you've already published), but I'd advise you strongly to go down the exclusive licensing route, and to be very specific about how your creative can be used (for *this* game and version on *these* platforms). Right off the bat licensing legally suggests a narrow usage.

Generally when you license music this way - beyond showcasing your work for self-promotion, and you should probably include a little language addressing that - you're giving up all rights to it and should expect to (e.g., they'll own soundtrack rights). Just make sure you'll get paid if it's used again in any way, or is *derived* for another platform or related work.
> 2 votes

# Answer
I don't know if there is a one size fits all solution for this. Generally it should be developers who will offer you a contract, and you need to decide if that contract will suit you. Here's helpful article from a developer's point of view on this.
> 0 votes

---
Tags: legal, music, business
---


# Question
Title: Why aren't my Unity rotations working properly?
I'm experiencing a rather annoying bug and I was hoping someone could offer some help because this just isn't making sense to me. I have a `Ballistic` script that tells the bullet to move in its local forward direction, which should be whichever way the gun is pointing. I have a `PlayerAttack` script that calls for a bullet to spawn with `OnShootEnter()`. It sets the bullets position to that of a `bulletSpawn` transform, which is a child of the gun.

`OnShootEnter()` is being properly called and `bulletSpawn` is properly assigned; and yet, when the bullet spawns, its facing `Vector3.forward`, instead of it facing `bulletSpawn.forward`. These are the only two scripts affecting the bullets spawn, rotation, and direction. Everything looks in order to me; what am I missing?

---

```
public class PlayerAttack : MonoBehaviour
{
    public GameObject bulletPrefab;

    public Transform gun;
    public Transform bulletSpawn;
    public float damage;

    void OnShootEnter()
    {
        GameObject bullet
            = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
     }
}

public class Ballistic : MonoBehaviour
{
    public GameObject model;
    public float range;
    public float accuracy;
    public float speed;

    Vector3 dir = Vector3.zero;

    void Start ()
    {
        model.transform.SetParent (this.transform);
        dir = transform.forward;
    }

    void Update ()
    {
        transform.GetComponent<Rigidbody> ().velocity = dir.normalized * speed;
        range -= Time.deltaTime;

        if (range <= 0)
            Destroy (this.gameObject);
    }
}

```

# Answer
> 1 votes
I have actually tested your scripts, and as far as I can tell, it works perfectly fine. I can rotate my gun, and shoot bullets out in the appropriate "forward direction". You can see this behaviour in the below screen capture, where I have ammended a custom editor script to provide a direct button to call `OnShootEnter()`.

### Why doesn't it work for me?

There is *one* element I can not account for; `Ballistic.model`. There is no explanation for this member, and the only logic applied to it is `model.transform.SetParent(this.transform)` in the `Start()` method. We know that this member reference *has* been set up, as the entire script will not run, without it.

### How could an additional child interfere with `transform.forward`?

I speculate that this is the source of your interference. I can only speculate, based off the name and logic, that this member represents the unique bullet model. In turn, I speculate that you have this model over the top of the game object containing `Ballistic`, and only need to ensure it is parented so it follows the movement and life cycle of your core `Ballistic` game object.

This should *not* be setting `transform.forward` to `(0, 0, 0)`; it *might* angle the game object, but not *specifically* to `Vector3.forward`. It might be possible that the rotation is being thrown off, and it only *appears* to be a deliberate `Vector3.forward` direction. This could be the result of moving two game objects that are on top of each other, which is even more likely given that the core `Ballistic` game object has a rigid body on it. It could also be the after effects of a bug, as I have personally encountered a fair few regarding the transform of an object with the addition of a new parent or child.

### How do I fix it?

If my speculation is correct, you should simply have the model directly attached to your `Ballistic` game object, regardless. You can then interchange the mesh in order to display different models. Alternatively, simply use the core `model` game object with an attached `Ballistic` script. There is really no reason why you would need two separate game objects for the functionality of a bullet.

# Answer
> -1 votes
You should try this in `OnShootEnter()`:

```
GameObject bullet =
    Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);

bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6;

```

# Answer
> -1 votes
`Vector3.forward` is not really a forward , as per official documentation, it is the shorthand for `new Vector3(0,0,1)`. That means that `Vector3.forward` will increase your `z` direction by `1`, *not* by your objects *real* "forward" .

`Transform.forward` is the blue axis of the transform, in world space. In other words, the blue line is the Z axis / direction of the transform, as per official documentation. If this thing is unclear, `transform.forward` means *only* move your object along the Z axis / direction.

*Z axis / direction* is like a compass; no matter your rotation, the north and south direction will have no change; the compass will still be pointing north and south.

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


# Question
Title: What programs could I use to render an animation based on points ("atoms") rather than models?
I've rendered the following animation using JavaScript and canvas:

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

For that, I used points exclusively - i.e., there is no mesh/trigs, not only the photons, but the geometry of the prism itself is made out of tons of small atoms. I then projected each atom to screen, ordered by depth and blended transparencies. I really like this atom-based rendering strategy, because it is very flexible, allowing me to create all sort of crazy geometries procedurally easily; doing the same for meshes would be hard. Obviously, this is way too slow on JavaScript/canvas, so it isn't really practical. I could do it with WebGL, but that'd be a lot of work.

Are there game engines and/or 3D software that I could use to make this kind of rendering strategy possible in an actual game? What exactly am I looking for? Is this a known pattern/feature? Keywords and references would be greatly appreciated.

# Answer
> 1 votes
This technique in general is known as Volume Rendering.

Most games use mesh rendering because it is very efficient in most use cases, but there are weaknesses, for example sculpting/carving, or representing very complex surfaces. In these few cases, volume rendering offers an alternative.

Volume rendering is mostly used outside games, because it's typically much more expensive. You find it in medical imaging, various scientific fields, where the graphics hardware is workstation-class or the rendering is non-real-time. So most volume rendering software is going to be too slow to do real-time games on commodity computer hardware.

Instead, the most common type of volume rendering you see in real games today is voxels, or blocks ala Minecraft. These games use a simple shape (e.g. a cube) that's used repeatedly to build complex shapes. With instancing, this technique is not that inefficient, but there are still hard problems, like culling, that make it much less efficient than regular surface meshes. This is why games that use voxels look so blocky - they must use large blocks otherwise the rendering will be too expensive.

One advantage with volume rendering is that it's very simple to do level-of-detail. A number of years back some people were talking about a solution called "Unlimited Detail". But there are a number of fundamental limitations with this approach that make it unsuitable for games.

---
Tags: 3d, animation, rendering, voxels
---


# Question
Title: Procedurally generated satellite view textures for large landmass rendering
I'm rendering a big land mass to be viewed from high altitude (40+ km), so I need satellite view style textures to be generated on the fly. The per vertex attributes I've got are:

* Biome (forest, snow, desert, mountain, etc)
* Elevation
* Moisture
* Temperature

Question is, is this even possible by solely shader code without any textures to sample from? It's downright impossible to find a decent looking texture pack for satellite view style textures. So far all techniques I've found were based on generating textures on existing terrain data, what I need is a procedural way to generate those on the fly per arbitrary terrain.

This is more or less the looks I'm aiming to achieve with already generated mesh and more biomes(tundra, desert, bare, shrubland, etc) and perhaps more "zoomed in":

# Answer
This looks remarkably similar to amitp's polygon map generator, which produces islands like this:

This was generated from scratch, no textures required. But as you'll find out in the article, he uses a variety of different techniques to get all the features in there: land formation, biome generation, placement of water features, noise filter. This won't be possible using pure shader code.
> 1 votes

---
Tags: textures, procedural-generation, terrain-rendering
---


title: Help creating a new gunfire code

text:
# Question
Title: Help creating a new gunfire code
I am working on a top down shooter project, utilizing the Tumult Hype program ( this means I cannot use Canvas and anything that works within canvas does me no good.) I have hit a small snag. The code I am working with only allows me to have 1 bullet on screen at it utilizes a single image that moves and then returns to it's default position after collision is detected or it leaves bounds.

I however need to write code that fires off duplicates of an ellipse I made as bullets ( so I can have multiple bullets at a time on screen) in the direction of the mouse, and detect collision with enemies moving on the screen and the games bounds.

That is a a bit above my skill level with javascript right now. I was hoping somebody might be able to show me the pieces I need, and provide just enough information for a beginner like me to figure out how to put the pieces together one my own. Any help would be greatly appreciated.

Here is my existing code, this is the part that fires on space bar press

```
var input1 = event.which || event.keyCode;

if (((input1 == "37") || (input1 == "49")) && (window.setLoopLeft == false) && (window.waveOver == false)) { // LEFT ARROW
    window.setLoopLeft = true;
    window.setLoopRight = false;
    window.intervalLeft = setInterval(moveLeft, 10);
} else if (((input1 == "39") || (input1 == "51")) && (window.setLoopRight == false) && (window.waveOver == false)) { // RIGHT ARROW
    window.setLoopRight = true;
    window.setLoopLeft = false;
    window.intervalRight = setInterval(moveRight, 10);
} else if ((input1 == "32") && (window.shotVisible == false) && (window.waveOver == false)) { // SPACE BAR
    window.shotVisible = true;
    hypeDocument.getElementById("laserBolt").style.visibility = "visible";
    hypeDocument.startTimelineNamed('laserFired');
    window.intervalShot = setInterval(moveShot, 5);
}

```

Here is the main function moving the shot

```
function moveShot() {
    var boltTop = parseInt(hypeDocument.getElementById("laserBolt").style.top);
    var boltLeft = parseInt(hypeDocument.getElementById("laserBolt").style.left);
    var motherShipStatus = hypeDocument.getElementById("motherShip").style.visibility;
    var motherShipLeft = parseInt(hypeDocument.getElementById("motherShip").style.left);
    // CHECK IF WENT OFF SCREEN
    if (boltTop == -14) {
        resetLaserBolt();
    // CHECK IF HIT MOTHERSHIP
    } else if   ((boltTop == 32) && (motherShipStatus == "visible") &&
                (boltLeft >= motherShipLeft) && (boltLeft < (motherShipLeft + 68))) {
        hypeDocument.getElementById("motherShip").style.visibility = "hidden";
        hypeDocument.startTimelineNamed('motherShipHit');
        updateScore(1000);
        hypeDocument.getElementById("motherShipScore").style.left = motherShipLeft + "px";
        resetLaserBolt();
    // CHECK ROWS 0 THROUGH 5
    } else if (boltTop == window.row0Bottom) {
        checkAlienHit(0, boltLeft, boltTop);
    } else if (boltTop == window.row1Bottom) {
        checkAlienHit(1, boltLeft, boltTop);
    } else if (boltTop == window.row2Bottom) {
        checkAlienHit(2, boltLeft, boltTop);
    } else if (boltTop == window.row3Bottom) {
        checkAlienHit(3, boltLeft, boltTop);
    } else if (boltTop == window.row4Bottom) {
        checkAlienHit(4, boltLeft, boltTop);
    } else if (boltTop == window.row5Bottom) {
        checkAlienHit(5, boltLeft, boltTop);
    // CHECK IF HIT BARRIER
    } else if  ((boltTop == 542) && (window.barriersVisible == true) &&
                (((boltLeft > 158) && (boltLeft < 192)) ||
                ((boltLeft > 254) && (boltLeft < 288)) ||
                ((boltLeft > 350) && (boltLeft < 384)) ||
                ((boltLeft > 446) && (boltLeft < 480)))) {
        resetLaserBolt();
    // HIT NOTHING. MOVE IT UP BY 2 PX
    } else {
        boltTop = boltTop - 2;
        hypeDocument.getElementById("laserBolt").style.top = boltTop + "px";
    }
}

```

This is code I used and messed with to simply make a bolt move, but it only takes a rectable object and makes it move until it collides with one of the objects on screen or leaves the bounds.

I need it to fire in the direction of the mouse when the left mouse button is clicked. My main issues if really just figuring out how to make an object spawn ( instead of making a single existing object move ) and have it move in the direction of the mouse. All code is formatted to work in hype since that is the program my partner wanted to experiment with.

# Answer
> 0 votes
OK it's a shooter so you definitely need to create a bullet pool. The game is firing only one bullet because there's only one bullet (see how you are getting the laserBolt by getting it's **ID**).

Now that we know what the issue is, we can easily fix the issue. To be more specific, you can easily fix the issue (I'm sadly not very well versed when it comes to Tumult Hype).

You can accomplish this like so:

```
var bulletPool = [];

for (var i = 0, numBullets = 20; i < numBullets; i++) {
  // You can create a div or whatever element you are using
  var bullet = document.createElement('div');

  // You won't be needing an ID or class attribute since you'll know where the elements are stored (in bulletPool)

  // We set the hidden attribute which acts as a way for us to know if the bullet is still alive. This is important when we are about to shoot
  bullet.setAttribute('hidden', true);

  // We then push it into the array...
  var index = bulletPool.push(bullet) - 1;

  // This will place the element in the body element
  document.body.appendChild(bulletPool[index]);
}

// making sure that the bullet pool is working
document.getElementById('totalbullets').innerText = "Total Number of bullets created: " + bulletPool.length;

// You can then shoot like so

function shoot() {
  var bullet = getFirstDeadBullet();

  // Make sure you have bullets available...
  if (bullet) {
    // ... you have a bullet available, now do your movement and collision checks here
  }

}

function getFirstDeadBullet() {
  for (var i = 0, length = bulletPool.length; i < length; i++) {
    if (bulletPool[i].hidden === true) {
      // Our bullet isn't on screen so we can use it
      return bulletPool[i];
    } else {
      return false;
    }
  }
}
```

```
<div id="totalbullets"></div>
```

You'll want to of course do all this in some function, not the global scope like I did lol.

But anyway, hope this helped. You can see a much better example here. The example is based on a canvas game but the concept is still the same.

Tell me if you need anything else! GODSpeed!

---
Tags: shooter
---


# Question
Title: What is the optimal way to store customisation options?
I am trying to understand the most optimal way of storing customisation options within a game, or to be precise, to store all the possible customisation options for multiple different objects.

For example, assuming we are making a game about tanks and their customisation, there will be several available tanks that the player can choose from and each of the tanks will have multiple different parts available; some parts will be shared across a few tanks, while some will be specific to a tank.

I was thinking about a relational database, but I do not know web development, so I was initially thinking to have a table with all the tanks and a table with all the parts, then create a linking table between the two and load the available parts based on the chosen tank; but I'm not sure if that would work, or if it would be the most optimal way of doing this.

I tried looking for an answer, but I'm not getting any good results. People mention using files, and then parsing the data, but I'm not sure how that will work on a large scale; multiple tanks with hundreds of customisation options.

What is the most optimal way to to do this? If at all relevant, I am using Unity 5.

# Answer
With the notable exception of massive-multiplayer games (persistent world shared by thousands of players), relational databases are very rarely used in game development. In a single-player game, there is little reason to use one. You have only one user, so you don't have to worry about consistency or transactions. And the data is already on the user's hardware, so you don't need to worry about loading times, bandwidth usage or security implications of loading data into the frontend which the user doesn't need at the moment.

Fixed data (like the stats of different items) and player preferences (keybinds, mouse sensitivity, music volume etc.) is usually read from config files on game start and kept in memory while the game is running. Very few games have so much data that the target platform couldn't handle that. Regarding the structure of these files: I have seen people use JSON, XML, YAML, INI, CSV or some homebrewed markup formats. I would always recommend to use something you have a library for, because writing good parsers is far more work than you would think at first (and also it's boring). Savegames are also loaded in one go and deserialized to the game state when the savegame is loaded.

Unity gives you another option by allowing you to create types of custom data-based assets in form of ScriptableObject's. That means you can have a folder "Tanks" and a folder "Tank Parts" in your Unity project, create and delete entries in them and edit their properties right in the Unity editor which you can enhance through editor scripting. There is also a video tutorial.

The only place where a relational database *could* make sense is when you have a dataset which is so huge that it doesn't fit into memory. The only candidate for this is usually the geometry of the game world. But most games rather create a custom file structure for this instead of using a relational database, because most RDBMS are not designed for spatial data.
> 3 votes

---
Tags: unity, c#, architecture, storage
---


# Question
Title: Drawing Sprites Depending On Mouse Position (LibGDX)
I'm making a small game where you play as a turret in the middle of the screen trying to shoot the enemies coming after you. I am having difficulties, however, in trying to figure out how to make the turret change sprites depending on where my mouse cursor is pointing. I don't want to rotate the sprite, mind you, as I already have made different variations of the same sprite for the different directions it will face:

I have an idea of how to accomplish this, but I don't know how to make it happen:

* The program generates 42 rays, (one for each turret sprite), that originate from the turret
* If the cursor falls between two of those rays, a specific sprite will be drawn

How would I go about doing this? It doesn't have to be the method described above as long as it produces the same result.

Thanks for your help in advance!

Plug

# Answer
The way I do this is by getting my mouse relative to the player by converting the mouse to screen coordinates.

```
Vector3 pos = new Vector3(Gdx.input.getX(),Gdx.input.getY(), 0);
cam.unproject(pos);

    mouseRelativePlayer = new Vector2(pos.getX() - sprite.getX(),
    pos.getY() - sprite.getY());

```

Next I use the variable mouseRelativePlayer to determine which direction to set my player.

```
if(player.mouseRelativePlayer.y > 01)
            player.direction = Entity.Direction.UP;
        if(player.mouseRelativePlayer.y < -01)
            player.direction = Entity.Direction.DOWN;
        if(player.mouseRelativePlayer.x < -01)
            player.direction = Entity.Direction.LEFT;
        if(player.mouseRelativePlayer.x > 01)
            player.direction = Entity.Direction.RIGHT;

```

And for diagonals just do the same but with different values.
> 0 votes

---
Tags: libgdx, mouse
---


title: C++ structure for component list

text:
# Question
Title: C++ structure for component list
I'm developing a game in C++, making use of the Entity-Component system.

I'm going to store a list of each component, with each component's position in the list mapping to it's entity. So, the 5th item in the list is a component for Entity 5, etc.

My inspiration came from this:

https://www.gamedev.net/resources/\_/technical/game-programming/implementing-component-entity-systems-r3382

My question is what data structure is the best for this. I guess my options are an array or a vector of `Component`s. When using either the array or the vector, is it possible to have empty elements. So, for example element 0, 1 and 4 might contain components, but positions 2 and 3 empty. I know I could achieve this with pointers to components, but is this the best way?

Advice appreciated.

Thanks, Rich.

# Answer
> 2 votes
Given the constraints (unknown number of components, components can be added or removed at runtime, components have different memory footprints, components derive from the same class), the straightforward solution is:

```
std::vector<std::unique_ptr<IComponent>>

```

One could argue in favor of another container that provides constant time insertion and deletion, but I don't think that's actually necessary or even beneficial. For a small number of elements, vector insertion and removal is faster than list insertion and removal.

It can be expected that the container does not ever contain empty elements.

# Answer
> 0 votes
In the game I'm making, which is not pure ECS, but something between it and common design (object oriented), I have two main types of components: 'standard' and 'extended'.

Standard are for example position, speed, health... which are common to almost all the entities and so are stored in simple arrays: there will be few gaps and can easily be iterated. Components of the same entity share the same index in the arrays and so is easy to retrieve them and create interactions.

Extended components are instead stored in arrays at the first slot available: there will be few "teleport\_on\_collision" entities and I can't afford to have one component at 1° slot, one at 10° and one at 23°, it would be a pain for the cache, while iterating them. So they are stored in the first free slots and each owner entity keeps in a vector (actually a linked list allocated into an array shared between all the entities) the list of extend components it has (pairs of 'type', 'slot'). Lookup is slightly slower because you have to search in this array if a component exists and in that case, get its index, its type and then get it. I'm implementing a message system to communicate between standard and extended components to avoid dependences: extended components are generally implemented after basics one which, so, can't know they existence and implementation: you just propagate messages such as "on\_hit" to them and they will react on their own. I decided to use this approach because, generally, you don't fire many messages each frame, but usually you need to update each component each frame, so linear lookup into a continuous array is what you have to aim for.

I hope I've been clear, English is not my main languages.

I'm just testing this approach and I'm not sure it's the best way, but I think this text is too long to be a simple comment. (I would like to have comments and criticisms)

---
Tags: c++, vector, entity-component
---


# Question
Title: Transform existing C++ OpenGL project from glut/glew to GLFW
Is it possible to easly transform existing glut/glew to GLFW API?

# Answer
> 1 votes
Yes, it is very easy. GLFW even uses callbacks for things like mouse/keyboard/controller input events, similar to glut, so the program can follow the same basic structure more or less. I use GLEW with GLFW, so no difference there.

---
Tags: opengl, c++, glut, glfw, glew
---


# Question
Title: How to Continue the state of Unity Game Scene
I am developing a simple Unity 2D game. During the development of Level One, I wanted the scene to continue after the player is triggered by the enemy and dead util the given 5 lives are completed. When I add Coroutine, it reloads the whole scene and I don't want that...I just want to continue its life from the last hit. So how can I make the scene continue until it loses the whole 5 lives?

```
void OnTriggerEnter2D (Collider2D col) {
    if (col.gameObject.tag == "Player" ) {
        health.CurrentVal -= 1;
        Explode ();
        if (health.CurrentVal != 0) {
            StartCoroutine ("ReloadGame");
        } else {
            StopAllCoroutines();
        }
    }
}

```

Thanks!

# Answer
> 1 votes
> tldr; Don't reload your scene if you don't want it to go away and start fresh.

---

This sounds like it has nothing to do with the concept of a `Coroutine`.

I assume you're reloading the current scene. Instead you should simply respawn your player. You can either:

1. Reset its stats, animations, etc... and physically move him
2. Destroy and re-create the player object at the spawn location

How exactly you do this is highly dependent on how you have your particular game set up. If you go with option #2 you'll need to ensure things like the number of lives you have aren't stored directly on a script attached to the player object else they'll get destroyed and reset as well.

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


# Question
Title: What is the difference between a mat3 and a float[9], in terms of size?
In my GLSL Compute Shader, I've declared a struct called `ParticleData`, and when I read in part of my buffer as a `mat3`, the size (which I assess by looking at the output) is different than if I use a `float[9]`.

I haven't been able to find a definitive source explaining the `mat3` structure. he data I'm writing to my buffer is simply 9 floats, stored in an `std::array<float,9>`.

What is the difference between a `mat3` and a `float[9]`, in terms of size?

# Answer
> 4 votes
It all depends on the GPU and driver.

Due to the way many GPUs work a mat3 may be padded internally to take 12 floats of space arranged as `[x0, y0, z0, pad][x1, y1, z1, pad][x2, y2, z2, pad]`.

A float\[9\] will take 9 floats of space but then may effectively be padded (or not) to 12 floats by adding 3 floats of padding at the end `[0, 1, 2, 3, 4, 5, 6, 7, 8][pad, pad, pad]` for the next data to align properly. Although those don't count as part of its size the next data item may start after the padding.

This is because some GPUs can only access data aligned to 16 bytes (4 floats) or are otherwise very limited in how they can access the data for performance reasons.

Some more info from the official OpenGL site: https://www.khronos.org/opengl/wiki/Interface\_Block\_(GLSL)#Memory\_layout

---
Tags: glsl
---


# Question
Title: Convert quaternion to a different coordinate system
OSVR has a right-handed system: x is right, y is up, z is near.

I need to convert orientation data from a sensor in OSVR to a different right-handed system in which x is forward, y is left, and z is up.

I need to calculate the transformation that will convert a quaternion from one system to the other.

I naively tried:

```
void osvrPoseCallback(const geometry_msgs::PoseStampedConstPtr &msg) { // osvr to ros
    geometry_msgs::PoseStamped outputMsg;

    outputMsg.header = msg->header;
    outputMsg.pose.orientation.x = msg->pose.orientation.y;
    outputMsg.pose.orientation.y = msg->pose.orientation.z;
    outputMsg.pose.orientation.z = msg->pose.orientation.x;
    outputMsg.pose.orientation.w = msg->pose.orientation.w;

    osvrPosePub.publish(outputMsg);
    ros::spinOnce();
}

```

But that made things really weird. Facing north pitch is pitch, facing west, pitch is yaw, facing south, pitch is negative pitch...

How can I convert my OSVR quaternion to the a corresponding quaternion in the new coordinate system?

# Answer
Summarizing your two coordinate spaces:

```
direction   OSVR    Output
------------------------------
right         x      -y
up            y       z
backward      z      -x

```

And since they're both right-handed, the sign of the angles does not change.

So to map from OSVR to the output coordinate system, we just map the letters as above:

```
outputMsg.pose.orientation.x = -1 * msg->pose.orientation.z;
outputMsg.pose.orientation.y = -1 * msg->pose.orientation.x;
outputMsg.pose.orientation.z = msg->pose.orientation.y;
outputMsg.pose.orientation.w = msg->pose.orientation.w;

```

Or, to go the other way and convert into OSVR's system, we flip it:

```
outputMsg.pose.orientation.x = -1 * msg->pose.orientation.y;
outputMsg.pose.orientation.y = msg->pose.orientation.z;
outputMsg.pose.orientation.z = -1 * msg->pose.orientation.x;
outputMsg.pose.orientation.w = msg->pose.orientation.w;

```
> 5 votes

---
Tags: rotation, coordinates, quaternion, vrpn
---


title: Function call time

text:
# Question
Title: Function call time
I'm making a game and I want an update method to be called every 120th of a second. I've looked up timers but they start the timer after the function has returned, but I want the timer to start when the function is called. Any suggestions?

# Answer
> 0 votes
*I do not know what timer solution you are using, in fact, I am not very familiar with the options available to you.*

---

Let us say you have a re-scheduled timer of the form (pseudo code):

```
int callback()
{
    doSomething();
    schedule_timer(callback, interval); // interval declared outside
}

```

In this case, callback isn't really running at `interval`, but at `interval` plus the time `doSomething()` takes, plus any time lost in calls or being preempted.

You might want to know the time at the start of the call, and use that to compute the time for the next interval.

Since you want to skip calls that do not fit into the interval, the time until the next call must be a multiple of `interval` (if the time is just a bit over, you skip until the next interval).

For example (pseudo code):

```
int callback()
{
    auto now = time_now();
    doSomething();
    auto elapsed_time = time_now() - now;
    auto next_time = interval - (elapsed_time % interval);
    schedule_timer(callback, next_time);
}

```

Of course, there would still be some overhead. This overhead comes from the time the computation takes, the function call, and any variation introduced by the timer itself.

You can solve that by moving the instructions around:

```
int callback()
{
    doSomething();
    auto new_now = time_now(); // time is measured around this point
    auto elapsed_time = new_now - now; // now declared outside
    auto next_time = interval - (elapsed_time % interval);
    now = new_now;
    schedule_timer(callback, next_time);
}

```

Now, you may encapsulate this logic away:

```
int callback()
{
    doSomething();
    schedule_next(callback);
}

```

As you have seen, I have said that `interval` and `now` are declared outside. In practice you may create a class that is initialized with `interval`, and takes the initial `now` value. If this class also takes the `callback` pointer, it can wrap the call with the necessary code to invoke it at stable intervals, skipping calls if it takes too long.

---

I see you tagged this with “game-loop”. You can totally use your game loop to schedule calls, what you need is to keep a sorted structure from where you can pull the next timer to go up, and if it has gone up, call it.

Of course, that would be single threaded and would be eating time from your game loop, the calls would NOT run in parallel. If you want calls to run in parallel, you would have to schedule in the timer a call that invokes what you want but to run from a thread pool.

There would be some overhead due to thread pool, but the good thing about this is that you do not have to wait for your invocations to complete because what is scheduled is the call to the thread pool, which returns immediately. Thus you can (if you want) code it to reschedule immediately, or you can push to the thread pool a call that wraps the invocations you want and reschedules at the end, whichever you prefer.

---
Tags: c++, game-loop, timer, linux
---


# Question
Title: How do I load an array of display objects with shared objects using action script 3.0?
I'm making a city builder game, where players can build their town using different constructions. A player has the possibility to save his city. In the main menu, a player can choose to see different cities of others players.

When a player want to save his city, a button is clicked and an array that contains all the display objects (so all the buildings) must be saved in a `sharedObject`. I've tried this solution, but it doesn't seem to work. I don't know how to load this type of array, because I've been told that I can store only plain data types in a shared object.

this is the sample code:

```
var SO:SharedObject=SharedObject.getLocal("myFile", "/");
var arr:Array=new Array();
var counter:Number=-1;

addBtn.addEventListener(MouseEvent.CLICK, addObjects);
saveBtn.addEventListener(MouseEvent.CLICK, saveObjects);
loadBtn.addEventListener(MouseEvent.CLICK, loadObjects);

function addObjects(event:Event) {

    counter++;
    var circle:circleClip=new circleClip();
    arr.push(circle);
    trace("current object: "+arr[counter]);
}

function saveObjects(event:Event) {

    SO.data.arrSaved=arr;
    SO.flush();
    trace("objects saved: "+SO.data.arrSaved);
}

function loadObjects(event:Event) {

    var arrLoaded:Array=new Array();
    arrLoaded=SO.data.arrSaved;
    trace("objects loaded: "+arrLoaded);
}

```

# Answer
> 0 votes
# You can't

Sorry. But SharedObjects can't actually serialize *movieclips.*

Quoting myself from 2010 (I was quite the AS guru back then):

> You need to individually save each variable the MC has (x and y position, etc) so you load them back in.

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


# Question
Title: how to make client and server to develop independently?
Currently, all i want to do is rapid prototyping of Tower-Defense-Like game, which means that i just need write client code only,single player, play with AI system. but shortly afterwards, maybe it's going to be a multiplayer game . my question is how can i design my game architecture suited for singleplayer mode firstly, and for multiplayer mode latterly, it doesn't mess up my previous effort(single player only). any design pattern, or architecture , or hint?

I really appreciate for your answer, thank your guys in advance. Have a good day!

# Answer
Use a model-view-controller pattern.

* Your Model is the current state of your game (how the map looks, which enemy is where, which tower is where, etc.)
* Your View is your graphics engine which visualizes the Model to the player
* Your Controllers are the game mechanics (which spawn enemies and make towers shoot at them) and the input handler for the player's commands.

Encapsulate all these modules against each other so that they interact with each other only through method calls. They should act as total black boxes to each other and make no assumptions about the implementation details of each other ("Loose Coupling").

Now if you want to make the game multiplayer, you can just add the network output as another View and the network input as another Controller.
> 1 votes

# Answer
I'd do it the other way around... It cost nothing to think on it as if it'd be already an online game by:

* having your logic isolated and comunicating with it via API: The point here is to be sure you only need to add server conection and a gateway on your app to do the same you do now against a real server. In MP games, the logic has to be in the server, in this case, if your logic lies out of the "scene" (in an isolated standalone module) it'll work exactly as a MP would do, but without network stuff
* separate states: In online games you need different states (usually) pointing to different endpoints or connected to sockets (your game-browse loby could use API calls but your game UDP sockets) this is not possible if your game states are all in a gigant switch/nested ifs. Build a StateMachine so you can switch between scenes and treat them as indepentent logic applications.

Once your game is done, you only have to write your server connection stuff and face the sincronization/connection issues
> 0 votes

# Answer
There are a couple of patterns that help here. The first one is the **Command** design pattern, where instead of directly coding to hardcoded keys you create objects that can operated. This is very useful for reconfiguring input controls or adding AI to control characters. It also makes it easy to send the input to other computers (since you don't care where the input came from).

This is very well explained in this chapter of the **Game Design Patterns** book which you can read online.

Another pattern that is useful is a logic/view architecture that uses events to communicate between the layers. Again the logic layer does not care where the input comes from. A great explanation of this architecture is in the second chapter of the **Game Coding Complete** book (where he talks in general about the game engine architecture) as well as in the implementation.
> 0 votes

---
Tags: architecture, networking, design-patterns
---


# Question
Title: In Final Fantasy VII, how are primary stats calculated upon level up?
I'm creating a stat level up calculator for Final Fantasy VII, and was reading through a guide.

For leveling up on primary stats, it says "This difference is then capped at 0 to 11 inclusive", however I see the number can be calculated above 11, when testing with my java code:

```
// Dexterity
// cloud starting level(6)
int levelUp = 7;
// cloud starting dexterity at level 6
dex = 6;
// cloud rank curve is 6 (for dex), and is within 2-11 levelUp bracket,
// so 6 is the number on table
baseNumber = 6;
// cloud rank curve is 6 (for dex), and is within 2-11 levelUp bracket,
// so 72 is the number on table
gradient = 72;

baselineStat = baseNumber + ((gradient * levelUp) / 100);

randomStatDifferenceOne = 1 + baselineStat - dex;
randomStatDifferenceTwo = 2 + baselineStat - dex;
randomStatDifferenceThree = 3 + baselineStat - dex;
randomStatDifferenceFour = 4 + baselineStat - dex;
randomStatDifferenceFive = 5 + baselineStat - dex;
randomStatDifferenceSix = 6 + baselineStat - dex;
randomStatDifferenceSeven = 7 + baselineStat - dex;
randomStatDifferenceEight = 8 + baselineStat - dex;

System.out.println(randomStatDifferenceOne);
System.out.println(randomStatDifferenceTwo);
System.out.println(randomStatDifferenceThree);
System.out.println(randomStatDifferenceFour);
System.out.println(randomStatDifferenceFive);
System.out.println(randomStatDifferenceSix);
System.out.println(randomStatDifferenceSeven);
System.out.println(randomStatDifferenceEight);

```

This gives me the following results with `Rnd(1-8)`:

> 6
> 7
> 8
> 9
> 10
> 11
> 12
> 13

In the guide, he has the following level up stats calculated for the different numbers (that should only be 0-11):

> * Difference | Stat Gain
> * 0-3 | 0
> * 4-6 | 1
> * 7-9 | 2
> * 10-11 | 3

In Final Fantasy VII, how are stat numbers above 11 and below 0 handled?

# Answer
> 1 votes
> This difference is then capped at 0 to 11 inclusive

means that when the difference is smaller than 0, it is set to 0 and when it is larger than 11, it is set to 11.

Example:

```
randomStatDifferenceOne = 1 + baselineStat - dex;
if (randomStatDifferenceOne < 0) {
    randomStatDifferenceOne = 0;
}
if (randomStatDifferenceOne > 11) {
    randomStatDifferenceOne = 11;
}

```

Disclaimer: That's what *the guide* says. I have no idea if that's how FF VII actually works.

By the way: Whenever you start naming variables `VarOne`, `VarTwo`, `VarThree` etc., you should really be using an array or an ArrayList. Whenever you want to do something with all of them, you should be using a for-loop.

---
Tags: java
---


title: How to solve a pow equation?

text:
# Question
Title: How to solve a pow equation?
I have an formula that generates a number from 20 to 180 (degree).

```
var a = 20 * Math.pow(str/dist, 1.5));
    a = Math.max(180, w);

```

Using this formulae, i can generates some arcs and draw them just fine and depending on `dist` (which is cursor distance from target), the arc is either very wide, or narrow (pow basicly makes it so the arc expands non-linear).

This approach works in one direction: Having a location, and a distant point, to create arc. I need a counter-equation that gives me the required DIST for a given angle.

i.e. assuming `str` is 800, what is the value of `dist` so `a` would be 114 (or 68 or anything).

```
114 = Math.pow(900/dist, 1.5)) // ????

```

How can i solve this equation for dist ?

thanks,

# Answer
I'm going to disregard your `max` line for a moment (did you mean `min`? Written with a `max`, any values in the 20-180 range you described will come out as 180, since `max` returns the greatest argument)

We can solve this step by step by reversing each operation. Starting with the multiplication by 20:

$$ \begin{align} a &= 20 \times{(\frac{str}{dist})}^{1.5} \\ \frac a {20} &= {(\frac{str}{dist})}^{1.5} \end{align} $$

The opposite operation of a power is a corresponding root. So to undo a square \\$ x^2 \\$ we'd take a square root \\$ \sqrt {x^2} = x \\$, often available as its own function, `sqrt()`. For less common roots, we can use `pow` as its own inverse, using the fact that the `n`th root of `x`, \\$ \sqrt\[n\]{x} \\$, is just `x` to the power of `1/n`:

$$ \begin{align} \frac a {20} &= {(\frac{str}{dist})}^{1.5} \\ {(\frac a {20})}^{\frac 1 {1.5}} &= \frac {str} {dist} \end{align} $$

And taking the reciprocal to get \\$dist\\$ on top (which is the same as negating the power), then multiplying both sides by \\$str\\$...

$$ \begin{align} {(\frac a {20})}^{-\frac 1 {1.5}} &= \frac {dist} {str} \\ str \times {(\frac a {20})}^{-\frac 1 {1.5} } &= dist \end{align} $$

Or in code:

```
dist = str * pow(a / 20.0, -1/1.5)

```
> 2 votes

---
Tags: mathematics
---