# Question
Title: How can I implement smooth tile-based lighting?
I have been working on a 2D tile game and I have implemented hard-edged lighting:

I want it to be smoothed out a bit. I don't need shadows or anything, just simple lighting. I'd like it to look more like this:

My current system uses light levels for each tile in the world and they are recalculated, when a tile is placed or removed. I'm using `batch.setColor(...)` to shade the tiles. What is a good way to achieve this smooth lighting?

I don't want to use the light map overlay method, I tried that already and I was not happy with the result. I want to be able to set how much light is able to pass through a block. For examble a dirt block should absorb some of the light, but a glass block should not block any light. This was not really possible with the light map overlay method. **UPDATE:** I missunderstood what this method actually is. I understand now. I was thinking the wrong way. Sorry!

# Answer
A simple way to achieve smooth lighting in a tile based game, is to draw a "lightmap" to a render target, and then drawing this render target over top your scene while alpha blending it.

Your light map render target would be the size of your tile map, but in pixels. Each pixel would represent the light color of its corresponding tile. This render texture would look something like this (top left texture in black and white):

Once you have this light map texture, you can then draw it as an overlay over your game world (stretched out). You are going to have to clamp it properly, so that it stretches perfectly overtop your tiles in the game world.

Then it is a matter of alpha blending this texture onto your game world in libGDX. In order to blend in LibGDX (I personally don't know how), you may have to look at the `Gdx.gl.glBlendFunc` function.
> 16 votes

# Answer
an engine agnostic way to do it is to use average light mapping. First, you need to generate a black and white map as a 2D array of booleans that is the size of the world where the blocks are True and empty is False.

Like This(1 is black, 0 is white):

Then you need to create a new 2D array that is the same size as the first array but is an array of floats. Then you go from black(True) block to black block in the array and average the nearby sampled value(explained below)

This image will help:

This image represents the sampling(where + means false and | means true). what we do is treat True values as 1 and False values as 0. Then you average the 9 numbers and put it into the correct part of the array. NOTE: Make sure that when you are sampling edges you use treat outer values as context sensitive. For example: underground the map outside the world might be 1 and the sky should be 0.

It should looks like this(taken from other post):

Then all you have to do is tint each block in the array with

```
rgba(tint,tint,tint,1)

```

(tint = the current averaged block value in the second array and alpha doesn't matter). Note: this assumes that the pseudo-function rgba takes floats from 0-1 instead of 0-255, if it does, just do this:

```
rgba(tint*255,tint*255,tint*255,255)

```

Hope This Made a little sense :) If you want code, please ask!
> 4 votes

# Answer
Since you are talking about things blocking light, I'm assuming you have some model for how light should spread. For example everything with no blocks above it is completely lit, light spreads to all neighbouring cells but loses a certain amount of brightness.

You should be able to implement those rules fairly easily on the software side at least the smoothing part is then just a matter of throwing some shader at the light map you have generated.

The methods others have suggested with overlaying a light map is something you should do anyway. But you can change how you generate this light map. You can initially fill it with just the block information, but then you could scale it up and smoothen it out in a shader for example. An added benefit of the light map approach is that you can simply draw dynamic lights into your light map as well to highlight explosions or what have you and it will naturally blend with the rest of your world.

Additive blend stuff into your light map then multiplicative blend your lightmap with the game world.

I did this a while ago which uses the same principles. This system does not support having light fall of differently for different types of terrain but at least it should illustrate the usefulness of overlaying a light map.
> 1 votes

# Answer
It's pretty easy for a torch : using a custom pixel shader you calculate the distance between each fragment and the torch ; you can then calculate where the first dense tile that blocks light coming from the torch. You then calculate the distance where the light isn't blocked, multiply that by something \< 1 so the torch doesn't light the sun, substract that from total distance, and repeat for the rest of the distance (where light was blocked by at least one tile) with a multiply value way smaller... I know how to do this math and it's not too complicated to implement in opengl.

EDIT : for a simple light source with a specific center point, my method is extremely simple. However mine does not work with sunlight, but while the alpha map works really well for sunlight, it would NOT be a good idea for a torch, given that it is potentially a moving object, and making a new map every frame is not pleasant a life experience. The best solution in my opinion is a mix : distance calculating for specific lights that are actually objects in the game, a separate shader that you just throw on top of the alpha map you procedurally generated by using the technique mentionned above : a texture of all the tiles alphas from your hard shading, as lots of squares, and mess around with techniques to smooth it out.
> 1 votes

# Answer
Does your rendering use vertex colors (or can you change it) ?

Assuming each block is a 4-vertex square, that would give you a couple of options, for example:

If your current lighting algorithm gives you a light value per block, you could change it to give you a value per vertex . Alternately, at each vertex you could average the light color of the current block plus its three neighbors. Either solution would be inexpensive.
> 0 votes

---
Tags: java, 2d, libgdx, tiles
---


# Question
Title: Libgdx OpenGL ES pixel shader behaves differently on android and on desktop
I'm currently working on a mobile game that ressembles a snake game ; what I wished to do was use my limited glsl knowledge to write a pixel shader that could efficiently draw a curve with a certain width between a set of a few 2D points.

This is what I managed on desktop using basic libgdx to draw on the whole screen with the shader, and for input.

via GIPHY

To do this, first, I find which point is closest to gl\_FragCoord, then, with quite a bit of math, I calculate the equation for a curve between the half-point before that point, and the half-point after it, using this point as control point for the curve... (by half-point I mean the average between it and the point next or before it in the table)

I then use more math to calculate all the local minimums of the distance between the pixel and this curve ; check which are valid, and calculate the minimum distance between the fragment and the snake. Then I can easily check if the pixel is in the width of the snake (named W).

I hope I explained it well, because the code is not annotated at all. I was hoping people had any ideas what could make the difference between the desktop version of libgdx that works perfectly (higher up), and the android version, that does less well...

Original Video

```
uniform vec2 stuff;
uniform vec2 points[10];

vec4 fragColor;

vec3 cubicsolve(float a,float b,float c,float d);

void main() {
    float tailLength = stuff.y;

    fragColor = vec4(0.,0.,0.,1.);
    vec4 primColor = vec4(92./255.,158./255.,237./255.,1.);//5C9EED
    vec4 degColor = vec4(236./255.,135./255.,192./255.,1.);//EC87C0

    int pointNum = int(stuff.x);
    vec2 F = gl_FragCoord.xy;
    float W = 10.; // width of the snake

    degColor = mix(primColor, degColor, 1.- (F.x/1920.+F.y/1080.)/2.);

    vec2 alux = points[0]-F;
    float first = alux.x*alux.x+alux.y*alux.y;
    int key = 0;

    for(int i = 1; i<pointNum-1; i++) {
        vec2 aux = points[i]-F;
        float dist2 = aux.x*aux.x+aux.y*aux.y;
        if(dist2<first) {
            first=dist2;
            key = i;
        }
    }

    float tlim = 1.00;
    if(key > pointNum-3) tlim = tailLength;

    vec2 t1,mid,t2;
    if(key == 0) {
        t1 = points[0];
        mid = points[1];
        t2 = (points[1]+points[2])/2.;
    } else {
        t1 = (points[key]+points[key-1])/2.;
        mid = points[key];
        t2 = (points[key]+points[key+1])/2.;
    }

    vec2 a = (t1-2.*mid+t2);
    vec2 b = 2.*(mid-t2);
    vec2 c = t2;
    vec2 P;

    vec2 A = 4.*a*a;
    vec2 B = 6.*a*b;
    vec2 C = 2.*b*b+4.*a*(c-F);
    vec2 D = 2.*b*(c-F);

    vec3 get = cubicsolve(A.x+A.y, B.x+B.y, C.x+C.y, D.x+D.y);
    float x[3];
    x[0] = get.x;x[1] = get.y;x[2] = get.z;

    float minDist = 1000.;

    for(int i = 0; i<3; i++) {
        float xi = x[i];
        if(xi>=1.-tlim && xi<=1.) {
            //fragColor += vec4(.01,.01,.01,.01);
            vec2 temp = a*xi*xi+b*xi+c;
            temp = temp * (temp-2.*F) + F*F;
            float tempDist = temp.x+temp.y;
            if(tempDist < minDist) minDist = tempDist;
        }
    }
    if(true) {
        vec2 temp = a*(1.-tlim)*(1.-tlim)+b*(1.-tlim)+c;
        temp = temp * (temp-2.*F)+F*F;
        float tempsol = temp.x+temp.y;
        if(tempsol < minDist) minDist = tempsol;
        temp = a*1.*1.+b*1.+c;
        temp = temp * (temp-2.*F)+F*F;
        tempsol = temp.x+temp.y;
        if(tempsol < minDist) minDist = tempsol;
    }

    if(minDist<W*W) {
        fragColor = vec4(1.,1.,1.,1.);
    }

    vec2 At = points[0];

    if((At.x-F.x)*(At.x-F.x)+(At.y-F.y)*(At.y-F.y)<7.*7.) {
        fragColor = vec4(0.,0.,0.,0.);
    } else if((At.x-F.x)*(At.x-F.x)+(At.y-F.y)*(At.y-F.y)<12.*12.) {
        fragColor = vec4(1.,1.,1.,1.);
    }

    fragColor+=degColor;

    for(int i = 0; i<pointNum ; i++) {
        vec2 T = points[i];
        if((T.x-F.x)*(T.x-F.x)+(T.y-F.y)*(T.y-F.y)<4.*4.) {
            fragColor = vec4(1.,0.,0.,1.);
        }
    }

    gl_FragColor = fragColor;
}

vec3 cubicsolve(float a,float b,float c,float d) {
    vec3 x = vec3(-1.,-1.,-1.);

    if (a == 0.) {
        //fragColor = vec4(1.0,0.0,0.0,0.);
        if(b == 0.) {
            if(c == 0.) {

                return x;
            }
            x.x = -d/c;
            return x;
        }
        float delta = c*c+4.*b*d;
        if(delta>0.) {
            delta = sqrt(delta);
            x.x = (-c+delta)/(2.*b);
            x.y = (-c-delta)/(2.*b);
        } else if(delta == 0.) {
            x.x = -c/(2.*b);
        }
        return x;
    }

    if (d == 0.) {
        //fragColor = vec4(0.0,1.0,0.0,0.);
        x.x = 0.;
        float delta = b*b+4.*a*c;
        if(delta>0.) {
            delta = sqrt(delta);
            x.y = (-b+delta)/(2.*a);
            x.z = (-b-delta)/(2.*a);
        } else if(delta == 0.) {
            x.y = -b/(2.*a);
        }
        return x;
    }
    b /= a;
    c /= a;
    d /= a;
    float disc, q, r, dum1, s, t, term1, r13;
    q = (3.0*c - (b*b))/9.0;
    r = -(27.0*d) + b*(9.0*c - 2.0*(b*b));
    r /= 54.0;
    disc = q*q*q + r*r;
    x.x = 0.; //The first root is always real.
    term1 = (b/3.0);
    if (disc > 0.) { // one root real, two are complex
        s = r + sqrt(disc);
        s = ((s < 0.) ? -pow(-s, (1.0/3.0)) : pow(s, (1.0/3.0)));
        t = r - sqrt(disc);
        t = ((t < 0.) ? -pow(-t, (1.0/3.0)) : pow(t, (1.0/3.0)));
        x.x = -term1 + s + t;
        return x;
    }
    // End if (disc > 0)
    // The remaining options are all real
    if (disc == 0.){ // All roots real, at least two are equal.
        r13 = ((r < 0.) ? -pow(-r,(1.0/3.0)) : pow(r,(1.0/3.0)));
        x.x = -term1 + 2.0*r13;
        x.y = -(r13 + term1);
        x.z = x.y;
        return x;
    } // End if (disc == 0)
    // Only option left is that all roots are real and unequal (to get here, q < 0)
    q = -q;
    dum1 = q*q*q;
    dum1 = acos(r/sqrt(dum1));
    r13 = 2.0*sqrt(q);
    x.x = -term1 + r13*cos(dum1/3.0);
    x.y = -term1 + r13*cos((dum1 + 2.0*3.14159265359)/3.0);
    x.z = -term1 + r13*cos((dum1 + 4.0*3.14159265359)/3.0);
    return x;
}

```

# Answer
> 0 votes
I found the solution, which is as obnoxious as opengl can get. While some time ago precision specifiers were still accepted but useless on desktop, for compatibility with opengl-es that still supports and needs these specifiers. So they decided to make it impossible to include a precision specifier on desktop glsl which means I spent two hours looking for a way to up the precision on mobile, but it wouldn't compile. I now need to make two different shaders : one for desktop, one for es.

The solution was to simply add the following at the very top of the code :

```
precision highp float;

```

while it still isn't desktop precision, it's enough for me.

---
Tags: libgdx, mathematics, shaders, glsl, opengl-es
---


# Question
Title: Pause a Coroutine while it's waiting for seconds
I have a Coroutine (X) that waits for seconds before it does something. However, during that time there is another Coroutine that may trigger (Y), and during the time it's on X has to pause waiting for seconds, until Y finishes its job. The point is not to waste the wait time of X.

Pausing the game is not possible since everything else has to work during that time.

I tried to add the bool `isLightningAbilityRunning` that checks if Y is running, but since X is not repeating itself and just waiting, it doesn't get to that point.

The whole X coroutine:

```
 private IEnumerator TriggerGravityAbility() {
    var gravityDuration = gravityInitialDuration + UpgradeManager.instance.GravityDurationUpgrade();
    AudioManager.instance.PlayGravitySound();
    CubeSpawner.instance.gameObject.SetActive(false); // Stop spawning cubes
    Physics2D.gravity = new Vector2(0f, 1f);
    ParticleModifier.instance.SetGravity(0f);
    CubeBehavior.instance.border.isTrigger = false;
    CubeBehavior.instance.ignoreBorderLightning = true;

    while (isLightningAbilityRunning) {
            yield return null;
    }

    yield return new WaitForSeconds(gravityDuration);

    CubeBehavior.instance.DestroyOutOfCameraCubes();

    CubeSpawner.instance.gameObject.SetActive(true); // Start spawning cubes
    Physics2D.gravity = new Vector2(0f, -9.81f);
    ParticleModifier.instance.ResetGravity();
    CubeBehavior.instance.border.isTrigger = true;
    CubeBehavior.instance.ignoreBorderLightning = false;
}

```

How can I make this work?

# Answer
> 1 votes
Have a boolean flag that indicates if Coroutine Y is running at the instant:

```
bool isYRunning = false;

IEnumerator Y
{
    isYRunning = true;

    //stuff...

    isYRunning = false;
}

```

And in X, have something like this:

```
int waitAmount = 10, waited = 0;

IEnumerator X
{
    //stuff...

    while(waited < waitAmount)
    {
        if(!isYRunning)
        {
            waited += Time.deltaTime;
        }

        yield return null;
    }

    waited = 0;
}

```

Notice that we only increment the `waited` time if Y is not running.

# Answer
> 0 votes
If I understand you, the total wait time should be `gravityDuration` plus however long `Y` takes to run. The straightforward way to solve this would be to let `TriggerGravityAbility` also trigger `Y`:

```
private IEnumerator TriggerGravityAbility() {
    float preDuration = gravityDuration * 0.2f;
    float postDuration = gravityDuration * 0.8f;

    yield return new WaitForSeconds(preDuration);
    yield return StartCoroutine(Y());
    yield return new WaitForSeconds(postDuration);
}

```

If `TriggerGravityAbility` can't be responsible for running `Y`, the solution is less clean (countdown timers are usually a bad habit, but this case warrants it):

```
private IEnumerator TriggerGravityAbility()
{
    float durationCountdown = gravityDuration;
    while (durationCountdown > 0)
    {
        if (!isLightningAbilityRunning)
            durationCountdown -= Time.deltaTime; // the timer is not running during lightning
        yield return null;
    }
}

```

---
Tags: unity, coroutines
---


title: Make a light only affect one object

text:
# Question
Title: Make a light only affect one object
I'm wondering if it's possible to make a light source only affect one object? I know that it's possible to use layers and culling mask, but then I would need one layer for every single object which is not possible.

Is there a way for example that I could make only children or siblings be affected by a light source? Or other solution?

Have a nice day!

**Update #1:**

# Answer
> 3 votes
Taken from Unity Answers:

> Yes, this is what Layers are for.
>
> Assign your objects to a specific layer (use an existing layer, or create your own custom layer). Then go to the light's inspector pane and adjust the "Culling Mask" setting to have it light (or not light) your desired layers.

# Answer
> 0 votes
What you can do is that instead of using lighting (as it is very expensive) you can play around with the emission property of the objects material. You can just put the texture you have used in it if you dont want any fancy light emission from it !!

---
Tags: unity, lighting
---


# Question
Title: Unity2D - How to destroy my Instantiate particle system
I'm having trouble trying to destroy my Instantiated particle system, I can only destroy my gameobject

```
using UnityEngine;
using System.Collections;

public class meteor_destruction : MonoBehaviour {

public GameObject meteor_d_effect;
public GameObject meteor_explo_effect;
public GameObject meteor_explo2_effect;

public int pointsIncrement = 1;

void OnCollisionEnter2D (Collision2D col)
{

    var effect_explo = Instantiate(meteor_explo_effect, col.gameObject.transform.position, col.transform.rotation);
    var effect_explo2 = Instantiate(meteor_explo2_effect, col.gameObject.transform.position, col.transform.rotation);
    var effect_d = Instantiate(meteor_d_effect, col.gameObject.transform.position, col.transform.rotation);
    Destroy (gameObject);
    Destroy (effect_explo,3);
    Destroy (effect_explo2,3);
    Destroy (effect_d,3);

}

```

It's generated after the meteor collide, but those 3 particle effects keeps adding inside my Hierarchy panel.

# Answer
Set the collider as a Trigger and use `void OnTriggerEnter2d (Collider2D coll)`.

A Trigger calls only once and does not keep calling the function. On collision enter function will be called multiple times.
> -1 votes

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


# Question
Title: Limiting framerate with a fixed timestep
**UPDATE:**

I still need help determining how `MAX_UPDATES` works. I want my game to be designed in such a way that if the user can't run the game at full speed, it slows down so that no updates are missed.. can someone help me understand that part of the code? Also, how can I calculate an accurate realtime fps?

```
double frametime = 1000000./60, remainingTime = 0;
const unsigned int MAX_UPDATES = 10;

void Game::gameLoop(sf::RenderWindow &window)
{
    remainingTime += clock.restart().asMicroseconds();
    unsigned int updates = 0;
    while (remainingTime >= frametime)
    {
        remainingTime -= frametime;
        if (updates++ < MAX_UPDATES)
        {
            update();
        }
    }
    render(window);
}

```

---

Hi I'm learning how to create a 2d platformer in C++ using the SFML2 library. My current goal is limiting the game's framerate. SFML2 has a `window.setFramerateLimit(unsigned int limit)` function for the window however I have found it to be imprecise due to it using `sf::sleep`. Therefore I'm attempting to implement my own solution. I want my game to used a fixed timestep and be framerate dependent as in the future when I implement attacks I want them to be based on frame data.

Since the game loop wont always execute exactly when a frame is supposed to happen, I create a delta variable that will account for the extra time spent starting the frame to start the next frame earlier by that same amount.

Does this all look right?

```
double frametime = 1000000./60, delta = 0;
void Game::gameLoop(sf::RenderWindow &window)
{
    t = clock.getElapsedTime().asMicroseconds();
    if (t + delta >= frametime)
    {
        clock.restart();
        delta = t + delta - frametime;
        update();
    }
    render(window);
}

```

edit: double shouldn't have f suffix doh

# Answer
While your setup should roughly work, it still locks updates and framerate. So if your framerate drops below 60 fps you won't be able to do 60 updates per second anymore. This essentially defeats the whole purpose, unless you really can always stay above 60 fps (which you shouldn't assume, even for simple games).

