# Question
Title: In lockstep networking game, how to handle sudden lags and disconnection?
I am trying to implement a game similar to "Street Fighter" by using lockstep networking model so that two players can play remotely via Internet.

I have read a lot of articles about lockstep networking method and I can basically implement the turn/frame handling for each step.

My understanding is that if it's now turn 101 and if player A has not received turn 101 action (packet) from player B, player A has to wait.

When this situation happens, player B has to wait too because player A will not send out further actions to player B because he is waiting.

Should the game do anything for this situation? For example, I saw games like Starcraft, sometimes there is a dialog showing up to wait for other players and if the count down goes to 0, players can disconnect this hanging player.

In order to do so, I don't understand how to decide who is lagging and what the proper handling is. Both player A or player B would think the other party is lagging because he does not receive the packet for his current turn. What am I going to show to the user? And if the lagging continues, how to end the game earlier by giving a correct game result (the player who lags should be given a loss and the other player should be given a win)? Just similar to the countdown dialog in Starcraft.

And on the other hand, what if the situation is not lagging but is a disconnection from player B?

# Answer
> 2 votes
With a multiplayer \>2 game like StarCraft you can do a best out of X to figure out who's lagging.

With a 2 player game there is no way to know who's at fault as it's a single connection, its that **one connection** that is having issue.

Again, there is no such thing as player B being disconnected as the one single connection gets broken, both A and B gets disconnected from one another.

You would need a 3rd party such as a game-lobby server to figure out who's at fault. If lobby server is still connected to A but both A and server lost connection to B then B got disconnected from the internet.

Now, the danger in automatically giving the player who lags a loss and the other player a win is that say player A has a fiber-optic connection or access to a botnet, and player B has a regular DSL (even a voice modem can have good ping to handle a street-fighter game), **player A can easily DDOS player B into lagging and a disconnection** for an easy win.

On the other hand, if you give out draws on disconnection player B seeing as he's losing can disconnect to force a draw.

Welcome to the mess that is dealing with cheaters to ensure en enjoyable experience for the other customers.

Cheers,

PS: I want to re-iterate that an actual hardware modem, even 14.4Kbps, can have a ping low enough to handle street-fighter style lock-step game if all you're sending are tiny game-controller data packets. Turning off the modem's data compression improves the ping further and can even beat DSLs connections on ping. Many rural areas are still forced to use old voice modems, just to say that you could have very different connection types playing your game, leading to the issues of packet-flooding cheaters.

# Answer
> 1 votes
Lockstep Networking is simple in theory but hard in practice. I've implemented lockstep networked fight systems for AAA online games and I have a few recommendations.

1. The most important thing is player comfort. If you do an attack, you must play some kind of action on the local player immediately (ie. The next frame). This can be a swing anim, or an effect, or whatever. You MUST not wait for a reply before starting the action as the added latency will make your game feel awful to play.
2. The most difficult part of Lockstep is to deal with the transmission latency. On LAN, its almost negligible, so it feels fast and good. However as soon as you play online, the 50 - 200ms or so of latency will make your game sluggish and unresponsive. There are a few things you can do to help this:
a) Decouple your sent inputs from your received ones. Build your system to allow received inputs to be several frames behind where your sent ones are. This means occasionally you will have input conflicts or incorrect actions, but correcting for these is better than dealing with bad latency.
b) The difference time between the inputs you're sending and the inputs you're recieving is called the 'Transmission Window'. It will shrink and grow depending on your latency. When it gets too big, you know that someone is lagging out. This is how you detect which players to kick. If you're sending at tick 15000 but only recieving tick 14000 from player N, it's time to kick player N out.
c) Packet loss is your enemy. Losing a single packet in a Lockstep system will screw up your simulation. Even with reliable transmission, the delay between re-requesting a given packet and waiting for it to arrive will grow your Transmission Window like crazy. The solution is to redundantly send historical data with each packet. Lockstep input messages tend to be small, so find out what the maximum packet size for your platform is, and then pack as many old inputs in there as you can. Then, when receiving, if you're expecting input 1200 but you get 1202, you can probably get the missing inputs from the newest packet and avoid a resend.

You mentioned dealing with disconnections: I have an answer to another question that deals with this: Dealing with disconnecting players

---
Tags: architecture, networking, multiplayer, synchronization, latency
---


# Question
Title: How to Convert a Z Up Matrix to a Y Up Matrix?
My 3D program exports my vertex data and instancing matrixes in Z+ up format. I want to store them in my own data format as Y+ up. If given a Matrix4 describing a position with Z+ being up. How can I convert that to a Y+ up Matrix4?

I know you can just rotate the object but I don't want to rotate the object.

# Answer
Anything you'd do would effectively be a rotation.

That's the matrix to apply to your other matrix:

```
[1 0 0 0]
[0 0 -1 0]
[0 1 0 0]
[0 0 0 1]

```

Alternatively:

```
[1 0 0 0]
[0 0 1 0]
[0 1 0 0]
[0 0 0 1]

```

Depending if you also need to convert a rhs/lhs (right-hand-system, left-hand-system) which I cannot infer from the information available. Both are a possibility.

If your mesh ends up all back-faces use the other matrix. That's because the 3D software package use a different system.
> 2 votes

---
Tags: matrix
---


# Question
Title: How to generate Bayer matrix of arbitrary size?
In ordered dithering Bayer matrix is used.

How is that matrix generated? What algorithm can be used to generate matrix of arbitrary size?

# Answer
(As @Bálint seems not to have gotten around to it… :)

To quote the article as it (likely) was when you initially asked:

> Arbitrary size threshold maps can be devised with a simple rule: First fill each slot with a successive integer starting from 1. Then reorder them such that the average distance between two successive numbers in the map is as large as possible, ensuring that the table "wraps" around at edges.

A more detailed explanation has since been added to the article:

> For threshold maps whose dimensions are a power of two, the map can be generated recursively via:
>
> The recursive expression can be calculated explicitly using only bit arithmetic:
> `M(i, j) = bit_reverse(bit_interleave(bitwise_xor(x, y), x)) / n ^ 2`

That last bit can be implemented with little trouble in e.g. Python:

```
def bit_reverse(x, n):
    return int(bin(x)[2:].zfill(n)[::-1], 2)

def bit_interleave(x, y, n):
    x = bin(x)[2:].zfill(n)
    y = bin(y)[2:].zfill(n)
    return int(''.join(''.join(i) for i in zip(x, y)), 2)

def bayer_entry(x, y, n):
    return bit_reverse(bit_interleave(x ^ y, y, n), 2*n)

def bayer_matrix(n):
    r = range(2**n)
    return [[bayer_entry(x, y, n) for x in r] for y in r]

print(bayer_matrix(2))

```

This doesn't produce *quite* the same matrix as listed in the Wikipedia article, but as the author of the original source writes, "it is good enough in practice".
> 2 votes

---
Tags: algorithm
---


# Question
Title: How to create a White Hot thermal camera?
I'm very new to Unity and at this point I don't even really know what questions to ask to move forward with what I want to do.

My end goal is the ability to switch between a standard color view, a White Hot thermal camera kind of view, and a Black Hot thermal view. If I can figure out how to do White Hot, I imagine it'll be trivial to do Black Hot as well.

Here is a real-world image of the effect I'm trying to come up with:

My guess right now is that I could achieve this with 3 different cameras. One for each view mode.

I figure I could create an object with a full color material and have a child object with a different material to show to a camera that only shows White Hot objects. I could filter on tags so only the main object or one of it's child objects is visible at a time but this would require 3 times as many objects in my game. I would hope there's a way to show a Color camera one material but show a WhiteHot camera a different material but I don't see any way to do that.

I found a forum thread about thermal vision but I don't know anything about shaders and the provided sample project won't run in the web player and doesn't gracefully upgrade to my version of Unity.

Where is square one when it comes to having different "camera modes" like this?

**EDIT:** A brief look into shaders has shown semi-fruitful. I've created the following ultra-simple shader:

```
Shader "Custom/WhiteHotUnlit"
{
    Properties
    {
        _Temp("Temperature", Float) = 0.0
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            float _Temp;

            struct vertInput {
                float4 pos : POSITION;
            };
            struct vertOutput {
                float4 pos : SV_POSITION;
            };

            vertOutput vert(vertInput input) {
                vertOutput o;
                o.pos = mul(UNITY_MATRIX_MVP, input.pos);
                return o;
            }

            half4 frag(vertOutput output) : COLOR {
                return half4(1.0 * _Temp, 1.0 * _Temp, 1.0 * _Temp, 1.0);
            }
            ENDCG
        }
    }
}

```

This allows me to use the shader on an object and set that object's Temperature and it'll show as a shade of gray depending on that temp. This also lets me set it on a per-object basis. So far so good! However, I can't seem to figure out how to have two shaders on an object. I want my Color Camera to display all objects using the Standard shader and when I switch to the WhiteHot Camera then it should render everything with the WhiteHot shader WITH THE TEMP VALUE ASSIGNED TO THAT OBJECT. I set up the second camera with:

```
WhiteHot.SetReplacementShader(whShader, null);

```

And nothing gets drawn when I'm using that camera. I also can't seem to give one object two mesh renderers. I guess that makes sense, but I was hoping to do one renderer per camera. I feel like I'm getting much closer! But I'm not there quite yet...

