# Question
Title: Can inflation exist in a fixed price Mmorpg world?
Assumptions:

* Crafting materials are infinite. Limit is player boredom.
* Players can only trade through the auction house. All prices are fixed. Players cannot decide arbitrary prices.
* Goods in auction house stay stored for infinite duration and cannot be withdrawn by auction creator (except if he pays 100% item price + 10% auction fee).
* Sell algorithm is FIFO (First item placed by any player is first item sold).
* Crafting and gathering professions have a cool-down of 10 craft points per day.

Questions / Points to talk about:

* All players will be happy, fair 100% prices, scam free, no need to play stock exchange market to make a profit through crafting. New Players would have the same experience even if they arrive too late to the game.
* Money never loses its value, you could store money in a bank, arrive after 10 years to the game and buy everything at the same price. In contrast in WOW, a simple copper ore was worth 10 silver at the game start and now has ended as 200 silver. That's 2000% inflation.
* By having fixed prices, you guarantee that even if all players in the universe have 99999999999g in their pocket, the goods are worth the same. So that's guaranteed 0% inflation. Hackers may cry all they want, but goods prices will never change.
* Why didn't WOW / Diablo III used this model? They would have become billionaires with the 10% money grab technique.

---

Btw: my previous question on economy overflow was never answered, probably that site is dead. https://economics.stackexchange.com/questions/14609/understanding-inflation-in-a-video-game

# Answer
> 27 votes
Publilius Syrus clearly stated it already in ~100 BC: *Everything is worth what its purchaser will pay for it*. Adam Smith explained why: prices represent an intersection of supply and demand curves.

You ignore the basic fundamentals, with a result we know all too well from failed non-capitalist economies: there's simply excess demand or excess supply. What's the point of a a bag of ore "selling" for 100 silver, when there's a 1% chance of the ore being sold? That's an **effective** price of 1 silver, no matter what you tried to establish. If I put up 1000 bags of ore, I can expect about 10 sales, 1000 silver, not 100.000. The excess supply will simply not be sold. And with your "no take back" rule, there's 990 bags of ore gathering dust in the back of the auction house. That means my 1000 ores are permanently gone, all for 1000 silver.

In reverse, if a product has a player value of 200 silver, and a fixed price of 100 silver, there won't be any sales at 100 silver, making that fixed price equally meaningless. E.g. if I can turn those 1000 bags of iron ore into iron bars which sell for 200s, then who is going to bother selling raw ore? (Assuming a pure economic choice, i.e. no XP gains for smelting iron or similar non-economic reasons)

Inflation is a shift in the point where goods are *actually* sold, the point where supply and demand are equal, where the supply and demand curves cross. These are factual curves determined by the real economy. Just wishing that the curves are fixed does not make it so. This is the main lesson from all those failed non-capitalist systems: *Thinking something does not make it true. Wanting something does not make it real.* (Michelle Hodkin).

# Answer
> 58 votes
The problem with this system is that it just fights the symptom, not the cause.

Inflation means that money loses value, because players have too much of it. It's not the items which become more expensive, it's the money which becomes less valuable.

When nobody needs money, they won't sell anything to the trading house (I won't call it "auction" house, because it is no auction when the price is fixed). There is no need to do so when they already have more money than they could ever spend. There are certainly a hundred other things to do in your game (I hope) which are more fun and more rewarding. When items can only be sold far under their actual value due to price fixing, people can just as well throw them away or hoard them in case they might ever become more useful. Even placing them in the trading house is more work than they would get out of it.

This will lead to a shortage of items in the trading house. Nobody is going to farm and craft the items other people need, because it's simply not rewarding to do so.

The item shortage will be further amplified due to the market power of your veterans with their 99999999999g purses. A high-level player can simply buy up the whole supply of a scarce good at once just because they are bored. When there are 2000 ore on the market for 1g each, they can just buy them all up and still have 99999997999g. Spare change for them, but they screw up the game for a ton of newbies to whom those ores are important. Why would they do that? For the lulz! Online gamers love trolling. When there is an easy way to grief other players, it *will* be used.

That means the newbies in your game will still be unable to buy stuff. Not because the prices are too high but because there simply is nothing to buy in the trading house.

**Bottom line:** You can not create a fair economy by not giving the players a trading system which allows to trade goods at their real economical value.

So what else can you do?

This wasn't asked in the question, so I am not going to spend any time on musing about money sinks, alternative currencies and wealth-by-level curves. Especially because we already have a very good question about this. But Extra Credits made some videos about how to balance ingame economies in MMO games which might be very interesting to you:

# Answer
> 3 votes
Nowhere in your description is there a source of silver/gold. There would be no money for anybody to buy anything. In the end, it would just be a single-player game of crafting. This was probably not what you had in mind.

So, let us assume you have some source of money. If you aren't careful about it, this leads to money piling up on higher-level players. That can be OK, if the game is challenging in other ways.

When you fix the prices, there really is no point in having players trade with each other. Just let them sell goods at one price and buy them at a higher price. No need to fiddle around with trading house inventories.

This is a *good thing*. It means that a high-level player can buy a potion of Godhood even if no crafter has made one. That takes money out of the system.

On the downside, you no longer have a multi-player game.

Making the economy single-player like this is much *simpler* for the game companies than making auction houses. When they make auction houses it is because they think it makes the game better. They may be right about that, if they are careful in their implementation.

# Answer
> 1 votes
No, because inflation is defined as a sustained rise in prices. If prices are fixed by the rules of the game, you cannot have inflation, by definition.

But if you have such fixed prices, the economy won't work very well. If an item is actually worth X and it can only be sold for Y, then nobody will want to sell it.

The MMORPG *Runescape* had a similar system where players could trade directly with each other, but there were price limits on items and trade limits were in place: trades couldn't be too imbalanced. The game developers essentially set the trade values of items directly. Players would trade a very valuable item to another player for more than the game thought it was worth by trading junk that is overpriced by the game along with the item they wanted to trade that was underpriced by the game, which evened out to the right total price.

For example, if the game considers a high level Sword to be worth $1m, and an unstrung bow to be worth $100, but players value the Sword at $5m and the unstrung bow at $5, then a player can buy a Sword from another play for $5m by trading $5.2m for a sword and what the computer thinks is $4.2m worth of unstrung bows: 42,105 of them. The computer values the trade at $5.2m because $1m + 42105 x $100 = $5.2m, and the players value the trade at $5.2m because $5 + 42105 x $5 = $5.2m. By the way, 42105 is (5m - 1m) / (100 - 5).

The computer inaccurately valuing items didn't actually prevent players from trading, it just made trading more difficult.

---
Tags: game-design, game-mechanics, mmo, economy
---


title: How can I make a "paint" effect?

text:
# Question
Title: How can I make a "paint" effect?
I am wondering how one could implement "paint" in games. As a reference, I have two games I am specifically thinking about which are Super Mario Sunshine with its "goo" and Splatoon.

I'm wondering how I could replicate that kind of paint effect, where paint can be sprayed on to both the walls and floors of the environment, and on to objects.

# Answer
Valve reports that for the gel-splatting in Portal 2, applying individual decals for each splat would have become too performance-intensive.

Instead, they re-used the second set of UV coordinates generated for all the level geometry as part of their lightmapping process. This second UV channel unwraps every triangle of the level to a unique portion of the lightmap texture. By creating a "gel map" texture, they could use these UVs to overlay gel onto any of this geometry. To paint a particular spot on a wall, you look up that spot's corresponding texels in the gel map texture and set them to your paint colour.

This was based on Tag: the Power of Paint, where the levels were small enough that this map could be displayed directly with reasonable resolution, so they could stamp detailed splatter patterns into it directly.

For Portal 2 with its larger levels, this map's resolution per world meter is relatively low. To mask the artifacts, they combine this with a tiling normal map for the surface of the gel, which has a blotchy pattern in the alpha channel. By mixing this alpha with the falloff from the gel map, they turn the gel map's low-res bilinear interpolation falloff into a more detailed-looking splatter edge.

I wouldn't be surprised if Splattoon uses a similar technique. When you expect to be painting a large percentage of your level, applying it as one consistent layer tends to scale better than applying large numbers of overlapping decals.
> 6 votes

# Answer
Without some images or mock-ups of what you want the desired result to be, my first guess would take use a splatter image as a texture & then project it as a decal.

The basic steps are:

* set up the projector
* crop your triangles so that they don't extend past the projector
    + transform the triangles from world space to projector space
    + crop them
    + transform them back
* apply your texture to the projected texture coordinates
> 1 votes

---
Tags: algorithm, rendering, graphics-programming
---


# Question
Title: Why are the inputs not changing the animation on keypress?
I have been following this tutorial. You can watch 16:00 - 18:20 to see what I am trying to do.

What should be happening is: I press a key, my animation plays and the parameters or Inputs get updated depending on which key I press. There are no errors in my script, but the parameters or Inputs are not updating. I have checked that I am using floats and that all my names match up. I've watched this part of the video and checked that my code was exactly like his multiple times. When using the model that he used in the video, the inputs *the inputs are working fine*. So would this mean there is something wrong with *my* animation, or is this an issue in my script?

```
using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{
    public Animator anim;

    private float inputH;
    private float inputV;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("1"))
        {
            anim.Play("Armature|Walking", -1, 0f);
        }
        if (Input.GetKeyDown("2"))
        {
            anim.Play("Armature|TurnRight", -1, 0f);
        }
        if (Input.GetKeyDown("3"))
        {
            anim.Play("Armature|TurnLeft", -1, 0f);
        }
        if (Input.GetMouseButtonDown(0))
        {
            int n = Random.Range(0, 2);

            if (n == 0)
            {
                anim.Play("Armature|Walking", -1, 0f);
            }
            else
            {
                anim.Play("Armature|TurnRight", -1, 0f);
            }
        }
        inputH = Input.GetAxis("Horizontal");
        inputV = Input.GetAxis("Vertical");

        anim.SetFloat("inputH", inputH);
        anim.SetFloat("inputV", inputV);
    }
}

```