---

Whenever I want a fixed framerate in SFML I'm doing something like this:

```
static const sf::time frameTime = sf::milliseconds(10); // 100 updates per second
static const unsigned int maxUpdates = 10; // Maximum number of updates between draws

sf::Clock updateTimer; // Initialized or reset right before the main loop starts
sf::Time remainingTime;

```

Now when it's time to run your updates:

```
sf::Time deltaTime = updateTimer.restart(); // Get the time difference and reset

update(deltaTime); // Do non-critical time based updates where you don't need exact ticks (e.g. visible particles)

remainingTime += deltaTime; // Add up the time we haven't updated yet

// Now update as long as the time passed is longer than one frame
unsigned int updates = 0;
while (remainingTime > frameTime) {
    remainingTime -= frameTime;

    if (updates++ < maxUpdates) // Ensure we don't get stuck if we can't reach our intended number of updates per second
        update(); // Do one game logic tick
}

```

Just let me explain `maxUpdates` in case you're not sure what it's for:

Imagine a scenario where you want to do 100 updates per second and the current machine only barely handles 90 updates per second. You'll be stuck with an overhead of 10 updates per second, which will inevitable stack up and kill your framerate, making the game unresponsive. By limiting the number of updates between drawing calls you ensure the game keeps running, but it will inevitably slow down, if performance is too bad (which at this point won't matter anymore, because the game should be stuttering anyway).
> 0 votes