**EDIT 2:** Since Vertex and Fragment shaders seem to override and remove shadows (please correct me if I'm wrong, PLEASE) then I've decided to try a surface shader. I've switched to a one camera, one shader approach.

Here's my surface shader right now:

```
Shader "Custom/WhiteHotLit" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.0
        _Metallic ("Metallic", Range(0,1)) = 0.0

        //_Mode ("Mode", Int) = 0
        _Temp ("Temperature", Range(0, 1)) = 0.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        uniform int _Mode = 0;
        float _Temp;

        void surf(Input IN, inout SurfaceOutputStandard o) {
            switch (_Mode) {
            case 1:
                // Here I don't want shadows or lighting
                o.Albedo = fixed3(_Temp, _Temp, _Temp);
                break;
            case 2:
                // Here I don't want shadows or lighting
                o.Albedo = fixed3(1.0 - _Temp, 1.0 - _Temp, 1.0 - _Temp);
                break;
            default:
                // Here I want shadows and lighting
                fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
                o.Albedo = c.rgb;
                o.Metallic = _Metallic;
                o.Smoothness = _Glossiness;
                o.Alpha = c.a;
                break;
            }
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Now I can make a call to `Shader.SetGlobalInt('_Mode', <int>);` and change it to 0 (Full Color), 1 (White Hot), or 2 (Black Hot). However, just like Vertex/Fragment Shaders seem to always exclude shadows, this Surface Shader always includes them. I'd like to find a way that for Mode's 1 and 2 I can turn off shadows.

I could turn off all the lights and adjust the ambient light but that sounds like a duct tape kind of solution to this. Could a multi-pass shader do what I want? On one pass could it be a surface shader and on another pass could it be a vertex/fragment shader?

# Answer
> 1 votes
Unfortunately, I think the *right* way to implement a realistic thermal vision would be difficult to execute in Unity, as it would require utilization of some experimental stuff. Ideally, you would add a temperature texture property to the standard deferred shader, then add a new 'temperature' buffer pass to the deferred rendering pipeline using that texture property, then your camera could then grab that pass and render it at the flick of a switch.

Alternatively, you could use a post-process effect to achieve a similar result. Here you'll write a shader similar to a ramp shader (see ToonRamp shader here), which maps the final color value of your image to a 'thermal' value. Work-pipeline wise this would be super easy to execute, but it may be difficult to achieve the desired look, because you won't have access to some hidden 'temperature' property.

As for your current implementation, it could work by writing a custom lighting function and adding your switch statement in there to switch between lighting styles, but in general, you want to avoid branching code in shaders because it significantly impacts performance. A much more efficient solution (and frankly, easier to implement on a complex project) is Unity's shader replacement feature. So, you'll want to use 3 separate shaders, one for normal, white-hot, and black hot, then flip between them. Keep in mind, though, that this will force forward-rendering onto your project, because for now, unity has its lighting system for deferred rendering hidden in a black box.

---
Tags: unity
---


# Question
Title: Converting UnityScript code to C#: What is the alternative for .ToBuiltin?
I'm trying to convert this code from UnityScript (Unity's version of JavaScript) to C#:

```
var polys = new Array(); // array to collect vertex locations
polys.Push((scanpoint + padding) + Vector2(0.5, 0.5) * Pixel_vs_Unit_Scale);
var poly:Vector2[] = polys.ToBuiltin(Vector2);

```

I converted the first two lines like so, with no errors:

```
var polys = new List<Vector2>();
polys.Add((scanpoint + padding) + new Vector2(0.5f, 0.5f) * Pixel_vs_Unit_Scale);

```

But when I try to adapt the last line like this:

```
Vector2[] poly = polys.ToBuiltin(Vector2);

```

I get two errors:

> ToBuiltin does not exist.

And also an error on the `Vector2` inside the `()`:

> Vector2 is a type which is not valid in the given context.

How can I convert this code to C# correctly?

# Answer
> 5 votes
In Unity's JavaScript implementation (sometimes called UnityScript), there are two types of array: JavaScript-style arrays, which have no particular type or length, and "Builtin" (native .NET arrays), which have a specific type and length.

In C#, we usually prefer to work with statically typed variables, so the usual equivalents we'd use would be:

* Generic Lists (`List<SomeType>`) if we want to be able to grow & shrink the collection dynamically
* Typed Arrays (`SomeType[]`) if we want to work with a fixed-size collection.

A list can produce a fixed-size typed array copy of its current contents with the `.ToArray` method. So, we can translate your code like so:

```
var polys = new List<Vector2>();
polys.Add((scanpoint+padding)+Vector2(0.5,0.5)*Pixel_vs_Unit_Scale);
var poly = polys.ToArray();

```

But this is a little silly - `poly` in this case will only ever contain that one item - we don't need the dynamically-sized intermediate to build it up. So unless we're reusing `polys` later in the code, we might as well define the `poly` array directly and then assign that one item to it:

```
var poly = new Vector2[1];
poly[0] = (scanpoint+padding)+Vector2(0.5,0.5)*Pixel_vs_Unit_Scale;

```

or even shorter:

```
var poly = new Vector2[]{(scanpoint+padding)+Vector2(0.5,0.5)*Pixel_vs_Unit_Scale};

```

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


# Question
Title: How can I use another script from a script?
The first script is very long, and I need to use only the top of it:

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

public class mBitmap2MeshV30a : MonoBehaviour
{
    public Texture2D SourceTexture;
    private float Pixel_vs_Unit_Scale = 1;
    public float extrudeDepth = 1;
    private Vector2 scanpoint;
    private bool gotStart = false;
    private int maxsteps = 512;
    public bool invertFaces = false;
    private Mesh srcMesh;
    private mMeshExtrusion2.Edge[] precomputedEdges;
    private List<ExtrudedTrailSectionBM3> sections;

    public class ExtrudedTrailSectionBM3
    {
        public Vector3 point;
        public Matrix4x4 matrix;
        public float time;
    }

```

I need to assign a value to `SourceTexture` from another script. This is the other script:

```
void Start ()
{
    text2d = new Texture2D(10, 10, TextureFormat.ARGB32, false);
    System.Drawing.Font myf = new System.Drawing.Font(FontFamily.GenericSerif, 12);
    Image myimage =  DrawText("Hello", myf, System.Drawing.Color.Red, System.Drawing.Color.Black);
    Bitmap mybitmap = new Bitmap(myimage);

    MemoryStream msFinger = new MemoryStream();
    mybitmap.Save(msFinger, mybitmap.RawFormat);

    text2d.LoadImage(msFinger.ToArray());
    filter.GetComponent<Renderer>().material.mainTexture = text2d;

    mBitmap2MeshV30a bb = new mBitmap2MeshV30a();
    bb.SourceTexture = text2d;
}

```

The problem is I can't make a new `mBitmap2MeshV30a bb = new mBitmap2MeshV30a();`. Both scripts are attached to the same GameObject, in the hierarchy.

# Answer
instead of doing this `mBitmap2MeshV30a bb = new mBitmap2MeshV30a();` make that class singleton.

to create any class as singleton you nees to make an static instance of that class by `public static mBitmap2MeshV30a instance` after creating instance you can provide the instance value to object by providing `instance=this` in `void Awake()` after providing instance you can call any function by `mBitmap2MeshV30a.instance.SourceTexture`.
> 0 votes

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


# Question
Title: Removing the billing permision from a apk build in unity
So recently we made a version of our game that is paid and not free. This of course means that we removed both ads and IAP capabilities. Now I'm sure that I have removed every single peice of code that references ads or IAP from scripts that get built into the apk but Unity still keeps adding the billing permision to the manifest. Apart from exporting a google android project and then modifying the manifest and then buidilng to apk what other options do I have to solve this ?

# Answer
> 1 votes
At least in my case it turns out that under the services tab the IAP option was still ticked on. So even when no scripts reference it that are getting build I guess unity still adds the permision to the manifest.

---
Tags: unity, android, in-app-purchase
---


title: to remove body....in libgdx

text:
# Question
Title: to remove body....in libgdx
I need to fix my destroyed fireball part. so, briefly, you can see there is condition, when fire ball takes 0.5 seconds, it will be destroyed, but the problem is that when I launch fireball more than 5 times, the state time is missing. meaning, statetime from first fireball takes only 0.2 or 0.3 seconds which means not to destroy firstfire ball, then, second fireball will start with 0 of statetime....

so I might need to put delay or change condition to destroy fireball, anyone give some good idea of delay...

```
public void update(float dt){
    if(destroyed)
      return;
    stateTime += dt;

    setRegion((TextureRegion) fireAnimation.getKeyFrame(stateTime, true));
    setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);

    if(b2body.getLinearVelocity().y > 2f)
        b2body.setLinearVelocity(b2body.getLinearVelocity().x, 2f);

if((stateTime > 0.5f &&  !destroyed)) {
        System.out.println("remove");
        world.destroyBody(b2body);
        destroyed = true;
        stateTime=0;
        }
    }

```

> 0.020851972 0.033725634 0.053520873 0.066143505 0.08290026 0.099830225 0.11613068 0.13314703 0.14978832 0.17205454 0.18305379 0.1999722 0.016918411 0.21638213 0.033328343 0.2332518 0.050198004 0.24974939 0.0666956 0.2671502 0.08409641 0.2834545 0.10040071 0.3003866 0.1173328 0.31650147 0.13344765 0.33359608 0.15054226 0.35006973 0.16701591 0.36673754 0.18368372 0.38316628 0.20011248 0.39938805 0.21633424 0.4166165 0.2335627 0.01722846 0.43257055 0.24951674 0.033182513 0.44934398 0.2662902 0.04995595 0.46642104 0.28336725 0.06703302 0.48323897 0.30018517 0.083850935 0.5002271 remove 0.017710429 0.032923356 0.04943849 0.07523671 0.08288573 0.100497365 0.11557686 0.13266633 0.14927213 0.1661589 0.1828977 0.19979131 0.21625298 0.23346049 0.017207505 0.24935424 0.03310126 0.26641506 0.05016208 0.28889254 0.07263956 0.2989407 0.08268771 0.31584114 0.09958816 0.33276853 0.116515554 0.3495424 0.13328943 0.3659887 0.1497357 0.3825479 0.16629489 0.39946073 0.18320774 0.41664386 0.20039086 0.01718313 0.4328036 0.21655062 0.033342883 0.44915196 0.23289897 0.049691234 0.465505 0.24925202 0.066044286 0.48231223 0.26605925 0.082851514 0.49968737 0.2834344 0.100226656 0.51679564 remove 0.01773908 0.03359734 0.050028652 0.06635733 0.08378251 0.1004918 0.117590256 0.13499662 0.15284775 0.16789775 0.18452707 0.016629318 0.20071205 0.0328143 0.21726353 0.04936579 0.23375686 0.06585911 0.25063464 0.082736894 0.26645997 0.098562226 0.28290412 0.11500637 0.299935 0.13203725 0.31656048 0.14866272 0.3334267 0.16552895 0.3501189 0.18222114 0.36671102 0.19881326 0.38633305 0.2184353 0.01962204 0.40130693 0.23340917 0.034595914 0.41854438 0.25064662 0.051833354 0.4356347 0.26773694 0.06892368 0.45077664 0.28287888 0.084065616 0.46706852 0.29917076 0.10035752 0.48343226 0.3155345 0.116721265 0.49974683 0.33184907 0.13303584 0.516265 remove 0.016947491 0.032934472 0.048946258 0.06602675 0.08432648 0.099015966 0.115975864 0.13195857 0.14873886 0.16540411 0.18193763 0.19992903 0.017991396 0.21548836 0.033550724 0.2321489 0.050211262 0.25003594 0.06809831 0.26674396 0.084806316 0.28344768 0.10151005 0.30490693 0.122969285 0.3170895 0.13515186 0.3336414 0.15170377 0.34876966 0.16683203 0.36539513 0.1834575 0.38354647 0.20160884 0.018151337 0.3993547 0.21741706 0.03395956 0.41623548 0.23429784 0.05084034 0.43323898 0.25130135 0.067843854 0.44962156 0.26768392 0.084226415 0.46707925 0.28514162 0.1016841 0.48308077 0.30114314 0.11768562 0.49984995 0.3179123 0.13445479 0.516058 remove 0.01654849 0.031967547 0.0488077 0.0658899 0.08240888 0.09975024 0.11665027 0.13329327 0.14952914 0.16542803 0.18207018 0.19933029 0.017260108 0.2156132 0.033543028 0.23173532 0.049665146 0.24841681 0.06634664 0.26591128 0.0838411 0.28397366 0.10190348 0.30036992 0.11829973 0.3168611 0.13479091 0.33443168 0.1523615 0.35014495 0.16807479 0.3657988 0.18372862 0.38298365 0.20091346 0.01718484 0.3988928 0.21682261 0.03309399 0.41890058 0.2368304 0.05310177 0.43216553 0.25009537 0.06636674 0.45275748 0.27068734 0.0869587 0.46601132 0.28394118 0.100212544 0.48274627 0.30067614 0.116947494 0.49909204 0.3170219 0.13329327 0.51553744 remove

# Answer
> 2 votes
It looks like you are using 1 timer value for all your fireballs and it looks like you want each fireball to last 0.5 seconds before being destroyed. So, what you need to do is to have each fireball have its own timer.

I would have a class called FiireBall which contains all the fireball components as well as its own timer like this:

```
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.physics.box2d.Body;

public class FireBall{
    public Body boxBody;
    public Animation<TextureRegion> animation;
    public float destroyTimer = 0.5f;
    public boolean toBeDestroyed = false;

    public FireBall(Body bod, Animation<TextureRegion>  anim){
        animation = anim;
        boxBody = bod;
    }
    public void update(float delta){
        destroyTimer-= delta;

        if(destroyTimer <= 0){
            toBeDestroyed = true; // set destroy flag
        }

        // .. do your usual drawing
        // setRegion((TextureRegion) fireAnimation.getKeyFrame(stateTime, true));
        // setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);

        //limit speed as usual
        if(boxBody.getLinearVelocity().y > 2f)
            boxBody.setLinearVelocity(boxBody.getLinearVelocity().x, 2f);
    }
}

```

Now you have your fireball you just need to add one when needed with

```
FireBall newBall = new FireBall(box2dBody,animation);

```

Finally, you need an array to store all the FireBalls

```
Array<FireBall> fireballs = new Array<FireBall>();

```

Now you have an array for each of you fireballs you just loop through them each frame like this:

```
    for(FireBall fball:fireballs){
        if(fball.toBeDestroyed){
            System.out.println("remove");
            world.destroyBody(b2body);
        }
    }

```

---
Tags: libgdx, box2d
---


# Question
Title: How can I get Unity to do letterbox/pillarbox to maintain aspect ratio?
I'd like my game to have the same aspect ratio *at all cost*, including keeping all UI elements fixed in the same place. I'm totally ok with losing screen space in the interest of fixing the aspect ratio.

# Answer
> 3 votes
First, attach a `Canvas Scaler` component to the `GameObject` with your `Canvas` on it. Set it to `Scale With Screen Size`. Set the resolution you want your game to mimic. I have 640x1136 set. Set `Screen Match Mode` to `Expand`.

Inside this `GameObject`, create a new one. In my scene, it's called "GameSizingPanel". You can see it just has a `CanvasRenderer` and an `Aspect Ratio Fitter`. Divide the width by the height that you set in the outer object. In my case, 640 / 1136 is 0.56338. Set this number in the `Aspect Ratio` slot. Set the `Aspect Mode` to `Fit In Parent`.

Attach all of your game objects to be displayed under the object with the `Aspect Ratio Fitter` in it.

If you'd like to see what the results are like, you can download the (free) finished product on iOS or Android. It's called "Cognizer". There's also a web version at my website, which you can find in my profile.

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


# Question
Title: Eliminate 0.25 unit 'force fields' around Bullet Physics soft bodies
When I create soft body assemblies in Bullet Physics they will fall under gravity and then float about 0.25 units above a ground plane rigid body, and other rigid bodies all appear to push and interact with them from that same distance (all the rigid bodies correctly interact with each other only when they appear to touch).

Does one of the many soft body parameters cause this?

I can run more experiments to see if this effect is confined to nodes or shared by links/faces/tetras.

The soft body demo is worth another look- perhaps it has the same problem but all objects are so much larger than what I'm working with that it isn't obvious- I was hoping to do 1 unit = 1 meter but then have cm scale objects.

The code is here https://github.com/lucasw/simple\_sim\_ros/blob/master/bullet\_server/src/soft\_body.cpp and elsewhere in that same repository.

**Update**  The soft body demo does appear to be floating just like my own project, the picture above shows a gap between the bottom of the ellipsoid and the ground.

# Answer
Look at btCollisionShape.h

All shapes have a setMargin() method.

`virtual void setMargin(btScalar margin);`

Don't set it to zero though, the manual warns against this! The default value is 0.04 by the way.
> 1 votes

---
Tags: bullet-physics
---


title: Unity App for mobile

text:
# Question
Title: Unity App for mobile
I'm a newbie here I'm willing to acquire a unity game from a developper and he mentionned that the app is Optimized for Mobile Devices. Does it mean I can build it for android and export the apk file?

Thank you for your answers

# Answer
Unity can export for Both IOS and Android... so yes.
> 0 votes

---
Tags: unity
---


# Question
Title: Procedurally generated terrain that has some caves
I want to generate a terrain that has a few overhangs, and some caves. So a simple height field from a 2D noise is out, as there would be no overhangs.

The other extreme, to define a world from a 3D noise field (I typically use marching cubes over a noise field) results in a wildly chaotic terrain.

What would be a good compromise between these two?

Something that produces mostly hills (like a height field), yet exhibits the occasional overhang/cave?

I've added a bias towards 'air' at high altitude, and a bias towards 'dirt' at low altitude, but that only helps me so far. It looks a bit better, but still too alien to be a real terrain.

Any quick hacks I can try, without actually having to simulate gravity, geology, and weather systems?

# Answer
A blog post at the accidental noise library addresses exactly this issue.

It offers the solution of perturbing the xy values, and of a single-pass implicit solution that creates caves that narrow as they near the surface.
> 2 votes

# Answer
You'll probably want to do a 2nd pass and carve caves after doing the regular quick height-map generation pass.

Find a steep slope in the low-frequency height map layer (if you use multiple resolution height map layers) and dig a cave started by using the slope's negated normal.

Same goes with crevices, canyons, and other terrain faults.

Once you build a multiple-pass system to select appropriate locations and spawn caves and canyons you can use it to span other exceptional features like volcanoes, houses, bridges, etc.
> 5 votes

---
Tags: procedural-generation, terrain, perlin-noise, heightmap
---


# Question
Title: Running a C# Function in Unity with a button press
Heads up - I'm not very experienced with Unity, and haven't coded in C# before. (I have some experience in Python)

I'm trying to create an app that requires small packets to be sent from a smartphone to a Raspberry Pi. In order to do this, I'm using OSC - or Open Sound Control. I have the Raspberry Pi setup to listen for messages, just having trouble with Unity.

I'm using UnityOSC (there's two of them) Github: https://github.com/thomasfredericks/UnityOSC Documentation: http://thomasfredericks.github.io/UnityOSC/