Anyone got any ideas?

# Answer
> 0 votes
Your using `Input.GetKeyDown(string)`. If you check the API, you will note that the string should correspond to a key in the Input Manager.

In the Input Manager, you use names such as "Horizontal" and "Vertical". You make no reference to " 1" or "2". When you call `Input.GetKeyDown`, you should use the *exact names as they are printed*, or alternatively, use a `KeyCode`.

If you intend to use the Input Manager, look for input with commands such as `Input.GetKeyDown("Horizontal")` or `Input.GetKeyDown("Vertical")`. Note that it is *case sensitive*. `Input.GetKeyDown("vertical")` will not trigger input on a key labelled " vertical".

If you intend to reference keys, directly, use `KeyCode`. *Every* key on the keyboard has an associated `KeyCode` enumeration value; `KeyCode.Alpha1` refers to the `1` button above the letters, for example, while `KeyCode. Keypad1` refers to the `1` button in your numeric layout, if your keyboard has one.

# Answer
> -4 votes
Here is the original text, with which I've compared, up until now.

```
using UnityEngine;
using System.Collections;

public class player : MonoBehaviour
{
    public Animator anim;
    public Rigidbody rbody;

    private float inputH;
    private float inputV;
    private bool run;

    // Use this for initialization
    void Start ()
    {
        anim = GetComponent<Animator>();
        rbody = GetComponent<Rigidbody>();
        run = false;
    }

    // Update is called once per frame
    void Update ()
    {
        if(Input.GetKeyDown("1"))
        {
            anim.Play("WAIT01",-1,0f);
        }
        else if(Input.GetKeyDown("2"))
        {
            anim.Play("WAIT02",-1,0f);
        }
        else if(Input.GetKeyDown("3"))
        {
            anim.Play("WAIT03",-1,0f);
        }
        else if(Input.GetKeyDown("4"))
        {
            anim.Play("WAIT04",-1,0f);
        }

        if(Input.GetMouseButtonDown(0))
        {
            int n = Random.Range(0,2);

            if(n == 0)
            {
                anim.Play ("DAMAGED00",-1,0f);
            }
            else
            {
                anim.Play ("DAMAGED01",-1,0f);
            }
        }

        if(Input.GetKey(KeyCode.LeftShift))
        {
            run = true;
        }
        else
        {
            run = false;
        }

        if(Input.GetKey(KeyCode.Space))
        {
            anim.SetBool("jump",true);
        }
        else
        {
            anim.SetBool("jump", false);
        }

        inputH = Input.GetAxis ("Horizontal");
        inputV = Input.GetAxis ("Vertical");

        anim.SetFloat("inputH",inputH);
        anim.SetFloat("inputV",inputV);
        anim.SetBool ("run",run);

        float moveX = inputH*20f*Time.deltaTime;
        float moveZ = inputV*50f*Time.deltaTime;

        if(moveZ <= 0f)
        {
            moveX = 0f;
        }
        else if(run)
        {
            moveX*=3f;
            moveZ*=3f;
        }

        rbody.velocity = new Vector3(moveX,0f,moveZ);

    }
}

```

Here is a \[link\] for the complete project.

---
Tags: unity, animation, input
---


title: Score over time

text:
# Question
Title: Score over time
I have the following code for adding 1 to `global.score` in the step event:

```
global.score +=1;

```

The problem is this adds the score at an alarmingly fast rate, I want to slow this down so I can give a semi realistic score that is going to represent distance. I am making an endless runner. I have tried to slow the room down but it just messes everything up. I tried to create an alarm event but to no avail.

using

```
alarm[0] = 10;

```

But I'm not 100% sure how to use the alarm properly. How would I go about slowing down how much `global.score` takes?

# Answer
> 5 votes
You can do this with a timer like this:

In your Create event *(or where you want to start your counting)*:

```
alarm[0] = 1;

```

Then in your Alarm 0 event:

```
global.score +=1;
alarm[0] = 10; // how many gamemaker steps until this alarm get's called again

```

A step in gamemaker is the same as fps, default is 30 so 1÷30 = 0.033334 seconds.

---
Tags: game-maker, timer
---


# Question
Title: Unity bounds includes the center of the scene
I'm trying to get the bounds of an object and put a box around it.

Sounds simple right? I just encapsulate all the bounds together and use its center and size to do so.

But the problem is one corner of the box is always at the center of the scene, like a part of the object is there, unless the center of the scene is in the bounds.

This is when object is at the center

This is when it isn't

This is the code i'm using:

```
    public static Bounds Calculate(Transform TheObject)
    {
        Renderer renderer = TheObject.GetComponent<Renderer>();
        Bounds combinedBounds = new Bounds();
        if (renderer != null)
            combinedBounds = renderer.bounds;
        var renderers = TheObject.GetComponentsInChildren<Renderer>();
        foreach (Renderer render in renderers)
        {
            if (render != renderer) combinedBounds.Encapsulate(render.bounds);
        }
        return combinedBounds;
    }

```

# Answer
As @DMGregory said the problem was that if I create a new bound to initialize the variable, it means I'm creating a bound that is located in the center of the scene and has 0 extents. So all I had to do was to rearrange the order of my code :

```
    public static Bounds Calculate(Transform TheObject)
    {
        var renderers = TheObject.GetComponentsInChildren<Renderer>();
        Bounds combinedBounds = renderers[0].bounds;
        for(int i = 1; i < renderers.Length; i++)
        {
             combinedBounds.Encapsulate(renders[i].bounds);
        }
        return combinedBounds;
    }

```
> 4 votes

---
Tags: unity, c#, bounding-boxes
---


# Question
Title: How do I convert distance covered from meters to kilometers, in Unity?
I am developing a game in Unity where I have to find a distance in kilometers, to find a passenger's fare based on the covered distance.

This is what I have tried:

```
private Vector3 previousPosition;
public float cumulatedDistance;

void Awake()
{
    // initialize to the current position
    previousPosition = transform.position;
}

// Update is called once per frame
void Update () {
    cumulatedDistance += (transform.position - previousPosition).magnitude;
    previousPosition = transform.position;
}

```

How can I determine the distance covered, and convert it to kilometers?

# Answer
Assuming you use the intended scale, one unit should be equivalent to one metre. In turn, you can work out kilometres travelled as `[units_travelled] / 1000`.

Your on the right track with how you implement tracking your distance. You *could* use `Vector3.Distance()` to work out the distance between each change in position, but if you look at the API, you will note that it reads *Vector3.Distance(a,b) is the same as (a-b).magnitude.* In other words, your already doing it. Using `Vector3.Distance()` might be more convenient, if you have trouble remembering the maths behind it and would rather directly reference it as *distance*, but there is no reason to use one over the other for functionality.

---

```
///<summary>How many game units make up a metre?</summary>
public float unitConversion = 1.0f;
///<summary>How much should be paid, per kilometre?</summary>
public float kiloMetreCost = 3.50f;
///<summary>Float to hold record of distance travelled</summary>
private float cumulatedDistance = 0.0f;
///<summary>Holds record of the last position</summary>
private Vector3 lastPosition;

public void Awake()
{
    lastPosition = transform.position;
}

public void Update()
{
    cumulatedDistance += ((transform.position - previous position).magnitude);
}

///<summary>Returns the current distance travelled, in metres.</summary>
public float GetDistanceInMetres()
{
    // use unit conversion to determine total metres
    return (cumulatedDistance / unitConversion);
}

///<summary>Returns the current cumulated distance, in kilometres.</summary>
public float GetDistanceInKiloMetres()
{
    // use distance conversion to determine total kilometres
    return (GetDistanceInMetres() / 1000.0f);
}

///<summary>Returns the total cost, based off cumulated distance.</summary>
public float GetTotalCost()
{
    // Use simple multiplication to determine final cost.
    return (kiloMetreCost * GetDistanceInKiloMetres());
}

```

---

The above script will keep track of its cumulated distance, and allow you to retrieve total distances. I included metres *and* kilometres, and as you mentioned a price, a total cost.

You can change 'unitConversion', if you do not use the standard unit scales. If you set your game up so that one unit equates to one centimetre, you would have `unitConversion = 100.0f`. If you set your game up so that one unit equates to eight metres, you would have `unitConversion = 7.0f`.

It is important to note that we retain `float` format to allow greater accuracy. If you need to work in integer values, remember that when you convert them to `int`, they will lose their decimal places.
> 2 votes

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


title: Uncontrollable platform spawning

text:
# Question
Title: Uncontrollable platform spawning
I made simple spawner like this:

```
void Update() {

    if (PlatformPosition.spawnNewPlatform) {
        NewPlatform();
    }
}

public void NewPlatform() {

    if (active) {
        newTransform = transform;
        Instantiate(prefabs[Random.Range(0, prefabs.Length)], newTransform.position, Quaternion.identity);
    }
}

```

And so it looks like my platform script:

```
public static bool spawnNewPlatform = true;

void Awake() {
    spriteSize = GetComponent<SpriteRenderer>();
    offscreenX = (Screen.width / PixelPerfect.pixelsToUnit) / 2 + offset;
}

void Update () {

    pos = transform.position;
    posX = pos.x;

    if (posX <= -offscreenX) {

        spawnNewPlatform = true;
    }
    else {
        spawnNewPlatform = false;
    }
}

```

Now when I start the "game" the spawner create unexpected number of platforms. Sometimes it's 2 clones sometimes it's 10... I don't understand what is the problem and how to fix it. Is it frame rate issue?

# Answer
> 2 votes
As long as you only have one spawner, it doesn't look like the spawner could be instantiating 10 platforms. However, it's definitely possible that you'll get two. On the frame after the platform is instantiated, if `Spawner.Update()` gets called before `Platform.Update()`, then `spawnNewPlatform` will still be `true` and another one will get created.