# Answer
I wrote a similar block of code into in my game, no problem on Windows, Mac, Linux, Android and low end platform.

Then I presume it's very correct for small games. Take care: Be precise can over consume the resources (do you really need it?). Prefer work with integer and not floating value (for performance reason, eg: Raspberry pi 1, no hardware float acceleration).
> -1 votes

---
Tags: c++, 2d, platformer, sfml
---


title: How to scale LibGdx TextButton?

text:
# Question
Title: How to scale LibGdx TextButton?
Apparently `textButton.setScale()` is not working. Even when the scale is set to 0.1, the button is displayed in it's original size.

How to properly scale a TextButton in LibGdx? The official documentation doesn't provide any details.

# Answer
A little late but to answer my own question, you have to `setTransform(true)` if you're scaling a `Button` or `Table`. So in my case:

```
textButton.setTransform(true);
textButton.setScale(0.5f);

```
> 7 votes

# Answer
You should use a table to setup. Tables can be aligned and there cells sizes can change. You can do something like:

```
table.row();
table.add (tb).width (tb.width*scale);

```

What I did here is setting the cell with to the size of the table times a scale. You can set various variables on table cells. A table is a container widget and you have more of these. A button is a actor and best belongs to a container widget.

Sometimes tables and Scene2d work like a bitch and sometimes like a charm. Look them up in the document. I sent a link when not at my phone.
> 2 votes

---
Tags: libgdx, scale
---


title: Unity Animation Tracking

text:
# Question
Title: Unity Animation Tracking
**Background**

I've recently reached a bottle neck in my game's code that forced me to completely decouple the logic/networking from the graphics. Thanks to the nature of my board game, I was able to build the following architecture:

```
Logic update loop:

+--> wait for event -> process event -> dispatch graphic events --+
|                                                                 |
+-----------------------------------------------------------------+

Graphics update loop:

+--> wait for event -> process event -> wait for animation --+
|                                                            |
+------------------------------------------------------------+

```

**Question**

From the previous design, tracking animation timing and knowing when they end is crucial, since that marks the end of the third phase in the graphics loop, allowing us to proceed to the next phase.

I'm using Unity, and I am not sure how to go about this. I am using Unity's animation system as well as LeanTween to perform animations on the 2D NGUI level as well as the 3d game scene level.

**Proposed Solutions**

Solutions that have occurred to me so far are:

*Callbacks*

Pass on a callback, and make the animation system trigger that callback when the animation finishes. This has proven to be high maintenance and redundant, as I have to manage passing data back and forth maintaining the overall animation state somehow (if multiple animations were triggered).

*Global Monitor*

Animations register under a global monitor, and I can emit a signal when the monitor becomes empty, triggering the end of the animations phase. I must make sure animations are registered immediately at the beginning of the animation phase, which I should be able to do. I should also maintain a list of animation IDs or a simple "anonymous" counter, which animations increment and decrement. Kinda like manual memory management. I might do this.

Any of those seem viable? Am I overlooking details about this system? Any better alternatives come to mind?

# Answer
> 0 votes
This has proven to be a really challenging task, especially since there is no deterministic object lifetime in C#. I mean, when I usually run into an issue where I need to track a shared resource, I'd simply wrap the resource access in a RAII object. Can't really do that in C#.

With that said, I first went with the global monitoring idea, which worked well until it didn't .. The main issue was that in some cases, animations would be canceled, and they wouldn't go through their normal lifecycle either! So, if I increment a global counter, it never gets decremented.

This all led me to a single and simple conclusion:

> The only way to truly track active animations is to check if the animator is active, regardless of anything else.

So, in the case of LeanTween, I would check:

```
LeanTween.isTweening()

```

As for the Unity animator controller, I can simply use the animator controller as an FSM system, and check if the current state is idle, then no animations are running. This can be achieved by either querying the animator object, or by attaching a behavior to the animation state.

**Update:**

To further simplify the process, I decided to query the animation durations ahead of time in the script that performs the animations on Unity's animator controller:

```
animationData = new Dictionary<string, float>();

foreach (var clip in animator.runtimeAnimatorController.animationClips) {
    animationData[clip.name] = clip.length;
}

```

And once I trigger any of those animations, I simply kick off a dummy LeanTween animation with the same duration:

```
LeanTween.value(gameObject, 0f, 1f, animationData["CubeDeath"]);

```

I understand this is not super ideal, but works really well as far as I've tested. These animations are guaranteed to finish at some point, so I won't be left with a hanging state. Also, if I use `LeanTween.cancel`, that case will also be taken care of, even though the `onComplete` handler isn't called.

# Answer
> 1 votes
The callback solutions via the Unity's animation system is kinda tricky and as you said expansive to maintain. I found out to discard that solution for my concerns.

The global monitor solution requires a bit of effort but should give some handlable ed effective solution to the problem. But it wraps up the concept of Coroutine. A Coroutine can handle your WaitForAnimation step on its own.

I use Coroutines. When the anymation starts, you can Sstart a Coroutine which calls a function that do things. You can code roughly every kind of situation.

I apologize since I'm not on my dev post now so I'll write some pseudocode to give an idea. I could update later if you think this is of eny help.

```
private IEnumerator HandleAction(GameObject entity){
    Animator anim = entity.GetComponent<Animator>();
    float duration = anim.GetCurrentState().GetClip().duration;//not sure of this syntax. will update later
    while(duration > 0){
        //do stuff or wait
        duration -= Time.deltaTime;
        yield return null;
    }
    //code to execute when animation ends
}

```

---
Tags: unity, animation, game-loop
---


# Question
Title: Unity's animation system is flipping out. Rotates only the long way around
I really dont know what is going on or how to even explain the problem so I made a gif. Its not a really well made gif so please bare with it.

# Answer
> 1 votes
Expand the dropdown. Manually change the z-axis rotation in negative equivalent. Like `350 degrees` to `-10 degrees`.

While testing, Unity 5.2.5 doesn't convert negative values but 5.3.5+ seems to be converting them to positive equivalent.

---
Tags: animation, unity, rotation
---


# Question
Title: Why does the following code print logs even after the game object is detroyed?
I have the following in a script attached to a game object in a unity scene. When I run this scene and press 'E', I get the following logs. (The game object is destroyed too)

**In destroy**
**After destroy**

```
void Update () {
    if(Input.GetKey(KeyCode.E)){
        Debug.Log ("In destroy");
        Destroy (gameObject);
        Debug.Log ("After destroy");
    }
}

```

My question is that if the game object is destroyed, then why does the execution continue to the code which logs "After destroy"?

# Answer
I found the reason for this. As per the Unity documentation (at this link), the actual object destruction is always delayed until after the current Update loop. Therefore, the current update method is executed and the logs are printed.
> 1 votes

# Answer
It's just finishing the current frame as the task in the same frame on `Update()`.

If you test like below you will not see anything form next frame. `LateUpdate()` is executed in next the frame after `Update()` execution.

```
void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Debug.Log("In destroy");
        Destroy(this.gameObject);
    }
}
void LateUpdate()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Debug.Log("After destroy");
    }
}

```
> 3 votes

---
Tags: unity
---


# Question
Title: What type of Collider should I add to a LineRenderer?
I am currently building a game where I need to generate some wires (as Bézier curves) using LineRenderer. After changing the width of each line

```
lineRenderer.SetWidth (0.15f, 0.15f);

```

I am attaching an EdgeCollider2D to the same game object (specifying the same points used in generating the Bézier curve). This seems to work. However, I would like to be able to know if the Mouse Pointer is at any time over the EdgeCollider2D (something similar to the popular Fruit Ninja game). I'm using Raycast as follows:

```
void CastRay() {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);

    if (hit) {
        Debug.Log (hit.collider.gameObject.name);
    }
}

```

I'm calling the CastRay method inside the Update method. Because EdgeCollider2D does not have width (as expected), the log message is never produced.

Do I need to use a different type of Collider? Do I need to call CastRay somewhere else?

# Answer
> 3 votes
Ok. After some experiments I ended up replacing the EdgeCollider2D with a PolygonCollider2D. I generated the collider points (taking the width of the wire into account) by computing the Euclidean distance between two consecutive points on the curve (you need to iterate through all the points) and the perpendicular on the distance vector (using the cross product).

Here's an example:

```
List<Vector2> edgePoints = new List<Vector2> ();
PolygonCollider2D collider = new PolygonCollider2D ();

for (int j = 0; j < bezierPoints.Count; j++) {
    Vector2 distanceBetweenPoints = bezierPoints[j-1] - bezierPoints[j];
    Vector3 crossProduct = Vector3.Cross (distanceBetweenPoints, Vector3.forward);

    Vector2 up = (wireWidth / 2) * new Vector2(crossProduct.normalized.x, crossProduct.normalized.y) + bezierPoints [j-1];
    Vector2 down = -(wireWidth / 2) * new Vector2(crossProduct.normalized.x, crossProduct.normalized.y) + bezierPoints [j-1];

    edgePoints.Insert(0, down);
    edgePoints.Add(up);

    if (j == bezierPoints.Count - 1) {
        // Compute the values for the last point on the Bezier curve
        up = (wireWidth / 2) * new Vector2(crossProduct.normalized.x, crossProduct.normalized.y) + bezierPoints [j];
        down = -(wireWidth / 2) * new Vector2(crossProduct.normalized.x, crossProduct.normalized.y) + bezierPoints [j];

        edgePoints.Insert(0, down);
        edgePoints.Add(up);
    }
}

collider.points = edgePoints.ToArray();

```

This will generate a Polygon collider that will wrap the entire wire (curve) based on the wireWdth.

I wanted to post the solution in case someone else is having similar issues.

---
Tags: collision-detection, unity, raycasting, beziers
---


# Question
Title: Card game design, converting cards back into gold
I'm working on a collectible card game on the card game platform dulst. https://dulst.com/nasuverse

I want to implement a mechanic for players to convert their unused cards back into a currency so that the cards aren't just sitting there doing nothing.