I'm trying to send a packet of data whenever a button is pressed (and each button needs to send a different packet to identify which button has been pressed). I don't know how I can create a script that is activated with a button press.

Is there a way to make one script with a function that takes the button name as a parameter and then send that?

Thanks for the help, and if you need more information, please ask! Again - I don't have experience with this and I would appreciate a "lower experience level" explination. Thanks!

# Answer
> 1 votes
1. Create a script with a `public void` method which does what you want.
2. Put that script on a game object in your scene which is always present. This can be the button itself, if you want, but can also be any other game object which is part of the scene from the start.
3. Select the button
4. Click the plus-button in the `On Click ()` panel of the Button's inspector (image 1)
5. Drag the game object with the script onto the slot which reads `None (Object)` (image 2)
6. Select the method from your script (image 3)

Image 1:

Image 2:

Image 3:

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


title: Frame Dependency vs Time Dependency

text:
# Question
Title: Frame Dependency vs Time Dependency
Just today, I was dealing with this very topic in class, and I had a hard time following through the lectures. Could someone explain to me what it means for something to be frame dependent, in layman's terms? As far as I know, it's not Unity-specific. I suppose this applies to every game, regardless of its engine.

An elaborate answer would do really good for me, as I'm a student, and I'm gonna be doing projects on this. Thanks!

# Answer
> 0 votes
A common beginners mistake in game development is to implement the game loop by alternating between moving everything by a fixed amount of pixels and drawing everything. The problem with this approach is that the game will run slower or faster depending on the speed of the user's computer and on how much there is to update and draw at the moment. This is called "frame-dependent game mechanics".

One of the earliest examples of this is the good old arcade classic Space Invaders. You might remember that the game gets faster the more enemy ships the player destroys. It's not a feature, it's a bug! The game has frame-dependent game meachanics. The less enemies there are to draw and update, the more frames the arcade cabinet calculates per second. In this particular game it works because the game starts with a large number of enemies and progresses by reducing them, so the unintended speedup creates a nice difficulty curve.