Try setting `spawnNewPlatform = false` within `Platform.Awake()`. That way, when a platform is spawned, it will immediately prevent spawning of any other platforms.

# Answer
> 0 votes
Try adding `if(spawnNewPlatform) return;` to the top of your platform `Update()` method.

Also if it's a scrolling level and not a static single screen level then the platforms may be hitting the respawn point early. If that's the case you may want to use `Camera.WorldToScreenPoint()`

`void Update()
{
 Vector3 screenPos = camera.WorldToScreenPoint(target.position);
 Debug.Log("target is " + screenPos.x + " pixels from the left");
}`

This will convert the world coordinates to those matching your screen so that you can check when they're out of sight.

Link to help: https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

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


# Question
Title: Cant make animation play continuously in Unity?
Alright, I have posted to Unity as well and watched tutorials but I am unable to make a walk animation work code wise. I have a complex problem being that in my game the user taps to move, thus the character is either idling, walking just one step at a time or walking continuously. So far I transition from idle to walking (in just individual steps, meaning the user isn't tapping repeatedly) with this setup and this code, and it works well -

I have an idle state and the walking clip, and the transition between the 2 is a bool "isWalking" that is either true or false.

I cannot merely trigger the walk animation without an offset because I have to alternate between left and right steps, so I use an increasing offset that (I think I did it right) should move through the whole animation, depending on if the object is moving:

```
     if (animOffset >= 1f) { //was full clip
                 animOffset = 0.0f;
             }

             //anim help
             currentPos = transform.position;

         if (currentPos != lastPos) {
             //print ("moving now");
             animator.SetBool ("isWalking", true);
             if (InputManager.stepCount % 2 != 0) {
                 print ("moving right");
                 animator.SetFloat ("walkOffset",animOffset);

             } else {
                 print ("moving left");
                 animator.SetFloat ("walkOffset",animOffset);

             }
             animOffset += 0.1f;
         } else {
             animator.SetBool ("isWalking", false);
         }
         lastPos = currentPos;

```

When the user taps repeatedly however, the animation SHOULD not start over again from its offset in individual steps - it should just play the animation for the duration of its movement. Problem is using this if I watch the blue bar on the animation states, it ALWAYS starts from the beginning if I keep a consecutive step count and set the offset to 0.0.

With just this, the walking is very glitchy if its not in individual steps as its starting again and again. Im new to animation - how can I do this?

How can I make sure an animation plays CONTINUOUSLY if the object is moving without stopping for too long? I have no idea how to do this

# Answer
> 1 votes
If you select the animation file in Unity's project explorer you should find a loop setting for the animation in the project inspector.

I had this same problem a while ago, no matter what I did in the code the animation would not loop until I set the animation settings up directly in the inspector.

# Answer
> 0 votes
Your problem is with the inputs and how you're handling the movement system. You're checking if the position has changed or not, and in case of Unity, the position had changed in that frame where you pressed the button, but did not change in the frame after it where you didn't press the button.

Let's put a timer in there shall we? First, define this float outsite the update code (where you define other variables): `float timerFloat = 3;`

```
if (currentPos != lastPos) {
        timerFloat=1;
      //print ("moving now");
        animator.SetBool ("isWalking", true);
if (InputManager.stepCount % 2 != 0) {
        print ("moving right");
        animator.SetFloat ("walkOffset",animOffset);
} else {
        print ("moving left");
        animator.SetFloat ("walkOffset",animOffset);

}
        animOffset += 0.1f;
} else {
        if(timerFloat <= 0){animator.SetBool ("isWalking", false);}
        timerFloat = timerFloat - Time.deltaTime;
}
lastPos = currentPos;

```

Now your character should still be "moving" for one second after the key press stops. (Change the values or play around with timers for "smoother" movement animation. Try not to include timers in movements themselves and only animations as this might mean taking control away from the player, which will make your game feel unresponsive.)

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


# Question
Title: Why do multiplayer games/chat services ever need to be able to open all NAT ports?
I understand that games need to be able to open NAT ports in order to receive incoming connections.

What I do not understand is why there is an issue between "limited" and "open" NAT. The only reason I can see that a game would ever need to have the flexibility to open *any* port is if it is intending to accept incoming connections on ports that aren't specified in advance as part of the protocol. (If there was a restricted set specified in advance, forwarding these and no others should satisfy all of the game's demands for NAT forwarding, meaning that "open" would not need to be a thing.)

This seems to imply there's some port negotiation going on as part of the protocol (otherwise how does the connector know that this port, not specified in advance, is available?) but if a connection is already established to conduct the negotiation, why move to a different port? And even then, why can't negotiation be limited to a subrange of ports rather than the entire range?

# Answer
> 8 votes
Just to make sure we're all on the same page in terms of terminology:

# What is NAT?

NAT is an acronym for "Network Address Translation". It's a system designed to allow a router to allow a whole private network of arbitrary size to appear to be a single device, from the point of view of the outside world. And the magic is that it does this completely transparently, without the clients on either the private or the public network ever needing to know it's happening.

In effect, it takes outgoing requests from the private network and rewrites them to appear to be coming from its single public address and some public port number, and then when it receives a response, it rewrites the response to forward it back into the private network, to whatever device sent the original request.

This was primarily needed because of the rapidly depleting supply of public IPv4 addresses as the Internet's popularity was taking off, but also brought some moderate security benefits by putting a largely one-way barrier between potentially unsecured consumer devices and the public internet. (It also dramatically slowed adoption of IPv6, but that's a topic for another day)

# NAT types

This particular classification of NAT types appears to have originated with Microsoft, where it was identified as useful during development of the original XBox game console, since it classed different NAT types into a useful way to determine which clients would be able to directly communicate with which other clients.

Sony uses essentially the same classification system, but uses different terms. In the discussion that follows, I'll mention both company's terms, and then use them interchangeably. But almost everybody has settled on using Microsoft's more human-readable terms for these NAT types; even Nintendo uses Microsoft's terms, now. The only holdout I'm aware of is Sony, who still use their own terms. (I once spent an enjoyable afternoon with a Sony dev rep, trying to make him slip up and use Microsoft's terms for NAT types. I think he figured out what I was doing, and I never managed it. But I did get him to actually say 'Xbox' once, which got him a stern look from his manager. That was a good day. I am a simple man of simple pleasures.)

**"Open" NAT** (Microsoft's term) or **"Type 1"** NAT (Sony's term) describes NAT behaviour where a particular private IP address and port behind the NAT device gets mapped to a single public address and port on the outside network. That is, anybody anywhere on the outside who sends a packet to that public address and port will have it successfully delivered to the inside, no matter what. This means that not having a NAT device gets categorised as "Open" NAT. Alternately, setting up a NAT device to forward the correct ports can also achieve this same result.

**"Moderate" NAT** (Microsoft's term) or **"Type 2"** NAT (Sony's term) describes NAT behaviour where a particular private IP address and port behind the NAT device gets mapped to a single public address and port on the outside, exactly the same as in "Open" NAT, except that incoming packets to that public IP address and port will only be delivered if we've already recently sent a packet OUT on that port, to the person who is now trying to send a packet IN. That is, people are allowed to *respond* to us, but not to *initiate* communication. (This is the most common sort of NAT). We use hole-punching to get through this; a central server tells both of us the other person's public address and port, and we then spam messages to each other, so both of us pretend that we're initiating the conversation, and our NAT devices let both sets of messages get through, thinking that they're "responses".

**"Strict" NAT** (Microsoft's term) or **"Type 3"** NAT (Sony's term) describes NAT behaviour which doesn't meet the requirements of Type 1 or Type 2. That is, a single private address and port sometimes get mapped to *different* public addresses and/or ports, most commonly based upon who the packets are being sent to. For example, if I send a packet from private port 80/UDP to person A and a packet from that same private port 80/UDP to a different person B, then A and B will see those packets as having come from different public port numbers on the NAT device. This means that A and B can't tell each other how to contact me, because my NAT device is going to be requiring that they each only reply to me using the special public port which it allocated for communication to each of them independently; any packets that A might send to the port which was allocated for talking with B won't get through, and vice-versa.

# NAT types are broad generalisations

As mentioned above, there are far more types of NAT than just these three, and many more ways to classify them. Sometimes they're classed as "symmetric", or "conical", or in other ways.

One particularly relevant difference, even inside this classification: Moderate/Type 2 NAT devices often differ in terms of how recently we have to have sent an outgoing packet, in order to accept incoming responses. If there's a long delay between our last packet out and someone's response to us, an otherwise Type 2 NAT device may appear to occasionally behave like a Type 3 NAT device.

Another common gotcha is that some routers which behave as Type 2 when there's just one client using the private network begin to behave as Type 3 when there are two clients both using the same private port numbers on that private network.

There is no "standard" implementation of NAT; everybody started from the basic concept for what a NAT device should do, but implemented it separately, so the little details are typically different in every device, and our "NAT types" discussion is just a useful classification system for carving useful information out of a broad spectrum, for the purposes of establishing peer to peer communication when both peers are behind different NAT devices.

Just something to bear in mind.

# On the technical support query in the comment

On the PlayStation, NAT type 2 is "moderate", not "restricted" (not sure where you got that term from). It should work perfectly well, since all modern game services are built to perform standard hole-punching to allow clients to communicate with each other.

# How to classify a NAT device's behaviour, yourself

To classify a router between the three types we're discussing here, all you need is a server with three different public IP addresses. We'll call these IP addresses 'A', 'B', and 'C'. Follow these steps:

1. Client sends a packet to A, and a packet to B.
2. Server compares the packets it received on its A and B addresses, and checks to see if the public IP address and port numbers it sees as the source of those two packets match each other. If not, the client is Type 3 (Strict).
3. If the packets did both show the same public source IP address and port, then the server sends a packet from C to that IP address and port. Remember that the client has never sent a packet to C, so if the client successfully receives that packet, then we know it's Type 1 (Open). If it fails to receive the packet, it's Type 2 (Moderate).