I'm considering allowing them to simply sell their cards for gold. Gold can then be used to buy more packs which give them random cards. Gold is normally obtained by winning games. In the future I would consider allowing real-money transactions to purchase gold.

Another thing I can do is to convert the cards into a separate currency that's not gold. That other currency can then be used to craft more cards. What are some reasons why you would want to use a separate currency instead of straight up gold?

Thanks.

# Answer
> 1 votes
First of all, let's examine why a game would use more than one currency in the first place.

Having more than one currency makes it far easier to balance. Each currency forms a closed ecosystem and allows you to experiment with it without too much influence from other game systems which rely on other currencies. For example, when you accidentally create some imbalance in your game which floods the game with currency A, any features which rely on currency B are unaffected. Similar, when you add a feature which greatly increases the value of currency B, that will not affect the perceived cost of anything which is bought with currency A.

Now how does this play out when you have a currency in the game which you sell for real-world money?

When you have a cash-currency, you need to be very careful not to devalue it. When you create an alternative way to obtain the cash-currency than buying it with real-world money, that will affect your revenue. When you screw up and your players find a way to acquire it far quicker than you intended, the result will be a notable downward spike in your profit chart which lasts until you find a way to fix it. That's why most games with a cash-currency usually offer either no way to obtain the cash-currency ingame, or only a very slow, tedious and very inefficient way to make the player notice that the cash-currency exist but not give them enough to acquire a notable amount of it with any reasonable effort.

However, many players perceive it as unfair when certain important items can only be acquired by investing real-world money. The description "pay to win" is often used in that context. A common marketing slogans used by games which try not to be "pay to win" is "Everything non-cosmetic can be obtained through regular play". The only way to do this without devaluating the cash-currency is by offering an alternative currency to buy cash-shop items which is acquired through regular play.

# Answer
> 1 votes
Reasons why people use multiple currencies:

* Tax player at exchange rates:
* Force player at different paths of obtaining each currency.
* Have a distinct premium currency to retain separate control of the primary game generated one.
* Have unconvertible currency that does not inflate due to player speculations.
* Control individual economy segments with dedicated currency (imbalanced segments don't threaten every system, just segmented ones dependent on the specific currency which is out of balance)
* With multiple currencies its easier to manipulate value as you can inflate and deflate without affecting everything in the economy. Doesn't matter if its the developer or the player doing it. Either one can have negative or positive impact due to that.
* Confuse the player about value. (Its easier to spend more money if you have not idea how much you are really spending and when it is more than you assume) = Your player buys 100$ of premium currency. Then hits the market and coverts that to millions of separate currencies at variable exchange rates. Then buys items with the end currencies. How much do those 3 guns he is trying to sell now cost him really? Nobody is figuring that out unless they keep notes and pick up the calculator every time. Couple that with a sense of abundance and people will overspend. Most folks are too lazy to keep track, the exceptions are your economy drivers. I usually make CMs keep an eye on them at all times. Your most active economy players know all your loopholes and usually get their hands on exploits before anybody else. Not mining them for data is a horrid waste.

Either way, most people come up with currency to serve specific purposes. If you don't need multiple you should avoid having em. It will only further confuse you.

I for instance use an internal fictional currency UV (universal value) that I convert everything to. And I mean everything. I can tell you what your unit damage is worth in gold or any other currency I use.

# Answer
> 1 votes
In game economy management, you should be looking for to "destroy" currencies. Because if your destroy rate falls behind the rate players earn currency (which is called inflation in the real world), at some point your players will be distinctively seperated like "OP players" and "new players".

*(Check this video of Extra Credits to find more about inflation in games.)*

That is where things start to fall apart, because you then would have only three options to keep your game alive:

1. **Power-creep:** Adding new content constantly that is more powerful than previous ones, rendering previous content useless. This will force all players to spend their currencies to keep being "OP".
2. **Allowing an easy way to earn currency, aka "Pay to Win":** Just because new players can't hold up to game, you introduce a paid package like some sort of "Kickstart package" (etc.) which will give newcomers an edge to compete with existing OP players. However, this can get worse if not much of newcomers are willing to pay cash just to be able to compete with existing players.
3. **Tiers:** This basically means match newcomers with newcomers and experienced players with experienced players. This system may seem the best first time, but has serious flaws:

1- High tier players may experience seriously long matchmaking times.
2- Some of the players will not see a reason to climb tiers, just to get competed with better players.
3- Seal-clubbing / Smurfing: High tier players playing low tier accounts *(aka smurf accounts)* and destroying newcomers.

---

As you can see things get really bad if you can't manage to balance game economy to prevent inflation. So how to solve/prevent this issue?

1. **Don't allow it at the first place:** Make in-game items more expensive and drops rare. This way players will not find a chance to stack up on currency.
2. **Make money destroying mechanics:** For example taxes, travel costs, upkeep costs, resurrection penalties, health potions *etc*...

---

**TL;DR:** Don't allow converting cards back into currency. Even if you allow, make pay-backs low, so players can't abuse it.

---
Tags: game-design, card-game
---


# Question
Title: Accessing entity config data without singleton
Every entity has some stats which change over time and some which are static for a given type of entity. For example current hp vs max hp: lets say humans have max 100hp, then every human would have an `int hp` member, but it doesn't make sense to have a `const int max_hp=100` for all the humans since it's always the same thing.

That can be solved by using `static` member variables, but here's the catch: I want to load all the stats such as `max_hp` from a config file when the app starts, which precludes use of `static`.

The only way I know how to reconcile these two things is to use a singleton object, which provides entities their stats via something like `singleton::instance().model("human").stat("max_hp")`. However, every mention of singletons I have ever seen has been in the context of warning against their use. And I wouldn't want to use it anyway, because then my entity update methods lose referential transparency.

So in short:

* I want to avoid duplicating data.
* I want to load that data from file.
* I want to avoid global state.
* Update methods must be pure functions.

What strategy can I use to meet these requirements?

---

I require update methods to be pure because my engine is built around the concept of updating every entity in parallel, and the way to do that is to have `entity.update` be a pure function which takes an immutable reference to the world and returns a new entity \[0\]. So every entity starts its update by making a copy of itself, which is then mutated as it goes through the update process, until finally being returned to the world to become the manifestation of that entity in the new generation. Now that would be a lot of copying if only the dynamic data were copied! But to also copy all the (duplicate) static data every frame is just crazy, and I'm looking for the approach which would let me copy only the dynamic stats while still having access to the model data.

\[0\] https://www.youtube.com/watch?v=Uooh0Y9fC\_M

# Answer
> 2 votes
Put all those maximum, default or fixed values in a template or "archetype" object. Point each entity at its appropriate archetype during creation.

You can load archetype data from a file:

```
// human_archetype.txt
max_hp = 100
max_mp = 40
flammability = 2.5

```

Load that data from a file into a template object:

```
struct EntityArchetype {
  float getFloat(const std::string& name) const {
    return m_numberProperties[name];
  }

  const std::string& getString(const std::string& name) const {
    return m_stringProperties[name];
  }

private:
  std::map<std::string, float> m_numberProperties;
  std::map<std::string, std::string> m_stringProperties;
  // ...etc...
};

```

Load all archetype data files into some storage you can index by name or key so you can look them up when you create an actual entity. Store a reference to that archetype in the entity:

```
struct Entity {
private:
  Archetype* m_archetype;
};

```

Then you can provide access to it via some accessor (so a component can check it for default or maximum values, et cetera).

When creating an entity, you'd need to know the archetype so you can look up the `Archetype` pointer you want to use and pass it to the entity. You can often infer this lookup from from the creation of the entity itself (that is, if your entity creation is from a data file, the file can include a field that says which archetype to use).

This allows all entities that use the same set of defaults and constants to simply refer to one shared, immutable instance of those values. It's sort of like an overridable-prototype pattern.

For maximum generality, you could even make the archetype just another entity instead of its own special `Archetype` class, if you were so-inclined (and your entity interface supported the appropriate methods).

---
Tags: c++, entity-system
---


# Question
Title: C++ SFML: Keypressed Event not registering half the time?
I have a very simple event handeling system at the moment.

```
void LevelScreen::PollInput()
{
    sf::Event event;

    while (pWindow->pollEvent(event))
    {
        if (event.type == sf::Event::KeyPressed)
        {
            int x = 0;
            int y = 0;

            if (event.key.code == sf::Keyboard::Left)
            {
                x = -1;
            }
            else if (event.key.code == sf::Keyboard::Right)
            {
                x = 1;
            }
            else if (event.key.code == sf::Keyboard::Up)
            {
                y = -1;
            }
            else if (event.key.code == sf::Keyboard::Down)
            {
                y = 1;
            }

            pCursor->Move(x, y);
        }
    }
}

```

The system gets updated every single cycle, yet many keypresses are not even registered eventhough there is no lag. Mouse movement is always registered, but when I press, for example, Down alot it fails to register from 30% to 50% of the time. Same counts for the mouse button, if I hold it down I can see that it registers it for 6 times in a row, then stops for about 5 seconds, continues, etc.

Putting it in the main loop doesn't change anything. I cannot find any reason for this input lag.

# Answer
> 1 votes
Have you tried using instead `sf::Keyboard::isKeyPressed` instead of an event based solution? (see http://www.sfml-dev.org/documentation/2.0/classsf\_1\_1Keyboard.php)

```
static bool     isKeyPressed (Key key)

```

You could use this in a way similar to how you have it, after your input method.

Sample code:

```
while (window.isOpen()) {
    // handle input

    // after pollEvent loop
    sf::Vector2f movement(0.f, 0.f);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
        movement.y = -1;
    } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
        movement.y = 1;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        movement.x = -1;
    } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        movement.x = 1;
    }

    pCursor->move(movement); // assuming pCursor is sf::Transformable*
}

```

---
Tags: c++, sfml, events
---


# Question
Title: Is there a convenient way to port a .apk file to a .swf file?
My friend just made a game and has a bunch of installs on the Android/Google Play.

I'm curious if it's possible at all to port said game to a flash game. I've seen tutorials on how to port an .swf to an .apk, but I haven't seen anything yet that would make it seem to go backwards.

I'd love to help my friend get extra exposure for his game. Is there any way he can port it?

# Answer
> 3 votes
Convenient? Unlikely. It may seem like just a file conversion, but it's much more than that. An apk file is an application package designed to run on the Android operating system. An swf file is an animation or applet designed to run in a flash player. They're completely different technologies. Similar to asking if there's a way to convert an .exe to a .swf. One of them is meant to run on an operating system, the other is run in much higher level application.

You might think since there are tools to turn swf files into apks that the reverse should be just as simple. It's not. "Converting" a swf into an apk is more like taking a pre-made Android application designed for playing flash content and adding the resources found in a swf file.

This type of conversion will have to be done at the source code level, not the packaged file level. It likely means re-writing the source code into a language capable of exporting to swf (likely actionscript).

# Answer
> -1 votes
You can use Adobe Flash Cs4 or latest applications. Use AS3 codes and publish it to Android apk. Or you want to try http://apkgen.com/ to publish into apk. If you find it easy Good luck. If you want to hack your .swf into other apk extensions It will not allow you to do that. You have to be owner of your .swf and prevent legal actions to do so. or you can use eclipse to use your own .swf games to android .apk.

---
Tags: porting
---


# Question
Title: Why does my framebuffer not work when rendering to texture?
I am having trouble rendering to a texture and then mapping that texture to a quad. I am using OpenGL 2.0. I am using code from the wiki. The class scene\_t has a texture called \_out\_tex, which is the texture that game\_window\_t will map to a quad filling the entire screen:

Code in main.c:

```
game_window_t gwin;
gwin.w = 800;
gwin.h = 600;
gwin.title = (char *) "2D Lighting";
gfx::create_window(&gwin);

math::poly2d poly;
poly.add_vertex(math::vec2f(400.0f, 0.0f));
poly.add_vertex(math::vec2f(0.0f,   600.0f));
poly.add_vertex(math::vec2f(800.0f, 600.0f));

gfx::object_t o;
o.set_color(math::vec4f(1.0f, 1.0f, 1.0f, 1.0f));
o.shape = &poly;

if(scene.set_parent_window(&gwin) < 0)
{
    printf("Error setting parent window\n");
    goto panic;
}

scene.add_object(&o);

scene.render();
gwin.put_scene(&scene);
gfx::flip(&gwin);

```

Code in scene.cpp:

```
char scene_t::set_parent_window(game_window_t *win)
{
    _parent_win = win;
    _w = win->w;
    _h = win->h;

     //RGBA8 2D texture, 24 bit depth texture, 256x256
   glGenTextures(1, &_out_tex);
   glBindTexture(GL_TEXTURE_2D, _out_tex);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   //NULL means reserve texture memory, but texels are undefined
   //**** Tell OpenGL to reserve level 0
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, _w, _h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
   //You must reserve memory for other mipmaps levels as well either by making a series of calls to
   //glTexImage2D or use glGenerateMipmapEXT(GL_TEXTURE_2D).
   //Here, we'll use :
   glGenerateMipmapEXT(GL_TEXTURE_2D);
   //-------------------------
   glGenFramebuffersEXT(1, &_fbuf);
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbuf);
   //Attach 2D texture to this FBO
   glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, _out_tex, 0);
   //-------------------------
   glGenRenderbuffersEXT(1, &_depth_rb);
   glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _depth_rb);
   glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, _w, _h);
   //-------------------------
   //Attach depth buffer to FBO
   glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, _depth_rb);
   //-------------------------
   //Does the GPU support current FBO configuration?
   GLenum status;
   status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);

   if(status != GL_FRAMEBUFFER_COMPLETE_EXT)
   {
        printf("Error setting up framebuffer\n"); return -1;
   }

    return 0;
}

void scene_t::render()
{
    // render to texture
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbuf);
    glViewport(0, 0, _w, _h);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    for(int i = 0; i < _objects.size(); i++)
    {
        _objects[i]->render();
    }

    return;
}

```

Code in game\_window.cpp:

```
char game_window_t::put_scene(scene_t *s)
{
    // if(s->_parent_win != this) { printf("SCENE DOES NOT BELONG TO WINDOW\n"); return -1; }

    // begin texture mapping
    glBindFramebuffer(GL_FRAMEBUFFER_EXT | GL_FRAMEBUFFER, 0);
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, s->_out_tex);

    printf("tex: %u\n", s->_out_tex);

    // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glViewport(0, 0, 800, 600);
    glBegin(GL_QUADS);
    glNormal3d(0.0f, 0.0f, 1.0f);
        glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f);    // top left
        glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, 600.0f);     // bottom left
        glTexCoord2f(1.0f, 1.0f); glVertex2f(800.0f, 600.0f);    // bottom right
        glTexCoord2f(1.0f, 0.0f); glVertex2f(800.0f, 0.0f);   // top right
    glEnd();

    printf("put!\n");
}

```

object\_t::render() just renders a triangle strip with the vertices of its shape polygon.

I don't understand why the texture (or whatever is rendered in game\_window\_t::put\_scene()) is just black. Any help would be greatly appreciated. I am aware that I am using a somewhat deprecated and outdated version of OGL, but I don't need the functionality of 3+ as far as I am concerned.

Thank you!

# Answer
> 1 votes
You aren't passing any `data` to `glTexImage2D` -- the last parameter, per the docs, "Specifies a pointer to the image data in memory." (see: https://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml)

Since your `target` (first param) is GL\_TEXTURE\_2D, relevant info from link:

> If target is GL\_TEXTURE\_2D, GL\_TEXTURE\_RECTANGLE or one of the GL\_TEXTURE\_CUBE\_MAP targets, data is read from data as a sequence of signed or unsigned bytes, shorts, or longs, or single-precision floating-point values, depending on type. These values are grouped into sets of one, two, three, or four values, depending on format, to form elements. Each data byte is treated as eight 1-bit elements, with bit ordering determined by GL\_UNPACK\_LSB\_FIRST

Try giving that function a small set of data and see if it works. From https://open.gl/textures, the following should give you a black and white checker board pattern.

```
float pixels[] = {
    0.0f, 0.0f, 0.0f, 1.0f,   1.0f, 1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 1.0f,   0.0f, 0.0f, 0.0f, 1.0f
};
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _w, _h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

```

NB: I did have to alter the above slightly to fit into what you have, but the general idea is the same.

---
Tags: opengl, c++, textures
---


# Question
Title: When scaling the camera with the player, how can I make it more noticeable?
I am making a game where you play as fish. When you eat food you become larger. I am counting the camera scale as follows:

```
camera.scale = (player.originalWidth / player.width)

```

Then I apply it as a transform to the whole world. Now when the fish grows up you don't see any change on your sprite, only on the surrounding world. I want to achieve that you will see the growing a little bit. How should I modify this equation?

# Answer
Because making the fish actually occupy more screen space would eventually cause problems, you could instantly grow the fish, but then zoom the camera out over a couple seconds from the old zoom to the new zoom level. To zoom gradually you could use linear interpolation (often abbreviated 'lerp'), or you could use a logistic function to make the zoom smoother.

To do this, you would first store the current zoom level when a growth event happens:

```
oldScale = camera.scale;
newScale = player.originalWidth / player.width
zoomDuration = 500 // time it will take to zoom out in ticks
zoomElapsed = 0;

```

Then you would run a short function every tick to animate the zoom (here's how to do it with linear interpolation):

```
if(zoomElapsed < zoomDuration) {
  camera.scale = (zoomElapsed/zoomDuration)*(newScale-oldScale)+oldScale;
  zoomElapsed++;
} else {
  camera.scale = newScale;
}

```

And that would be it. Note that the linear interpolation above is going to 'jerk' into movement then instantly stop when it hits the new scale; to avoid that, the logistic curve would do nicely because it has tapered ends.
> 3 votes

---
Tags: mathematics, camera
---


title: How should I store trading cards?

text:
# Question
Title: How should I store trading cards?
I'm working on a Magic-esque TCG in Unity. Currently, the cards themselves are all prefabs: I have a Satyr Archer prefab, a Candle Wisp prefab, etc. This works fine for now, since I only have a few cards, but by the time I get to several hundred, I feel that this may become unwieldy.

Are prefabs a good way to store a large list of cards? Should I be making those prefabs using an XML document and a script?

# Answer
If you want to contain your whole workflow within Unity then you might be looking for `ScriptableObject`s. Create a class which extends ScriptableObject and stores all the properties of a card. The nice thing about ScriptableObjects is that you can manage them as assets in your games resource folder. You can even write an editor extension for them to better edit your card properties within Unity.

Outsourcing your game data to XML is also an option, but it means that you will need a second program to edit it. That can be a simple text editor or a more fancy XML editor, but when you rely on general-purpose tools to edit XML it would likely be less comfortable than what Unity offers out-of-the-box when you use ScriptableObjects. You could also write your own application outside of Unity to edit your XML card database. When you don't have to work within the confines of what Unity editor scripting allows you to do (although that is quite a lot) you might be able to create a far more powerful application which is far better tailored for your needs. But you will have to invest quite a lot of work for that. You need to make your own cost-benefit analysis if such an editor would be worth it or not for your particular project.
> 1 votes

---
Tags: unity, card-game
---


# Question
Title: How to load values into a script from a file?
I have a prefab of a "generic unit;" each one has a script with some public variables: name, health, and attack.

Currently, I am manually making copies of that prefab and editing their names, health and damage values in the inspector. This seems unwise to me.

I would rather be able to make a simple file for each unit type, containing its important information, like this:

```
name = "Archer"
health = 3
attack = 1

```

And so on. Then, I would like to be able to turn that into actual GameObjects in Unity, presumably by instantiating the prefab and filling in its values with values from the file.

I could then make a script that runs when the game begins and iterates through, making all the objects I need.

However, I do not know the proper way to go about doing this. Is there some way to read files and slot values into variables of a script?

To be clear, I would like to be able to tell Unity to make an Archer, then have it read the Archer file, look up its values for health and attack, then instantiate a copy of the Generic Unit prefab and slot the values that it read into the public variables of a script component of the newly-created game object.

# Answer
Short of using a third-party parser or writing your own parser for any file format, Unity 5.3 has a built-in JsonUtility class that can automatically parse a JSON string and apply its values to a class:

> `JsonUtility.FromJsonOverwrite`: Overwrite data in an object by reading from its JSON representation.

For example, say you had a Creature class:

```
public class Creature : MonoBehaviour {
    public string creatureName;
    public int health;
    public int attack;
}

```

You could have a JSON file named Archer.json placed in your Resources folder containing:

```
{
    "creatureName": "Archer",
    "health": 3,
    "attack": 1
}

```

You could then load and assign the JSON values to a Creature like so:

```
// Load the JSON file
TextAsset textAsset = (TextAsset)Resources.Load("Archer"); // Don't include the .json extension
string jsonString = textAsset.text;

// Instantiate a Creature, assuming you have a `GenericCreature` prefab in your Resources folder
GameObject prefab = (GameObject)Resources.Load("GenericCreature");
GameObject newObject = (GameObject)Instantiate(prefab);
Creature newCreature = newObject.GetComponent<Creature>();

// Assign the Archer JSON values to the Creature
JsonUtility.FromJsonOverwrite(jsonString, newCreature);

```
> 4 votes

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


# Question
Title: Creating a curved mesh on inside of sphere based on texture image coordinates
In Blender, I have created a sphere with a panoramic texture on the inside. I have also manually created a plane mesh (curved to match the size of the sphere) that sits on the inside wall where I can draw a different texture.

This is great, but I really want to reduce the manual labor, and do some of this work in a script -- like having a variable for the panoramic image, and coordinates of the area in the photograph that I want to replace with a new mesh.

The hardest part of doing this is going to be creating a curved mesh in code that can sit on the inside wall of a sphere.

Can anyone point me in the right direction?

# Answer
What you are trying to achieve seems very much related to this :

Analogue of spherical coordinates in n-dimensions

in your case in 2 dimensions then you just use this formula to map the vertices of rectangle you have (lets hope it is subdivided) on your sphere (dont forget to multiply by the halfDiameter somewhere. Only mathematicians are living on a unit sphere all other decent people are using diameters...)

EDIT : As all this is a bit vague i give some more insights What you need from this formula to be used :

```
x = r*sinθ*cosφ
y = r*sinθ*sinφ
z = r*cosθ

```

θ and φ being the spherical coordinates you are looking for (Latitude and Longitude) to get it you take the x/y coordinates of the points on portion of the panoramic image as such :

```
public Void getPointPosOnSphere(float Longitude,float Latitude,float r) {
    x = r*Mathf.sin(Longitude)*Mathf.cos(Latitude);
    y = r*Mathf.sin(Longitude)*Mathf.sin(Latitude);
    z = r*Mathf.cos(Longitude);
    return new Vector3(x,y,z);
}

//here you could have a for loop iterating through points of your rectangle for each
//point you'd have associated a map coordinate :
Vector3 pointSpacePos = getPointPosOnSphere(pointCoordY,pointCoordX,HalfDiamater);
//End of the for loop

```

then you would get your quad mapped on a sphere based from his xy position on a 2D coordinate system translated to the 3D position on the space according to sphere mapping.

EDIT : Just got an idea, to go further you could encapsulate the coordinates of the plane on the sphere using UV values as such :

```
for(int i = 0;i < vertices.Length; i++) {
    vertices[i] = getPointPosOnSphere(UV[i].y,UV[i].x,HalfDiamater);
}

```

There you could manage the quad position on your favorite 3D software (or even by code through unity) just by assigning UV values (if from 0 to 1 on both axes then quad will be wrapped all around the sphere)

WARNING : Using UV's will require you to do a Radians to Degrees conversion. (as UV is 0 to 1)
> 0 votes

# Answer
Géry Arduino's answer above pointed me in the right direction, but I would like to add couple of things here.

1) Following will not work in unity because of coordinate system differences

```
    return new Vector3(x,y,z);

```

change this to

```
    return new Vector3(x,z,y);

```

2) I was not clear on input range of long and lat values defined in the method signature

```
     public Void getPointPosOnSphere(float Longitude,float Latitude,float r)

```

Both Longitude and Latitude values should be in radians. Their range is as follows

```
     Longitude: 0°-180° (0 - π)
     Latitude: 0°-360° (0 - 2π)

```
> 0 votes

---
Tags: unity, mesh, dynamic-mesh
---


# Question
Title: Is it feasible to playback 4K video in Unity?
I'm starting work on a 360 VR video player, aimed at mobile devices (iOS/Android Cardboard + GearVR) and I'm evaluating whether it is possible to get video quality from 1080p to 4k in Unity or if I should instead just do the project natively (aka, OpenGL).

I've been trying to find information on the state of video in Unity but I haven't arrived to a clear answer. I'm going to explain the info I'm running on as of now, hopping that someone can add to this or provide an answer or at least show that I am erring on the side of ignorance :)