But in most other games where the number of enemies on the screen just increases with higher difficulty, you would get the opposite effect. Situations which are supposed to be difficult become easy because they run in slow motion. Also, it only works when you target just one very specific hardware setup. When you target devices with different CPUs, your game will run slower or faster depending on the users device. That will make it impossible to deliver a consistent game experience.

But modern games rarely suffer from that problem. As you might have noticed from personal experience with high-end 3d games, the rendering framerate of games tends to go down when there are is a lot going on on the screen. But usually the game mechanics still run with the same speed, even when only 5 frames are actually rendered per second. That's because experienced game developers implement the game mechanics "time-dependent".

There are two approaches to this. The first thing you need to do in either approach at the beginning of your game mechanics update function is to check how much time elapsed since the last time it was called. Unity does this for you, but on other platforms you might have to do your own timekeeping.

One approach is then to take this time difference into account for every single game mechanics calculation you have. Unity makes this quite easy, because it exposes this information in the global variable `Time.deltaTime`. When you use this technique with Unity, you should implement your game mechanics in the `Update` functions of your MonoBehaviour and always take Time.deltaTime into account.

Another approach is to just perform multiple game mechanic updates until the simulated time has caught up with the real time. When you use Unity, you can let Unity do that for you, by putting your code into your `FixedUpdate` function. Unity calls these functions a fixed number of times per second. But it is still good practice to use `Time.deltaTime` in FixedUpdate functions, because you can change the timestep in the Time Manager. When you change the settings of the TimeManager and don't use Time.deltaTime in your scripts, it will affect everything handled by Unity itself but it won't have any effect on what your scripts are doing. This is going to end badly. So either use Time.deltaTime or remember to never touch the TimeManager.

---
Tags: unity, frame-rate
---


# Question
Title: How can i add to a List<Bitmap> also strings?
In the top i have:

```
private Dictionary<String, List<Point>> pointsList;
private List<Bitmap> Scales = new List<Bitmap>();

```

Then in the constructor:

```
for (int i = 0; i < Scales.Count; i++)
        {
            CreateArray(Scales[i]);
        }

```

Then the method CreateArray:

```
private unsafe void CreateArray(Bitmap bmp)
    {
        bool[,] bwValues = new bool[bmp.Height, bmp.Width];

        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        System.Drawing.Imaging.BitmapData bmpData =
            bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
            bmp.PixelFormat);

        byte* ptr = (byte*)bmpData.Scan0;

        int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
        byte[] rgbValues = new byte[bytes];

        for (int y = 0; y < bmp.Height; y++)
        {
            var row = ptr + (y * bmpData.Stride);

            for (int x = 0; x < bmp.Width; x++)
            {
                var pixel = row + x * 4;

                bool isWhite = (pixel[0] == 255 &&
                                pixel[1] == 255 &&
                                pixel[2] == 255 &&
                                pixel[3] == 255);

                bwValues[y, x] = isWhite;

                if (isWhite == true)
                {
                    pointsList["GroupName"].Add(new Point(y, x));
                    //pointsList.Add(new Point(y, x));
                }
            }
        }
    }

```

This is where i want to group the Point List:

```
pointsList["GroupName"].Add(new Point(y, x));

```

Then i'm looping over the pointsList:

```
for (int x = 0; x < pointsList.Count; x++)
        {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.parent = transform;
            cube.transform.position = new Vector3(-pointsList[x].Y, 0, pointsList[x].X);
        }

```

When looping over the pointsList i want to create a prefab of each group of Points. "Group 1" then the points in the list from "Group 2" another prefab.

But i have like 100 Bitmaps in the List i want somehow to separate them to groups in the List for example by string numbers so each numbers of Bitmaps to add "1" then "2" then "3" or maybe "Group 1" and "Group 2" and "Group 3" then i want to be able to read each Group of Bitmaps for example all the Bitmaps from Group 2 to Group 3.

# Answer
Separate the bitmaps into lists that you key by a string:

```
private Dictionary<String, List<Bitmap>> tests;

```
> 1 votes

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


# Question
Title: Skeletal Mesh Cloth Simulation bug (UDK), unexpected behaviour
When I try to move to the left (A) the pawn *and* the cloth move to the left, and when I move to the right (D) the pawn *and* the cloth move to the right too...

Why the cloth always goes in *same* direction than the pawn? I would expect the cloth to go in the *opposite* direction, like dragged by the pawn.

To anyone who's experienced with pawn with cloth simulation: please help me T\_T

Flag model for testing : Flag bug

# Answer
> 0 votes
I found the solution.
The problem was because I combined the cloth with the pawn. That's why when I move the pawn, the cloth will also move to similar direction too.
I have solve it by **separate the cloth as another object and then attach it to the pawn**..

---
Tags: blender, udk, cloth
---


title: How to design an AssetManager?

text:
# Question
Title: How to design an AssetManager?
What is the best approach to designing an AssestManager that will hold references to graphics, sounds, etc. of a game?

Should these assets be stored in a key/value Map pair? I.e. I ask for "background" asset and the Map returns the associated bitmap? Is there an even better way?

Specifically I'm writing an Android/Java game, but answers can be generic.

# Answer
It depends on the scope of your game. An asset manager is absolutely essential for larger titles, less so for smaller games.

For larger titles you have to manage problems such as the following:

* Shared assets - is that brick texture being used by multiple models?
* Asset lifetime - is that asset you loaded 15 minutes ago no longer needed? Reference counting your assets to make sure you know when something is finished with etc
* In DirectX 9 if certain asset types are loaded and your graphics device gets 'lost' (this happens if you press Ctrl+Alt+Del amongst other things) - your game will need to recreate them
* Loading assets in advance of needing them - you couldn't build big open world games without this
* Bulk loading assets - We often pack lots of assets into a single file to improve loading times - seeking around the disc is very time consuming

For smaller titles these things are less of an issue, frameworks like XNA have asset managers within them - there is very little point in re-inventing it.

If you find yourself needing an asset manager, there is no one-size-fits-all solution really, but I've found that a hash map with the key as a hash\* of the filename (lowered and separators all 'fixed') works well for the projects I've worked on.

It is usually not advisable to hardcode filenames in your app, it is usually better to have another data format (such as xml) depict filenames to 'IDs'.

* As an amusing side note, you normally get one hash collision per project.
> 18 votes

# Answer
(Trying to avoid the "don't use an asset manager"-discussion here, since I consider it offtopic.)

A key/value map is a very usable approach.

We have one ResourceManager implementation where Factories for different Resource types can register.

The "getResource" method uses templates to find the correct Factory for the wanted resourcetype and returns a specific ResourceHandle (again using the template to return a SpecificResourceHandle).

The resources are refcounted by the ResourceManager (inside the ResourceHandle) and released when they are not needed anymore.

The first addon we wrote was the "reload(XYZ)" method, which allows us to change resources from outside the running engine without changing any code or reloading the game. (This is essential when artists work on consoles ;) )

Most of the time we have only on instance of the ResourceManager, but sometimes we create a new instance just for a level or a map. This way we can just call "shutdown" on the levelResourceManager and ensure nothing is leaking.

### (brief) example

```
// very abbreviated!
// this code would never survive our coding guidelines ;)

ResourceManager* pRm = new ResourceManager;
pRm->initialize( );
pRm->registerFactory( new TextureFactory );
// [...]
TextureHandle tex = pRm->getResource<Texture>( "test.otx" ); // in real code we use some macro magic here to use CRCs for filenames
tex->storeToHardware( 0 ); // channel 0

pRm->releaseResource( pRm );

// [...]
pRm->shutdown(); // will log any leaked resource

```
> 9 votes

# Answer
Dedicated Manager classes are almost never the right engineering tool. If you only need the asset once (like a background or map) you should only request it once, and let it die normally when you're done with it. If you need to cache a particular kind of object, you should use a factory that first checks a cache and otherwise loads something, puts it in the cache, and then returns it - and that factory can just be a static function accessing a static variable, not a type of its own.

Steve Yegge (among many, many others) has written a good story about how useless manager classes, by way of the singleton pattern, end up being. http://sites.google.com/site/steveyegge2/singleton-considered-stupid
> 6 votes

# Answer
What I like to do for assets is to set up a *lump manager*. Inspired by the Doom engine, lumps are pieces of data that contain assets, stored in a *lump file* that declares lumps' names, lengths, type (bitmap, sound, shader, etc.), and content type (file, another lump, inside the lump file itself). On startup, these lumps are entered into a binary tree, but not loaded yet. Each map (which is also a lump) has a list of dependencies, which are simply the names of lumps that the map needs to work. These lumps, unless they've already been loaded, are loaded at the time the map is loaded. Additionally, the map's adjoining maps' lumps are loaded, just not at the same time, but when the engine is idling for some reason. This can make the maps seamless, and there is no loading screen.

My method is perfect for open-world maps, but a level-based game won't benefit from the seamlessness this method gets you. Hope this helps!
> 4 votes

# Answer
I've always thought that a good asset manager should have several modes of operation. These modes would most likely be separate source modules adhering to a common interface. The two basic modes of operation would be:

* Production Mode - all assets are local and stripped of all meta data
* Development Mode - assests are stored in a database (e.g. MySQL, etc) with additional meta data. The database would be a two tier system with a local database caching a shared database. Content creators would be able to edit and update the shared database and updates automatically propegated to developer / QA systems. It should also be possible to create placeholder content. Since everything is in a database, queries can be made on the database and reports generated to analyse the state of the production.

You'd need a tool that can grab all the assests from the shared database and create the production dataset.

In my years as a developer, I've never seen anything like this, although I've only worked for a handful of companies so my view is not really representative.

*Update*

OK, some negative votes. I'll expand on this design.

Firstly, you don't really need factory classes because if you've got:

```
TextureHandle tex = pRm->getResource<Texture>( "test.otx" );

```

you know the type, so just do:

```
TextureHandle tex = new TextureHandle ("test.otx");

```

but then, what I was trying to say above is that you wouldn't be using explicit filenames anyway, the texture to load would be specified by the model the texture is used on, so you don't actually need a human readable name, it could be a 32 bit integer value, which is much easier for the CPU to handle. So, in the constructor for TextureHandle you'd have:

```
if (texture already loaded)
  update texture reference count
else
  asset_stream = new AssetStream (resource_id)
  asset_stream->ReadBytes
  create texture
  set texture ref count to 1

```

AssetStream uses the resource\_id parameter to find the location of the data. The way it did this would be dependant on the environment you're running in:

In Development: the stream looks up the ID in a database (using SQL for example) to get a filename and then opens the file, the file could be cached locally, or pulled from a server if the local file doesn't exist or is out of date.

In Release: the stream looks up the ID in a key/value table to get an offset/size into a large, packed file (like Doom's WAD file).
> 2 votes

---
Tags: architecture, assets, android
---


# Question
Title: Unity 3D - Game is fine in "play" but when built, player moves diagonal up+left
So I just completed the first "Roll-a-ball" tutorial, but when I run the build, the game ball races to the Upper-Left corner even when I don't press any buttons.

I did the obvious stuff (reboot, build again...) but it still does it for the PC stand-alone build, and not when I play directly from Unity.

My code doesn't seem to be different from the tutorial (see link above). Here's the input handling code inside of the "PlayerController.cs":

```
    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

 Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

 rb.AddForce (movement * speed);
    }
```

Then I added statements to print the Horizontal and Vertical. When inside the IDE and I play it, they're zero, and when I press an arrow key, they move from 0 to 1 floating point in about a second. In the built stand-alone, Horiz is -1, Vert is 1.

```
void SetCountText ()
{
    countText.text =
        "Count: " + count.ToString () + "\n" +
        "Horizontal: " + Input.GetAxis("Horizontal").ToString() + "\n" +
        "Vertical:" + Input.GetAxis("Vertical").ToString()
        ;
    if (count >= 12) {
        winText.text = "YOU WIN!!";
    }
}

```

# Answer
So after a lot of digging and trying random things, I found out that it's my 3DMouse driver. Even when I didn't have the spacenavigator plugged in, there was something that Unity was seeing.

I fixed the issue in settings by unchecking all of the axis.
> 1 votes

---
Tags: unity, build-process
---


# Question
Title: How can i compare Input.anyKeyDown to prefab name?
```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ClickOnKeys : MonoBehaviour
{
    public GameObject[] prefabs;

    void Start()
    {
        prefabs = Resources.LoadAll("Prefabs", typeof(GameObject)).Cast<GameObject>().ToArray();
    }

    void Update()
    {
        if (Input.anyKeyDown)
        {

        }
    }
}

```

For example i have two prefabs the first prefab name is "Hello" the second prefab name is "World"

I want that if i click on the key H it will do something with the prefab name Hello and if i click on W then to do something with the prefab W

I want to compare the clicked key name to the prefab name.

# Answer
This is what i was looking for:

```
void Update()
    {
        if (Input.anyKeyDown)
        {
            if (Input.inputString == prefabs[0].name)
            {
                Instantiate(prefabs[0]);
            }
        }
     }

```
> 0 votes

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


# Question
Title: How to 'point' an arrow in the direction that it's going?
I am relatively new to OpenGL and 3D environments and am having trouble creating a rotation matrix that will rotate an arrow model so it 'points' in the direction that it is going. I am using GLM as a math library. My current approach is to predict the position the arrow will be at next frame and try to rotate the arrow to face that position.

```
double nextVelY = velocity.y - (gravity * (((glfwGetTime() + dt) - clock) / 1000.0));
glm::vec3 nextVelocity = velocity;
nextVelocity.y = pos.y - 0.5 > -3 ? nextVelY : velocity.y;

glm::vec3 lookat = glm::vec3((nextVelocity * glm::vec3(20) * glm::vec3(dt)));
glm::vec3 pos2 = glm::vec3(0);

```

And then try to calculate angles between the current position and the predicted position

```
model = glm::translate(model, pos);
model = glm::scale(model, glm::vec3(0.05));

float angleX = atan(nextVelocity.y / nextVelocity.z);
float angleY = atan(nextVelocity.x / nextVelocity.z);
float angleZ = atan(nextVelocity.x / nextVelocity.y);

glm::vec3 zAxis = glm::normalize(lookat - pos2);
glm::vec3 xAxis = glm::normalize(glm::cross(up, zAxis));
glm::vec3 yAxis = glm::cross(zAxis, yAxis);

model = glm::rotate(model, angleX, xAxis);
model = glm::rotate(model, angleY, yAxis);
model = glm::rotate(model, angleZ, zAxis);

```

I'm not at all sure if this is a good way to try and achieve this. I've also tried using glm::lookAt

```
model = glm::transpose(glm::lookAt(pos2, lookat, glm::vec3(0, 1, 0)));

```

and various other methods I've found with no success.

# Answer
The problem of creating a matrix to point somewhere becomes easy to solve once you understand the make-up of a matrix.

Fundamentally, the 4x4 matrix is just a collection of four vectors:

* The X-Axis
* The Y-Axis
* The Z-Axis
* The Translation (Position)

The identity matrix has x=(1,0,0,0) y=(0,1,0,0), z=(0,0,1,0) and p=(0,0,0,1).

To create a matrix to orient your arrow model, you first need to check how you have modelled your arrow. Is it along the x-axis, the y or the z?

For this discussion I will assume your arrow model points at +x.

The generation of your matrix comes down to generating the four vectors and assembling them into the matrix.

Now, the choice of x-axis is easy: it points to the target for the arrow. Just normalize the target position.

Next, you need to construct two perpendicular axes to this chosen x to come up with an y and z. We will avoid "roll" of the arrow by making the y axis perpendicular to (0,0,1) which is +z, as well as to our chosen x.

This is done with cross product operations.

Recall that for our orthonormal basis, the following is true:

```
x = y × z
y = z × x
z = x × y

```

So in pseudo code:

```
x = targetpos.normalize()
// x now points at target, unit length
y = (0,0,1,0).crossprod( x )
y = y.normalize()
// y is now perpendicular to x, unit length
z = x.crossprod( y )
// z is now perpendicular to both x and y, and unit length
matrix.setRow(0, x)
matrix.setRow(1, y)
matrix.setRow(2, z)
matrix.setRow(3, arrowposition)

```

**Warning**: this code will **not work** if the arrow needs to point straight up to +z, or straight down to -z. In that case, you need to generate the z first, followed by the y-axis.
> 2 votes

---
Tags: opengl, c++, 3d, rotation, glm
---


# Question
Title: How to get object position from a ray hit?
I've been coding a program to teleport an object to a player hands(which is just and empty game object). I did this using ray collision on mouse down, but I cant think of a way to find the position of the object I'm trying to teleport. I'm using GameObject.Find to find position of the hands, but I wanted to know if there was a way to find the position of an object via a ray collision. If there isn't a way to find the position of an object from a ray collision what other way could I find its position.

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

public class BasicCollisonSound : MonoBehaviour {
    public Transform hands;
    public Transform obj;

    void Start()
    {
        hand = GameObject.Find("Hand");
    }

    void Update () {
        if (Input.getkeydown("mouse1"))
        {

            Ray ray;
            RaycastHit hit;

            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit, 100.0f))
            {
                if (hit.collider.tag == "Grabbable")
                {

                    obj.position = hands.position;
                }
            }

        }
    }
}

```

# Answer
You can use `hit.transform` to access the transform property of the object your ray hit. Then you can just set the position from there. (Code not tested, please comment on whether it works or not)

```
if(Physics.Raycast(ray, out hit, 100.0f))
{
     if (hit.collider.tag == "Grabbable")
     {
          hit.transform.position = hands.position;
     }
}

```
> 1 votes

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


# Question
Title: What is the best option to implement buttons as player controls?
I am familiar with programming, but new to Unity. There seems to be a million ways to implement a right and left button for turning the plane. I'm wondering what the standard/easiest/best way to do this would be.

Do I make a single script that references the two sprites "left" and "right" and then detects mouse clicks and figures out whether they are over the sprite?

Should the buttons even be sprites / game objects? Or is there a better option for UI objects?

Should the left and right buttons both have their own scripts?

ps. I absolutely can't stand video tutorials, and it seems like that's all there is for unity :'( so if there is a good written tutorial on unity desgin patterns, let me know please :)

# Answer
> 0 votes
It doesn't matter. At all.

Unless you intend to make some user programmable interface, or to reuse your UI across a large number of games, the only thing that matters about making 2 buttons is that you won't spend more than a couple minutes doing it, thus pondering over how to implement them for a long period of time is a waste of time. You're currently doing a form of premature optimization.

The "official" way is to use the Unity.UI.Button, here's a random video tutorial.

Detecting clicks on sprites, which you suggest, is good too.

If you're really worried about a clean design, the one thing that matters with small things, like 2 buttons, is that the code is easy to delete and redo once you decide to do it a different way. If you just do it, it takes 10 minutes. If deleting the code takes no time and re-implementing it a different way takes another 10 minutes, you didn't really lose anything. But if you constantly worry about doing things the best possible way, instead of implementing solutions, you will lose a lot of time. Just do it, in a way that can easily be removed and replaced by "the best possible way" later, once you decided what "the best possible way" is.

---

It follows that when you need to design a piece of code which you won't be able to easily remove and replace later, it indeed is necessary to think long and hard about the design first.

---
Tags: unity, control
---


# Question
Title: Designing Drops system - How and where chance of drops are defined?
Just found a related topic but I have different/extended questions

I was wondering how the implement the drop system. I have to start designing the DB model for this so I was wondering whether what I am thinking is a good practice or not.

My game is like "City building" kind of browser based game (Flex/Flash app) with PHP and MySQL in the backend. In my game, like in any other games, there are chance based drop rate. I want to design the drop system such a way that I can easily configure

* What item(s) can be dropped from which game element
* What is the percent chance (probability) of getting a drop (a 100% meaning there will be some drop always)
* What percent chance of getting a specific drop. Here I define for each item (if can drop various items) what is the chace of drop, 90% to very frequent, 5% to very rare

I am wondering how the probability is determined? It might sound very noobish but just want to confirm does it mean roll a random number and compare with the odds we defined? If I am not wrong this is good for determining "how much to drop" but not for "what to drop"

Example: If we say drop 1-10 coins or 20-50 coins. I will simply call a random() function and generate a random numbed from the desired range.

Now for other example: Drop one of Bullets (95%), Empty Gun (4%), Loaded Gun (1%)

If I roll a random number range from 1-100 and compare with probability I defined

so, a number between 1-95 drops bullet, and a number between 96-99 drops empty gun and a loaded gun when it generates 100?

Is this how it has to be done? or is there a better way?

**Update:**

Removed 2nd question about hack safety

# Answer
Let me try to go through all your questions in turn.

**1. Checking whether or not a drop occurs given a certain drop chance**

Just use a pseudo-random number generator and compare the result with the drop chance, just as you suggested in your question. For example, if you specify the drop chance in percentage points with up to two decimal places, you could ask

```
rand = generatePseudoRandomNumber(0, 10000) // between 0 and 10,000
if(rand <= dropChance * 100)