That's all it takes!

# Why any of this matters

Fundamentally, any number of Type 1 and Type 2 clients can successfully talk to each other; the Type 1 clients because anybody can talk to them on their public address/port, and the Type 2 clients because they can hole-punch out, as long as they know the public address/port that is going to be contacting them.

Type 3 clients, on the other hand, can only talk to Type 1 clients, and they require the Type 1 client to have special NAT traversal code to do that successfully; (the program has to be smart enough for the Type 1 client to receive a packet it wasn't expecting from an unknown address/port, and realise that it must actually be the *true* address/port from the Type 3 client, and redirect itself to talk to that address, instead of the one it had been expecting to hear from. I would be surprised if many folks actually write that sort of code any more; the vast majority of people are using Type 2 NAT devices, these days, so it'd be hard to test and few folks would get any benefit from this work).

Anyhow, Type 3 clients can't talk to Type 2 clients, because the Type 2 clients don't know the correct address/port to send packets to in order to hole-punch through their own NAT device. And obviously two Type 3 clients will likely never manage to reach each other at all, since neither actually knows the correct address/port for talking to the other.

If you're making a multiplayer game, it can be useful to know which NAT type each player is; for example, knowing that Type 3 players will only be able to talk to Type 1 players, you immediately know not to even bother suggesting that they join a game session which includes any Type 2 or Type 3 players; you already know they won't be able to connect to each other!

And similarly, you know not to send Type 2 players to join a game session which includes any Type 3 players; you know they won't be able to connect. All this logic lets you reduce frustrating "trying to connect to game session" processes which will never complete.

And that's pretty much all there is to it!

# Answer
> 4 votes
Your question is a bit fuzzy regarding the terminology, but if i get you correctly:

A multiplayer solution may want to establish both a persistent connection (TCP or a kept-alive UDP) to a well known public server (a matchmaking/handshaking/hole throughpunching server - maybe it has a better name), while at the same time it may want to allow peers to establish direct connections between each other. Game manufacturers want this to work with the common, normal behaviour of popular home routers. By default, a router does not have static NAT behaviour, as it has no pre-set information about the local computers connecting to it. Meaning that the router itself decides what public port number it assigns to a specific local computer, of multiple, in the local network. This port then points at a specific IP address in the local 192.168.n.n address space.

Clients normally announce themselves (tell their home routers public IP + port that points at a local box) to the matchmaking server, which distributes that endpoint information to other clients, after which all clients can begin to bombard each other with packets - this opens the NATs as needed in the entire cloud. Then there may be different behaviours among the NATs (routers), ie. different restrictions regarding how to allow/disallow ports in opposite peers. The worst case is the symmetric NAT, which changes your routers public port *per connection*, causing the information it announced to a matchmaking server to be useless for another peer, as these are *different* connections.

The router needs to have freedom to do this, and nobody wants to set up port assignment tables in the routers, most even don't know how to do this. Hence the router will want to use it's entire public port space, as needed, and dynamically. Eventually, the application(s) started inside the local network determine the extent of all this.

Looking from a coding point of view, this can be a matter of convenience. On can use a single socket for talking with multiple peers, in the case of UDP packets. However one must then parse the remote endpoint in each incoming packet and act accordingly. Another alternative is to use an individual socket for each remote endpoint, in which case the OS sends a callback directly to the correct, assigned callback function. An individual socket however requires an individual local port number, which will translate into an individual port number from the router outwards too - again requiring the routers automation to handle this gracefully.

---
Tags: networking
---


# Question
Title: How do I pass my objects to the update method?
I've had formal education in Java for around half a year now, and as a hobby I would like to attempt game development. I've downloaded the Slick2d library to help with this.

I've run into a problem as of right now. When I create my game objects, like player, etc. I presume I have to do this in the pre-build init() method, but I probably could do it in the main() as well (What one would you suggest?). Now, my question is, when I create a Player instance in init() or main(), how do I pass it to the update() method? I could of course make the player object public/global, but I've been taught that this is very poor programming, so I'm reluctant to do this.

I would greatly appreciate an answer, since I would like to learn to do things the "correct" way, and as of right now I have no single clue what that is. Thanks for your consideration.

# Answer
> 1 votes
As long as all of your mentioned methods are in the same class, you do not need to pass your objects to the methods - if you just declare your objects in that class. That is the normal way to do it.

This is not the same as declaring the variables "public". You can do that, if you want. But without declaring this explicitely, variables are set to "private" in java, thus restricted to the scope of their class. So just go ahead an declare your player object at the start of your class.

Where you initialize the objects is a different question. Usually, the init() method in frameworks is called ONCE before the game goes into its loop. As you probably would want to initialize your objects once, you can do that in this method. You can also create your own initialization method that only initializes some of your game's objects.

public static void main(String args\[\]){} is the method that is the starting point for any java-program IIRC. You can only initialize static or local variables here, though. But you cann call your init()-method from here and start the game loop.

```
public class Game{

 private Player p1;

 public static void main(String args[]) {
   init();
   //alternative: initializePlayer();
   //gameloop
 }

 public void init(){
     p1 = new Player();
 }

 /*private void initializePlayer(){
     p1 = new Player();
 }*/

 public void update(){
    p1.update();
 }

```

}

# Answer
> 0 votes
Simply - you shouldn't!

The good way is to make some class to keep objects to be updated, or simply keep them in public array or list and then do something with it in your update method.

---
Tags: java, game-loop, slick, objects, oop
---


# Question
Title: I'm a single developer making a game made of blocks. Can I make 3d characters made of blocks without looking like Minecraft?
I would like to differentiate the look as much as I can but yet it has to be within the limits of what is reasonable for a single programmer can do. I have alot of ideas that would make the game itself different but I'm afraid the look of the blocky world and blocky characters are going to be too much like Minecraft. I've toyed around with the idea of giving the characters big heads, or skinny bodies, or elbows and knees.

# Answer
> 14 votes
You shouldn't be worried if a game 'looks' like another. Take Terraria; early alpha screenshots, people were 'ZOMG IT IS A MINECRAFT CLONE'. It gets released - obviously not like Minecraft at all.

Then take something like FortressCraft - that is obviously a Minecraft clone. It has the same features, pretty much. The graphics have changed, maybe.

As long as the core concept is different, and the graphics are different enough so that you would not confuse the two, you will not have a problem. Maybe try a realistic style person, instead of a blocky one?

# Answer
> 10 votes
If you end up stuck with overall body shapes that look like Minecraft's, your textures can help you stand apart. Without knowing your game's goals and limitations, you could use:

-Higher or lower resolution textures.

-Animated textures.

-High-contrast textures (think Tron)

There are lots of games done in pixel-art style that have interesting characters that stand out. And this is an odd time, just after Minecraft came out. For a while, everything will be compared to it, but eventually it will just be the first in a series of games in this genre/style. Maybe yours could be the *other* game we all compare to. :)

# Answer
> 6 votes
I think Minecraft is almost a genre, at this point. There are many success where people are taking the core concept adding something new. But you have to find the core mechanic that differentiates you from the original.

# Answer
> 2 votes
I would mention a few specific games (such as Stonehearth, which is where most of the Qubicle character images come from) but there are a *ton* of games, art (e.g. on DeviantArt), demos, movies, etc that use different styles. Hence, I suggest an **image search.**

Search for `voxel characters`, `blocky characters`, and `"qubicle" characters`. (Yes, put "qubicle" in quotes, or else your search engine might think you meant "cubicle" and give you other random stuff.) **Qubicle** is an app for creating voxel models, in the sense of "volumetric pixel" instead of the "textured cube" model that Minecraft is.

You'll find that there a lot of different ideas of how to create characters in a low-res, 8-bit, and/or boxy style without being stuck with Minecraft's aesthetics. An image search will show you a wide range of styles, and if you're working with an artist they can riff on a few of your favorites to come up with something new.

# Answer
> 0 votes
Yes, If you take a loot at blockstorm characters are done by cubes, but they look much more serious than minecraft.