*Assume a video in mp4, H264 at 4K resolution (equirectangular mapping):*
**OpenGL Approach:**

If I were to do this in OpenGL, a (somewhat simplified) workflow would entail decoding each video frame, updating a GL\_TEXTURE\_2D with the pixel contents, and rendering to a sphere with glCullFace(GL\_FRONT) as if it where a regular skybox.

***With the above setup, the limiting factors would be:***

* Does the GPU in my device support 4K textures? what marketing calls 4k is usually 3840 horizontal, and, an iPhone6 for instance, returns 4096 for `glGetIntegerv(GL_MAX_TEXTURE_SIZE,...)`. So I'd assume the iPhone6 can load textures as big as required for 4K.
* Fill rate: i.e.: my iPhone6's GPU might be capable of storing 4K Textures, but it might not be fast enough to fill up a 4K frame buffer at an acceptable frame rate. This unfortunately I think the only way to know is by testing. There is also the added overhead of the Cardboard rendering which means 2 passes per frame.

**Unity Approach:**

Now for a Unity approach, this is what I did:

1. Empty scene with a sphere and cardboard camera at the origin.
2. For the sphere, I created a material based on the Unlit shader with one texture and set the cull face to front.
3. imported the video and assigned it as the material's texture.

***My observations from the above test are:***

1. When importing images, Unity also allows texture sizes of 4096 so 4K should be possible.
2. Importing a video however, takes a ridiculous amount of time. I believe this is because Unity actually uses Ogg Theora and so it takes forever to transcode to Ogg. As a matter of fact, sometimes I was able to import and sometimes Unity would just stall.
3. When importing a video, I was not given any mmap, filtering or size options as if I was importing an image. So I'm not really sure what Unity is doing to the video. All I get is a quality / compression slider. The end video is still 3840x1920, which was the original resolution.
4. The rest of the experiment works ok, as in, yes, the video playbacks in the sphere. But the framerate is not great.

**So at this point my conclusions are:**

1. Is it possible to do 4K in Unity? Kind of, In the sense that you can import 4K videos and reproduce them without any external assets.
2. Is it really 4K quality? Probably not. mp4 is lossy and so is ogg, So I assume my video went a second round of lossy compression when it was transcoded to Ogg.
3. Is it practical? Not sure. So far, video importing takes an impractical amount of time. Also, 4K in general might be too much for a mobile device rending in stereo, regardless of Unity or doing it straight in OpenGL.

# Answer
Short answer:

If you want to playback 4K in Unity you are better off finding some plugin (or coding your own) that uses the native API for video playback that the OS you are targeting uses.

Then you place the video file in either Streaming Assets or PersistentDataPath.

This way you avoid Unity's transcoding.
> 0 votes

---
Tags: unity, virtual-reality, video, 360-video
---


# Question
Title: What should I wear to a job interview with a game development company?
Many game development companies are less formal in terms of workplace attire than other types of software development houses. For example, I know that one place at which I will be interviewing soon has a predominant workplace culture of jeans and polos or t-shirts.

Should I wear a suit? Shirt and tie? Shirt and sport jacket, with or without tie? I want to show that I'm serious about the job, but that I understand the culture, too.

# Answer
As with a lot of hiring questions, "it depends". The human element in hiring can't be ignored.

That being said, there are a couple of things to keep in mind.

Are you going to be talking to a big company or a small one? Bigger companies might have HR personnel who aren't necessarily game developers who do the initial filtering. They might be more inclined to look at appearances for their opinions on candidates than, say, the art director at a small company simply because they don't have the expertise to really look analytically at someone's portfolio.

Also, remember just like any other job you're going to be working side by side with people for (hopefully) a long period of time. First impressions matter. As an interviewer I'm looking for both game development skills and people skills. Namely, am I going to want to work side-by-side with whoever I'm talking to? Do they show poor judgement (like wearing an offensive t-shirt to a professional setting where they don't know the audience)? How's their hygiene? Dressing sharper might help with those sides of things.

But don't dress sharp if you don't know how. Don't wear a button down shirt that isn't ironed. Don't put on too much cologne. And if you're not comfortable in a tie, don't wear one. An interview is stressful enough as it is, and you don't want your clothes working against you.

I've interviewed junior candidates that wore suits and ties. If we thought they were smart (and likely to get the job), we'd poke fun at them a bit. Mainly just to get the point across that our culture didn't really care about that kind of thing (and, as far as I know, most game companies really don't care). But generally it didn't count against them.
> 18 votes

# Answer
Find out how people generally dress there. Dress one step fancier than that.
> 10 votes

# Answer
Personally, I feel that you should always convey a professional image. You don't have to be completely suited and booted, but you should at least make an effort to wear an ironed shirt and some smart trousers. Regardless of whether you have a small or large games company, even if the culture is to work in T-shirts and jeans, like it is as my place (and many other games companies), first impressions count.

You don't know who is going to interview you, and it's not always possible to find out exactly how people dress at the company you're going to, so it's always best to paint yourself in a positive light.

Other general tips for interviews:

* Check your teeth for food before going in
* Don't smell (either too much cologne, or not enough)
* Relax in the interview and be yourself, but don't go so far as to slouch completely.
* Smile lots and make eye contact
> 7 votes

# Answer
There isn't a "it depends" on company. You don't get hired based on what you wear, so wear the standard interview gear (e.g. dress shirt, tie and dress shoes). This is universally accepted by all companies and dressing otherwise is running the risk of "it depends" on company.
> 1 votes

# Answer
Easy answer: when you are offered the interview in the first place, ask how they prefer applicants to dress! If you forget, you can always call/email your contact at that company and ask in advance. It's a reasonable question and you don't lose points for asking.

The good news is that the game industry is mostly a meritocracy. I personally like to wear a suit and tie for the interview (it was just drilled into me when I was young to always always always do this), I usually get some gentle ribbing about how I'd better not show up to work looking like that, and then we get down to actually figuring out whether I'm a good fit for the position. I have plenty of colleagues who "dress down" and get hired that way, too.