```

**2. Checking which events happens given a set of possible events**

Try to use a data structure that is more flexible than hard-coded switch expressions. I coded a basic version of a Lottery class here: https://gist.github.com/3368046. Lottery allows you to do stuff like this:

```
$Lottery = new Lottery();
$Lottery->addEntry($item1, $dropChanceOfItem1);
$Lottery->addEntry($item2, $dropChanceOfItem2);
$Lottery->addEntry($item3, $dropChanceOfItem3);
$drop = $Lottery->getWinner();

```

With my implementation, the drop chances do not even have to add up to 100%; the lottery determines the winner based on the number of lots that each participant has in relation to the other participants of the lottery.

**3. When to check for drops and how to communicate the result to the player**

I'd decide based on what the most critical bottleneck is: If bandwidth is expensive and if your service has a good latency (Amazon?), go for variant 1. If your service has latency issues, go for 2.
> 4 votes

# Answer
Yes, you take each percentage and map it to one or more numbers in that range. E.g. if there's 50% chance of getting a killer rabbit, and 20% chance of getting John Lennon glasses, and 30% of getting chainsaw fuel, then you would have 1...50 be the range for the rabbit, 51...70 for the glasses, and 71...100 for the fuel.

Now you generate a random number (e.g. using rand() or whatever your language offers, limiting it to 1...100 using `1 +(rand() % (100-1)`), and depending on what range it falls in, you know what to drop.

Now this only gives you a single item. To get several items, you just draw several times\*. So you'd be guaranteed to get one of the three above items from draw one, and one of four other smaller items from draw 2. You can even have draws where one of the items that can drop is "nothing". So to have a 2% chance of this dropping the Super Mega Ultra Grooveshark(tm), you'd have range 1-2 be the shark, and 3 to 100 "nothing" and just do an extra draw (generate another random number between 1 and 100) with that.

So your data structure would probably be a list of draws containing a list of items and their percentages, one of which could be a "nothing" item. Then your items (e.g. enemies) would simply reference one of those data structures as their "drop this when I die" structure.

\*) Of course, if you want to always drop two items *together*, you may need to define some sort of "box" item that just contains those to items, then just draw once to get those two.
> 0 votes

# Answer
I'm doing something like this to generate and drop random items.

1. There are 6 main categories.
2. Each category has more than ten items with drop probability percentages.
3. There are 2 attributes that determine the drop system: exploration and intelligence.

This is an example:

```
If exploration < 30

 - category1 0-1 //0= no item. 1= 1 item
 - category2 0-1
...

```

Then, a random number for each category (in case the result was 1) to determinate what item to drop (0-100)

and the last step:

```
if intelligence < 20

 - category1 0-4 //quantity of the item selected.
 - category2 0-4
 - category3 0-4
...

```

in summary, with that "system" the player can get or not-get an item for each category, and a random quantity of each item they do get.
> 0 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: What are the different attributes of a vertex array object (VAO)?
What are the 16 attributes of a VAO?
0. vertex position
1. vertex colours
2. normal vector
3. texture coords
4. ???
5. ???
6. ???
7. ???
8. ???
9. ???
10. ???
11. ???
12. ???
13. ???
14. ???
15. ???

# Answer
> 3 votes
There are not 16 attributes with fixed meaning.

In old (pre 3.x) OpenGL there are a limited number of fixed function vertex attributes, and it is possible to use these in VAOs *in compatibility contexts only*. These correspond to generic vertex attribute (see the following discussion) slots as follows:

0: Position.
1: Vertex weight.
2: Normal.
3: Primary color.
4: Secondary color.
5: Fog coordinate.
8-15: Texture coordinates.

(Slots 6 and 7 have no corresponding fixed attribute).

The GL\_ARB\_vertex\_program extension (from which this list comes) and OpenGL 2.0 introduced generic vertex attributes: these use the numbered slots *only* and they *do not have any particular meaning*. You can interpret the attribute any way that you wish in your shader code.

There are typically 16 of these generic attribute slots, numbered 0 to 15; newer GL\_VERSIONs (and the associated hardware) may support more but you can rely on there being at least 16.

Where the correspondance I mentioned matters is if you are mixing fixed vertex attributes with generic vertex attributes in the same shader, *and only in that case*. So if you use the fixed Position and Normal attributes, for example, then slots 0 and 2 are not available for use by generic attributes in the same shader. If you're not using other fixed attributes then their slot numbers *are* available for use.

On the other hand, if you *only* use fixed attributes then you don't need to worry about slot numbers.

Likewise if you *only* use generic attributes (which is your only choice in core contexts) you can forget that the correspondance even exists. If you wish to use slot 2 for a texture coordinate and slot 4 for the airspeed velocity of an unladen swallow, you can.

So as you should be able to see, for the common cases where you're *only* using fixed attributes, or *only* using generic attributes, then none of this matters and you needn't be concerned with it. If on the other hand you're mixing fixed attributes with generic attributes, then you need to be aware of which slot numbers are or are not available for use.

---
Tags: opengl, lwjgl, vao
---


# Question
Title: Is it legal to use formulas from a professional game?
The *Pokémon* series uses a total of 5 different formulas to determine how much experience is required to get to the next level. Likewise, in RPG games, each character has a formula for determining when they're going to level up, sometimes shared, but generally different.

I want to have that kind of simplicity in my game—I want to have a quick few formulas for each character, or, better yet, for each class.

My question is simple. Am I able to use the formulas that *Pokémon* uses for their level ups (namely **4n^3 / 5**, **n^3** and **5n^3 / 4**), or would I have to come up with my own?

# Answer
I think my comments sway dangerously close to answering this question as best as we can, for being a question and answer site based on *Game Development* and not *Law*, so I am going to elaborate in an answer.

As a disclaimer, I am not a lawyer. This is not legal advice, and when in doubt, you should *always* consult a lawyer; but that is the entire point I am trying to make.

---

Your effectively asking if an *algorithm* is can be copyrighted. This question has been asked on Quora, with the top answer suggesting that the algorithm is automatically protected by being distributed in source code. It goes on to say that the original created is not protected against others recreating the algorithm using *different logic*, suggesting that you may be protected by *changing* the algorithm.

> Jon Seymour, programmer, problem solver, procrastinator. Answered Jan 3, 2016
>
> **The expression of an algorithm in a source code file can be copyrighted.**
>
> Such rights may allow the rights holder to prevent unauthorised reproduction of particular pieces of source code that embody an algorithm. However, such rights do not pertain to the algorithm itself and so copyright itself does not prevent others creating **other** expressions of the same algorithm in some other form, such as a different source code file.

I have found further articles that detail how tricky and confusing this can be, including on imranontech, which describes how the author had the assumption that an algorithm *could not* be copyrighted, and changed their mind after consulting actual legal documentation. It is worth a read, if your interested; he also goes into some case studies of situations where this has come up in court.

---

Bálint makes an excellent point, though from the opposite perspective:

> BTW, since these aren't patented (I'm not sure if you could even patents them) and they're literally 3 to 6 characters long, it's like getting sued by the producer of "Night of the living dead", because your game uses the word zombie – Bálint 3 hours ago

The reason this is an excellent point is because the word zombie *was* a trademark of Marvel. You quite literally *could* have been sued for using it. I can only find articles conveying this fact as one of "ten fun facts", or the like, in the limited time I currently have. I may bring this up, later, on Skeptics.

---

### The point I am trying to make is that you should really consult a lawyer

At the end of the day, these are all sources from other people, on the Internet. Likewise, we are all just random people, on the Internet. If you have *any* doubt, you should consult a lawyer. The reasoning is rather simple; if you can not afford the peace of mind of consulting a lawyer on the matter, you could not afford the repercussions of being sued over your use of the algorithm. In fact, if you *are* allowed to use this algorithm, The Pokemon Company could still sue you over it. It is the resulting action of the court case that determines whether you have the right to use this algorithm, and you could easily be spending a lot of money fighting the case, before you reach this ultimate decision. *Assuming The Pokemon Company finds out, and actually takes action*.

Ultimately, it may not be worth it, and that it something you need to decide for yourself. I am not going to be in any serious trouble, if I am wrong. Neither are any of the other users here. You have a lot more invested in this, and considering your comment that you will very likely alter the algorithm, that might very well be the safest bet to make.
> -1 votes

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


# Question
Title: Android - Google play - enable download app for devices that supports opengl extension
I am using OpenGL ES 2 in my game. However, for simplicity i have used some extensions like VAO. Is there a way, how to disable dowloading of my app for devices, that do not support this (and other) extensions?

I can check it in code, but that is a little late, when user already bought my game and it wont work.

# Answer
> 1 votes
A quick solution is to require OpenGL ES3, by specifying in the AndroidManifest.xml file:

```
<uses-feature android:glEsVersion="0x00030000"/>

```

But that will reduce the number of compatible devices. The good news is that the majority of devices that are active on Google Play support ES3.

Less than 37% of the devices (as of oct 2017) are still on ES2. And that number will continue to drop.

https://developer.android.com/about/dashboards/index.html

---
Tags: android, opengl-es2, google-play
---


# Question
Title: How to manage time in a two player game?
I'm making my first online board game. After the two players accept to play with each other, I want to show a get ready message for 3 seconds, then both start playing together, each has 30 seconds to do an action in his turn.

But I don't know the process.

* Should I pass to clients the time the game will start?
* Should I check from server whether a player's 30 seconds is over? There may be a slight difference in server and client time, and I end a game from server while client still has 27 seconds for example.

What are the steps to have an accurate multiplayer game. Thanks.

# Answer
> 3 votes
The most common and secure way to manage countdown synchronization in a multiplayer game is to make server the authoritative timekeeper. The clients then may request the remaining turn time every 1-5 seconds (arbitrary), which the server will pass down, and interpolate the received amount of seconds based on the ping time. That way, if it took 90 ms to process the request, then the final remaining time for the player to conduct his turn will be `ReceivedAmount` \+ `90 ms`. It is not going to be the *perfect* synchronization, naturally, but it comes pretty close to it.

Since your server handles the time operations, you can be pretty sure that the clients won't be able to change the turn time and gain an advantage. It could be done from the server side, however, depending on the way you implement the feature. Considering the interpolation, you shouldn't run into ping-related desynchronization either.

---
Tags: multiplayer
---


# Question
Title: How to make a player walk over the network
First of all, it is a newbie question and I am a noob so ya.

I am working on `Unity` with `low level network API`. I am able to connect multiple client's to the server and they spawn on clients. All the clients get the information about the location of the other connected player, that is `transform.position` (ie. x, y and z coordinates) Position of all players is updated on all clients, that is, their `transform.position` gets updated with new available coordinates.

**The question:** How do I simulate walking animation (of connected players) on client's screens? (I use `Unity's` `Horizontal` and `Vertical` input)

# Answer
> 0 votes
Welcome to the world of multiplayer online game development, you will find that a lot of stuff is a mix of cheating and interpolation. For example you want to be able to know when to play a walk animation on remote client's screens? Then get the old position aof the object to animate and the new position just received and compute its velocity using the difference in the time stamp of those (yes, you should start using time stamps on your messages).

I cannot be more percise because the argument is very huge. I can suggest you some very useful and informative read that will guide you in this magical word. First of all this important series of articles from Gabriel Gambetta, and then this very useful website with articles about physics in 3d and how to network it.

Hope you are satisfied with my answer, good luck with your learning.

---
Tags: unity, c#, networking, multiplayer, unity-networking
---


title: Game AI architecture for a RTS game

text:
# Question
Title: Game AI architecture for a RTS game
I am developing a **RTS (real-time strategy) game** involving robber and cops. I have designed a simple **rule based AI** system for the robber.

**Goals of the robber AI:**

* Escape from the cops (robber should not get caught)
* Conduct robbery

**Current implementation:**

The robber AI uses a rule based system to escape from the cops. I have written IF-THEN clauses to build the rule based AI system. The robber AI uses the knowledge of cops’ current positions.

**Future requirements:**

I am worried about the current architecture of this robber AI system. I read that rule based systems are inefficient and difficult to maintain. For the future,

1. I want the robber AI to use some power-ups (to escape)
2. The AI should consider the power-ups used by the cops before making decisions.
3. For conducting the robbery, the robber has to move to a specific location escaping from the cops.

**Questions:**

1. Is the current rule based AI system will flexible enough (and easy to maintain) to meet the future requirements?
2. What can be better alternatives for the existing rule based system? (Like decision trees or state machines etc.)
3. I read people suggesting that the rule based systems are difficult to debug. Can anyone explain why?

I would appreciate any thought/suggestions on this topic. Thank you.

# Answer
> 2 votes
**Is the current rule based AI system will flexible enough (and easy to maintain) to meet the future requirements?**

This really depends on your specific implementation. Are all your rules defined in one giant class which has to maintain many states and check those constantly? Are the rules easily readable and understandable? When you want to expand the system how hard would it be to add a rule to the system And would adding that rule lead to problems with the existing rules?

For example if rule A wants to get left and rule B wants to go right what happens? Is rule A checked first and executed without consideration for rule B? Are both rules executed with the delta difference actually happening (Moving left + moving right = standing still).

When you're making the system you have to watch out for what takes priority and what should happen when multiple rules clash. If you don't you will get those hard to debug situations!

**Updated**

Example2: You add a rule that the robber should run away when fired at. Makes sense right? Now you go and add power-ups and one of those is a shield (no bullet damage for X seconds). Now you have to go in and add a rule that when the police is shooting at the robber and there is a shield power up next to him he goes and grabs it and shoots back at the police. You play the game and the robber entirely ignores the power up and runs away. Ok, you switch the priority and it works, awesome. You then decide to spawn more police and run the scenario again.

Like before the robber grabs the shield and shoots back at the police, but once the shield runs out the robber is immediately killed since the shield is no longer protecting him. So then you go and add a new rule that is if there are lots police and they are shooting and you have a shield powerup, use the opportunity and run away. You do that but he doesn't get far enough and is gunned down. So you add a new rule that if he has a shield and is running away from the police but the shield is about to run out find cover.

You can see how this gets out of control quickly... Just add 2-3 more power ups and you will need an exponential amount of rules to cover the different situations that the robber can get into. Then you have to manage priorities for each of of those situations too!

**What can be better alternatives for the existing rule based system? (Like decision trees or state machines etc.)**

Have a look at Task based AI. It is kind of similar to rule based except that a task must be complete before the next one is started (or i suppose you could cancel one and start another based on what is happening around it) this avoids the problem that you face in question 1 as there is always a defined next step in the middle of a task and the only points where it could be troublesome are during the period of time were the next task must be chosen.

A better solution but one that may be harder to implement is an AI which does what is best for the current situation, Goal based AI. Basically you have a bunch of possible actions that the AI can take and you essentially evaluate how useful every action is at the current moment and then do the one which is best. So for a shooter you will want to shoot at the enemy but as you shoot the ammo will be go lower and lower until the point where the score for shooting is lower than reloading (and you reload). I think this would be better in your case as you could just pop in new actions and tweak the scoring function to get the correct behaviour for the game.

**I read people suggesting that the rule based systems are difficult to debug. Can anyone explain why?**

This about the examples from question 1. How would you debug that? You could print out everything that the rules are looking at and try to follow the program but that only works with very few rules, the more you add the more possibility the AI has to go crazy because of X rule. You could make a program which visualises why the AI chose to do a certain action but thats a lot of work that you could avoid by using a different AI technique.

Funnily enough the developers of Sims did have a program which would show why a Sim did a certain thing See this GDC Video (it's a perfect example)

---
Tags: ai, game-mechanics, game-loop, rts
---


title: Game is very slow. How to run it fast?

text:
# Question
Title: Game is very slow. How to run it fast?
I'm developing Android 2D game by extending `SurfaceView`. This is my first game on Android, so I'm not very knowledgeable. I have taken care to optimise the code, but still it's running very slowly.

I'm trying to draw 5 objects, 2 circles, 2 lines and 1 text by using canvas. The circle's radius has to change second by second. I could not to see a change in the circle's radius; it might be software rendering problem. Circles radius is generated by a random value for every second. This random generation is good.

How can I optimise my game to run faster?

# Answer
> 1 votes
In order to make sure you are optimizing the right things you need to figure out which parts of the app are taking so long. Programs which measure programs like that are called "profilers". If you are using an IDE like Android Studio etc., there is usually a profiler built in. The profiler should tell you which functions/methods are slow. Once you know which parts are slow, if you don't know how to make them fast you can ask another more specific question about the code in question.

---
Tags: android, optimization
---


# Question
Title: What do I have to take into consideration when developing both singleplayer and multiplayer coop without dedicated servers?
The premise is simple - a game that can be played in singleplayer mode and that allows seamless partying for coop without dedicated servers. This would of course require server and client components and a singleplayer session would be nothing other than a client joining a (local) server (running in the background). Such a local server would in turn allow others to connect seamless and join a friends session without the need of restarting in a multiplayer game session. And eventually it would make development slightly "easier" since I would not need to work on two different game modes (that behave the same in this setting). I was curious about the workflow during development and some questions came to my mind I'd like to get some input on:

1. At first I'd be tempted to develop everything in the game client itself and not bother about the server since testing the gameplay and game elements themselves would be straightaway easier. With this mindset though I might have trouble moving the game logic that worked locally in the game to the server component and might end up tweaking something. **I'd like to know whether it is feasible/reasonable to develop the core elements of the singleplayer and afterwards migrating to a server/client structure or should I plan on working on both ends simultaneously?**
2. With regards to networking I don't have any experience with it in C++ and appropriate libraries (although I am fairly fluent in C++ and my game will be written using it) and was considering to take a bold approach by ignoring performance at first and sticking to something I am familiar with. Basically I'd write the server using C# or Node and the client networking code in C# (and possibly some library for shared components between the two) and would need a C++/CLI wrapper to call the client network code in my game itself. I'd have extra work to implement the bridge but ultimately I'd be able to get the basics going no matter how patchwerk they might be. At some point of course I'll probably have to translate all three of them (server, client, shared codebase) to native C++ not only for performance but for compatibility. **So do you have suggestions on whether I should be going for something "patchy" using familiar tools and libraries and then migrating it later or should I invest the time to start "properly" with the same codebase and language on both sides?**
3. Finally I have a question that boils down to the design of partying / matchmaking. Usually in multiplayer games you join via directly entering an IP address or using features like the Steam friend list. I'd really like to include a way to connect to specific games without having to mess around with ip addresses and using something like a lobby or even better a friend list. In this case though I'd need a small dedicated server for managing users and such friend lists. **Is there any other design or way to connect besides using raw IP addresses?**

# Answer
OK, so in regards to programming the game itself, there's no real difference. You have to program the server and client. The host connects to his own server, the other players connect to the server which happens to be running on one of the players computers rather than a server somewhere.

Your main problems come in two flavours.

1. Networking. Most people connect to the internet through a dynamically allocated IP address which is inaccessible to other end users.

If I type in the IP address your computer thinks it has on mine. I wont be able to send you any data.

2. Server discovery/Matchmaking etc

Even If you have a public IP address I can connect to, I still need to write you a letter or something to find out what it is. You really need a central server everyone can connect to to check for available games, match making and the like.

Both of these problems tend to be solved by having a server on the internet which everyone connects to and has their game traffic routed though. Cheaper than running the game server yourself, but still you need something.

This is the classic approach. You might be able to do something clever if you only care about local players on the same network, or bluetooth, or if your messages are low bandwidth enough to go over another network, email or twitter or something.
> -1 votes

---
Tags: networking, multiplayer, client-server, server
---


title: How to calculate players engagement?

text:
# Question
Title: How to calculate players engagement?
What metrics could be used to know what certain people think about the game and how much they liked it? I would prefer parameters that don't need players to rate by themselves. Would hours of playing in a single seat be a good parameter about how much players wanted to spend time on game?

# Answer
This is a very tricky concept to measure for many reasons. DMGregory suggests very common metrics in modern games. I would suggest that these metrics, again very common in the industry, do not accurately measure "player engagement" as much as they do "player use". To put that more accurately, these metrics measure both player engagement AND unengaged addiction or unengaged habit. Mobile games, specifically, have become global leaders in using psychology, addictiveness, and gamification to encourage obsessive, addictive, or habitual play for corporate gain.

If you want to measure "fun" or "engagement", I would suggest looking at (some of) those metrics with many, many others to gain a fuller picture of play style.

Metrics that would be useful for this process include:

* Biometrics: Expressions, microexpressions, pulse, brain waves, verbal feedback, nonverbal audible feedback, nonverbal body language, etc. These can require different types of equipment which can be cost prohibitive, or different types of software to utilize facial recognition which could also be cost prohibitive.
* Survey/polling: This can be polling for opinions after the play session, after multiple play sessions, during the play session, or even integrated into the play session as a play mechanic either overtly (the game systems ask for ratings of different levels, areas, enemies) or covertly (the player is asked to choose which level to repeat or which enemy they would rather face again)
* Typical play time metrics: Whether measuring attrition (how many people stop playing after the first jump, the first enemy, the first level, the second level, the third level) or direct play time (how long do players play before quitting for the day? For the week? Forever?), this can give an idea of player engagement, but can also be misleading if the game is designed for an addictive or habitual play style
* Less typical play time metrics: If there are multiple challenges or goals presented in parallel, which are chosen more often? Which less often? Those that are chosen less often, are they never chosen in the first place (meaning the problem lies in the presentation) or are chosen but never chosen again (meaning the problem lies in the execution)
* Attempting to measure frustration or boredom: If player engagement is how much "fun" or "invested" a player is in a game, then the opposite would be how "frustrated" or "bored" the player is. If engagement is "flow", attempt to measure the lack of flow. Is the player dying or repeating a certain segment repeatedly before quitting for the day/week/forever? Is the player breezing through a rather simple segment of the game before quitting for the day/week/forever? Is there a point when the player starts mashing buttons on the controller or mouse or tapping frantically on the phone? Is there a point when frantic mashing or tapping happens right before a loss? Does the player lose "a little" and come back or does the player seem to lose with frantic mashing followed by the session ending? The former suggests normal play while the latter is something everyone has experienced and can easily recognized as "not fun" or "not engaging".
> 13 votes

# Answer
There are a lot of metrics or KPIs (key performance indicators) in common use in mobile games, some which might touch on what you're looking for:

* DAU (Daily Active Users) - how many distinct users play in a single day?
* MAU (Monthly Active Users) - how many distinct users play at least once over a month?
* Stickiness (DAU ÷ MAU) - what fraction of your players are coming back daily?
* Churn - what fraction of players who were active last month don't return this month?
* Duration (1 ÷ Churn) - how long does the average player keep playing the game?

For games with micro-transactions, we can also get a proxy of engagement via willingness to invest money into the game:

* Conversion Rate - what fraction of your players eventually buy at least once?
* ARPU/ARPPU (Average Revenue per (Paying) User) - how much do players spend?
* ARPDAU (Average Revenue per Daily Active User)...

...etc.
> 6 votes

# Answer
Simply tracking user per day and related metrics isn't the only way of measuring user engagement. Another approach involves tracking events, such as: how many users make it through the first level, how many went on the first sidequest, did any users find that secret shortcut you made, etc. Here is an article that should hopefully get you started with this sort of analytics.

https://www.gamasutra.com/blogs/ChristinaChen/20170215/291552/How\_to\_start\_using\_game\_analytics\_in\_2017.php

However if you are interested in the data science behind basic game analytics and commonly used metrics (churn, KPI, etc.) here is an article on that:

https://www.gamasutra.com/blogs/AdamFletcher/20170817/303993/Applying\_Data\_Science\_to\_Understand\_Your\_Players.php

If you are looking for specific implementation for whatever engine you are using probably check the docs for your engine, and then ask another question here if necessary.
> 5 votes

---
Tags: game-design, level-design, metrics
---


# Question
Title: Calculating the latitude & longitude of a raycast hit point on a sphere
I am working on a game where you look at a sphere and get the latitude and longitude of the position.

I get the position on the globe with a raycast along the direction the user is looking. Using this I pass the position and the radius into a method to get the correct latitude and longitude.

**Problem**

I don't believe my math is correct on this one and I am having some trouble figuring it out.

**Code**

```
void Update () {

    if (Physics.Raycast(transform.position, direction: transform.forward, hitInfo: out hit, maxDistance: range))
    {
        Vector3 pointHit = hit.point;
        radius = earth.GetComponent<SphereCollider>().radius;
        //radius = earth.GetComponentInChildren<Renderer>().bounds.extents.magnitude;
        FromVector3(pointHit, radius);
    }
}

public void FromVector3(Vector3 position, float sphereRadius)
{
    float lat = (float)(Math.Acos(position.y / sphereRadius));
    float lon = (float)Math.Atan(position.x / position.z);

    //convert from radians to degrees
    lat *= Mathf.Rad2Deg;
    lon *= Mathf.Rad2Deg;

    Debug.Log(lat + ", " + lon);
}

```

**Output**

My Output for latitude ranges from 89 to 90 and doesn't change very much

My Output for longitude ranges from -11 to 11

# Answer
> 2 votes
I'd modify the method like so:

```
void Update () {

    if (Physics.Raycast(transform.position, transform.forward, out hit, range))
    {
        // Transform into collider's local coordinate system.
        Vector3 offset = hit.collider.transform.InverseTransformPoint(hit.point);
        longLat = ToSpherical(offset);
    }
}

public Vector2 ToSpherical(Vector3 position)
{
    // Convert to a unit vector so our y coordinate is in the range -1...1.
    position = normalize(position);

    // The vertical coordinate (y) varies as the sine of latitude, not the cosine.
    float lat = Mathf.Asin(position.y) * Mathf.Rad2Deg;

    // Use the 2-argument arctangent, which will correctly handle all four quadrants.
    float lon = Mathf.Atan2(position.x, position.z) * Mathf.Rad2Deg;

    // Here I'm assuming (0, 0, 1) = 0 degrees longitude, and (1, 0, 0) = +90.
    // You can exchange/negate the components to get a different longitude convention.

    Debug.Log(lat + ", " + lon);

    // I usually put longitude first because I associate vector.x with "horizontal."
    return new Vector2(lon, lat);
}

```

---
Tags: unity, mathematics, maps, coordinates, sphere
---


title: Marketing a game with limited budget

text:
# Question
Title: Marketing a game with limited budget
I am building a decent multiplayer iOS-Android card based game. While this game is played with regular old 52 cards deck, it does have unique rules and game play. That makes it little hard to market since no one is precisely looking to play initially.

I have been researching quite a bit about game marketing and most recommendations are to build out fan following which is also quite hard and time consuming (taking away from building game).

I have some indie marketing budget (~5k) I set aside to help gain some traction. While I understand that this not my strengths, what are the best ways to invest it into the game?

# Answer
Real marketing with a limited budget is a difficult game. But an important factor is to expose the game and put it on display as much as possible. With some clever ideas and some luck, this doesn't necessarily even require loads of money.

Any publicity is good publicity.

Do whatever other indie companies/developers are doing. For instance post Youtube videos, create a development blog, invite beta testers, ask well-known gaming sites for reviews/articles. Heck, even start a Kickstarter campaign. It really doesn't matter if it's successful or not. Your game would be on display.

Job well done, you might end up having somekind of a low-cost snowball effect.

All of these are things you can do with little to no cost. If you really lack the time to do any of these, it should be relatively cheap to find someone to do them for you.
> 1 votes

# Answer
Marketing is work. It takes various mixtures of time, money and luck. If you're lacking in one of those elements, you're options are either to supplement with more of the others, or settle for less than you might otherwise achieve.

While communities vary in policy, it's natural that they don't want to be exploited (give something for nothing) & frankly, those are the ones that matter the most. Consider the extreme alternative of letting anyone post anything. The result would be a signal to noise ratio so bad that very little would stand out. Reigning in the chaos to something more useful requires some type of filter. Again we return to the iron triangle: some places filter with time (community participation), some with money (paid ads) & others by luck (getting featured as game of the day, happening to deliver a niche experience to a niche audience, etc).

In general I'd recommend:

* reading the other marketing questions on GDSE, especially the ones linked to left of this one in the **Related** section
* approaching focused communities that your game would resonate with
* finding promoters that your game would resonate with
> 0 votes

---
Tags: marketing
---


# Question
Title: What is the difference between these options when saving an image as a PNG in Photoshop for my game?
I'm creating sprites and tilemaps for 2D games. I might just use Unity.

What is the impact of choosing different options when saving as a .png?

# Answer
> 5 votes
The compression rate of your graphical resources directly affects loading times and size of your game. "*No compression*" will result in a bigger PNG file, but the file will be opened extremely fast. "*Smallest compression*" will result in a smaller sized file, but will take considerably longer to decompress and open. Being a lossless format, PNG quality won't be degraded even if compressed (as opposed to, say, JPEG). **EDIT:** as @*Le Comte du Merde-fou* has pointed out, the loading times will vary depending on the platform. For example, on **some** platforms disk I/O will be a bigger bottleneck than decompression process, therefore a smaller file will be processed faster than a larger one. Find out the capabilities of your target platform prior to making the decision.

"*Interlaced*" option is tricky, though. Depending on your render methods it may or may not have a real impact on your game, so I'd check how your graphical engine handles interlaced/non-interlaced PNG files. There are examples of using either of them out there: for example, you may have noticed how sometimes in some games textures are blurry/low-res, and then gradually improve their quality while loading the full file - that is "*interlaced*" file in action. Some games simply won't let you see the game world while the textures are still loading: they're likely to use *non-interlaced* resources, which undergo a different loading process.

The image below may provide a better idea of the differences between the interlaced / non-interlaced PNG files.

---
Tags: textures
---