I think the trick is using enough cubes to approximate a real Surface. Of course if you do not limit to cubes but to prism or even use lowpoly models you can still make stuff that appears creepy and serious (I'm thinking to the first First person shooters using polygonal enemies).

You should search some artist specialized in voxel art, I've seen on internet some very cool artworks.

---
Tags: game-design, 3d, art, voxels, minecraft-modding
---


title: Multi purpose item class design in C#

text:
# Question
Title: Multi purpose item class design in C#
I'm currently trying to get my head around how to create an item class which contains data for multiple purposes.

As for example I would like to have an Axe which could be used as weapon, but also as a tool to chop trees. The class should contain the following:

Durability, weight, damage vs npcs/players (when attacking), damage vs trees (when chopping), attack speed, chop speed and some enum in which equipment slot the axe fits (e.g. melee slot).

What would be the typical approach?

I stumbled about this answer, but I'm not 100% sure if I'm understanding him right. Is it something like:

```
public class Item {

    public int durability;
    public float weight;

    public Weapon weapon;
    public Tool tool;

    public class Weapon {
        public int damage; // damage vs players
        public int speed; // attack speed
    }

    public class Tool {
        public int damage; // damage vs trees
        public int speed; // chop speed
    }
}

```

?

# Answer
> 3 votes
A common approach which is quite popular among game developers is the Entity-Component-System.

Each Entity (`class Item`) only contains the most basic functionality and data which is common to all items, plus a `List<ItemComponent>`. `ItemComponent` is an abstract class with sub-classes like `WeaponItemComponent`, `ToolItemComponent` and any other features you only want to have on some of your items. These components contain the data and code which is relevant for performing that feature. Each Item *can* have one of each of these components (or more than one, if you want to allow that), but doesn't have to.

One way to interact with components is by using an event system. Your item class would have a method `HandleEvent(event)` which then calls `component.HandleEvent(event)` for all components. The internal implementation of each component decides if it needs to do something for that event.

Another way is by explicitly getting a component from an item:

```
WeaponItemComponent wic = item.GetComponent<WeaponItemComponent>();
if (wic != null) {
    enemy.hp -= wic.damage;
}

```

# Answer
> 0 votes
It seems right but it doesn't allow for as much future-proofing if you decide to add further items that the item can interact with to your game at a later date.

Maybe try something like:

```
public enum ItemType {Weapon, Tool}

public struct ItemInfo
{
     public ItemType itemType;
     public int damage;
     public int speed;
}

public class Item
{
    private int durability;
    private float weight;
    private List<ItemInfo> _itemInfo = new <itemInfo>();
}

```

This allows you to keep a simple list of all of the interactions your item may have.

---
Tags: c#
---


title: How to reset my game?

text:
# Question
Title: How to reset my game?
What I want is that when ever my player left click(mouse click) in the menuState, My `init()` method in my `Game Class` must reload. How can i do that???

My game class witn the `init()` method

```
public class Game implements Runnable {

private Display display;
private int width,
            height;
public String title;

private boolean running = false;
private Thread thread;

private BufferStrategy bs;
private Graphics g;

//States
public State gameState;
public MenuState menuState;
public SplashScreen splashscreen;

//Input
private KeyManager keyManager;
private MouseManager mouseManager;

//Camera
private GameCamera gameCamera;

//Handler
private Handler handler;

public Game(String title, int width, int height){
    this.width = width;
    this.height = height;
    this.title = title;
    keyManager = new KeyManager();
    mouseManager = new MouseManager();
}

// MY INIT METHOD!!

private void init(){
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);
    Assets.init();

    handler = new Handler(this);
    gameCamera = new GameCamera(handler, 0, 0);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);
    splashscreen = new SplashScreen(handler);
    State.setState(splashscreen);
}

private void tick(){
    keyManager.tick();

    if(State.getState() != null);
        State.getState().tick();
}

private void render(){
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null){
        display.getCanvas().createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();
    //Clear Screen
    g.clearRect(0, 0, width, height);
    //Draw Here!

    if(State.getState() != null);
        State.getState().render(g);

    //End Drawing!
    bs.show();
    g.dispose();
}
//WHEN THE GAME RUNS, it also runs the intit() method and shows fps and tick

public void run(){

    init();

    int fps = 1000;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();
    long timer = 0;
    int ticks = 0;

    while(running){
        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        timer += now - lastTime;
        lastTime = now;

        if(delta >= 1){
            tick();
            render();
            ticks++;
            delta--;
        }

        if(timer >= 1000000000){
            System.out.println("Ticks and Frames: " + ticks);
            ticks = 0;
            timer = 0;
        }

    }

    stop();

}

public KeyManager getKeyManager(){
    return keyManager;
}

public MouseManager getMouseManager(){
    return mouseManager;
}

public GameCamera getGameCamera(){
    return gameCamera;
}

public int getWidth(){
    return width;
}

public int getHeight(){
    return height;
}

public synchronized void start(){
    if(running)
        return;
    running = true;
    thread = new Thread(this);
    thread.start();
}

public synchronized void stop(){
    if(!running)
        return;
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

```

# Answer
> 0 votes
Thnx Djindjidj for making my doubt clear on what to do

I made a method called `reload()` and in that, I call my asset, game camera and gamestate. And in the tick method i put `if(handler.getMouseManager().isLeftPressed() && State.getState()==menuState)` then it calls my `reload()method`

```
private void reload(){
    Assets.init();
    gameState = new GameState(handler);
    gameCamera = new GameCamera(handler, 0, 0);

}

private void tick(){
    if(handler.getMouseManager().isLeftPressed() &&  State.getState()==menuState){
        reload();
    }

```

# Answer
> -1 votes
The more I think about it, the more it gets clear to me that I do not know enough about your code to be able to give you a working answer. Judging from what you write and wrote in the last post, I guess that you do not know much about the framework, either.

It seems to provide you with a static class "State" that you can store the current state of your game into. It is also called in your tick() and your render()-method to call the tick()- and render()-methods of that current state.

I thus guess that each gamestate has its own assets and game logic. If this is the case, you have two options:

1. check for a right click in your menustate's tick()-method and call a load()-method from there, reinitializing all your assets (similar to my old post below).
2. check for a right click and the menu state in the tick()-method of the class you provided here and reinitialize the gamestate object.

> You have no dedicated "update"method in your game loop, if not `tick()` is there for that. Anyways, just prompt your mouse / mouse manager for a right button klick in that method and call the init() method.
>
> *Edit:*
>
> I have no idea what framework you are using (I suppose you do use one?), but judging from the last post you made, I can derive this:
>
> Am I right in supposing that you want the game to restart when the user clicks the right mouse button while in the menu?
>
> To reset the game, you do not have to reset the display or your handler, you have to reset your game logic and your assets. My first response was thus **false**, you really don't want to call init() again.
>
> To reset your game, add a new function (could be called "load()") that initializes your game assets, score, game logics etc. Anything that is relevant to gameplay, but not to your engine (like the display or your keyboardmanager). If you want to reset the game to a fresh start without restarting the program, you would have to call that function.
>
> To trigger the load function, use your MouseManager() class. From your last post, I can derive that it should have a function called "isRightPressed()". To restart the game when your right mouse button is clicked and released, do this (for example) in your tick() method:
>
> ```
> if(mouseManager().isLeftPressed() && State.getState()==menuState){ //Don't know if this works, I don't know your menustate and State
>
> ```
>
> classes load(); } This will reset your game as you provide it in the "load()-method". You can improve on this by storing the last mouse state and the current to only do this when the right mouse button is released. Else the game will reset each tick as long as you press the right button down. Also, as in the comment, I don't know how you would compare game states in your framework. Do not forget to update your mousemanager in tick(), too.

---
Tags: java
---


title: libgdx game not disposing

text:
# Question
Title: libgdx game not disposing
My game does not exit entirely even after calling dispose() method. It loads a black screen when I launch it for the second time and works well if I kill the game manually and restart it.

I get an error that says `buffer not allocated with newUnsafeByteBuffer or already disposed` when I try to dispose off the SpriteBatch object. This is were I suspect the problem to be. But not able to fix it entirely. Please help!

Here is how I have built it (I have put the sample code here just to show you guys that there are no visible loop backs in dispose function, please correct me if I'm wrong)- In game screen,

```
public void dispose() {
  AssetLoader.dispose();
  render.dispose();
  Gdx.app.exit(); }

```

Under class AssetLoader-

```
public void dispose(){
  Texture.dispose();
  sound.dispose();
}

```

Under game render class -

```
public void dispose(){
  spritebatch.dispose(); //throws an error when I GameScreen.dispose is called
  font.dispose();
  shaperender.dispose();
}

```

I believe that my spritebatch isn't disposing which is causing the black screen but I cannot find a way to dispose it off successfully. Any help would be greatly appreciated.

# Answer
The body of the `dispose()` method is not the right place to call the `Gdx.app.exit()` method. Calling the latter will invoke the call of the former and so you end up with calling `dispose()` on your objects for the second time. Hint: Read the javadoc of the `Gdx.app.exit()` method to see exactly what it does.

What you should do is:

1. Remove the `Gdx.app.exit()` call from your `dispose()` method.
2. You have a `hide()` method, which is called when your app gets "hidden" when you press the home button, got an incoming call, etc. Place a call to the dispose method here.
3. Put the call to the `Gdx.app.exit()` for example in the listener body of a button that's responsible for quitting the game, or catch the hit of the back button in Android and use it there.

This way you'll make sure all your resources are disposed of correctly and that you are not attempting to dispose of something for a second time.

Hope this helps.
> 4 votes

# Answer
Yes you can write your all code of your dispose in hide method. But if the problem still occurs then you can do your all dispose work just before when you load your Assets and make the SpriteBatch null at the starting and then make its object.

Like :

AssetLoader.dispose(); AssetLoader.load("path of texture","Type.class");

and

spriteBatch=null; spriteBatch=new SpriteBatch();
> 0 votes

# Answer
This is an old topic, but I had the same problem and finally figured it out by using `Gdx.app.log("note: ", "dispose called")` LogCat prints in the dispose method of each screen. What actually happens is (on Android):

1. Press the HOME button =\> the method `pause()` gets called.
2. Restart application again and at restart the dispose method of the last screen gets called to refresh the screen. Normally there shouldn't be any problems here.

The problem arises (at least in my case) when I pressed the RETURN button and restarted the app again, resulting in a crash. Now, this happens:

1. Press the RETURN button =\> this calls the main `dispose()` method, NOT the `pause()` method. Therefore, every resource gets disposed.
2. Afterwards, when relaunching the app, it tries to dispose the last screen again to refresh, but that already got disposed by pressing the RETURN button. So here is the problem: the dispose method of the current screen gets called twice when pressing RETURN, resulting in the following error: `java.lang.IllegalArgumentException: buffer not allocated with newUnsafeByteBuffer or already disposed`.

I solved this problem by using a boolean to check if the current screen already got disposed. Below is an example (I use an abstract `Screen` class and a `ScreenManager`, that sets a new screen by calling the `create` method of a subclass):

```
public class MainScreen extends Screen {

    private boolean disposed;

    @Override
    public void create() {
        disposed = false;
        //rest of your code here
    }

    @Override
    public void dispose() {
        if (disposed == false) {
            //dispose your resources here
            disposed = true;
        }
    }
}

```

So after pressing RETURN, `disposed` will be set to `true`. When relaunching it will still be true, so the resources do not get disposed twice. Next the screen gets reset, automatically calling `create` so `disposed = false`

I hope this helps anyone with a similar problem in the future :)
> 0 votes