Ultimately, a hire / don't hire decision is going to come down to your skills, abilities, and fit. I have never, NEVER heard of anyone in the game industry getting (or not getting) a job solely because they did or didn't wear a suit. (I suppose if you showed up wearing a t-shirt with an offensive image on it that would count against you, or if you showed up wearing nothing but a Speedo or something, but accounting for basic common sense you should stress about showing why you're an awesome developer, not a snazzy dresser :)
> 1 votes

# Answer
In my admittedly limited experience (my previous job was at a game studio and I have a bunch of friends who work at different studios), game studios tend to be pretty casual. Personally, I wouldn't dress up past an ironed button-down and solid-colour, non-embellished jeans or dress pants for an interview at a game studio. They're generally places where people wear jeans and t-shirts to work, you're likely to look out of place and like you don't understand the culture if you dress up too much.

That said, it's just an interview and what you wear (as long as you're clean and presentable) doesn't matter as much as your skills, plus good interviewers understand when candidates overdress because they're worried about making a good impression.
> 1 votes

# Answer
Just like for any other job, dress as you would like to dress every day if you get the job.

You can't complain you have to wear a tie, if you wore one during your interview.
> 0 votes

# Answer
It does depend but the answer is very specific to the type of interview.

I never wear a tie for a software or tech company and no one ever shows up with them for interviews in the places I work unless they are from China or something like that. I just wear a nice dress shirt with a solid color, nice pants and dress shoes. Pretty close to how I show up to work. And that is how everyone else seems to show up as well.

For government work or trying to get a contract with a fortune 500 company you need to wear a dark, conservatively cut suit. You will look and feel horribly out of place in anything else. And be sure to act very polite and formal as well and don't be opinionated at all, which you can usually get away with a little at a software company so long as you are somewhat inline with the opinions of the locals - and if you are not, then maybe you should avoid working their anyway.

There's probably some places that won't care if you are less formal than option A) but I would not push my luck. You don't want to be seen as too eccentric.

As for hiring only on abilities goes - ha. Some fantasy world. People are not so objective as that even at the best tech companies. Not to mention they are only able to judge that within their own abilities. And not the abilities of the best programmer there but of the upper management who are usually a whole different ball of wax compared to their top tech guys.
> 0 votes

---
Tags: jobs
---


# Question
Title: Way to check if rectangle contains anything (without passing the "anything" as a parameter)
Using it for a chess game, i want the tiles to be able to tell if anything is on it without the function passing the other object as a parameter so it can see if the tile global bounds of the tile contains the global bounds of the other object. The only objects in those tiles will be the chess piece anyway.

# Answer
> 1 votes
Your question reminds me of GameMaker's `instance_place()` function, that's able to retrieve any existing object that's colliding with something.

Unfortunately, there is no way to query "all of the existing objects" in C++. First that would be **way** too many objects, but also, most of them don't have spatial information at all (how do you check for collisions with `std::cout` ?)

However you go about it, you have to pass the list of pieces to your function somehow, so it can iterate through it and find whether one intersects. Some ways are:

## Parameter passing

```
Piece *Tile::findCollision(PieceList &pieces);

```

... or its more `<algorithm>`-flavoured counterpart:

```
template <class Ite>
Ite Tile::findCollision(Ite first, Ite last);

```

Both would return an iterator (pointer) to the colliding `Piece`, or `last` (`nullptr`) if none is. That is the solution you wish to avoid, but is the most idiomatic.

## Class member

The `Chessboard` class would contain `PieceList _myPieces` as a member variable, which could then be accessed from within the function:

```
// Accesses this->_myPieces
Piece *Chessboard::findPiece(Tile const &position);

```

## Global variable

Global state is generally frowned upon, but is still technically a solution : you'd make your `PieceList chessPieces` globally accessible, and then access it from the function:

```
// No parameter, invisibly accesses some global state somewhere :(
Piece *Tile::findCollidingPiece();

```

## Capturing

That one would be quite unusual. You can capture the `PieceList` by reference inside a lambda, and store it for future use.

```
PieceList chessPieces;
auto findCollidingPiece = [&chessPieces](Tile const &position) -> Piece* { /*...*/ };

```

---

## Is that necessary at all?

But all of these deal with real-space collisions. While they are applicable here, the better idea would be to acknowledge the grid-based nature of chess in your design, and do everything with integer coordinates and no collision checking. You'd store a 2D array of `std::unique_ptr<Pieces>` inside your `Chessboard` class, which would expose the function:

```
Piece *Chessboard::pieceAt(int x, int y);

```

A `Tile`, if you actually needed one, would store its integer coordinates and the `Chessboard &` it belongs to, and access the latter for any queries, effectively acting as a proxy.

---
Tags: c++, sfml
---


# Question
Title: Unity: OnTriggerEnter2D does not get called when using Raycast
In a previous post I talked about creating wires (using Bézier curve) using LineRenderer. I am using a PolygonCollider2D to wrap the wire (see below):

```
GameObject wire = new GameObject ();
LineRenderer lineRenderer = wire.AddComponent<LineRenderer> ();
PolygonCollider2D wireCollider = wire.AddComponent<PolygonCollider2D> ();

```

After drawing the curve and attaching the collider (as described in previous post), I added a new component to my gameObject (a WireController):

```
WireController wireController = wire.AddComponent<WireController> ();

```

The WireController currently has only one method:

```
void OnTriggerEnter2D(Collider2D other) {
    Debug.Log ("I'm hit!");
}

```

I use a Physics2D.Raycast to check if my mouse pointer is at any point interacting with the wire:

```
void CastRay() {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, 100);

    if (hit) {
        Debug.Log (hit.collider.gameObject.name);
    }
}

```

If I call CastRay() inside a Update() loop, `if (hit)` returns true (if the mouse pointer is over the gameObject, in this case, the wire), but the `OnTriggerEnter2D` method never gets called.

A few observations:

* `collider.isTrigger = true;`
* The `WireController` is attached to the newly created gameObject (it's visible in the Unity editor at runtime)

Any help is much appreciated!

# Answer
> 0 votes
I created a Helper class responsible for checking if the wire is cut, that contains the following method:

```
public delegate void CallbackAction();

public static void CheckIfWireIsCut(Camera camera, string tag, CallbackAction callback) {
    if (!Input.GetMouseButton (0)) {
        return;
    }

    Ray ray = camera.ScreenPointToRay (Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, 100);

    if (hit && hit.collider.gameObject.tag.Equals(tag)) {
        callback ();
    }
}

```

In the WireController code, I created a callback method and in the Update() loop I check if the wire is cut:

```
void Update () {
    GameHelper.CheckIfWireIsCut (Camera.main, gameObject.tag, CutWire);
}

public void CutWire() {
    Debug.Log ("Cut me!");
}

```

This works for my use case. Hope it helps other people with similar issues.

---
Tags: collision-detection, unity, raycasting
---


# Question
Title: Does Unreal Engine Has Good grapic texture editor or I have to Learn Maya?
I'm new in game Development , and I had no experience of it (except programming) So , for my Engine , I preferred to use Unreal Engine. So here's the question: Are Maya or 3D'sMax needed to be learned or Unreal Engine has a built in Editor ? and , in comment , After i learned graphic , witch programming Language Does Unreal Engine support and recommended ?

# Answer
> 0 votes
Unreal Engine does not provide a builtin editor for creating graphical content like meshes and textures. Even if it did you would probably better off using a tool that is dedicated to the job because UE is doing a lot more and totally different things for you.

For the programming language you will use C++ for traditional coding but can also use a visual programming language called Blueprint. You can use one of the two without the other or mix it up as they are designed to interact with each other. You can start reading in the wiki from here: Programming Guide

---
Tags: udk, unreal
---


# Question
Title: How to copy FrontBuffer to BackBuffer in DirectX11
I want to render the surface base on the the last surface. So I try to copy `FrontBuffer` to `BackBuffer`, but it does not work:

```
//Get the BackBuffer(it will be FrontBuffer after SwapChain swapped the BackBuffer and FrontBuffer)
ID3D11Texture2D* backBufferTexture1 = NULL;
swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture1);
D3D11_MAPPED_SUBRESOURCE mapResource1;
HRESULT result1 = m_pID3DContext->Map(backBufferTexture1, 0, D3D11_MAP_READ, 0, &mapResource1);
assert(result1 == S_OK);

swapChain->Present(1,0); //swap the BackBuffer and FrontBuffer

//Get the BackBuffer
ID3D11Texture2D* backBufferTexture2 = NULL;
swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture2);
D3D11_MAPPED_SUBRESOURCE mapResource2;
HRESULT result2 = m_pID3DContext->Map(backBufferTexture2, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource2);
assert(result2 == S_OK);

//Copy the FrontBuffer to the BackBuffer
memcpy(mapResource2.pData, mapResource1.pData, sizeof(mapResource1.pData));
m_pID3DContext->Unmap(backBufferTexture1, 0);
m_pID3DContext->Unmap(backBufferTexture2, 0);

```

The `result1` and `result2` both return **E\_INVALIDARG One or more arguments are invalid.** How could I get this to work?

# Answer
> 1 votes
You can't `Map` a swapchain buffer as they are not necessarily created in CPU-readable memory. You could in theory copy it to a CPU staging resource, but the performance would be terrible.

A better option is to create another render target that you do your drawing on to, then you copy that texture to the backbuffer for Present. Then you can render your next scene on the same render target. The performance here is probably not as good as just rendering the whole scene again, but it really depends on what exactly you are doing.

# Answer
> 0 votes
I finally found the most easy way to do this work. What I do is just change the SwapChain's SwapEffect to `DXGI_SWAP_EFFECT_SEQUENTIAL` and don't Clear RenderTargetView before draw to keep the backbuffer as same as last time.

---
Tags: directx, directx11
---


# Question
Title: How can I create a "fuzzy crayon" effect?
I spent sometime looking at Media Molecule's Dreams. In it, the user is allowed to fuzzy crayon strokes in the mid air (in 3D space)(at the point of the video around 43:00).

How can I implement a similar effect? Is it a polygon with texture or some complex particle system? I believe it have something to do shader but not sure how.

# Answer
I expect that you are talking about this:

There are two ways, that I can think of, with which one might achieve such an effect:

**1.** You could create a mesh made out of many connected cylinders, apply a texture to it like the one used in the example, and then use post-processing effects(like a bloom effect or a blur) to make it glow. Also, before each frame, you could add an offset to the uv texture coordinates of the mesh to make it look animated. The mesh can be created in a modeling program or you could create an algorithm the generates a mesh in real time.

or

**2.** You could have a list of nodes, where each node is connected with it's two neighboring nodes. These nodes will create a curve, around which you could have particles that slowly move from one node to the other. Also each particle could have a different speed so that it look more realistic.
> 1 votes

---
Tags: shaders, particles
---


title: Problem with wheelcollider on bike game

text:
# Question
Title: Problem with wheelcollider on bike game
I have a problem with my first test on Unity, it's a simple motorcycle game. I found a script to start learning and runs very good, is this (answers.unity3d.com/questions/528298/bike-physics.html). Well, the bike is moving good, and turns well, the problem comes when I try to knock down the bike. I'm using this example (docs.unity3d.com/ScriptReference/Transform-rotation.html), and the movement is perfect, but the bike don't turns as expected, making a strange movement (a small jumps, seems a bug xD). What is the correct (and easy) way to get work the wheels on bike, because on car works perfectly. Sorry for my english, and I appreciate a answers for noobs to my question, please.

I'm thinking on the possibility of keep the wheelcolliders always straight and rotate the other parts of the bike... Or here, the user reccomends a sphere collider...but, how to make a "wheelcollider" with a spherecollider?? I'm very lost...

A lot of thanks!!!

----- EDIT -----

PROBLEM SOLVED!! This is the code I used to solve the problem, I don't know if is correct but works perfect for me:

```
//INCLINACION MOTO AL GIRAR
var tiltAroundZ = -(Input.GetAxis("Horizontal") * tiltAngle);
var target : Vector3;
target = Vector3 (0,0,tiltAroundZ);
var deltaRotation : Quaternion = Quaternion.Euler(target * Time.deltaTime);
// Dampen towards the target rotation
rb.MoveRotation(rb.rotation * deltaRotation);
if(Input.GetButton("Horizontal")==false)
{
if(rb.rotation.z > 0){
target.Set(0,0,-30);
deltaRotation = Quaternion.Euler(target * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
}
if(rb.rotation.z < 0){
target.Set(0,0,30);
deltaRotation = Quaternion.Euler(target * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
}

```

# Answer
> 2 votes
When you have an object controlled by the Unity physics engine (one with a Rigidbody), you should never manipulate its `transform` or `position` directly. That confuses the physics engine and can lead to all kinds of weird results.

Always control the object through the methods of Rigidbody or WheelCollider. For any vehicles which uses wheels, you should do almost everything through WheelCollider. When you want it to turn, don't rotate the rigidbody, change the steering of the front wheel collider and let the engine handle the rest.

When you control a bike with realistic physics, it might get difficult to prevent it from falling to the side. In the real world the rider of a bike needs to keep the bike in balance, but your simulation doesn't have that yet. A simple solution might be to detect the current rotation and add a torque to rebalance it when it isn't straight. A more realistic but more complicated solution might be to do what a human driver would do and adjust the center of mass of the rigidbody to prevent the vehicle from tipping over.

Riding a bike isn't easy in the real world, and when you want to simulate it in a game with real-world like physics, it won't be easy either.

But there is of course the most simple solution: When your goal is to create a game with very simplified physics, then you can also opt to not use Unity physics at all. Don't use a rigidbody *or* a wheel collider and move the object around by taking complete control over its transform and position.

---
Tags: unity
---


# Question
Title: C++ Multithreading: accessing objects together
I'm kinda new to C++ Multithreading, and I'm keeping it simple right now. I will keep things simple and write psuedo-code. I'm making a Turn Based Strategy Game but let's keep it at Chess for now.

I have a basic draw thread and update thread.

```
function DrawThread
    CurrentScreen Drawn
end

function LogicThread
    CurrentScreen Update
end

```

Both of these functions run in their seperate threads. Now I've run into a few problems.

For example: My pieces (units) are stored in a vector in the CurrentScreen

```
Class MapScreen
public:
    GetPieces returns VectorOfpieces

private:
    VectorOfpieces
end

```

The draw thread constantly draws the Chess pieces.

```
function Drawn
    for each chesspiece in VectorOfpieces
        draw chesspiece
    end
end

```

I have a cursor that moves grid-based and on, for example, ENTER checks if there is a Chess piece underneath it. (I've omitted any other code that has nothing to do with it)

```
function PollInput
    if KeyPressed is ENTER
        CheckUnderNeath
    end
end

function CheckUnderNeath
    for each chesspiece in MapScreen.GetPieces
        if chesspiece position is cursor position
            return chesspiece
        end
    end
end

```

Now as you might have guessed this Cursor update is in the other thread

```
function Update
    Cursor PollInput
end

```

And as you might have seen coming miles away, both threads will eventually end up using the same vector at the same time, causing a crash.

Is there any easy implementation to fix a problem like this, as my 2-3 problems right now are eventually down to this problem, threads bumping heads.

What bothers me is this crash isn't consistant. Because it's a vector I will get a "map/set iterator not dereferencable" error.

I'd appreciate a C++ answer eventhough my question was in Psuedocode. Thanks in advance!

TL:DR One thread tries to update the position of the same pointer the other tries to draw.

# Answer
When you have multiple threads that need to access a shared bit of data, you can wrap that access in a thread synchronization primitive, such as a mutex. While one thread has access to the data via the primitive, other threads will be blocked from acquiring the access and will wait. Thus, you prevent scenarios where two threads are writing to data, or one is writing while one is reading, et cetera.

(C++ containers in particular are not generally thread-safe on their own, concurrent access and modification *must* be synchronized, or you'll get all kinds of problems like invalidated iterators in other thread leading to crashes.)

However in the worst-case scenario this can completely eliminate any point to threads at all, because they will simply execute serially waiting for the requisite access. Generally, when you find yourself needing to write a bunch of locks around data access, you should ask yourself if you're really spreading your work out across threads ideally.

In this case I don't think you are. You have three tasks: updating the game, rendering, and collecting input. All of these tasks have significant dependencies on each. You can't update without current input (and there is little reason to update more than once based on prior input). You don't need to render unless there's new state to display (issues related to decoupling render and update rates notwithstanding).

Putting each of these tasks on its own thread isn't a very good use of concurrency. Not only do they all depend on eachother serially, but there's on three of them, so the architecture isn't scalable. You achieve maximum theoretical throughput at three cores. With fewer cores, you suffer an active penalty because at least one task must always be blocked. With more cores, you simply waste the processing power since you can't do more than three things.

A better approach is probably to break each task into as many concurrent chunks of work as possible. Go "wide" within each task, but continue to execute each task serially.

This involves identifying, for each kind of task, isolated groups of sub-tasks that don't rely on eachother. This might be updating sets of objects that exists in logical "islands" (all of them are near eachother, but far enough away from everything else that they could only possibly interact with eachother), or updating all physics on one thread while you update all lifetime/countdown timers on another. Or grouping renderable objects into batches of 25 obejcts that you farm out to threads to update animations for prior to drawing.

Basically, *identify functions that do not interact directly* or share data, and make those your tasks that you farm out to as many cores as are available.

This addresses both problems. You don't need locks because nothing shares data, so they can't read/write or write/write or anything. It scales better: you can group these independent tasks onto threads based on how many threads are actually reasonable for the actual machine (based on core count), so you can always attempt to maximize throughput.
> 3 votes

# Answer
I think one of the core reasons to use multithreading is extra speed you can get, but that not always happens ! Choosing multithreading leads to a bunch of problems, one of them is asynchronized shared access to some data between multiple threads. This is the problem you are facing now. A simple solution is the usage of `mutexes`. A good explanation . But in your case I would just get rid of all the threading you have. It is not needed. Using multithreading to separate game logic is pointless. You won't get anything but time loss. Write your game first, then if you have any performance issues you can take a look at multithreading and such.
> 1 votes

# Answer
Multithreading wont really improve efficiency. With gl commands, the biggest bottleneck comes when issuing draw calls to the GPU (vbos being filled). This doesnt mean the GPU will struggle drawing, but the CPU will have problems sending all the objects' information to it quickly. Multithreading wont solve that, but it might 'feel' like its an ideal solution to get a hang of. In fact, im guessing it will only cause problems, and uneccessary overhead.

What you want to look at are ways to reduce the amount of data being sent from the CPU to the GPU (if you worry about efficiency) this will be the biggest bottleneck further down the line. Calls such as `gldrawelements()` and `gldrawlementsinstanced()` (or instanced drawing) is what you should look at, rather than thinking of ways to make the engine run multithreaded. Like in my engine, the cpu cycle finishes in less than 2 milliseconds, leaving it to idle 3ms, and still being updated every 5ms, thats 200 fps, without a problem. The engine is rarely the bottleneck, and it wont be solved by multithreading.

When you multithread, its the same as running 2 seperate programs. The CPU doesnt know that however, and while the 2 exes will run seperately, they each still send tasks to the CPU for it to solve, much like they would have if they were running as functions being called every now and then.

Your game shouldnt be using 100% cpu ever. Lying between 0.5% 10% is more than enough to know that you havent done something horribly wrong.

So take my advice, and dont worry about multithreading to seperate your engine and draw calls (which I suspect is what your trying to do). I use freegluts `glutTimerFunc()` and have it run an engine cycle and a draw cycle. I combine that with this stopwatch class:

```
class stopwatch
{
    double PCFreq = 0.0;
    __int64 CounterStart = 0;
    LARGE_INTEGER li;

public:

    void StartCounter()
    {
        if (!QueryPerformanceFrequency(&li))ExitProcess(0);
        PCFreq = double(li.QuadPart) / 1000.0;
        QueryPerformanceCounter(&li); CounterStart = li.QuadPart;
    }

    double GetCounter() { QueryPerformanceCounter(&li); return double(li.QuadPart - CounterStart) / PCFreq; }
};

stopwatch drawclock, pushclock;

```

I use them like this in my push/draw functions:

```
//make sure calculations are done before waiting
Sleep(3); //leave 2ms for calculations (more than enough)
while (pushclock.GetCounter() <= 5) {};
//cout << pushclock.GetCounter() << endl; //cout timer for each pushcycle
pushclock.StartCounter();

```

This will delay each cycle of the engine to 5ms and sleep when in between, to avoid the CPU from running away.

I think this is the problem your facing, and this is how I solve it; by using freeglut (which is great, dont let its old website fool you, its updated still) and the stopwatch class to regulate the cycles.
> 0 votes

---
Tags: c++, multithreading
---


# Question
Title: Can I make and test PS Vita games without registration?
I am currently not registered as a Playstation Developer at the moment, but I have emailed Sony in the mean time to ask how a single person can register as an Indie Developer to publish. But can I still make my game in the mean time?

I have Unity and I know that Unity has Playstation support, so is there any chance that I can test my current game on PS Vita as well without registering with Sony first? That way, when I do register, the game can be closer to release.

# Answer
> 4 votes
I found an answer from an email from Sony. In order to deploy from Unity, you do have to sign up as a registered developer as the SDKs from Sony have to be present.

---
Tags: unity
---