# Answer
Calling the `Gdx.app.exit` function calls the `dispose` function from the main `ApplicationListener` of the game anyway. Calling the function inside of the dispose causes a recursion of the function as it will reach the `Gdx.app.exit` function inside of the `dispose` function it calls leading to an error as it tries to dispose something that has already been disposed.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Prevent camera from moving through walls (no engine or framework)
I'm building a fairly basic 3D first-person puzzle game. The only objects for which collisions matter are walls, and all walls are at convenient 90 degree angles aligned with the coordinate axes.

Unfortunately, I cannot consistently prevent the camera from moving through walls. There is no off-the-shelf game engine or framework involved, so I have to implement all this from scratch.

Currently, my algorithm (in GLSL-ish psuedo code) looks something like this:

```
void update_position(seconds){
    vec3 ray = Raycast(position, speed, map.grid);
    float xmax = max(ray.x-.01,0);
    float ymax = max(ray.y-.01,0);
    float zmax = max(ray.z-.01,0);

    float dx = speed.x * seconds;
    float dy = speed.y * seconds;
    float dz = speed.z * seconds;

    if(abs(dx) > xmax){
        dx = (dx > 0 ? xmax : -xmax);
        speed.x = 0;
    }
    if(abs(dy) > ymax){
        dy = (dy > 0 ? ymax : -ymax);
        speed.y = 0;
    }
    if(abs(dz) > zmax){
        dz = (dz > 0 ? zmax : -zmax);
        speed.z = 0;
    }

    position.x += dx;
    position.y += dy;
    position.z += dz;
}

```

In prose: I cast a ray from the player's/camera's current position along the speed vector, which extends until it hits wall. (The Raycast function is used elsewhere, so I already know it works correctly.) I then define the maximum distance the player is permitted to move in each dimension to be slightly less than the component of the ray in that dimension (so that we never end up exactly *on* a wall). I then compute a provisional set of deltas to add to the current position based on the speed and the time since the last frame (in fractional seconds), and check to see if any of them exceed the maximum allowed magnitude which would take the player through the wall. If they do, I clamp the magnitude of the offending component to its max value, and set the component of speed in that direction to 0; so, the player should end up just barely outside the wall, and sliding along it.

This usually works pretty well if you happen to run straight into a wall, but it fails frequently but unpredictably (as in, sometimes it doesn't fail) near corners, and especially near three-way corners (where two walls and a ceiling or floor come together).

So, what is wrong with this algorithm, and how do I fix it?

# Answer
You could use planes for the walls and only update the camera if the camera sphere and potential new postion do not intersect the planes.

A basic sphere plane intersection would look something like:

```
bool intersecting_or_behind_plane = (dot(position, plane_normal) - plane_d) <= sphere_radius

```

Collsion detection is quite a large topic, but searching for things like geometry intersection should help.
> 1 votes

---
Tags: collision-detection, collision-resolution
---


# Question
Title: How to prevent corner slipping with a shortest axis collision solver
Currently I use AABB's to represent objects in my game engine, I resolve collisions between them by finding the shallowest axis, but this leads to a problem if an object is approaching another in a way that their corners would collide at a fast velocity, they will slip past each other and resolve on the wrong axis because one penetrated too deeply, for example:

We can see that the red square is approaching the green rectangle. They intersect and the solver sees that the smallest intersection is on the Y axis

Thus they sepparate on the Y axis, and the red square flies by the green rectangle, when it should have stopped on the left edge

I'm currently at a loss on how to solve this, any sugestions or fixes would be greatly appreciated!

# Answer
> 1 votes
I think you want to take the velocity direction into account when considering how to move the red box back. I'm thinking you want to move back along the velocity vector when you detect an intersection.

It seems you have the the x and y intersection depths, so just work out the magnitude of the 2D vector formed by those values and move the red box position by negative magnitude. Something like

```
inters_vec = (xintersect,yintersect)
velocity_dir = norm(velocity)
new_pos = red_pos - vel_dir*mag(inter_vec)

```

---
Tags: collision-detection, physics, collision-resolution, aabb
---


# Question
Title: Circular soft body? Matter.js or other js engine?
I am using Matter.js physics in an attempt to create soft bodies. I was able to create a body like this:

However I am not sure if this is the "soft body" I want. It is true that this body is not entirely rigid and has that bouncy feel when it collides and gets dragged. I was looking for a body that shares similarities with a gelly. This image might visually help explaining the concept:

I was wondering how these type of bodies can be made. Is it the same as the as matter.js soft body but with a very specific type of properties? I can only get the body to be kind of rigid-squared and not as moldable and circular as I would like it to be.

I am also interesting in manipulating the physics body with in-game interactions which would increase or decrease the physics body size which leads me once more to the conclusion that the type of body that I want must be quite moldable.

Can matter.js handle this or do I have to change the physics engine? Any solutions to approach this?

NOTE: I am using Phaser.js for some in-game components but matter.js physics for physics manipulation because I believe Phaser integrated Physics can't simulate this type of complex body.

Thanks

EDIT: It is very similar to this https://stackoverflow.com/questions/18298329/box2d-roll-soft-body-ball?rq=1. I just need to do that with a js engine I guess. Is there any?

# Answer
> 2 votes
Making the softbody part of a physics engine isn't an easy task... Thankfully a few people have already worked really hard to do this.

Among these you can find the Unity plugins "Truss Physics" and "VertExMotion".

And then others like "Jelly Physics". (It's C#, but I believe others have converted it to diferent languages, have fun looking for these :p)

You can find it at this link (in c#): https://github.com/kwanchangnim/Jello-Physics

Then the one I am actually using for my game -which is a sort of extension for Box2D- is called "liquid physics" (also many languages) made by Google.

You can it find here: https://github.com/google/liquidfun/tree/master/liquidfun/Box2D/lfjs

I had your exact same issue, so I hope this helps. (It took a whole day of research to find all of these...)

# Answer
> 0 votes
The first illustration in your question is the exact same technique used by many softbody physics engines.

If you mean liquid physics by saying "Jelly alike", then that's a different subject.

But the thing is, there is no need to "re-discover America". There are tons of plug-and-play softbody libraries out there that you can use.

---
Tags: javascript, physics-engine, soft-body-dynamics
---


# Question
Title: Unity - how to switch between ratios in a Scene View?
I'm complately new to `Unity`, but I know what's going on, I've made some games with `LibGDX` earlier.

In GDX, to handle all resolutions perfectly I always create 5 different sets of backgrounds (cause they have to be perfectly sized) and I place UI widgets on percentage for each ratio independantly (hardcoded values). I was just checking what's the ratio on runtime.

As we know, there are only 5 possible aspect ratios for mobile devices (I target mobile only).

Now, when I started using `Unity`, the first thing I looked up was how devs handle ratios. I found some scripts in the web, which add pillarboxes which in my case is unacceptable.

So I thought - ok, let's do it my way, and make it for all aspect ratios.

And my question is:

***Is there any option in `Unity`, which will allow me to 'switch' in the Unity Editor between ratios and the 'Scene View' will understand this and resize?***

What I want to do is to create a 16:9 with the editor, then switch to 5:3, adjust elements for it, and remaining ratios too.

To be clear, I don't mean the 'preview', when you check the desired device and it shows how the game will look like.

Any help and tips are appreciated! :)

# Answer
As Uri Popov notes in the comment above, this is done via the Game window rather than the Scene window itself.

Just beside the display selector at the top of the Game window, you'll see a drop-down menu that lets you select different aspect ratios or fixed resolutions. By clicking on the "+" at the bottom of the menu, you can add your own custom versions.

Changing your settings here (or resizing the window, if using a non-fixed resolution) will feed back into your Camera and UI Canvas objects in the scene, and you'll see them / their gizmos rearrange and reshape themselves accordingly.

This lets you tune your layout for multiple different resolutions in-editor, without necessarily needing to run to check the results each time you change something.
> 2 votes

---
Tags: unity, resolution, aspect-ratio
---


# Question
Title: Which Unreal Engine 4 project files can I ignore in source control?
I want to put an Unreal Engine 4 project under source control with git. (I know the editor has Perforce and Subversion support, but I don't care for those.)

What folder and files do I include in the repository and which can I ignore?

The way I see it, the following is needed: `Config`, `Content`, `Source`, `*.sln`, `*.uproject`

Things that I can ignore: `Binaries`, `DerivedDataCache`, `Intermediate`, `Saved`, `*.suo`, `*.sdf`, `*.opensdf`

Is this correct?

# Answer
I'm using GitHub for Windows which generates a nice gitignore ignoring most extraneous files like log files or files specific to VS that don't need to be shared.

From what I can gather from this page in the Unreal docs, you can probably ignore these directories:

```
DerivedDataCache
Intermediate
Saved

```

I'm not going to ignore Binaries, if only because I'm working with a level designer who doesn't have VS and so will need the DLL files I build (I assume, I could be wrong).

Again keep in mind I'm using Git for Windows that generates gitignore for you when you create a project, and it's pretty big. I'm pretty much only committing the following (where "ReallyCoolGame" is the name of your project):

```
.gitattributes
.gitignore
Binaries
Config
Content
Source
ReallyCoolGame.sln
ReallyCoolGame.uproject

```

I've only just committed this myself, and I've yet to test it with my level designer, so caveat emptor.

Also, I'm referring to a project created using the first-person C++ template, which gets saved to: `E:\Documents\Unreal Projects\ReallyCoolGame` (`My Documents == E:\Documents` on my machine) and not within the Unreal Engine source directory structure.

Edit: I also don't want to include all the default content, so I'm going to have a subdirectory within Content just for the game assets themselves with the same name as the project, and ignore all other subdirectories of Content. So the lines at the top of my .gitignore now look like:

```
DerivedDataCache
Intermediate
Saved
Content/*
!Content/ReallyCoolGame

```

And the level designer will put all of our assets in `Content/ReallyCoolGame` instead.

**UPDATE:**

The Intermediate directory actually contains Visual Studio's project files, which are needed to build the project. If the Intermediate directory is ignored, you won't be able to build the project because the Visual Studio solution won't find it. But there are two easy workarounds for this.

1) Just don't ignore the Intermediate directory. Of course in that case Visual Studio will still find all project files it needs and be able to build the project.

2) This one is even better, especially for version control: Open your project in Unreal Engine 4 editor and go to "File \> Refresh Visual Studio Project". This will generate an all new solution file for you, which means you won't even need to commit it and can add the \*.sln in the project folder to the .gitignore file.

Also \*.suo and \*.sdf files can be ignored in general, since Visual Studio just generates new ones when you open your solution.
> 23 votes

# Answer
I don’t know the differences between the public version of UE4 and mine, but here is the `.gitignore` file I have been using:

```
Engine/Binaries/
Engine/DerivedDataCache/
Engine/Intermediate/
Engine/Plugins/*/*/Binaries/
Engine/Plugins/*/*/Intermediate/
Engine/Programs/UnrealHeaderTool/
Engine/Programs/UnrealPak/
Engine/Saved/
Engine/Shaders/Binaries/
Engine/Source/*/*/*/obj/
Engine/Source/*/*/obj/
Engine/Source/*/obj/

UE4.opensdf
UE4.sdf
UE4.sln
UE4.suo
UE4.*.suo

GameName/Binaries/
GameName/DerivedDataCache/
GameName/Intermediate/
GameName/Saved/

```
> 16 votes

# Answer
This is what I have in my .gitignore

```
#Unreal Engine
StarterContent/
Saved/
Binaries/
Build/
Debug/
Intermediate/
DerivedDataCache/
UnrealHeaderTool/
UnrealPak/
obj/
*.VC.opendb
*.opensdf
*.sdf
*.suo

```
> 1 votes

---
Tags: unreal, file, version-control, git
---


# Question
Title: How to add Facebook Data Storage to Mobile Game?
I was wondering how I would add the option for players to sign into their Facebook profiles on my mobile game and then have Facebook store their game save data, so they can recover it on any device when they sign into Facebook. Other Facebook features would include seeing their friends on the Facebook leaderboards, inviting their friends to the game and challenging their friends to beat their scores. I would hate for the Player's data to be lost, so the Facebook data save part is very important. A good reference to this feature is the Hungry Shark mobile game.

I wasn't sure how this works. My programming friend and I are creating the game together, but he doesn't know how to do this and I don't know how to program. Once I figure out exactly what has to be done, I would like to hire a programmer who knows how to add this feature.

Thank you!

# Answer
Facebook does not provide storage for saved games. Facebook's OAuth API can be used to login with Facebook and obtain a Facebook-specific user ID (and other data like name, email, friends, etc.) but that only solves a part of the problem.

Games will typically then use their own database solution (either on their own servers or a hosted cloud solution) to make things like Facebook IDs to their game-specific accounts. This mapping can be used to associate multiple authentication services to the same account, allowing a user to login with Facebook, Google, Twitter, Microsoft, or so on. That also illustrates why it's a bad idea to use the authentication provider's user id as the account id, because the same user will have completely different user ids across the various authentication providers.

The database solution used to store account metadata can also be used to store all saved game information, or a different storage service could provide that feature. It will be typical to wrap the various backend services (accounts, saved games, leaderboards, etc.) behind a single game-specific gateway API service so that the game clients only need to interact with one external platform (and don't need things like secret access keys to databases distributed with the clients!).

Note that there are also all-in-one "platforms" that provide the entirety of these services plus many others that a shipping game needs (telemetry, monetization, etc.). Larger game studios may build their own platform, like Battle.net or Steam, while smaller indie games might use something like PlayFab or GameSparks.

I would note that building out the platform for a game is a very large and serious undertaking; the effort to build out a scalable platform for a successful game can take far more time, money, and effort than building most games themselves. I'd recommend using an existing service like PlayFab, especially if you have limited experience building online games or a very small dev team (e.g. one person).
> 2 votes

---
Tags: unity, mobile, facebook
---


title: 2d Grid Generation (Unity C#)

text:
# Question
Title: 2d Grid Generation (Unity C#)
I am creating a simple program in Unity C# that will generate a 2d grid using a 2d sprite prefab. I am stuck here, I don't know what to do. When ran, I receive an error.

```
Assets/Generator.cs(22,75): error CS0165: Use of unassigned local variable `grid_object'

```

I am a beginner, so I'm not sure what to do. This is most likely a rookie mistake, so thanks in advance.

```
using UnityEngine;
using System.Collections;
public class Generator : MonoBehaviour {

public float Width = 20;
public float Height = 20;
public Transform grid_object;
private GameObject [,] grid = new GameObject[20,20];

void Start () {
    CreateGrid();
}

private void CreateGrid() {

    for (int x = 0; x < Width; x++) {
        for (int y = 0; y < Height; y++) {
            GameObject grid_object = (GameObject)Instantiate(grid_object);
            grid_object.transform.position = new Vector2(
                grid_object.transform.position.x+x,
                grid_object.transform.position.y+y);
            grid[x,y] = grid_object;
        }
    }
 }
}

```

# Answer
Your Transform grid\_object and your GameObject grid\_object have the same name. Change one of them to something different and it should work.
> 1 votes

---
Tags: unity, c#, 2d, grid
---


title: Storing large amounts of voxels in file

text:
# Question
Title: Storing large amounts of voxels in file
I'm making a game similar to Dwarf Fortress and I've run into a large problem from the start. How can you store such a large amount of land on disk. With every voxel holding an integer with the 28 MSB representing its type and the 8 LSB having flags like transparency or if it can be walked through a world similar to dwarf fortress would take up almost 18 000 GB. chunks(16 X 16 X 256 voxels) regions(64 X 64 chunks) and world(128 X 128 regions).

I know about Run Length Encoding which could save a lot of memory but its unpredictable because I don't know how many different block types there will be. However it will definitely use less memory so I will use it. I also thought that if I use Perlin Noise for everything I could regenerate everything from scratch if the player came close and only store the areas the player changed (and maybe towns because regenerating them could be time consuming) so I could definitely save a lot of memory there.

I read that Dwarf Fortress doesn't use Perlin Noise or anything like that, and it seems that it generates the whole map at once and saves it with data like erosion from rivers. Can anyone suggest another method that I could use to store a map as much expansive as the one in dwarf fortress?

Ok so it thought of a way to store rivers erosion, as a heightmap of subtractions to the terrain height and only store the heightmap of chunks that have rivers and also use run length encoding, then generate everything else that the player didn't change each time.

# Answer
I store the voxel values(-1 to 1 range) in a volume texture 512 x 512 x 48 and just convert the 16bit floats to a byte like this value\*255 and then write that out to disk and then when I come to reading it back in to be polygonised I just do value/255.

While it may not be the exact value that I had to start with its very close and because I want random terrain it works well plus it only gets rounded up by a little bit. I use Marching cubes to polygonise the volume texture.

That comes in at 25-50mb depending on how full the volume texture is.

Maybe you could store a few volume textures at different resolutions for you regions and world.

I don't really start with an array because I generate my noise on the GPU(Volume Texture). Once I have my volume texture I convert that into one big flat array like this:

```
    Public Sub ProcessVolumeData(_device As DirectXDevice, ByRef _Context As DrawContext)
    Dim textureCopy As Texture3D
    Dim texDesc As Texture3DDescription
    texDesc.Width = mWidth
    texDesc.Height = mHeight
    texDesc.Depth = mDepth
    texDesc.MipLevels = 0
    texDesc.Format = DXGI.Format.R16_Float
    texDesc.Usage = ResourceUsage.Staging
    texDesc.BindFlags = BindFlags.None
    texDesc.CpuAccessFlags = CpuAccessFlags.Read
    texDesc.OptionFlags = ResourceOptionFlags.None
    textureCopy = New Texture3D(_device, texDesc)

    _Context.CopyResource(NoiseVolume, textureCopy)

    Dim dataBox As DataBox = _Context.MapSubresource(textureCopy, 0, MapMode.Read, Direct3D11.MapFlags.None)

        If mScalars IsNot Nothing Then
            mScalars = Nothing
        End If
        mScalars = New Single(mWidth * mHeight * mDepth - 1) {}
        Utilities.Read(Of Single)(dataBox.DataPointer, mScalars, 0, mScalars.Count)
        HaveVolumeData = True
        dataBox = Nothing
        textureCopy.Dispose()
        textureCopy = Nothing

End Sub

```

I don't ever write to the volume texture from the CPU so I cant help you with away to convert your array into a volume texture but it should just be a matter of writing the values in a flat array to a volume texture with the correct stride(just guessing).

I store my noise values in the -1 to 1 range as a float16 on the GPU and then when I want to write it to disk I do this:

```
        Dim fs As New FileStream(DirectXDevice.ContentPath & "\VolumeData.vdf", FileMode.Create)
        Dim swriter As New BinaryWriter(fs)

        Dim i As Integer = 0
        While i < mScalars.Length
            Dim sc As SByte = CType(mScalars(i) * (255), SByte)
            swriter.Write(sc)
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While

```

Now for marching cubes you should really start a new question because its a complex yet fun topic in it self... but ill give you a little bit just to get you started.

I use a very modified version of Paul Bourke's marching cube algorithm well its kind based off of it but I think its a good place to start.

Basically with marching cubes you use array of scalar values as a density field and convert it into a polygon mesh

I run marching cubes and build a 3 dimensional array(512x512x48) of voxels like this using pos.x(512), pos.z(512), pos.y(48) where +Y is up.

```
  Parallel.[For](0, CInt(size.X), po, Sub(xxx)
                                            Dim y As Integer = 0
                                            While y < size.Y
                                                Dim z As Integer = 0
                                                While z < size.Z
                                                    Dim position As New Vector3(xxx, y, z)
                                                    _grids(xxx, y, z) = New Voxel
                                                    _grids(xxx, y, z).Position = position

                                                    Dim weight As Single
                                                    weight = CSng(WorldVolume.sampleVolume(_grids(xxx, y, z).Position.X, _grids(xxx, y, z).Position.Y, _grids(xxx, y, z).Position.Z))
                                                    _grids(xxx, y, z).Weight = Clamp(weight, -1, 1)

                                                    z += 1
                                                End While
                                                y += 1
                                            End While
                                        End Sub)

 Private Function fSample1(X As Single, Y As Single, Z As Single) As Single
    Return CSng(mScalars(X + (Z * mWidth) + (Y * mWidth * mHeight)))
End Function

Public Function sampleVolume(x As Integer, y As Integer, z As Integer) As Half

    Dim w As Integer = mWidth - 1
    Dim h As Integer = mDepth - 1
    Dim d As Integer = mHeight - 1

    x = If(x < 0, x Mod w + w, x Mod w)
    y = If(y < 0, y Mod h + h, y Mod h)
    z = If(z < 0, z Mod d + d, z Mod d)

    Dim ix As Integer = CType(x, Integer)
    Dim iy As Integer = CType(y, Integer)
    Dim iz As Integer = CType(z, Integer)

    Dim dx As Double = x - ix
    Dim dy As Double = y - iy
    Dim dz As Double = z - iz

    Dim ixi As Integer = ix + 1
    Dim iyi As Integer = iy + 1
    Dim izi As Integer = iz + 1

    ixi = If(ixi = mWidth, 0, ixi)
    iyi = If(iyi = mDepth, 0, iyi)
    izi = If(izi = mHeight, 0, izi)

    Dim c1 As Double = fSample1(ix, iy, iz)
    Dim c2 As Double = fSample1(ix, iy, izi)
    Dim c3 As Double = fSample1(ixi, iy, izi)
    Dim c4 As Double = fSample1(ixi, iy, iz)
    Dim c5 As Double = fSample1(ix, iyi, iz)
    Dim c6 As Double = fSample1(ix, iyi, izi)
    Dim c7 As Double = fSample1(ixi, iyi, izi)
    Dim c8 As Double = fSample1(ixi, iyi, iz)

    Dim c14 As Double = c4 * dx + c1 * (1 - dx)
    Dim c23 As Double = c3 * dx + c2 * (1 - dx)
    Dim c58 As Double = c8 * dx + c5 * (1 - dx)
    Dim c67 As Double = c7 * dx + c6 * (1 - dx)

    Dim c1423 As Double = c23 * dz + c14 * (1 - dz)
    Dim c5867 As Double = c67 * dz + c58 * (1 - dz)

    Dim result As Double = c5867 * dy + c1423 * (1 - dy)

    Return result
End Function

```

Only showing a very very small part of the marching cubes stuff.

Ps. marching cubes is not the best but I'm sure you will find that out after doing some reading.... still works well for me but there is better.
> 1 votes

---
Tags: voxels, storage, compression
---


title: AI and EntitySystem

text:
# Question
Title: AI and EntitySystem
I'm using an Entity-Component System and have an AI System that acts on certain entities (agents) within the system. My question is: how should the AI system interact with the world and the agents? I'm considering two opposite approaches:

If the AI deems something is supposed to happen (e.g. an agent is sleeping, which causes its Fatigue level to decrease):

1. It does this directly. (e.g. the AI system mutates the fatigue property on the agent on each update)
2. It adds one or more Components to the entities. (e.g. the AI system adds, once, a SleepNowComponent to the agent, and then waits for it to reach a terminal state on each update)

Pros/cons of #1: it's simple, however if I ever had another section of code that did basically the same thing, I'd have to either duplicate or factor it out into a common function.

Pros/cons of #2: it's more complicated -- if the agent's AI is in the "sleep" subroutine, the AI system will basically do nothing on that agent except check to make sure that the proper component is attached to the entity. When the component is finished (e.g. the fatigue property of the agent reaches 0), the AI will move onto the next task. On the bright side, if any part of the game needs the entity to sleep, it's as simple as adding the right component.

What are people's thoughts on this? I'm pretty evenly split between the #1 and #2 options right now.

# Answer
> 1 votes
Your second option seems like an over-engineered way to perform the first option. Consequently I'd advise you simply go with the first option.

An agent has an API, a public interface that dictates what can be asked of that agent by other systems in your code. It's *perfectly reasonable* (and in fact, *perfectly clear*) to manipulate an object through its public API. It's usually the best way to go about things.

Your second option, attaching some component to the agent, implies one of three things:

1. either the component will directly tell the agent what to do (adjust the fatigue level) via the agent's public API
2. or the agent will know to look for the component and if it exists, manipulate its fatigue privately
3. or the component will manipulate the agent's fatigue privately via some back-door API (such as `friend` access in C++)

None of these are great, in my experience. With (1), you're just creating an unnecessary level of indirection between the AI deciding something should happen to the agent and the agent being made to respond accordingly.

(2) could be used if the agent didn't want to expose its fatigue publicly for whatever reason (more on this below), but means that this behavior needs to be written for any entity that might support "sleeping;" the AI system could easily attach a `SleepNowComponent` to an object that doesn't know about `SleepNowComponent` and will effectively do nothing. Now you're written to an *assumed-public* API that you have less certainty will actually have any effect.

(3) doesn't seem like the best use of friendship or similar to me; by connecting the component and the entity together in such a fashion behind the scenes you're not really saving yourself a ton of work or protecting yourself from an otherwise easy-to-make logical error. Fatigue should really be a public part of the API, obviating the need for the friendship and bringing us back to scenario (1).

So I think you should have the AI directly tell agents what to do when it is appropriate. I don't quite see how you think this would end up with a code-duplication problem, but perhaps I am missing something about the rest of your architecture or what you are thinking.

---

That said, for all that I went with your fatigue/sleeping example above, I don't think that example itself is a great idea. If being "asleep" means fatigue should decrease over time, this seems to be something that should be handled *by the thing that is sleeping* itself, otherwise it seems like you're building architectures where it's very easy for alleged invariants to be violated (e.g., "sleeping decrease fatigue" but only if something *else* tells a sleeping thing to remove fatigue).

I also think it smells funny to leverage a whole component to simply toggle a state (which is what the name of `SleepNowComponent` implies).

---
Tags: entity-system
---


# Question
Title: How do I get more installs for my android app?
Me and my team developed a slot machine game, and posted it on Google Play. Right now, it sits in position 460+ of the casino category. The number of installs is less than 1,000 and daily users range between 90 and 140.

I want to increase the number of installs to promote my game in the store, but I need also these installs to be converted to daily users. I tried some big networks that provide a huge amount of installs, but they only convert to uninstalls.

Can anyone suggest a trusted source with good prices and good quality of installs?

# Answer
"Buying" installs isn't a sustainable marketing model. Such "bought" users are usually bots or employees of the company. These are fake users who won't actually use your app seriously.

It might help you to temporarily get a few ranks in the app store popularity charts, but unless you buy so many that you get into the toplist of a very frequent search term, that won't give you the exposure you need to attract real users. Also, Google, Apple et al. really hate people who use such underhanded tactics to fake the popularity of their products and will punish you accordingly when they catch you.

If you want to have a successful game, make a game which is worth being successful. Make something with a new, unique and innovative game idea which you can market properly using the methods described in the question "How can I promote my game?".
> 0 votes

---
Tags: marketing, appstore
---


# Question
Title: Framerate-independent game loops and discrete tasks
When writing good framerate-independent game code, you take some sort of `deltaTime` parameter in your main `render()` function and then scale your calculations based on that -- this is essential for things like physics engines.

However, in my game there are often discrete tasks -- the AI system might add components representing a "task" to the agents that should be removed (finished) after `x` seconds have passed. To make a contrived example, if a task/component takes 60ms to process, and the game is running at 60fps (16.6ms/frame), then the first three frames will run, bringing the "work done" on that task to 50ms, and then one last frame will do 10ms of work, but then the remaining 6.6ms will be "lost", because the AI system won't run and schedule new work until the next frame.

Ideally, I'd like to not lose the "loose change" of ms that occurs at the end of tasks.

How do people normally deal with this? I can think of a few options:

1. Ignore it -- the shortest tasks will probably never be less than 100ms anyway, generally more in the 1-5 second range. It's not multiplayer, and provided the game can maintain 60 fps (which it probably can), the experience should be the same for all players.
2. "Carry" the remainder over to the next frame. In the example above, give the agents 23.2ms of time to "spend" in the next frame.
3. Amp up the framerate. At 60fps, the most time you can possibly waste is 16.6ms, but at 200fps you can lose at most 5ms. (Currently my logic loop and render loop are coupled and capped at 60fps, but I can easily change that.)

# Answer
> 1 votes
I typically use a variation of #2 where I keep track of the amount of time since the task was last executed, and then subtract the interval as shown in the pseudo-code below:

```
private float timeSinceExecution = 0.00f;
private float taskLength = 5.00f; // 5 seconds
@Override public void render() {
  // Do render-y stuff.
  timeSinceExecution += Gdx.graphics.getDeltaTime();
  while(timeSinceExecution > taskLength) {
    executeTask();
    timeSinceExecution -= taskLength;
  }
}

```

This could easily be enhanced to be a task system or to include tasks that only run a set number of times. The reason I like using this method is that it makes sure that these interval-based tasks execute a consistent number of times regardless of the delays.

#1 and #3 I don't recommend because your game's behavior will change based on the host computer's speed. I've seen this before on older games and it's a bummer. That being said, with today's computers this is a lot less likely, and I agree with @JustinWilliamStanleyBryant that this is probably not a real issue.

---
Tags: libgdx, game-loop
---